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"
22 #include "tabledefs.h"
23 #include "tokentype.h"
24 #include "metadata-internals.h"
26 #include <mono/io-layer/io-layer.h>
27 #include <mono/utils/mono-logger.h>
28 #include <sys/types.h>
32 #define INVALID_ADDRESS 0xffffffff
35 * Keeps track of the various assemblies loaded
37 static GHashTable *loaded_images_hash;
38 static GHashTable *loaded_images_guid_hash;
39 static GHashTable *loaded_images_refonly_hash;
40 static GHashTable *loaded_images_refonly_guid_hash;
42 static gboolean debug_assembly_unload = FALSE;
44 #define mono_images_lock() EnterCriticalSection (&images_mutex)
45 #define mono_images_unlock() LeaveCriticalSection (&images_mutex)
46 static CRITICAL_SECTION images_mutex;
49 mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
51 const int top = iinfo->cli_section_count;
52 MonoSectionTable *tables = iinfo->cli_section_tables;
55 for (i = 0; i < top; i++){
56 if ((addr >= tables->st_virtual_address) &&
57 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
58 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
62 return INVALID_ADDRESS;
66 mono_image_rva_map (MonoImage *image, guint32 addr)
68 MonoCLIImageInfo *iinfo = image->image_info;
69 const int top = iinfo->cli_section_count;
70 MonoSectionTable *tables = iinfo->cli_section_tables;
73 for (i = 0; i < top; i++){
74 if ((addr >= tables->st_virtual_address) &&
75 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
76 if (!iinfo->cli_sections [i]) {
77 if (!mono_image_ensure_section_idx (image, i))
80 return (char*)iinfo->cli_sections [i] +
81 (addr - tables->st_virtual_address);
89 canonicalize_path (const char *path)
91 gchar *abspath, *pos, *lastpos, *dest;
94 if (g_path_is_absolute (path)) {
95 abspath = g_strdup (path);
97 gchar *tmpdir = g_get_current_dir ();
98 abspath = g_build_filename (tmpdir, path, NULL);
102 abspath = g_strreverse (abspath);
105 dest = lastpos = abspath;
106 pos = strchr (lastpos, G_DIR_SEPARATOR);
108 while (pos != NULL) {
109 int len = pos - lastpos;
110 if (len == 1 && lastpos [0] == '.') {
112 } else if (len == 2 && lastpos [0] == '.' && lastpos [1] == '.') {
114 } else if (len > 0) {
119 /* The two strings can overlap */
120 memmove (dest, lastpos, len + 1);
125 pos = strchr (lastpos, G_DIR_SEPARATOR);
128 if (dest != lastpos) strcpy (dest, lastpos);
129 return g_strreverse (abspath);
135 * Initialize the global variables used by this module.
138 mono_images_init (void)
140 InitializeCriticalSection (&images_mutex);
142 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
143 loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
144 loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
145 loaded_images_refonly_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
147 debug_assembly_unload = getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
151 * mono_image_ensure_section_idx:
152 * @image: The image we are operating on
153 * @section: section number that we will load/map into memory
155 * This routine makes sure that we have an in-memory copy of
156 * an image section (.text, .rsrc, .data).
158 * Returns: TRUE on success
161 mono_image_ensure_section_idx (MonoImage *image, int section)
163 MonoCLIImageInfo *iinfo = image->image_info;
164 MonoSectionTable *sect;
167 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
169 if (iinfo->cli_sections [section] != NULL)
172 sect = &iinfo->cli_section_tables [section];
174 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
176 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
178 /* FIXME: we ignore the writable flag since we don't patch the binary */
179 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
184 * mono_image_ensure_section:
185 * @image: The image we are operating on
186 * @section: section name that we will load/map into memory
188 * This routine makes sure that we have an in-memory copy of
189 * an image section (.text, .rsrc, .data).
191 * Returns: TRUE on success
194 mono_image_ensure_section (MonoImage *image, const char *section)
196 MonoCLIImageInfo *ii = image->image_info;
199 for (i = 0; i < ii->cli_section_count; i++){
200 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
203 return mono_image_ensure_section_idx (image, i);
209 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
211 const int top = iinfo->cli_header.coff.coff_sections;
214 iinfo->cli_section_count = top;
215 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
216 iinfo->cli_sections = g_new0 (void *, top);
218 for (i = 0; i < top; i++){
219 MonoSectionTable *t = &iinfo->cli_section_tables [i];
221 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
223 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
224 offset += sizeof (MonoSectionTable);
226 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
227 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
228 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
229 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
230 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
231 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
232 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
233 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
234 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
235 t->st_flags = GUINT32_FROM_LE (t->st_flags);
237 /* consistency checks here */
244 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
248 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
249 if (offset == INVALID_ADDRESS)
252 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
254 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
256 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
257 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
258 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
259 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
260 SWAP32 (iinfo->cli_cli_header.ch_size);
261 SWAP32 (iinfo->cli_cli_header.ch_flags);
262 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
263 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
264 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
265 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
266 SWAPPDE (iinfo->cli_cli_header.ch_resources);
267 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
268 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
269 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
270 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
271 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
272 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
273 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
274 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
275 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
276 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
277 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
278 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
279 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
284 /* Catch new uses of the fields that are supposed to be zero */
286 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
287 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
288 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
289 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
290 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
291 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
292 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
293 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
294 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
297 * No need to scare people who are testing this, I am just
298 * labelling this as a LAMESPEC
300 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
308 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
310 guint32 offset, size;
316 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
317 if (offset == INVALID_ADDRESS)
320 size = iinfo->cli_cli_header.ch_metadata.size;
322 if (offset + size > image->raw_data_len)
324 image->raw_metadata = image->raw_data + offset;
326 ptr = image->raw_metadata;
328 if (strncmp (ptr, "BSJB", 4) == 0){
329 guint32 version_string_len;
332 image->md_version_major = read16 (ptr);
334 image->md_version_minor = read16 (ptr);
337 version_string_len = read32 (ptr);
339 image->version = g_strndup (ptr, version_string_len);
340 ptr += version_string_len;
341 pad = ptr - image->raw_metadata;
343 ptr += 4 - (pad % 4);
347 /* skip over flags */
350 streams = read16 (ptr);
353 for (i = 0; i < streams; i++){
354 if (strncmp (ptr + 8, "#~", 3) == 0){
355 image->heap_tables.data = image->raw_metadata + read32 (ptr);
356 image->heap_tables.size = read32 (ptr + 4);
358 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
359 image->heap_strings.data = image->raw_metadata + read32 (ptr);
360 image->heap_strings.size = read32 (ptr + 4);
362 } else if (strncmp (ptr + 8, "#US", 4) == 0){
363 image->heap_us.data = image->raw_metadata + read32 (ptr);
364 image->heap_us.size = read32 (ptr + 4);
366 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
367 image->heap_blob.data = image->raw_metadata + read32 (ptr);
368 image->heap_blob.size = read32 (ptr + 4);
370 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
371 image->heap_guid.data = image->raw_metadata + read32 (ptr);
372 image->heap_guid.size = read32 (ptr + 4);
374 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
375 g_print ("Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name);
378 g_message ("Unknown heap type: %s\n", ptr + 8);
379 ptr += 8 + strlen (ptr + 8) + 1;
381 pad = ptr - image->raw_metadata;
383 ptr += 4 - (pad % 4);
386 g_assert (image->heap_guid.data);
387 g_assert (image->heap_guid.size >= 16);
389 image->guid = mono_guid_to_string (image->heap_guid.data);
395 * Load representation of logical metadata tables, from the "#~" stream
398 load_tables (MonoImage *image)
400 const char *heap_tables = image->heap_tables.data;
402 guint64 valid_mask, sorted_mask;
403 int valid = 0, table;
406 heap_sizes = heap_tables [6];
407 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
408 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
409 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
411 valid_mask = read64 (heap_tables + 8);
412 sorted_mask = read64 (heap_tables + 16);
413 rows = (const guint32 *) (heap_tables + 24);
415 for (table = 0; table < 64; table++){
416 if ((valid_mask & ((guint64) 1 << table)) == 0){
417 if (table > MONO_TABLE_LAST)
419 image->tables [table].rows = 0;
422 if (table > MONO_TABLE_LAST) {
423 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
425 image->tables [table].rows = read32 (rows);
427 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
428 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
434 image->tables_base = (heap_tables + 24) + (4 * valid);
436 /* They must be the same */
437 g_assert ((const void *) image->tables_base == (const void *) rows);
439 mono_metadata_compute_table_bases (image);
444 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
446 if (!load_metadata_ptrs (image, iinfo))
449 return load_tables (image);
453 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
454 const char *name, guint32 index)
456 GHashTable *nspace_table;
457 GHashTable *name_cache = image->name_cache;
459 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
460 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
461 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
463 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
467 load_modules (MonoImage *image, MonoImageOpenStatus *status)
472 gboolean refonly = image->ref_only;
477 t = &image->tables [MONO_TABLE_MODULEREF];
478 image->modules = g_new0 (MonoImage *, t->rows);
479 image->module_count = t->rows;
480 base_dir = g_path_get_dirname (image->name);
481 for (i = 0; i < t->rows; i++){
484 guint32 cols [MONO_MODULEREF_SIZE];
486 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
487 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
488 module_ref = g_build_filename (base_dir, name, NULL);
489 image->modules [i] = mono_image_open_full (module_ref, status, refonly);
490 if (image->modules [i]) {
491 mono_image_addref (image->modules [i]);
492 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
495 * FIXME: what do we do here? it could be a native dll...
496 * We should probably do lazy-loading of modules.
499 *status = MONO_IMAGE_OK;
507 load_class_names (MonoImage *image)
509 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
510 guint32 cols [MONO_TYPEDEF_SIZE];
513 guint32 i, visib, nspace_index;
514 GHashTable *name_cache2, *nspace_table;
516 /* Temporary hash table to avoid lookups in the nspace_table */
517 name_cache2 = g_hash_table_new (NULL, NULL);
519 for (i = 1; i <= t->rows; ++i) {
520 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
521 /* nested types are accessed from the nesting name */
522 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
523 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
525 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
526 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
528 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
529 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
531 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
532 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
533 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
536 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
539 /* Load type names from EXPORTEDTYPES table */
541 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
542 guint32 cols [MONO_EXP_TYPE_SIZE];
545 for (i = 0; i < t->rows; ++i) {
546 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
547 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
548 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
550 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
551 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
553 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
554 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
555 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
558 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
562 g_hash_table_destroy (name_cache2);
566 register_guid (gpointer key, gpointer value, gpointer user_data)
568 MonoImage *image = (MonoImage*)value;
570 if (!g_hash_table_lookup (loaded_images_guid_hash, image))
571 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
575 build_guid_table (gboolean refonly)
577 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
578 g_hash_table_foreach (loaded_images, register_guid, NULL);
582 mono_image_init (MonoImage *image)
584 image->mempool = mono_mempool_new ();
585 image->method_cache = g_hash_table_new (NULL, NULL);
586 image->class_cache = g_hash_table_new (NULL, NULL);
587 image->field_cache = g_hash_table_new (NULL, NULL);
588 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
589 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
591 image->delegate_begin_invoke_cache =
592 g_hash_table_new ((GHashFunc)mono_signature_hash,
593 (GCompareFunc)mono_metadata_signature_equal);
594 image->delegate_end_invoke_cache =
595 g_hash_table_new ((GHashFunc)mono_signature_hash,
596 (GCompareFunc)mono_metadata_signature_equal);
597 image->delegate_invoke_cache =
598 g_hash_table_new ((GHashFunc)mono_signature_hash,
599 (GCompareFunc)mono_metadata_signature_equal);
600 image->runtime_invoke_cache =
601 g_hash_table_new ((GHashFunc)mono_signature_hash,
602 (GCompareFunc)mono_metadata_signature_equal);
604 image->managed_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
605 image->native_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
606 image->remoting_invoke_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
607 image->synchronized_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
608 image->unbox_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
610 image->typespec_cache = g_hash_table_new (NULL, NULL);
611 image->memberref_signatures = g_hash_table_new (NULL, NULL);
612 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
613 image->method_signatures = g_hash_table_new (NULL, NULL);
617 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
618 gboolean care_about_cli)
620 MonoCLIImageInfo *iinfo;
621 MonoDotNetHeader *header;
622 MonoMSDOSHeader msdos;
625 mono_image_init (image);
627 iinfo = image->image_info;
628 header = &iinfo->cli_header;
631 *status = MONO_IMAGE_IMAGE_INVALID;
633 if (offset + sizeof (msdos) > image->raw_data_len)
635 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
637 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
640 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
642 offset = msdos.pe_offset;
644 if (offset + sizeof (MonoDotNetHeader) > image->raw_data_len)
646 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
647 offset += sizeof (MonoDotNetHeader);
649 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
650 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
651 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
652 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
653 SWAP32 (header->coff.coff_time);
654 SWAP32 (header->coff.coff_symptr);
655 SWAP32 (header->coff.coff_symcount);
656 SWAP16 (header->coff.coff_machine);
657 SWAP16 (header->coff.coff_sections);
658 SWAP16 (header->coff.coff_opt_header_size);
659 SWAP16 (header->coff.coff_attributes);
661 SWAP32 (header->pe.pe_code_size);
662 SWAP32 (header->pe.pe_data_size);
663 SWAP32 (header->pe.pe_uninit_data_size);
664 SWAP32 (header->pe.pe_rva_entry_point);
665 SWAP32 (header->pe.pe_rva_code_base);
666 SWAP32 (header->pe.pe_rva_data_base);
667 SWAP16 (header->pe.pe_magic);
669 /* MonoPEHeaderNT: not used yet */
670 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
671 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
672 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
673 SWAP16 (header->nt.pe_os_major); /* must be 4 */
674 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
675 SWAP16 (header->nt.pe_user_major);
676 SWAP16 (header->nt.pe_user_minor);
677 SWAP16 (header->nt.pe_subsys_major);
678 SWAP16 (header->nt.pe_subsys_minor);
679 SWAP32 (header->nt.pe_reserved_1);
680 SWAP32 (header->nt.pe_image_size);
681 SWAP32 (header->nt.pe_header_size);
682 SWAP32 (header->nt.pe_checksum);
683 SWAP16 (header->nt.pe_subsys_required);
684 SWAP16 (header->nt.pe_dll_flags);
685 SWAP32 (header->nt.pe_stack_reserve);
686 SWAP32 (header->nt.pe_stack_commit);
687 SWAP32 (header->nt.pe_heap_reserve);
688 SWAP32 (header->nt.pe_heap_commit);
689 SWAP32 (header->nt.pe_loader_flags);
690 SWAP32 (header->nt.pe_data_dir_count);
692 /* MonoDotNetHeader: mostly unused */
693 SWAPPDE (header->datadir.pe_export_table);
694 SWAPPDE (header->datadir.pe_import_table);
695 SWAPPDE (header->datadir.pe_resource_table);
696 SWAPPDE (header->datadir.pe_exception_table);
697 SWAPPDE (header->datadir.pe_certificate_table);
698 SWAPPDE (header->datadir.pe_reloc_table);
699 SWAPPDE (header->datadir.pe_debug);
700 SWAPPDE (header->datadir.pe_copyright);
701 SWAPPDE (header->datadir.pe_global_ptr);
702 SWAPPDE (header->datadir.pe_tls_table);
703 SWAPPDE (header->datadir.pe_load_config_table);
704 SWAPPDE (header->datadir.pe_bound_import);
705 SWAPPDE (header->datadir.pe_iat);
706 SWAPPDE (header->datadir.pe_delay_import_desc);
707 SWAPPDE (header->datadir.pe_cli_header);
708 SWAPPDE (header->datadir.pe_reserved);
715 if (header->coff.coff_machine != 0x14c)
718 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
721 if (header->pesig[0] != 'P' || header->pesig[1] != 'E' || header->pe.pe_magic != 0x10B)
726 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
727 * which produces binaries with 7.0. From Sergey:
729 * The reason is that MSVC7 uses traditional compile/link
730 * sequence for CIL executables, and VS.NET (and Framework
731 * SDK) includes linker version 7, that puts 7.0 in this
732 * field. That's why it's currently not possible to load VC
733 * binaries with Mono. This field is pretty much meaningless
734 * anyway (what linker?).
736 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
741 * FIXME: byte swap all addresses here for header.
744 if (!load_section_tables (image, iinfo, offset))
747 if (care_about_cli == FALSE) {
751 /* Load the CLI header */
752 if (!load_cli_header (image, iinfo))
755 if (!load_metadata (image, iinfo))
758 load_class_names (image);
760 /* modules don't have an assembly table row */
761 if (image->tables [MONO_TABLE_ASSEMBLY].rows)
762 image->assembly_name = mono_metadata_string_heap (image,
763 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
764 0, MONO_ASSEMBLY_NAME));
766 image->module_name = mono_metadata_string_heap (image,
767 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
768 0, MONO_MODULE_NAME));
770 load_modules (image, status);
774 *status = MONO_IMAGE_OK;
779 mono_image_close (image);
784 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
785 gboolean care_about_cli, gboolean refonly)
787 MonoCLIImageInfo *iinfo;
790 struct stat stat_buf;
792 if ((filed = fopen (fname, "rb")) == NULL){
794 *status = MONO_IMAGE_ERROR_ERRNO;
798 if (fstat (fileno (filed), &stat_buf)) {
801 *status = MONO_IMAGE_ERROR_ERRNO;
804 image = g_new0 (MonoImage, 1);
805 image->file_descr = filed;
806 image->raw_data_len = stat_buf.st_size;
807 image->raw_data = mono_raw_buffer_load (fileno (filed), FALSE, 0, stat_buf.st_size);
808 iinfo = g_new0 (MonoCLIImageInfo, 1);
809 image->image_info = iinfo;
810 image->name = canonicalize_path (fname);
811 image->ref_only = refonly;
813 return do_mono_image_load (image, status, care_about_cli);
817 mono_image_loaded_full (const char *name, gboolean refonly)
820 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
823 res = g_hash_table_lookup (loaded_images, name);
824 mono_images_unlock ();
829 mono_image_loaded (const char *name)
831 return mono_image_loaded_full (name, FALSE);
835 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
838 GHashTable *loaded_images = refonly ? loaded_images_refonly_guid_hash : loaded_images_guid_hash;
841 res = g_hash_table_lookup (loaded_images, guid);
842 mono_images_unlock ();
847 mono_image_loaded_by_guid (const char *guid)
849 return mono_image_loaded_by_guid_full (guid, FALSE);
853 register_image (MonoImage *image)
856 GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
859 image2 = g_hash_table_lookup (loaded_images, image->name);
862 /* Somebody else beat us to it */
863 mono_image_addref (image2);
864 mono_images_unlock ();
865 mono_image_close (image);
868 g_hash_table_insert (loaded_images, image->name, image);
869 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
870 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);
871 g_hash_table_insert (image->ref_only ? loaded_images_refonly_guid_hash : loaded_images_guid_hash, image->guid, image);
872 mono_images_unlock ();
878 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
880 MonoCLIImageInfo *iinfo;
884 if (!data || !data_len) {
886 *status = MONO_IMAGE_IMAGE_INVALID;
891 datac = g_try_malloc (data_len);
894 *status = MONO_IMAGE_ERROR_ERRNO;
897 memcpy (datac, data, data_len);
900 image = g_new0 (MonoImage, 1);
901 image->raw_data = datac;
902 image->raw_data_len = data_len;
903 image->raw_data_allocated = need_copy;
904 image->name = g_strdup_printf ("data-%p", datac);
905 iinfo = g_new0 (MonoCLIImageInfo, 1);
906 image->image_info = iinfo;
907 image->ref_only = refonly;
909 image = do_mono_image_load (image, status, TRUE);
913 return register_image (image);
917 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
919 return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
923 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
926 GHashTable *loaded_images;
929 g_return_val_if_fail (fname != NULL, NULL);
931 absfname = canonicalize_path (fname);
934 * The easiest solution would be to do all the loading inside the mutex,
935 * but that would lead to scalability problems. So we let the loading
936 * happen outside the mutex, and if multiple threads happen to load
937 * the same image, we discard all but the first copy.
940 loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
941 image = g_hash_table_lookup (loaded_images, absfname);
945 mono_images_unlock ();
948 mono_images_unlock ();
950 image = do_mono_image_open (fname, status, TRUE, refonly);
954 return register_image (image);
959 * @fname: filename that points to the module we want to open
960 * @status: An error condition is returned in this field
962 * Returns: An open image of type %MonoImage or NULL on error.
963 * if NULL, then check the value of @status for details on the error
966 mono_image_open (const char *fname, MonoImageOpenStatus *status)
968 return mono_image_open_full (fname, status, FALSE);
973 * @fname: filename that points to the module we want to open
974 * @status: An error condition is returned in this field
976 * Returns: An open image of type %MonoImage or NULL on error. if
977 * NULL, then check the value of @status for details on the error.
978 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
979 * It's just a PE file loader, used for FileVersionInfo. It also does
980 * not use the image cache.
983 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
985 g_return_val_if_fail (fname != NULL, NULL);
987 return(do_mono_image_open (fname, status, FALSE, FALSE));
991 free_hash_table (gpointer key, gpointer val, gpointer user_data)
993 g_hash_table_destroy ((GHashTable*)val);
997 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
999 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1003 free_blob_cache_entry (gpointer key, gpointer val, gpointer user_data)
1009 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
1015 * mono_image_addref:
1016 * @image: The image file we wish to add a reference to
1018 * Increases the reference count of an image.
1021 mono_image_addref (MonoImage *image)
1023 InterlockedIncrement (&image->ref_count);
1027 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1029 stream->alloc_size = stream->index = stream->offset = 0;
1030 g_free (stream->data);
1031 stream->data = NULL;
1033 g_hash_table_destroy (stream->hash);
1034 stream->hash = NULL;
1040 * @image: The image file we wish to close
1042 * Closes an image file, deallocates all memory consumed and
1043 * unmaps all possible sections of the file
1046 mono_image_close (MonoImage *image)
1049 GHashTable *loaded_images, *loaded_images_guid;
1052 g_return_if_fail (image != NULL);
1054 if (InterlockedDecrement (&image->ref_count) > 0)
1057 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s %p.", image->name, image);
1059 mono_images_lock ();
1060 loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1061 loaded_images_guid = image->ref_only ? loaded_images_refonly_guid_hash : loaded_images_guid_hash;
1062 image2 = g_hash_table_lookup (loaded_images, image->name);
1063 if (image == image2) {
1064 /* This is not true if we are called from mono_image_open () */
1065 g_hash_table_remove (loaded_images, image->name);
1066 g_hash_table_remove (loaded_images_guid, image->guid);
1068 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1069 g_hash_table_remove (loaded_images, (char *) image->assembly_name);
1071 /* Multiple images might have the same guid */
1072 build_guid_table (image->ref_only);
1074 mono_images_unlock ();
1076 if (image->file_descr) {
1077 fclose (image->file_descr);
1078 image->file_descr = NULL;
1079 if (image->raw_data != NULL)
1080 mono_raw_buffer_free (image->raw_data);
1083 if (image->raw_data_allocated) {
1084 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1085 MonoCLIImageInfo *ii = image->image_info;
1087 if ((image->raw_metadata > image->raw_data) &&
1088 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1089 image->raw_metadata = NULL;
1091 for (i = 0; i < ii->cli_section_count; i++)
1092 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1093 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1094 ii->cli_sections [i] = NULL;
1096 g_free (image->raw_data);
1099 if (debug_assembly_unload) {
1100 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1102 g_free (image->name);
1103 g_free (image->guid);
1104 g_free (image->version);
1105 g_free (image->files);
1108 g_hash_table_destroy (image->method_cache);
1109 g_hash_table_destroy (image->class_cache);
1110 g_hash_table_destroy (image->field_cache);
1111 g_hash_table_destroy (image->array_cache);
1112 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1113 g_hash_table_destroy (image->name_cache);
1114 g_hash_table_destroy (image->native_wrapper_cache);
1115 g_hash_table_destroy (image->managed_wrapper_cache);
1116 g_hash_table_destroy (image->delegate_begin_invoke_cache);
1117 g_hash_table_destroy (image->delegate_end_invoke_cache);
1118 g_hash_table_destroy (image->delegate_invoke_cache);
1119 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1120 g_hash_table_destroy (image->remoting_invoke_cache);
1121 g_hash_table_destroy (image->runtime_invoke_cache);
1122 g_hash_table_destroy (image->synchronized_cache);
1123 g_hash_table_destroy (image->unbox_wrapper_cache);
1124 g_hash_table_destroy (image->typespec_cache);
1125 /* The ownership of signatures is not well defined */
1126 //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1127 g_hash_table_destroy (image->memberref_signatures);
1128 //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1129 g_hash_table_destroy (image->helper_signatures);
1130 g_hash_table_destroy (image->method_signatures);
1132 if (image->interface_bitset) {
1133 mono_unload_interface_ids (image->interface_bitset);
1134 mono_bitset_free (image->interface_bitset);
1136 if (image->image_info){
1137 MonoCLIImageInfo *ii = image->image_info;
1139 if (ii->cli_section_tables)
1140 g_free (ii->cli_section_tables);
1141 if (ii->cli_sections)
1142 g_free (ii->cli_sections);
1143 g_free (image->image_info);
1146 for (i = 0; i < image->module_count; ++i) {
1147 if (image->modules [i])
1148 mono_image_close (image->modules [i]);
1150 /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1151 if (!image->dynamic) {
1152 if (debug_assembly_unload)
1153 mono_mempool_invalidate (image->mempool);
1155 mono_mempool_destroy (image->mempool);
1159 /* Dynamic images are GC_MALLOCed */
1160 struct _MonoDynamicImage *di = (struct _MonoDynamicImage*)image;
1162 g_free ((char*)image->module_name);
1164 g_hash_table_destroy (di->typespec);
1166 g_hash_table_destroy (di->typeref);
1168 g_hash_table_destroy (di->handleref);
1170 mono_g_hash_table_destroy (di->tokens);
1171 if (di->blob_cache) {
1172 g_hash_table_foreach (di->blob_cache, free_blob_cache_entry, NULL);
1173 g_hash_table_destroy (di->blob_cache);
1175 g_list_free (di->array_methods);
1177 g_ptr_array_free (di->gen_params, TRUE);
1178 if (di->token_fixups)
1179 mono_g_hash_table_destroy (di->token_fixups);
1180 if (di->method_to_table_idx)
1181 g_hash_table_destroy (di->method_to_table_idx);
1182 if (di->field_to_table_idx)
1183 g_hash_table_destroy (di->field_to_table_idx);
1184 if (di->method_aux_hash)
1185 g_hash_table_destroy (di->method_aux_hash);
1186 g_free (di->strong_name);
1187 g_free (di->win32_res);
1188 /*g_print ("string heap destroy for image %p\n", di);*/
1189 mono_dynamic_stream_reset (&di->sheap);
1190 mono_dynamic_stream_reset (&di->code);
1191 mono_dynamic_stream_reset (&di->resources);
1192 mono_dynamic_stream_reset (&di->us);
1193 mono_dynamic_stream_reset (&di->blob);
1194 mono_dynamic_stream_reset (&di->tstream);
1195 mono_dynamic_stream_reset (&di->guid);
1196 for (i = 0; i < MONO_TABLE_NUM; ++i) {
1197 g_free (di->tables [i].values);
1199 mono_mempool_destroy (image->mempool);
1204 * mono_image_strerror:
1205 * @status: an code indicating the result from a recent operation
1207 * Returns: a string describing the error
1210 mono_image_strerror (MonoImageOpenStatus status)
1215 case MONO_IMAGE_ERROR_ERRNO:
1216 return strerror (errno);
1217 case MONO_IMAGE_IMAGE_INVALID:
1218 return "File does not contain a valid CIL image";
1219 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1220 return "An assembly was referenced, but could not be found";
1222 return "Internal error";
1226 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1227 guint32 lang_id, gunichar2 *name,
1228 MonoPEResourceDirEntry *entry,
1229 MonoPEResourceDir *root, guint32 level)
1231 gboolean is_string=entry->name_is_string;
1233 /* Level 0 holds a directory entry for each type of resource
1234 * (identified by ID or name).
1236 * Level 1 holds a directory entry for each named resource
1237 * item, and each "anonymous" item of a particular type of
1240 * Level 2 holds a directory entry for each language pointing to
1245 if((is_string==FALSE && entry->name_offset!=res_id) ||
1246 (is_string==TRUE)) {
1249 } else if (level==1) {
1252 is_string==TRUE && name!=lookup (entry->name_offset)) {
1256 } else if (level==2) {
1257 if ((is_string == FALSE &&
1258 entry->name_offset != lang_id &&
1260 (is_string == TRUE)) {
1264 g_assert_not_reached ();
1267 if(entry->is_dir==TRUE) {
1268 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+entry->dir_offset);
1269 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1272 entries=res_dir->res_named_entries + res_dir->res_id_entries;
1274 for(i=0; i<entries; i++) {
1275 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1278 ret=mono_image_walk_resource_tree (info, res_id,
1289 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+entry->dir_offset);
1296 * mono_image_lookup_resource:
1297 * @image: the image to look up the resource in
1298 * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1299 * @lang_id: The language id.
1300 * @name: the resource name to lookup.
1302 * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1303 * of the given resource.
1306 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1308 MonoCLIImageInfo *info;
1309 MonoDotNetHeader *header;
1310 MonoPEDatadir *datadir;
1311 MonoPEDirEntry *rsrc;
1312 MonoPEResourceDir *resource_dir;
1313 MonoPEResourceDirEntry *res_entries;
1320 info=image->image_info;
1325 header=&info->cli_header;
1330 datadir=&header->datadir;
1335 rsrc=&datadir->pe_resource_table;
1340 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1341 if(resource_dir==NULL) {
1345 entries=resource_dir->res_named_entries + resource_dir->res_id_entries;
1346 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1348 for(i=0; i<entries; i++) {
1349 MonoPEResourceDirEntry *entry=&res_entries[i];
1352 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1353 name, entry, resource_dir,
1364 * mono_image_get_entry_point:
1365 * @image: the image where the entry point will be looked up.
1367 * Use this routine to determine the metadata token for method that
1368 * has been flagged as the entry point.
1370 * Returns: the token for the entry point method in the image
1373 mono_image_get_entry_point (MonoImage *image)
1375 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1379 * mono_image_get_resource:
1380 * @image: the image where the resource will be looked up.
1381 * @offset: The offset to add to the resource
1382 * @size: a pointer to an int where the size of the resource will be stored
1384 * This is a low-level routine that fetches a resource from the
1385 * metadata that starts at a given @offset. The @size parameter is
1386 * filled with the data field as encoded in the metadata.
1388 * Returns: the pointer to the resource whose offset is @offset.
1391 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1393 MonoCLIImageInfo *iinfo = image->image_info;
1394 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1397 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1400 data = mono_image_rva_map (image, ch->ch_resources.rva);
1405 *size = read32 (data);
1411 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1413 char *base_dir, *name;
1415 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1419 if (fileidx < 1 || fileidx > t->rows)
1422 if (image->files && image->files [fileidx - 1])
1423 return image->files [fileidx - 1];
1426 image->files = g_new0 (MonoImage*, t->rows);
1428 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1429 fname = mono_metadata_string_heap (image, fname_id);
1430 base_dir = g_path_get_dirname (image->name);
1431 name = g_build_filename (base_dir, fname, NULL);
1432 res = mono_image_open (name, NULL);
1435 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1436 res->assembly = image->assembly;
1437 for (i = 0; i < res->module_count; ++i) {
1438 if (res->modules [i] && !res->modules [i]->assembly)
1439 res->modules [i]->assembly = image->assembly;
1442 image->files [fileidx - 1] = res;
1450 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1452 MonoCLIImageInfo *iinfo = image->image_info;
1453 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1456 if (!de->size || !de->rva)
1458 data = mono_image_rva_map (image, de->rva);
1467 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1469 MonoCLIImageInfo *iinfo = image->image_info;
1470 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1471 const int top = iinfo->cli_section_count;
1472 MonoSectionTable *tables = iinfo->cli_section_tables;
1474 guint32 addr = de->rva;
1478 if (!de->size || !de->rva)
1480 for (i = 0; i < top; i++){
1481 if ((addr >= tables->st_virtual_address) &&
1482 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
1483 return tables->st_raw_data_ptr +
1484 (addr - tables->st_virtual_address);
1493 mono_image_get_public_key (MonoImage *image, guint32 *size)
1497 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1499 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1502 pubkey = mono_metadata_blob_heap (image, tok);
1503 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1510 mono_image_get_name (MonoImage *image)
1512 return image->assembly_name;
1516 mono_image_get_filename (MonoImage *image)
1522 mono_image_get_guid (MonoImage *image)
1527 const MonoTableInfo*
1528 mono_image_get_table_info (MonoImage *image, int table_id)
1530 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1532 return &image->tables [table_id];
1536 mono_image_get_table_rows (MonoImage *image, int table_id)
1538 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1540 return image->tables [table_id].rows;
1544 mono_table_info_get_rows (const MonoTableInfo *table)
1550 mono_image_get_assembly (MonoImage *image)
1552 return image->assembly;
1556 mono_image_is_dynamic (MonoImage *image)
1558 return image->dynamic;
1562 mono_image_has_authenticode_entry (MonoImage *image)
1564 MonoCLIImageInfo *iinfo = image->image_info;
1565 MonoDotNetHeader *header = &iinfo->cli_header;
1566 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
1567 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
1568 return ((de->rva != 0) && (de->size > 8));