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>
27 #include <sys/types.h>
31 #define INVALID_ADDRESS 0xffffffff
34 * Keeps track of the various assemblies loaded
36 static GHashTable *loaded_images_hash;
37 static GHashTable *loaded_images_guid_hash;
39 static CRITICAL_SECTION images_mutex;
42 mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
44 const int top = iinfo->cli_section_count;
45 MonoSectionTable *tables = iinfo->cli_section_tables;
48 for (i = 0; i < top; i++){
49 if ((addr >= tables->st_virtual_address) &&
50 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
51 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
55 return INVALID_ADDRESS;
59 mono_image_rva_map (MonoImage *image, guint32 addr)
61 MonoCLIImageInfo *iinfo = image->image_info;
62 const int top = iinfo->cli_section_count;
63 MonoSectionTable *tables = iinfo->cli_section_tables;
66 for (i = 0; i < top; i++){
67 if ((addr >= tables->st_virtual_address) &&
68 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
69 if (!iinfo->cli_sections [i]) {
70 if (!mono_image_ensure_section_idx (image, i))
73 return (char*)iinfo->cli_sections [i] +
74 (addr - tables->st_virtual_address);
82 canonicalize_path (const char *path)
84 gchar *abspath, *pos, *lastpos, *dest;
87 if (g_path_is_absolute (path)) {
88 abspath = g_strdup (path);
90 gchar *tmpdir = g_get_current_dir ();
91 abspath = g_build_filename (tmpdir, path, NULL);
95 abspath = g_strreverse (abspath);
98 dest = lastpos = abspath;
99 pos = strchr (lastpos, G_DIR_SEPARATOR);
101 while (pos != NULL) {
102 int len = pos - lastpos;
103 if (len == 1 && lastpos [0] == '.') {
105 } else if (len == 2 && lastpos [0] == '.' && lastpos [1] == '.') {
107 } else if (len > 0) {
111 if (dest != lastpos) strncpy (dest, lastpos, len + 1);
116 pos = strchr (lastpos, G_DIR_SEPARATOR);
119 if (dest != lastpos) strcpy (dest, lastpos);
120 return g_strreverse (abspath);
126 * Initialize the global variables used by this module.
129 mono_images_init (void)
131 InitializeCriticalSection (&images_mutex);
133 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
134 loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
138 * mono_image_ensure_section_idx:
139 * @image: The image we are operating on
140 * @section: section number that we will load/map into memory
142 * This routine makes sure that we have an in-memory copy of
143 * an image section (.text, .rsrc, .data).
145 * Returns: TRUE on success
148 mono_image_ensure_section_idx (MonoImage *image, int section)
150 MonoCLIImageInfo *iinfo = image->image_info;
151 MonoSectionTable *sect;
154 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
156 if (iinfo->cli_sections [section] != NULL)
159 sect = &iinfo->cli_section_tables [section];
161 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
163 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
165 /* FIXME: we ignore the writable flag since we don't patch the binary */
166 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
171 * mono_image_ensure_section:
172 * @image: The image we are operating on
173 * @section: section name that we will load/map into memory
175 * This routine makes sure that we have an in-memory copy of
176 * an image section (.text, .rsrc, .data).
178 * Returns: TRUE on success
181 mono_image_ensure_section (MonoImage *image, const char *section)
183 MonoCLIImageInfo *ii = image->image_info;
186 for (i = 0; i < ii->cli_section_count; i++){
187 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
190 return mono_image_ensure_section_idx (image, i);
196 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
198 const int top = iinfo->cli_header.coff.coff_sections;
201 iinfo->cli_section_count = top;
202 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
203 iinfo->cli_sections = g_new0 (void *, top);
205 for (i = 0; i < top; i++){
206 MonoSectionTable *t = &iinfo->cli_section_tables [i];
208 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
210 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
211 offset += sizeof (MonoSectionTable);
213 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
214 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
215 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
216 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
217 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
218 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
219 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
220 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
221 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
222 t->st_flags = GUINT32_FROM_LE (t->st_flags);
224 /* consistency checks here */
231 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
235 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
236 if (offset == INVALID_ADDRESS)
239 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
241 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
243 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
244 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
245 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
246 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
247 SWAP32 (iinfo->cli_cli_header.ch_size);
248 SWAP32 (iinfo->cli_cli_header.ch_flags);
249 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
250 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
251 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
252 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
253 SWAPPDE (iinfo->cli_cli_header.ch_resources);
254 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
255 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
256 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
257 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
258 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
259 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
260 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
261 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
262 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
263 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
264 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
265 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
266 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
271 /* Catch new uses of the fields that are supposed to be zero */
273 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
274 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
275 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
276 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
277 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
278 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
279 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
280 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
281 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
284 * No need to scare people who are testing this, I am just
285 * labelling this as a LAMESPEC
287 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
295 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
297 guint32 offset, size;
303 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
304 if (offset == INVALID_ADDRESS)
307 size = iinfo->cli_cli_header.ch_metadata.size;
309 if (offset + size > image->raw_data_len)
311 image->raw_metadata = image->raw_data + offset;
313 ptr = image->raw_metadata;
315 if (strncmp (ptr, "BSJB", 4) == 0){
316 guint32 version_string_len;
319 version_string_len = read32 (ptr);
321 image->version = g_strndup (ptr, version_string_len);
322 ptr += version_string_len;
323 pad = ptr - image->raw_metadata;
325 ptr += 4 - (pad % 4);
329 /* skip over flags */
332 streams = read16 (ptr);
335 for (i = 0; i < streams; i++){
336 if (strncmp (ptr + 8, "#~", 3) == 0){
337 image->heap_tables.data = image->raw_metadata + read32 (ptr);
338 image->heap_tables.size = read32 (ptr + 4);
340 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
341 image->heap_strings.data = image->raw_metadata + read32 (ptr);
342 image->heap_strings.size = read32 (ptr + 4);
344 } else if (strncmp (ptr + 8, "#US", 4) == 0){
345 image->heap_us.data = image->raw_metadata + read32 (ptr);
346 image->heap_us.size = read32 (ptr + 4);
348 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
349 image->heap_blob.data = image->raw_metadata + read32 (ptr);
350 image->heap_blob.size = read32 (ptr + 4);
352 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
353 image->heap_guid.data = image->raw_metadata + read32 (ptr);
354 image->heap_guid.size = read32 (ptr + 4);
356 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
357 g_print ("Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name);
360 g_message ("Unknown heap type: %s\n", ptr + 8);
361 ptr += 8 + strlen (ptr + 8) + 1;
363 pad = ptr - image->raw_metadata;
365 ptr += 4 - (pad % 4);
368 g_assert (image->heap_guid.data);
369 g_assert (image->heap_guid.size >= 16);
371 image->guid = mono_guid_to_string (image->heap_guid.data);
377 * Load representation of logical metadata tables, from the "#~" stream
380 load_tables (MonoImage *image)
382 const char *heap_tables = image->heap_tables.data;
384 guint64 valid_mask, sorted_mask;
385 int valid = 0, table;
388 heap_sizes = heap_tables [6];
389 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
390 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
391 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
393 valid_mask = read64 (heap_tables + 8);
394 sorted_mask = read64 (heap_tables + 16);
395 rows = (const guint32 *) (heap_tables + 24);
397 for (table = 0; table < 64; table++){
398 if ((valid_mask & ((guint64) 1 << table)) == 0){
399 if (table > MONO_TABLE_LAST)
401 image->tables [table].rows = 0;
404 if (table > MONO_TABLE_LAST) {
405 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
407 image->tables [table].rows = read32 (rows);
409 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
410 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
416 image->tables_base = (heap_tables + 24) + (4 * valid);
418 /* They must be the same */
419 g_assert ((const void *) image->tables_base == (const void *) rows);
421 mono_metadata_compute_table_bases (image);
426 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
428 if (!load_metadata_ptrs (image, iinfo))
431 return load_tables (image);
435 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
436 const char *name, guint32 index)
438 GHashTable *nspace_table;
439 GHashTable *name_cache = image->name_cache;
441 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
442 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
443 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
445 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
449 load_modules (MonoImage *image, MonoImageOpenStatus *status)
458 t = &image->tables [MONO_TABLE_MODULEREF];
459 image->modules = g_new0 (MonoImage *, t->rows);
460 image->module_count = t->rows;
461 base_dir = g_path_get_dirname (image->name);
462 for (i = 0; i < t->rows; i++){
465 guint32 cols [MONO_MODULEREF_SIZE];
467 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
468 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
469 module_ref = g_build_filename (base_dir, name, NULL);
470 image->modules [i] = mono_image_open (module_ref, status);
471 if (image->modules [i]) {
472 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
475 * FIXME: what do we do here? it could be a native dll...
476 * We should probably do lazy-loading of modules.
479 *status = MONO_IMAGE_OK;
487 load_class_names (MonoImage *image)
489 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
490 guint32 cols [MONO_TYPEDEF_SIZE];
493 guint32 i, visib, nspace_index;
494 GHashTable *name_cache2, *nspace_table;
496 /* Temporary hash table to avoid lookups in the nspace_table */
497 name_cache2 = g_hash_table_new (NULL, NULL);
499 for (i = 1; i <= t->rows; ++i) {
500 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
501 /* nested types are accessed from the nesting name */
502 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
503 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
505 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
506 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
508 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
509 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
511 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
512 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
513 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
516 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
519 /* Load type names from EXPORTEDTYPES table */
521 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
522 guint32 cols [MONO_EXP_TYPE_SIZE];
525 for (i = 0; i < t->rows; ++i) {
526 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
527 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
528 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
530 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
531 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
533 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
534 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
535 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
538 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
542 g_hash_table_destroy (name_cache2);
546 register_guid (gpointer key, gpointer value, gpointer user_data)
548 MonoImage *image = (MonoImage*)value;
550 if (!g_hash_table_lookup (loaded_images_guid_hash, image))
551 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
555 build_guid_table (void)
557 g_hash_table_foreach (loaded_images_hash, register_guid, NULL);
561 mono_image_init (MonoImage *image)
563 image->mempool = mono_mempool_new ();
564 image->method_cache = g_hash_table_new (NULL, NULL);
565 image->class_cache = g_hash_table_new (NULL, NULL);
566 image->field_cache = g_hash_table_new (NULL, NULL);
567 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
568 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
570 image->delegate_begin_invoke_cache =
571 g_hash_table_new ((GHashFunc)mono_signature_hash,
572 (GCompareFunc)mono_metadata_signature_equal);
573 image->delegate_end_invoke_cache =
574 g_hash_table_new ((GHashFunc)mono_signature_hash,
575 (GCompareFunc)mono_metadata_signature_equal);
576 image->delegate_invoke_cache =
577 g_hash_table_new ((GHashFunc)mono_signature_hash,
578 (GCompareFunc)mono_metadata_signature_equal);
579 image->runtime_invoke_cache =
580 g_hash_table_new ((GHashFunc)mono_signature_hash,
581 (GCompareFunc)mono_metadata_signature_equal);
583 image->managed_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
584 image->native_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
585 image->remoting_invoke_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
586 image->synchronized_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
587 image->unbox_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
589 image->typespec_cache = g_hash_table_new (NULL, NULL);
590 image->memberref_signatures = g_hash_table_new (NULL, NULL);
591 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
595 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
596 gboolean care_about_cli)
598 MonoCLIImageInfo *iinfo;
599 MonoDotNetHeader *header;
600 MonoMSDOSHeader msdos;
603 mono_image_init (image);
605 iinfo = image->image_info;
606 header = &iinfo->cli_header;
609 *status = MONO_IMAGE_IMAGE_INVALID;
611 if (offset + sizeof (msdos) > image->raw_data_len)
613 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
615 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
618 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
620 offset = msdos.pe_offset;
622 if (offset + sizeof (MonoDotNetHeader) > image->raw_data_len)
624 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
625 offset += sizeof (MonoDotNetHeader);
627 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
628 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
629 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
630 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
631 SWAP32 (header->coff.coff_time);
632 SWAP32 (header->coff.coff_symptr);
633 SWAP32 (header->coff.coff_symcount);
634 SWAP16 (header->coff.coff_machine);
635 SWAP16 (header->coff.coff_sections);
636 SWAP16 (header->coff.coff_opt_header_size);
637 SWAP16 (header->coff.coff_attributes);
639 SWAP32 (header->pe.pe_code_size);
640 SWAP32 (header->pe.pe_data_size);
641 SWAP32 (header->pe.pe_uninit_data_size);
642 SWAP32 (header->pe.pe_rva_entry_point);
643 SWAP32 (header->pe.pe_rva_code_base);
644 SWAP32 (header->pe.pe_rva_data_base);
645 SWAP16 (header->pe.pe_magic);
647 /* MonoPEHeaderNT: not used yet */
648 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
649 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
650 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
651 SWAP16 (header->nt.pe_os_major); /* must be 4 */
652 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
653 SWAP16 (header->nt.pe_user_major);
654 SWAP16 (header->nt.pe_user_minor);
655 SWAP16 (header->nt.pe_subsys_major);
656 SWAP16 (header->nt.pe_subsys_minor);
657 SWAP32 (header->nt.pe_reserved_1);
658 SWAP32 (header->nt.pe_image_size);
659 SWAP32 (header->nt.pe_header_size);
660 SWAP32 (header->nt.pe_checksum);
661 SWAP16 (header->nt.pe_subsys_required);
662 SWAP16 (header->nt.pe_dll_flags);
663 SWAP32 (header->nt.pe_stack_reserve);
664 SWAP32 (header->nt.pe_stack_commit);
665 SWAP32 (header->nt.pe_heap_reserve);
666 SWAP32 (header->nt.pe_heap_commit);
667 SWAP32 (header->nt.pe_loader_flags);
668 SWAP32 (header->nt.pe_data_dir_count);
670 /* MonoDotNetHeader: mostly unused */
671 SWAPPDE (header->datadir.pe_export_table);
672 SWAPPDE (header->datadir.pe_import_table);
673 SWAPPDE (header->datadir.pe_resource_table);
674 SWAPPDE (header->datadir.pe_exception_table);
675 SWAPPDE (header->datadir.pe_certificate_table);
676 SWAPPDE (header->datadir.pe_reloc_table);
677 SWAPPDE (header->datadir.pe_debug);
678 SWAPPDE (header->datadir.pe_copyright);
679 SWAPPDE (header->datadir.pe_global_ptr);
680 SWAPPDE (header->datadir.pe_tls_table);
681 SWAPPDE (header->datadir.pe_load_config_table);
682 SWAPPDE (header->datadir.pe_bound_import);
683 SWAPPDE (header->datadir.pe_iat);
684 SWAPPDE (header->datadir.pe_delay_import_desc);
685 SWAPPDE (header->datadir.pe_cli_header);
686 SWAPPDE (header->datadir.pe_reserved);
693 if (header->coff.coff_machine != 0x14c)
696 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
699 if (header->pesig[0] != 'P' || header->pesig[1] != 'E' || header->pe.pe_magic != 0x10B)
704 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
705 * which produces binaries with 7.0. From Sergey:
707 * The reason is that MSVC7 uses traditional compile/link
708 * sequence for CIL executables, and VS.NET (and Framework
709 * SDK) includes linker version 7, that puts 7.0 in this
710 * field. That's why it's currently not possible to load VC
711 * binaries with Mono. This field is pretty much meaningless
712 * anyway (what linker?).
714 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
719 * FIXME: byte swap all addresses here for header.
722 if (!load_section_tables (image, iinfo, offset))
725 if (care_about_cli == FALSE) {
729 /* Load the CLI header */
730 if (!load_cli_header (image, iinfo))
733 if (!load_metadata (image, iinfo))
736 load_class_names (image);
738 /* modules don't have an assembly table row */
739 if (image->tables [MONO_TABLE_ASSEMBLY].rows)
740 image->assembly_name = mono_metadata_string_heap (image,
741 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
742 0, MONO_ASSEMBLY_NAME));
744 image->module_name = mono_metadata_string_heap (image,
745 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
746 0, MONO_MODULE_NAME));
748 load_modules (image, status);
752 *status = MONO_IMAGE_OK;
759 mono_image_close (image);
764 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
765 gboolean care_about_cli)
767 MonoCLIImageInfo *iinfo;
770 struct stat stat_buf;
772 if ((filed = fopen (fname, "rb")) == NULL){
774 *status = MONO_IMAGE_ERROR_ERRNO;
778 if (fstat (fileno (filed), &stat_buf)) {
781 *status = MONO_IMAGE_ERROR_ERRNO;
784 image = g_new0 (MonoImage, 1);
785 image->ref_count = 1;
786 image->file_descr = filed;
787 image->raw_data_len = stat_buf.st_size;
788 image->raw_data = mono_raw_buffer_load (fileno (filed), FALSE, 0, stat_buf.st_size);
789 iinfo = g_new0 (MonoCLIImageInfo, 1);
790 image->image_info = iinfo;
791 image->name = canonicalize_path (fname);
793 return do_mono_image_load (image, status, care_about_cli);
797 mono_image_loaded (const char *name)
801 EnterCriticalSection (&images_mutex);
802 res = g_hash_table_lookup (loaded_images_hash, name);
803 LeaveCriticalSection (&images_mutex);
808 mono_image_loaded_by_guid (const char *guid)
812 EnterCriticalSection (&images_mutex);
813 res = g_hash_table_lookup (loaded_images_guid_hash, guid);
814 LeaveCriticalSection (&images_mutex);
819 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
821 MonoCLIImageInfo *iinfo;
825 if (!data || !data_len) {
827 *status = MONO_IMAGE_IMAGE_INVALID;
832 datac = g_try_malloc (data_len);
835 *status = MONO_IMAGE_ERROR_ERRNO;
838 memcpy (datac, data, data_len);
841 image = g_new0 (MonoImage, 1);
842 image->ref_count = 1;
843 image->raw_data = datac;
844 image->raw_data_len = data_len;
845 image->raw_data_allocated = need_copy;
846 image->name = g_strdup_printf ("data-%p", datac);
847 iinfo = g_new0 (MonoCLIImageInfo, 1);
848 image->image_info = iinfo;
850 return do_mono_image_load (image, status, TRUE);
855 * @fname: filename that points to the module we want to open
856 * @status: An error condition is returned in this field
858 * Returns: An open image of type %MonoImage or NULL on error.
859 * if NULL, then check the value of @status for details on the error
862 mono_image_open (const char *fname, MonoImageOpenStatus *status)
864 MonoImage *image, *image2;
867 g_return_val_if_fail (fname != NULL, NULL);
869 absfname = canonicalize_path (fname);
872 * The easiest solution would be to do all the loading inside the mutex,
873 * but that would lead to scalability problems. So we let the loading
874 * happen outside the mutex, and if multiple threads happen to load
875 * the same image, we discard all but the first copy.
877 EnterCriticalSection (&images_mutex);
878 image = g_hash_table_lookup (loaded_images_hash, absfname);
882 mono_image_addref (image);
883 LeaveCriticalSection (&images_mutex);
886 LeaveCriticalSection (&images_mutex);
888 image = do_mono_image_open (fname, status, TRUE);
892 EnterCriticalSection (&images_mutex);
893 image2 = g_hash_table_lookup (loaded_images_hash, image->name);
896 /* Somebody else beat us to it */
897 mono_image_addref (image2);
898 LeaveCriticalSection (&images_mutex);
899 mono_image_close (image);
902 g_hash_table_insert (loaded_images_hash, image->name, image);
903 if (image->assembly_name && (g_hash_table_lookup (loaded_images_hash, image->assembly_name) == NULL))
904 g_hash_table_insert (loaded_images_hash, (char *) image->assembly_name, image);
905 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
906 LeaveCriticalSection (&images_mutex);
913 * @fname: filename that points to the module we want to open
914 * @status: An error condition is returned in this field
916 * Returns: An open image of type %MonoImage or NULL on error. if
917 * NULL, then check the value of @status for details on the error.
918 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
919 * It's just a PE file loader, used for FileVersionInfo. It also does
920 * not use the image cache.
923 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
925 g_return_val_if_fail (fname != NULL, NULL);
927 return(do_mono_image_open (fname, status, FALSE));
931 free_hash_table (gpointer key, gpointer val, gpointer user_data)
933 g_hash_table_destroy ((GHashTable*)val);
937 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
939 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
943 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
950 * @image: The image file we wish to add a reference to
952 * Increases the reference count of an image.
955 mono_image_addref (MonoImage *image)
957 InterlockedIncrement (&image->ref_count);
961 mono_dynamic_stream_reset (MonoDynamicStream* stream)
963 stream->alloc_size = stream->index = stream->offset = 0;
964 g_free (stream->data);
967 g_hash_table_destroy (stream->hash);
974 * @image: The image file we wish to close
976 * Closes an image file, deallocates all memory consumed and
977 * unmaps all possible sections of the file
980 mono_image_close (MonoImage *image)
985 g_return_if_fail (image != NULL);
987 EnterCriticalSection (&images_mutex);
988 /*g_print ("destroy image '%s' %p (dynamic: %d) refcount: %d\n", image->name, image, image->dynamic, image->ref_count);*/
989 g_assert (image->ref_count > 0);
990 if (--image->ref_count) {
991 LeaveCriticalSection (&images_mutex);
994 image2 = g_hash_table_lookup (loaded_images_hash, image->name);
995 if (image == image2) {
996 /* This is not true if we are called from mono_image_open () */
997 g_hash_table_remove (loaded_images_hash, image->name);
998 g_hash_table_remove (loaded_images_guid_hash, image->guid);
999 /* Multiple images might have the same guid */
1000 build_guid_table ();
1002 if (image->assembly_name && (g_hash_table_lookup (loaded_images_hash, image->assembly_name) == image))
1003 g_hash_table_remove (loaded_images_hash, (char *) image->assembly_name);
1004 LeaveCriticalSection (&images_mutex);
1006 if (image->file_descr) {
1007 fclose (image->file_descr);
1008 image->file_descr = NULL;
1009 if (image->raw_data != NULL)
1010 mono_raw_buffer_free (image->raw_data);
1013 if (image->raw_data_allocated) {
1014 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1015 MonoCLIImageInfo *ii = image->image_info;
1017 if ((image->raw_metadata > image->raw_data) &&
1018 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1019 image->raw_metadata = NULL;
1021 for (i = 0; i < ii->cli_section_count; i++)
1022 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1023 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1024 ii->cli_sections [i] = NULL;
1026 g_free (image->raw_data);
1028 g_free (image->name);
1029 g_free (image->guid);
1030 g_free (image->files);
1032 g_hash_table_destroy (image->method_cache);
1033 g_hash_table_destroy (image->class_cache);
1034 g_hash_table_destroy (image->field_cache);
1035 g_hash_table_destroy (image->array_cache);
1036 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1037 g_hash_table_destroy (image->name_cache);
1038 g_hash_table_destroy (image->native_wrapper_cache);
1039 g_hash_table_destroy (image->managed_wrapper_cache);
1040 g_hash_table_destroy (image->delegate_begin_invoke_cache);
1041 g_hash_table_destroy (image->delegate_end_invoke_cache);
1042 g_hash_table_destroy (image->delegate_invoke_cache);
1043 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1044 g_hash_table_destroy (image->remoting_invoke_cache);
1045 g_hash_table_destroy (image->runtime_invoke_cache);
1046 g_hash_table_destroy (image->synchronized_cache);
1047 g_hash_table_destroy (image->unbox_wrapper_cache);
1048 g_hash_table_destroy (image->typespec_cache);
1049 g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1050 g_hash_table_destroy (image->memberref_signatures);
1051 g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1052 g_hash_table_destroy (image->helper_signatures);
1054 if (image->image_info){
1055 MonoCLIImageInfo *ii = image->image_info;
1057 if (ii->cli_section_tables)
1058 g_free (ii->cli_section_tables);
1059 if (ii->cli_sections)
1060 g_free (ii->cli_sections);
1061 g_free (image->image_info);
1064 for (i = 0; i < image->module_count; ++i) {
1065 if (image->modules [i])
1066 mono_image_close (image->modules [i]);
1068 /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1069 if (!image->dynamic) {
1070 mono_mempool_destroy (image->mempool);
1073 /* Dynamic images are GC_MALLOCed */
1074 struct _MonoDynamicImage *di = (struct _MonoDynamicImage*)image;
1076 g_free ((char*)image->module_name);
1078 g_hash_table_destroy (di->typespec);
1080 g_hash_table_destroy (di->typeref);
1082 g_hash_table_destroy (di->handleref);
1084 mono_g_hash_table_destroy (di->tokens);
1086 g_hash_table_destroy (di->blob_cache);
1087 g_list_free (di->array_methods);
1089 g_ptr_array_free (di->gen_params, TRUE);
1090 if (di->token_fixups)
1091 mono_g_hash_table_destroy (di->token_fixups);
1092 if (di->method_to_table_idx)
1093 g_hash_table_destroy (di->method_to_table_idx);
1094 if (di->field_to_table_idx)
1095 g_hash_table_destroy (di->field_to_table_idx);
1096 if (di->method_aux_hash)
1097 g_hash_table_destroy (di->method_aux_hash);
1098 g_free (di->strong_name);
1099 g_free (di->win32_res);
1100 /*g_print ("string heap destroy for image %p\n", di);*/
1101 mono_dynamic_stream_reset (&di->sheap);
1102 mono_dynamic_stream_reset (&di->code);
1103 mono_dynamic_stream_reset (&di->resources);
1104 mono_dynamic_stream_reset (&di->us);
1105 mono_dynamic_stream_reset (&di->blob);
1106 mono_dynamic_stream_reset (&di->tstream);
1107 mono_dynamic_stream_reset (&di->guid);
1108 for (i = 0; i < MONO_TABLE_NUM; ++i) {
1109 g_free (di->tables [i].values);
1111 mono_mempool_destroy (image->mempool);
1116 * mono_image_strerror:
1117 * @status: an code indicating the result from a recent operation
1119 * Returns: a string describing the error
1122 mono_image_strerror (MonoImageOpenStatus status)
1127 case MONO_IMAGE_ERROR_ERRNO:
1128 return strerror (errno);
1129 case MONO_IMAGE_IMAGE_INVALID:
1130 return "File does not contain a valid CIL image";
1131 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1132 return "An assembly was referenced, but could not be found";
1134 return "Internal error";
1138 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1139 guint32 lang_id, gunichar2 *name,
1140 MonoPEResourceDirEntry *entry,
1141 MonoPEResourceDir *root, guint32 level)
1143 gboolean is_string=entry->name_is_string;
1145 /* Level 0 holds a directory entry for each type of resource
1146 * (identified by ID or name).
1148 * Level 1 holds a directory entry for each named resource
1149 * item, and each "anonymous" item of a particular type of
1152 * Level 2 holds a directory entry for each language pointing to
1157 if((is_string==FALSE && entry->name_offset!=res_id) ||
1158 (is_string==TRUE)) {
1161 } else if (level==1) {
1164 is_string==TRUE && name!=lookup (entry->name_offset)) {
1168 } else if (level==2) {
1169 if ((is_string == FALSE &&
1170 entry->name_offset != lang_id &&
1172 (is_string == TRUE)) {
1176 g_assert_not_reached ();
1179 if(entry->is_dir==TRUE) {
1180 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+entry->dir_offset);
1181 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1184 entries=res_dir->res_named_entries + res_dir->res_id_entries;
1186 for(i=0; i<entries; i++) {
1187 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1190 ret=mono_image_walk_resource_tree (info, res_id,
1201 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+entry->dir_offset);
1208 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1210 MonoCLIImageInfo *info;
1211 MonoDotNetHeader *header;
1212 MonoPEDatadir *datadir;
1213 MonoPEDirEntry *rsrc;
1214 MonoPEResourceDir *resource_dir;
1215 MonoPEResourceDirEntry *res_entries;
1222 info=image->image_info;
1227 header=&info->cli_header;
1232 datadir=&header->datadir;
1237 rsrc=&datadir->pe_resource_table;
1242 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1243 if(resource_dir==NULL) {
1247 entries=resource_dir->res_named_entries + resource_dir->res_id_entries;
1248 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1250 for(i=0; i<entries; i++) {
1251 MonoPEResourceDirEntry *entry=&res_entries[i];
1254 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1255 name, entry, resource_dir,
1266 mono_image_get_entry_point (MonoImage *image)
1268 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1272 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1274 MonoCLIImageInfo *iinfo = image->image_info;
1275 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1278 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1281 data = mono_image_rva_map (image, ch->ch_resources.rva);
1286 *size = read32 (data);
1292 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1294 char *base_dir, *name;
1296 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1300 if (fileidx < 1 || fileidx > t->rows)
1303 if (image->files && image->files [fileidx - 1])
1304 return image->files [fileidx - 1];
1307 image->files = g_new0 (MonoImage*, t->rows);
1309 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1310 fname = mono_metadata_string_heap (image, fname_id);
1311 base_dir = g_path_get_dirname (image->name);
1312 name = g_build_filename (base_dir, fname, NULL);
1313 res = mono_image_open (name, NULL);
1316 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1317 res->assembly = image->assembly;
1318 for (i = 0; i < res->module_count; ++i) {
1319 if (res->modules [i] && !res->modules [i]->assembly)
1320 res->modules [i]->assembly = image->assembly;
1323 image->files [fileidx - 1] = res;
1331 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1333 MonoCLIImageInfo *iinfo = image->image_info;
1334 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1337 if (!de->size || !de->rva)
1339 data = mono_image_rva_map (image, de->rva);
1348 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1350 MonoCLIImageInfo *iinfo = image->image_info;
1351 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1352 const int top = iinfo->cli_section_count;
1353 MonoSectionTable *tables = iinfo->cli_section_tables;
1355 guint32 addr = de->rva;
1359 if (!de->size || !de->rva)
1361 for (i = 0; i < top; i++){
1362 if ((addr >= tables->st_virtual_address) &&
1363 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
1364 return tables->st_raw_data_ptr +
1365 (addr - tables->st_virtual_address);
1374 mono_image_get_public_key (MonoImage *image, guint32 *size)
1378 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1380 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1383 pubkey = mono_metadata_blob_heap (image, tok);
1384 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1391 mono_image_get_name (MonoImage *image)
1393 return image->assembly_name;
1397 mono_image_get_filename (MonoImage *image)
1402 const MonoTableInfo*
1403 mono_image_get_table_info (MonoImage *image, int table_id)
1405 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1407 return &image->tables [table_id];
1411 mono_image_get_table_rows (MonoImage *image, int table_id)
1413 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1415 return image->tables [table_id].rows;
1419 mono_table_info_get_rows (const MonoTableInfo *table)
1425 mono_image_get_assembly (MonoImage *image)
1427 return image->assembly;
1431 mono_image_is_dynamic (MonoImage *image)
1433 return image->dynamic;
1437 mono_image_has_authenticode_entry (MonoImage *image)
1439 MonoCLIImageInfo *iinfo = image->image_info;
1440 MonoDotNetHeader *header = &iinfo->cli_header;
1441 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
1442 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
1443 return ((de->rva != 0) && (de->size > 8));