2 * image.c: Routines for manipulating an image stored in an
3 * extended PE/COFF file.
6 * Miguel de Icaza (miguel@ximian.com)
7 * Paolo Molaro (lupus@ximian.com)
9 * (C) 2001-2003 Ximian, Inc. http://www.ximian.com
20 #include "rawbuffer.h"
21 #include "mono-endian.h"
23 #include "tabledefs.h"
24 #include "tokentype.h"
25 #include "metadata-internals.h"
26 #include <mono/io-layer/io-layer.h>
28 #define INVALID_ADDRESS 0xffffffff
31 * Keeps track of the various assemblies loaded
33 static GHashTable *loaded_images_hash;
34 static GHashTable *loaded_images_guid_hash;
36 static CRITICAL_SECTION images_mutex;
39 mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
41 const int top = iinfo->cli_section_count;
42 MonoSectionTable *tables = iinfo->cli_section_tables;
45 for (i = 0; i < top; i++){
46 if ((addr >= tables->st_virtual_address) &&
47 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
48 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
52 return INVALID_ADDRESS;
56 mono_image_rva_map (MonoImage *image, guint32 addr)
58 MonoCLIImageInfo *iinfo = image->image_info;
59 const int top = iinfo->cli_section_count;
60 MonoSectionTable *tables = iinfo->cli_section_tables;
63 for (i = 0; i < top; i++){
64 if ((addr >= tables->st_virtual_address) &&
65 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
66 if (!iinfo->cli_sections [i]) {
67 if (!mono_image_ensure_section_idx (image, i))
70 return (char*)iinfo->cli_sections [i] +
71 (addr - tables->st_virtual_address);
79 canonicalize_path (const char *path)
81 gchar *abspath, *pos, *lastpos, *dest;
84 if (g_path_is_absolute (path)) {
85 abspath = g_strdup (path);
87 gchar *tmpdir = g_get_current_dir ();
88 abspath = g_build_filename (tmpdir, path, NULL);
92 abspath = g_strreverse (abspath);
95 dest = lastpos = abspath;
96 pos = strchr (lastpos, G_DIR_SEPARATOR);
99 int len = pos - lastpos;
100 if (len == 1 && lastpos [0] == '.') {
102 } else if (len == 2 && lastpos [0] == '.' && lastpos [1] == '.') {
104 } else if (len > 0) {
108 if (dest != lastpos) strncpy (dest, lastpos, len + 1);
113 pos = strchr (lastpos, G_DIR_SEPARATOR);
116 if (dest != lastpos) strcpy (dest, lastpos);
117 return g_strreverse (abspath);
123 * Initialize the global variables used by this module.
126 mono_images_init (void)
128 InitializeCriticalSection (&images_mutex);
130 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
131 loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
135 * mono_image_ensure_section_idx:
136 * @image: The image we are operating on
137 * @section: section number that we will load/map into memory
139 * This routine makes sure that we have an in-memory copy of
140 * an image section (.text, .rsrc, .data).
142 * Returns: TRUE on success
145 mono_image_ensure_section_idx (MonoImage *image, int section)
147 MonoCLIImageInfo *iinfo = image->image_info;
148 MonoSectionTable *sect;
151 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
153 if (iinfo->cli_sections [section] != NULL)
156 sect = &iinfo->cli_section_tables [section];
158 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
161 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
163 /* FIXME: we ignore the writable flag since we don't patch the binary */
164 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
167 iinfo->cli_sections [section] = mono_raw_buffer_load (
168 fileno (image->f), writable,
169 sect->st_raw_data_ptr, sect->st_raw_data_size);
171 if (iinfo->cli_sections [section] == NULL)
178 * mono_image_ensure_section:
179 * @image: The image we are operating on
180 * @section: section name that we will load/map into memory
182 * This routine makes sure that we have an in-memory copy of
183 * an image section (.text, .rsrc, .data).
185 * Returns: TRUE on success
188 mono_image_ensure_section (MonoImage *image, const char *section)
190 MonoCLIImageInfo *ii = image->image_info;
193 for (i = 0; i < ii->cli_section_count; i++){
194 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
197 return mono_image_ensure_section_idx (image, i);
203 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
205 const int top = iinfo->cli_header.coff.coff_sections;
208 iinfo->cli_section_count = top;
209 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
210 iinfo->cli_sections = g_new0 (void *, top);
212 for (i = 0; i < top; i++){
213 MonoSectionTable *t = &iinfo->cli_section_tables [i];
216 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
218 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
219 offset += sizeof (MonoSectionTable);
221 if (fread (t, sizeof (MonoSectionTable), 1, image->f) != 1)
225 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
226 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
227 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
228 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
229 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
230 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
231 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
232 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
233 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
234 t->st_flags = GUINT32_FROM_LE (t->st_flags);
236 /* consistency checks here */
243 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)
253 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
255 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
257 if (fseek (image->f, offset, SEEK_SET) != 0)
260 if ((n = fread (&iinfo->cli_cli_header, sizeof (MonoCLIHeader), 1, image->f)) != 1)
264 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
265 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
266 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
267 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
268 SWAP32 (iinfo->cli_cli_header.ch_size);
269 SWAP32 (iinfo->cli_cli_header.ch_flags);
270 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
271 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
272 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
273 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
274 SWAPPDE (iinfo->cli_cli_header.ch_resources);
275 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
276 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
277 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
278 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
279 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
280 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
281 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
282 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
283 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
284 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
285 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
286 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
287 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
292 /* Catch new uses of the fields that are supposed to be zero */
294 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
295 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
296 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
297 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
298 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
299 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
300 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
301 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
302 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
305 * No need to scare people who are testing this, I am just
306 * labelling this as a LAMESPEC
308 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
316 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
318 guint32 offset, size;
324 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
325 if (offset == INVALID_ADDRESS)
328 size = iinfo->cli_cli_header.ch_metadata.size;
331 if (offset + size > image->raw_data_len)
333 image->raw_metadata = image->raw_data + offset;
335 image->raw_metadata = mono_raw_buffer_load (fileno (image->f), FALSE, offset, size);
336 if (image->raw_metadata == NULL)
340 ptr = image->raw_metadata;
342 if (strncmp (ptr, "BSJB", 4) == 0){
343 guint32 version_string_len;
346 version_string_len = read32 (ptr);
348 image->version = g_strndup (ptr, version_string_len);
349 ptr += version_string_len;
350 pad = ptr - image->raw_metadata;
352 ptr += 4 - (pad % 4);
356 /* skip over flags */
359 streams = read16 (ptr);
362 for (i = 0; i < streams; i++){
363 if (strncmp (ptr + 8, "#~", 3) == 0){
364 image->heap_tables.data = image->raw_metadata + read32 (ptr);
365 image->heap_tables.size = read32 (ptr + 4);
367 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
368 image->heap_strings.data = image->raw_metadata + read32 (ptr);
369 image->heap_strings.size = read32 (ptr + 4);
371 } else if (strncmp (ptr + 8, "#US", 4) == 0){
372 image->heap_us.data = image->raw_metadata + read32 (ptr);
373 image->heap_us.size = read32 (ptr + 4);
375 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
376 image->heap_blob.data = image->raw_metadata + read32 (ptr);
377 image->heap_blob.size = read32 (ptr + 4);
379 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
380 image->heap_guid.data = image->raw_metadata + read32 (ptr);
381 image->heap_guid.size = read32 (ptr + 4);
383 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
384 g_print ("Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name);
387 g_message ("Unknown heap type: %s\n", ptr + 8);
388 ptr += 8 + strlen (ptr + 8) + 1;
390 pad = ptr - image->raw_metadata;
392 ptr += 4 - (pad % 4);
395 g_assert (image->heap_guid.data);
396 g_assert (image->heap_guid.size >= 16);
398 image->guid = mono_guid_to_string (image->heap_guid.data);
404 * Load representation of logical metadata tables, from the "#~" stream
407 load_tables (MonoImage *image)
409 const char *heap_tables = image->heap_tables.data;
411 guint64 valid_mask, sorted_mask;
412 int valid = 0, table;
415 heap_sizes = heap_tables [6];
416 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
417 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
418 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
420 valid_mask = read64 (heap_tables + 8);
421 sorted_mask = read64 (heap_tables + 16);
422 rows = (const guint32 *) (heap_tables + 24);
424 for (table = 0; table < 64; table++){
425 if ((valid_mask & ((guint64) 1 << table)) == 0){
426 if (table > MONO_TABLE_LAST)
428 image->tables [table].rows = 0;
431 if (table > MONO_TABLE_LAST) {
432 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
434 image->tables [table].rows = read32 (rows);
436 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
437 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
443 image->tables_base = (heap_tables + 24) + (4 * valid);
445 /* They must be the same */
446 g_assert ((const void *) image->tables_base == (const void *) rows);
448 mono_metadata_compute_table_bases (image);
453 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
455 if (!load_metadata_ptrs (image, iinfo))
458 return load_tables (image);
462 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
463 const char *name, guint32 index)
465 GHashTable *nspace_table;
466 GHashTable *name_cache = image->name_cache;
468 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
469 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
470 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
472 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
476 load_modules (MonoImage *image, MonoImageOpenStatus *status)
485 t = &image->tables [MONO_TABLE_MODULEREF];
486 image->modules = g_new0 (MonoImage *, t->rows);
487 image->module_count = t->rows;
488 base_dir = g_path_get_dirname (image->name);
489 for (i = 0; i < t->rows; i++){
492 guint32 cols [MONO_MODULEREF_SIZE];
494 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
495 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
496 module_ref = g_build_filename (base_dir, name, NULL);
497 image->modules [i] = mono_image_open (module_ref, status);
498 if (image->modules [i]) {
499 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
502 * FIXME: what do we do here? it could be a native dll...
503 * We should probably do lazy-loading of modules.
506 *status = MONO_IMAGE_OK;
514 load_class_names (MonoImage *image)
516 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
517 guint32 cols [MONO_TYPEDEF_SIZE];
520 guint32 i, visib, nspace_index;
521 GHashTable *name_cache2, *nspace_table;
523 /* Temporary hash table to avoid lookups in the nspace_table */
524 name_cache2 = g_hash_table_new (NULL, NULL);
526 for (i = 1; i <= t->rows; ++i) {
527 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
528 /* nested types are accessed from the nesting name */
529 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
530 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
532 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
533 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
535 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
536 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
538 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
539 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
540 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
543 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
546 /* Load type names from EXPORTEDTYPES table */
548 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
549 guint32 cols [MONO_EXP_TYPE_SIZE];
552 for (i = 0; i < t->rows; ++i) {
553 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
554 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
555 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
557 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
558 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
560 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
561 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
562 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
565 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
569 g_hash_table_destroy (name_cache2);
573 register_guid (gpointer key, gpointer value, gpointer user_data)
575 MonoImage *image = (MonoImage*)value;
577 if (!g_hash_table_lookup (loaded_images_guid_hash, image))
578 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
582 build_guid_table (void)
584 g_hash_table_foreach (loaded_images_hash, register_guid, NULL);
588 mono_image_init (MonoImage *image)
590 image->method_cache = g_hash_table_new (NULL, NULL);
591 image->class_cache = g_hash_table_new (NULL, NULL);
592 image->field_cache = g_hash_table_new (NULL, NULL);
593 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
594 image->array_cache = g_hash_table_new (NULL, NULL);
596 image->delegate_begin_invoke_cache =
597 g_hash_table_new ((GHashFunc)mono_signature_hash,
598 (GCompareFunc)mono_metadata_signature_equal);
599 image->delegate_end_invoke_cache =
600 g_hash_table_new ((GHashFunc)mono_signature_hash,
601 (GCompareFunc)mono_metadata_signature_equal);
602 image->delegate_invoke_cache =
603 g_hash_table_new ((GHashFunc)mono_signature_hash,
604 (GCompareFunc)mono_metadata_signature_equal);
605 image->runtime_invoke_cache =
606 g_hash_table_new ((GHashFunc)mono_signature_hash,
607 (GCompareFunc)mono_metadata_signature_equal);
609 image->managed_wrapper_cache = g_hash_table_new (NULL, NULL);
610 image->native_wrapper_cache = g_hash_table_new (NULL, NULL);
611 image->remoting_invoke_cache = g_hash_table_new (NULL, NULL);
612 image->synchronized_cache = g_hash_table_new (NULL, NULL);
613 image->unbox_wrapper_cache = g_hash_table_new (NULL, NULL);
615 image->typespec_cache = g_hash_table_new (NULL, NULL);
616 image->memberref_signatures = g_hash_table_new (NULL, NULL);
617 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
621 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
622 gboolean care_about_cli)
624 MonoCLIImageInfo *iinfo;
625 MonoDotNetHeader *header;
626 MonoMSDOSHeader msdos;
630 mono_image_init (image);
632 iinfo = image->image_info;
633 header = &iinfo->cli_header;
636 *status = MONO_IMAGE_IMAGE_INVALID;
639 if (offset + sizeof (msdos) > image->raw_data_len)
641 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
643 if (fread (&msdos, sizeof (msdos), 1, image->f) != 1)
647 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
650 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
652 if (msdos.pe_offset != sizeof (msdos)) {
654 fseek (image->f, msdos.pe_offset, SEEK_SET);
656 offset = msdos.pe_offset;
659 if (offset + sizeof (MonoDotNetHeader) > image->raw_data_len)
661 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
662 offset += sizeof (MonoDotNetHeader);
664 if ((n = fread (header, sizeof (MonoDotNetHeader), 1, image->f)) != 1)
668 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
669 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
670 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
671 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
672 SWAP32 (header->coff.coff_time);
673 SWAP32 (header->coff.coff_symptr);
674 SWAP32 (header->coff.coff_symcount);
675 SWAP16 (header->coff.coff_machine);
676 SWAP16 (header->coff.coff_sections);
677 SWAP16 (header->coff.coff_opt_header_size);
678 SWAP16 (header->coff.coff_attributes);
680 SWAP32 (header->pe.pe_code_size);
681 SWAP32 (header->pe.pe_data_size);
682 SWAP32 (header->pe.pe_uninit_data_size);
683 SWAP32 (header->pe.pe_rva_entry_point);
684 SWAP32 (header->pe.pe_rva_code_base);
685 SWAP32 (header->pe.pe_rva_data_base);
686 SWAP16 (header->pe.pe_magic);
688 /* MonoPEHeaderNT: not used yet */
689 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
690 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
691 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
692 SWAP16 (header->nt.pe_os_major); /* must be 4 */
693 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
694 SWAP16 (header->nt.pe_user_major);
695 SWAP16 (header->nt.pe_user_minor);
696 SWAP16 (header->nt.pe_subsys_major);
697 SWAP16 (header->nt.pe_subsys_minor);
698 SWAP32 (header->nt.pe_reserved_1);
699 SWAP32 (header->nt.pe_image_size);
700 SWAP32 (header->nt.pe_header_size);
701 SWAP32 (header->nt.pe_checksum);
702 SWAP16 (header->nt.pe_subsys_required);
703 SWAP16 (header->nt.pe_dll_flags);
704 SWAP32 (header->nt.pe_stack_reserve);
705 SWAP32 (header->nt.pe_stack_commit);
706 SWAP32 (header->nt.pe_heap_reserve);
707 SWAP32 (header->nt.pe_heap_commit);
708 SWAP32 (header->nt.pe_loader_flags);
709 SWAP32 (header->nt.pe_data_dir_count);
711 /* MonoDotNetHeader: mostly unused */
712 SWAPPDE (header->datadir.pe_export_table);
713 SWAPPDE (header->datadir.pe_import_table);
714 SWAPPDE (header->datadir.pe_resource_table);
715 SWAPPDE (header->datadir.pe_exception_table);
716 SWAPPDE (header->datadir.pe_certificate_table);
717 SWAPPDE (header->datadir.pe_reloc_table);
718 SWAPPDE (header->datadir.pe_debug);
719 SWAPPDE (header->datadir.pe_copyright);
720 SWAPPDE (header->datadir.pe_global_ptr);
721 SWAPPDE (header->datadir.pe_tls_table);
722 SWAPPDE (header->datadir.pe_load_config_table);
723 SWAPPDE (header->datadir.pe_bound_import);
724 SWAPPDE (header->datadir.pe_iat);
725 SWAPPDE (header->datadir.pe_delay_import_desc);
726 SWAPPDE (header->datadir.pe_cli_header);
727 SWAPPDE (header->datadir.pe_reserved);
734 if (header->coff.coff_machine != 0x14c)
737 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
740 if (header->pesig[0] != 'P' || header->pesig[1] != 'E' || header->pe.pe_magic != 0x10B)
745 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
746 * which produces binaries with 7.0. From Sergey:
748 * The reason is that MSVC7 uses traditional compile/link
749 * sequence for CIL executables, and VS.NET (and Framework
750 * SDK) includes linker version 7, that puts 7.0 in this
751 * field. That's why it's currently not possible to load VC
752 * binaries with Mono. This field is pretty much meaningless
753 * anyway (what linker?).
755 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
760 * FIXME: byte swap all addresses here for header.
763 if (!load_section_tables (image, iinfo, offset))
766 if (care_about_cli == FALSE) {
770 /* Load the CLI header */
771 if (!load_cli_header (image, iinfo))
774 if (!load_metadata (image, iinfo))
777 load_class_names (image);
779 /* modules don't have an assembly table row */
780 if (image->tables [MONO_TABLE_ASSEMBLY].rows)
781 image->assembly_name = mono_metadata_string_heap (image,
782 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
783 0, MONO_ASSEMBLY_NAME));
785 image->module_name = mono_metadata_string_heap (image,
786 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
787 0, MONO_MODULE_NAME));
789 load_modules (image, status);
793 *status = MONO_IMAGE_OK;
800 mono_image_close (image);
805 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
806 gboolean care_about_cli)
808 MonoCLIImageInfo *iinfo;
812 if ((filed = fopen (fname, "rb")) == NULL){
814 *status = MONO_IMAGE_ERROR_ERRNO;
818 image = g_new0 (MonoImage, 1);
819 image->ref_count = 1;
821 iinfo = g_new0 (MonoCLIImageInfo, 1);
822 image->image_info = iinfo;
823 image->name = canonicalize_path (fname);
825 return do_mono_image_load (image, status, care_about_cli);
829 mono_image_loaded (const char *name)
833 EnterCriticalSection (&images_mutex);
834 res = g_hash_table_lookup (loaded_images_hash, name);
835 LeaveCriticalSection (&images_mutex);
840 mono_image_loaded_by_guid (const char *guid)
844 EnterCriticalSection (&images_mutex);
845 res = g_hash_table_lookup (loaded_images_guid_hash, guid);
846 LeaveCriticalSection (&images_mutex);
851 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
853 MonoCLIImageInfo *iinfo;
857 if (!data || !data_len) {
859 *status = MONO_IMAGE_IMAGE_INVALID;
864 datac = g_try_malloc (data_len);
867 *status = MONO_IMAGE_ERROR_ERRNO;
870 memcpy (datac, data, data_len);
873 image = g_new0 (MonoImage, 1);
874 image->ref_count = 1;
875 image->raw_data = datac;
876 image->raw_data_len = data_len;
877 image->raw_data_allocated = need_copy;
878 image->name = g_strdup_printf ("data-%p", datac);
879 iinfo = g_new0 (MonoCLIImageInfo, 1);
880 image->image_info = iinfo;
882 return do_mono_image_load (image, status, TRUE);
887 * @fname: filename that points to the module we want to open
888 * @status: An error condition is returned in this field
890 * Returns: An open image of type %MonoImage or NULL on error.
891 * if NULL, then check the value of @status for details on the error
894 mono_image_open (const char *fname, MonoImageOpenStatus *status)
896 MonoImage *image, *image2;
899 g_return_val_if_fail (fname != NULL, NULL);
901 absfname = canonicalize_path (fname);
904 * The easiest solution would be to do all the loading inside the mutex,
905 * but that would lead to scalability problems. So we let the loading
906 * happen outside the mutex, and if multiple threads happen to load
907 * the same image, we discard all but the first copy.
909 EnterCriticalSection (&images_mutex);
910 image = g_hash_table_lookup (loaded_images_hash, absfname);
915 LeaveCriticalSection (&images_mutex);
918 LeaveCriticalSection (&images_mutex);
920 image = do_mono_image_open (fname, status, TRUE);
924 EnterCriticalSection (&images_mutex);
925 image2 = g_hash_table_lookup (loaded_images_hash, image->name);
928 /* Somebody else beat us to it */
929 image2->ref_count ++;
930 LeaveCriticalSection (&images_mutex);
931 mono_image_close (image);
934 g_hash_table_insert (loaded_images_hash, image->name, image);
935 if (image->assembly_name && (g_hash_table_lookup (loaded_images_hash, image->assembly_name) == NULL))
936 g_hash_table_insert (loaded_images_hash, (char *) image->assembly_name, image);
937 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
938 LeaveCriticalSection (&images_mutex);
945 * @fname: filename that points to the module we want to open
946 * @status: An error condition is returned in this field
948 * Returns: An open image of type %MonoImage or NULL on error. if
949 * NULL, then check the value of @status for details on the error.
950 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
951 * It's just a PE file loader, used for FileVersionInfo. It also does
952 * not use the image cache.
955 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
957 g_return_val_if_fail (fname != NULL, NULL);
959 return(do_mono_image_open (fname, status, FALSE));
963 free_hash_table (gpointer key, gpointer val, gpointer user_data)
965 g_hash_table_destroy ((GHashTable*)val);
969 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
971 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
975 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
982 * @image: The image file we wish to add a reference to
984 * Increases the reference count of an image.
987 mono_image_addref (MonoImage *image)
989 InterlockedIncrement (&image->ref_count);
994 * @image: The image file we wish to close
996 * Closes an image file, deallocates all memory consumed and
997 * unmaps all possible sections of the file
1000 mono_image_close (MonoImage *image)
1004 g_return_if_fail (image != NULL);
1006 EnterCriticalSection (&images_mutex);
1007 if (--image->ref_count) {
1008 LeaveCriticalSection (&images_mutex);
1011 image2 = g_hash_table_lookup (loaded_images_hash, image->name);
1012 if (image == image2) {
1013 /* This is not true if we are called from mono_image_open () */
1014 g_hash_table_remove (loaded_images_hash, image->name);
1015 g_hash_table_remove (loaded_images_guid_hash, image->guid);
1016 /* Multiple images might have the same guid */
1017 build_guid_table ();
1019 if (image->assembly_name && (g_hash_table_lookup (loaded_images_hash, image->assembly_name) == image))
1020 g_hash_table_remove (loaded_images_hash, (char *) image->assembly_name);
1021 LeaveCriticalSection (&images_mutex);
1025 if (image->raw_data_allocated) {
1026 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1027 MonoCLIImageInfo *ii = image->image_info;
1030 if ((image->raw_metadata > image->raw_data) &&
1031 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1032 image->raw_metadata = NULL;
1034 for (i = 0; i < ii->cli_section_count; i++)
1035 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1036 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1037 ii->cli_sections [i] = NULL;
1039 g_free (image->raw_data);
1041 g_free (image->name);
1042 g_free (image->guid);
1043 g_free (image->files);
1045 g_hash_table_destroy (image->method_cache);
1046 g_hash_table_destroy (image->class_cache);
1047 g_hash_table_destroy (image->field_cache);
1048 g_hash_table_destroy (image->array_cache);
1049 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1050 g_hash_table_destroy (image->name_cache);
1051 g_hash_table_destroy (image->native_wrapper_cache);
1052 g_hash_table_destroy (image->managed_wrapper_cache);
1053 g_hash_table_destroy (image->delegate_begin_invoke_cache);
1054 g_hash_table_destroy (image->delegate_end_invoke_cache);
1055 g_hash_table_destroy (image->delegate_invoke_cache);
1056 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1057 g_hash_table_destroy (image->remoting_invoke_cache);
1058 g_hash_table_destroy (image->runtime_invoke_cache);
1059 g_hash_table_destroy (image->synchronized_cache);
1060 g_hash_table_destroy (image->unbox_wrapper_cache);
1061 g_hash_table_destroy (image->typespec_cache);
1062 g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1063 g_hash_table_destroy (image->memberref_signatures);
1064 g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1065 g_hash_table_destroy (image->helper_signatures);
1067 if (image->raw_metadata != NULL)
1068 mono_raw_buffer_free (image->raw_metadata);
1070 if (image->image_info){
1071 MonoCLIImageInfo *ii = image->image_info;
1074 for (i = 0; i < ii->cli_section_count; i++){
1075 if (!ii->cli_sections [i])
1077 mono_raw_buffer_free (ii->cli_sections [i]);
1079 if (ii->cli_section_tables)
1080 g_free (ii->cli_section_tables);
1081 if (ii->cli_sections)
1082 g_free (ii->cli_sections);
1083 g_free (image->image_info);
1086 if (!image->dynamic)
1087 /* Dynamic images are GC_MALLOCed */
1092 * mono_image_strerror:
1093 * @status: an code indicating the result from a recent operation
1095 * Returns: a string describing the error
1098 mono_image_strerror (MonoImageOpenStatus status)
1103 case MONO_IMAGE_ERROR_ERRNO:
1104 return strerror (errno);
1105 case MONO_IMAGE_IMAGE_INVALID:
1106 return "File does not contain a valid CIL image";
1107 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1108 return "An assembly was referenced, but could not be found";
1110 return "Internal error";
1114 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1115 guint32 lang_id, gunichar2 *name,
1116 MonoPEResourceDirEntry *entry,
1117 MonoPEResourceDir *root, guint32 level)
1119 gboolean is_string=entry->name_is_string;
1121 /* Level 0 holds a directory entry for each type of resource
1122 * (identified by ID or name).
1124 * Level 1 holds a directory entry for each named resource
1125 * item, and each "anonymous" item of a particular type of
1128 * Level 2 holds a directory entry for each language pointing to
1133 if((is_string==FALSE && entry->name_offset!=res_id) ||
1134 (is_string==TRUE)) {
1137 } else if (level==1) {
1140 is_string==TRUE && name!=lookup (entry->name_offset)) {
1144 } else if (level==2) {
1145 if ((is_string == FALSE &&
1146 entry->name_offset != lang_id &&
1148 (is_string == TRUE)) {
1152 g_assert_not_reached ();
1155 if(entry->is_dir==TRUE) {
1156 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+entry->dir_offset);
1157 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1160 entries=res_dir->res_named_entries + res_dir->res_id_entries;
1162 for(i=0; i<entries; i++) {
1163 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1166 ret=mono_image_walk_resource_tree (info, res_id,
1177 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+entry->dir_offset);
1184 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1186 MonoCLIImageInfo *info;
1187 MonoDotNetHeader *header;
1188 MonoPEDatadir *datadir;
1189 MonoPEDirEntry *rsrc;
1190 MonoPEResourceDir *resource_dir;
1191 MonoPEResourceDirEntry *res_entries;
1198 info=image->image_info;
1203 header=&info->cli_header;
1208 datadir=&header->datadir;
1213 rsrc=&datadir->pe_resource_table;
1218 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1219 if(resource_dir==NULL) {
1223 entries=resource_dir->res_named_entries + resource_dir->res_id_entries;
1224 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1226 for(i=0; i<entries; i++) {
1227 MonoPEResourceDirEntry *entry=&res_entries[i];
1230 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1231 name, entry, resource_dir,
1242 mono_image_get_entry_point (MonoImage *image)
1244 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1248 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1250 MonoCLIImageInfo *iinfo = image->image_info;
1251 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1254 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1257 data = mono_image_rva_map (image, ch->ch_resources.rva);
1262 *size = read32 (data);
1268 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1270 char *base_dir, *name;
1272 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1276 if (fileidx < 1 || fileidx > t->rows)
1279 if (image->files && image->files [fileidx - 1])
1280 return image->files [fileidx - 1];
1283 image->files = g_new0 (MonoImage*, t->rows);
1285 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1286 fname = mono_metadata_string_heap (image, fname_id);
1287 base_dir = g_path_get_dirname (image->name);
1288 name = g_build_filename (base_dir, fname, NULL);
1289 res = mono_image_open (name, NULL);
1292 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1293 res->assembly = image->assembly;
1294 for (i = 0; i < res->module_count; ++i) {
1295 if (res->modules [i] && !res->modules [i]->assembly)
1296 res->modules [i]->assembly = image->assembly;
1299 image->files [fileidx - 1] = res;
1307 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1309 MonoCLIImageInfo *iinfo = image->image_info;
1310 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1313 if (!de->size || !de->rva)
1315 data = mono_image_rva_map (image, de->rva);
1324 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1326 MonoCLIImageInfo *iinfo = image->image_info;
1327 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1328 const int top = iinfo->cli_section_count;
1329 MonoSectionTable *tables = iinfo->cli_section_tables;
1331 guint32 addr = de->rva;
1335 if (!de->size || !de->rva)
1337 for (i = 0; i < top; i++){
1338 if ((addr >= tables->st_virtual_address) &&
1339 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
1340 return tables->st_raw_data_ptr +
1341 (addr - tables->st_virtual_address);
1350 mono_image_get_public_key (MonoImage *image, guint32 *size)
1354 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1356 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1359 pubkey = mono_metadata_blob_heap (image, tok);
1360 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1367 mono_image_get_name (MonoImage *image)
1369 return image->assembly_name;
1373 mono_image_get_filename (MonoImage *image)
1378 const MonoTableInfo*
1379 mono_image_get_table_info (MonoImage *image, int table_id)
1381 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1383 return &image->tables [table_id];
1387 mono_image_get_table_rows (MonoImage *image, int table_id)
1389 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1391 return image->tables [table_id].rows;
1395 mono_table_info_get_rows (const MonoTableInfo *table)
1401 mono_image_get_assembly (MonoImage *image)
1403 return image->assembly;
1407 mono_image_is_dynamic (MonoImage *image)
1409 return image->dynamic;
1413 mono_image_has_authenticode_entry (MonoImage *image)
1415 MonoCLIImageInfo *iinfo = image->image_info;
1416 MonoDotNetHeader *header = &iinfo->cli_header;
1417 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
1418 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
1419 return ((de->rva != 0) && (de->size > 8));