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"
25 #include <mono/io-layer/io-layer.h>
26 #include <sys/types.h>
30 #define INVALID_ADDRESS 0xffffffff
33 * Keeps track of the various assemblies loaded
35 static GHashTable *loaded_images_hash;
36 static GHashTable *loaded_images_guid_hash;
38 static CRITICAL_SECTION images_mutex;
41 mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
43 const int top = iinfo->cli_section_count;
44 MonoSectionTable *tables = iinfo->cli_section_tables;
47 for (i = 0; i < top; i++){
48 if ((addr >= tables->st_virtual_address) &&
49 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
50 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
54 return INVALID_ADDRESS;
58 mono_image_rva_map (MonoImage *image, guint32 addr)
60 MonoCLIImageInfo *iinfo = image->image_info;
61 const int top = iinfo->cli_section_count;
62 MonoSectionTable *tables = iinfo->cli_section_tables;
65 for (i = 0; i < top; i++){
66 if ((addr >= tables->st_virtual_address) &&
67 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
68 if (!iinfo->cli_sections [i]) {
69 if (!mono_image_ensure_section_idx (image, i))
72 return (char*)iinfo->cli_sections [i] +
73 (addr - tables->st_virtual_address);
81 canonicalize_path (const char *path)
83 gchar *abspath, *pos, *lastpos, *dest;
86 if (g_path_is_absolute (path)) {
87 abspath = g_strdup (path);
89 gchar *tmpdir = g_get_current_dir ();
90 abspath = g_build_filename (tmpdir, path, NULL);
94 abspath = g_strreverse (abspath);
97 dest = lastpos = abspath;
98 pos = strchr (lastpos, G_DIR_SEPARATOR);
100 while (pos != NULL) {
101 int len = pos - lastpos;
102 if (len == 1 && lastpos [0] == '.') {
104 } else if (len == 2 && lastpos [0] == '.' && lastpos [1] == '.') {
106 } else if (len > 0) {
110 if (dest != lastpos) strncpy (dest, lastpos, len + 1);
115 pos = strchr (lastpos, G_DIR_SEPARATOR);
118 if (dest != lastpos) strcpy (dest, lastpos);
119 return g_strreverse (abspath);
125 * Initialize the global variables used by this module.
128 mono_images_init (void)
130 InitializeCriticalSection (&images_mutex);
132 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
133 loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
137 * mono_image_ensure_section_idx:
138 * @image: The image we are operating on
139 * @section: section number that we will load/map into memory
141 * This routine makes sure that we have an in-memory copy of
142 * an image section (.text, .rsrc, .data).
144 * Returns: TRUE on success
147 mono_image_ensure_section_idx (MonoImage *image, int section)
149 MonoCLIImageInfo *iinfo = image->image_info;
150 MonoSectionTable *sect;
153 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
155 if (iinfo->cli_sections [section] != NULL)
158 sect = &iinfo->cli_section_tables [section];
160 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
162 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
164 /* FIXME: we ignore the writable flag since we don't patch the binary */
165 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
170 * mono_image_ensure_section:
171 * @image: The image we are operating on
172 * @section: section name that we will load/map into memory
174 * This routine makes sure that we have an in-memory copy of
175 * an image section (.text, .rsrc, .data).
177 * Returns: TRUE on success
180 mono_image_ensure_section (MonoImage *image, const char *section)
182 MonoCLIImageInfo *ii = image->image_info;
185 for (i = 0; i < ii->cli_section_count; i++){
186 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
189 return mono_image_ensure_section_idx (image, i);
195 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
197 const int top = iinfo->cli_header.coff.coff_sections;
200 iinfo->cli_section_count = top;
201 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
202 iinfo->cli_sections = g_new0 (void *, top);
204 for (i = 0; i < top; i++){
205 MonoSectionTable *t = &iinfo->cli_section_tables [i];
207 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
209 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
210 offset += sizeof (MonoSectionTable);
212 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
213 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
214 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
215 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
216 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
217 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
218 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
219 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
220 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
221 t->st_flags = GUINT32_FROM_LE (t->st_flags);
223 /* consistency checks here */
230 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
234 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
235 if (offset == INVALID_ADDRESS)
238 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
240 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
242 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
243 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
244 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
245 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
246 SWAP32 (iinfo->cli_cli_header.ch_size);
247 SWAP32 (iinfo->cli_cli_header.ch_flags);
248 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
249 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
250 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
251 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
252 SWAPPDE (iinfo->cli_cli_header.ch_resources);
253 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
254 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
255 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
256 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
257 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
258 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
259 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
260 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
261 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
262 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
263 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
264 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
265 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
270 /* Catch new uses of the fields that are supposed to be zero */
272 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
273 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
274 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
275 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
276 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
277 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
278 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
279 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
280 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
283 * No need to scare people who are testing this, I am just
284 * labelling this as a LAMESPEC
286 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
294 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
296 guint32 offset, size;
302 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
303 if (offset == INVALID_ADDRESS)
306 size = iinfo->cli_cli_header.ch_metadata.size;
308 if (offset + size > image->raw_data_len)
310 image->raw_metadata = image->raw_data + offset;
312 ptr = image->raw_metadata;
314 if (strncmp (ptr, "BSJB", 4) == 0){
315 guint32 version_string_len;
318 version_string_len = read32 (ptr);
320 image->version = g_strndup (ptr, version_string_len);
321 ptr += version_string_len;
322 pad = ptr - image->raw_metadata;
324 ptr += 4 - (pad % 4);
328 /* skip over flags */
331 streams = read16 (ptr);
334 for (i = 0; i < streams; i++){
335 if (strncmp (ptr + 8, "#~", 3) == 0){
336 image->heap_tables.data = image->raw_metadata + read32 (ptr);
337 image->heap_tables.size = read32 (ptr + 4);
339 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
340 image->heap_strings.data = image->raw_metadata + read32 (ptr);
341 image->heap_strings.size = read32 (ptr + 4);
343 } else if (strncmp (ptr + 8, "#US", 4) == 0){
344 image->heap_us.data = image->raw_metadata + read32 (ptr);
345 image->heap_us.size = read32 (ptr + 4);
347 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
348 image->heap_blob.data = image->raw_metadata + read32 (ptr);
349 image->heap_blob.size = read32 (ptr + 4);
351 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
352 image->heap_guid.data = image->raw_metadata + read32 (ptr);
353 image->heap_guid.size = read32 (ptr + 4);
355 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
356 g_print ("Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name);
359 g_message ("Unknown heap type: %s\n", ptr + 8);
360 ptr += 8 + strlen (ptr + 8) + 1;
362 pad = ptr - image->raw_metadata;
364 ptr += 4 - (pad % 4);
367 g_assert (image->heap_guid.data);
368 g_assert (image->heap_guid.size >= 16);
370 image->guid = mono_guid_to_string (image->heap_guid.data);
376 * Load representation of logical metadata tables, from the "#~" stream
379 load_tables (MonoImage *image)
381 const char *heap_tables = image->heap_tables.data;
383 guint64 valid_mask, sorted_mask;
384 int valid = 0, table;
387 heap_sizes = heap_tables [6];
388 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
389 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
390 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
392 valid_mask = read64 (heap_tables + 8);
393 sorted_mask = read64 (heap_tables + 16);
394 rows = (const guint32 *) (heap_tables + 24);
396 for (table = 0; table < 64; table++){
397 if ((valid_mask & ((guint64) 1 << table)) == 0){
398 if (table > MONO_TABLE_LAST)
400 image->tables [table].rows = 0;
403 if (table > MONO_TABLE_LAST) {
404 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
406 image->tables [table].rows = read32 (rows);
408 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
409 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
415 image->tables_base = (heap_tables + 24) + (4 * valid);
417 /* They must be the same */
418 g_assert ((const void *) image->tables_base == (const void *) rows);
420 mono_metadata_compute_table_bases (image);
425 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
427 if (!load_metadata_ptrs (image, iinfo))
430 return load_tables (image);
434 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
435 const char *name, guint32 index)
437 GHashTable *nspace_table;
438 GHashTable *name_cache = image->name_cache;
440 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
441 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
442 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
444 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
448 load_modules (MonoImage *image, MonoImageOpenStatus *status)
457 t = &image->tables [MONO_TABLE_MODULEREF];
458 image->modules = g_new0 (MonoImage *, t->rows);
459 image->module_count = t->rows;
460 base_dir = g_path_get_dirname (image->name);
461 for (i = 0; i < t->rows; i++){
464 guint32 cols [MONO_MODULEREF_SIZE];
466 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
467 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
468 module_ref = g_build_filename (base_dir, name, NULL);
469 image->modules [i] = mono_image_open (module_ref, status);
470 if (image->modules [i]) {
471 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
474 * FIXME: what do we do here? it could be a native dll...
475 * We should probably do lazy-loading of modules.
478 *status = MONO_IMAGE_OK;
486 load_class_names (MonoImage *image)
488 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
489 guint32 cols [MONO_TYPEDEF_SIZE];
492 guint32 i, visib, nspace_index;
493 GHashTable *name_cache2, *nspace_table;
495 /* Temporary hash table to avoid lookups in the nspace_table */
496 name_cache2 = g_hash_table_new (NULL, NULL);
498 for (i = 1; i <= t->rows; ++i) {
499 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
500 /* nested types are accessed from the nesting name */
501 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
502 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
504 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
505 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
507 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
508 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
510 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
511 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
512 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
515 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
518 /* Load type names from EXPORTEDTYPES table */
520 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
521 guint32 cols [MONO_EXP_TYPE_SIZE];
524 for (i = 0; i < t->rows; ++i) {
525 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
526 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
527 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
529 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
530 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
532 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
533 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
534 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
537 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
541 g_hash_table_destroy (name_cache2);
545 register_guid (gpointer key, gpointer value, gpointer user_data)
547 MonoImage *image = (MonoImage*)value;
549 if (!g_hash_table_lookup (loaded_images_guid_hash, image))
550 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
554 build_guid_table (void)
556 g_hash_table_foreach (loaded_images_hash, register_guid, NULL);
560 mono_image_init (MonoImage *image)
562 image->mempool = mono_mempool_new ();
563 image->method_cache = g_hash_table_new (NULL, NULL);
564 image->class_cache = g_hash_table_new (NULL, NULL);
565 image->field_cache = g_hash_table_new (NULL, NULL);
566 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
567 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
569 image->delegate_begin_invoke_cache =
570 g_hash_table_new ((GHashFunc)mono_signature_hash,
571 (GCompareFunc)mono_metadata_signature_equal);
572 image->delegate_end_invoke_cache =
573 g_hash_table_new ((GHashFunc)mono_signature_hash,
574 (GCompareFunc)mono_metadata_signature_equal);
575 image->delegate_invoke_cache =
576 g_hash_table_new ((GHashFunc)mono_signature_hash,
577 (GCompareFunc)mono_metadata_signature_equal);
578 image->runtime_invoke_cache =
579 g_hash_table_new ((GHashFunc)mono_signature_hash,
580 (GCompareFunc)mono_metadata_signature_equal);
582 image->managed_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
583 image->native_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
584 image->remoting_invoke_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
585 image->synchronized_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
586 image->unbox_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
588 image->typespec_cache = g_hash_table_new (NULL, NULL);
589 image->memberref_signatures = g_hash_table_new (NULL, NULL);
590 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
594 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
595 gboolean care_about_cli)
597 MonoCLIImageInfo *iinfo;
598 MonoDotNetHeader *header;
599 MonoMSDOSHeader msdos;
602 mono_image_init (image);
604 iinfo = image->image_info;
605 header = &iinfo->cli_header;
608 *status = MONO_IMAGE_IMAGE_INVALID;
610 if (offset + sizeof (msdos) > image->raw_data_len)
612 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
614 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
617 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
619 offset = msdos.pe_offset;
621 if (offset + sizeof (MonoDotNetHeader) > image->raw_data_len)
623 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
624 offset += sizeof (MonoDotNetHeader);
626 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
627 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
628 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
629 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
630 SWAP32 (header->coff.coff_time);
631 SWAP32 (header->coff.coff_symptr);
632 SWAP32 (header->coff.coff_symcount);
633 SWAP16 (header->coff.coff_machine);
634 SWAP16 (header->coff.coff_sections);
635 SWAP16 (header->coff.coff_opt_header_size);
636 SWAP16 (header->coff.coff_attributes);
638 SWAP32 (header->pe.pe_code_size);
639 SWAP32 (header->pe.pe_data_size);
640 SWAP32 (header->pe.pe_uninit_data_size);
641 SWAP32 (header->pe.pe_rva_entry_point);
642 SWAP32 (header->pe.pe_rva_code_base);
643 SWAP32 (header->pe.pe_rva_data_base);
644 SWAP16 (header->pe.pe_magic);
646 /* MonoPEHeaderNT: not used yet */
647 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
648 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
649 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
650 SWAP16 (header->nt.pe_os_major); /* must be 4 */
651 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
652 SWAP16 (header->nt.pe_user_major);
653 SWAP16 (header->nt.pe_user_minor);
654 SWAP16 (header->nt.pe_subsys_major);
655 SWAP16 (header->nt.pe_subsys_minor);
656 SWAP32 (header->nt.pe_reserved_1);
657 SWAP32 (header->nt.pe_image_size);
658 SWAP32 (header->nt.pe_header_size);
659 SWAP32 (header->nt.pe_checksum);
660 SWAP16 (header->nt.pe_subsys_required);
661 SWAP16 (header->nt.pe_dll_flags);
662 SWAP32 (header->nt.pe_stack_reserve);
663 SWAP32 (header->nt.pe_stack_commit);
664 SWAP32 (header->nt.pe_heap_reserve);
665 SWAP32 (header->nt.pe_heap_commit);
666 SWAP32 (header->nt.pe_loader_flags);
667 SWAP32 (header->nt.pe_data_dir_count);
669 /* MonoDotNetHeader: mostly unused */
670 SWAPPDE (header->datadir.pe_export_table);
671 SWAPPDE (header->datadir.pe_import_table);
672 SWAPPDE (header->datadir.pe_resource_table);
673 SWAPPDE (header->datadir.pe_exception_table);
674 SWAPPDE (header->datadir.pe_certificate_table);
675 SWAPPDE (header->datadir.pe_reloc_table);
676 SWAPPDE (header->datadir.pe_debug);
677 SWAPPDE (header->datadir.pe_copyright);
678 SWAPPDE (header->datadir.pe_global_ptr);
679 SWAPPDE (header->datadir.pe_tls_table);
680 SWAPPDE (header->datadir.pe_load_config_table);
681 SWAPPDE (header->datadir.pe_bound_import);
682 SWAPPDE (header->datadir.pe_iat);
683 SWAPPDE (header->datadir.pe_delay_import_desc);
684 SWAPPDE (header->datadir.pe_cli_header);
685 SWAPPDE (header->datadir.pe_reserved);
692 if (header->coff.coff_machine != 0x14c)
695 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
698 if (header->pesig[0] != 'P' || header->pesig[1] != 'E' || header->pe.pe_magic != 0x10B)
703 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
704 * which produces binaries with 7.0. From Sergey:
706 * The reason is that MSVC7 uses traditional compile/link
707 * sequence for CIL executables, and VS.NET (and Framework
708 * SDK) includes linker version 7, that puts 7.0 in this
709 * field. That's why it's currently not possible to load VC
710 * binaries with Mono. This field is pretty much meaningless
711 * anyway (what linker?).
713 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
718 * FIXME: byte swap all addresses here for header.
721 if (!load_section_tables (image, iinfo, offset))
724 if (care_about_cli == FALSE) {
728 /* Load the CLI header */
729 if (!load_cli_header (image, iinfo))
732 if (!load_metadata (image, iinfo))
735 load_class_names (image);
737 /* modules don't have an assembly table row */
738 if (image->tables [MONO_TABLE_ASSEMBLY].rows)
739 image->assembly_name = mono_metadata_string_heap (image,
740 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
741 0, MONO_ASSEMBLY_NAME));
743 image->module_name = mono_metadata_string_heap (image,
744 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
745 0, MONO_MODULE_NAME));
747 load_modules (image, status);
751 *status = MONO_IMAGE_OK;
758 mono_image_close (image);
763 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
764 gboolean care_about_cli)
766 MonoCLIImageInfo *iinfo;
769 struct stat stat_buf;
771 if ((filed = fopen (fname, "rb")) == NULL){
773 *status = MONO_IMAGE_ERROR_ERRNO;
777 if (fstat (fileno (filed), &stat_buf)) {
780 *status = MONO_IMAGE_ERROR_ERRNO;
783 image = g_new0 (MonoImage, 1);
784 image->ref_count = 1;
785 image->file_descr = filed;
786 image->raw_data_len = stat_buf.st_size;
787 image->raw_data = mono_raw_buffer_load (fileno (filed), FALSE, 0, stat_buf.st_size);
788 iinfo = g_new0 (MonoCLIImageInfo, 1);
789 image->image_info = iinfo;
790 image->name = canonicalize_path (fname);
792 return do_mono_image_load (image, status, care_about_cli);
796 mono_image_loaded (const char *name)
800 EnterCriticalSection (&images_mutex);
801 res = g_hash_table_lookup (loaded_images_hash, name);
802 LeaveCriticalSection (&images_mutex);
807 mono_image_loaded_by_guid (const char *guid)
811 EnterCriticalSection (&images_mutex);
812 res = g_hash_table_lookup (loaded_images_guid_hash, guid);
813 LeaveCriticalSection (&images_mutex);
818 register_image (MonoImage *image)
822 EnterCriticalSection (&images_mutex);
823 image2 = g_hash_table_lookup (loaded_images_hash, image->name);
826 /* Somebody else beat us to it */
827 mono_image_addref (image2);
828 LeaveCriticalSection (&images_mutex);
829 mono_image_close (image);
832 g_hash_table_insert (loaded_images_hash, image->name, image);
833 if (image->assembly_name && (g_hash_table_lookup (loaded_images_hash, image->assembly_name) == NULL))
834 g_hash_table_insert (loaded_images_hash, (char *) image->assembly_name, image);
835 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
836 LeaveCriticalSection (&images_mutex);
842 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
844 MonoCLIImageInfo *iinfo;
848 if (!data || !data_len) {
850 *status = MONO_IMAGE_IMAGE_INVALID;
855 datac = g_try_malloc (data_len);
858 *status = MONO_IMAGE_ERROR_ERRNO;
861 memcpy (datac, data, data_len);
864 image = g_new0 (MonoImage, 1);
865 image->ref_count = 1;
866 image->raw_data = datac;
867 image->raw_data_len = data_len;
868 image->raw_data_allocated = need_copy;
869 image->name = g_strdup_printf ("data-%p", datac);
870 iinfo = g_new0 (MonoCLIImageInfo, 1);
871 image->image_info = iinfo;
873 image = do_mono_image_load (image, status, TRUE);
877 return register_image (image);
882 * @fname: filename that points to the module we want to open
883 * @status: An error condition is returned in this field
885 * Returns: An open image of type %MonoImage or NULL on error.
886 * if NULL, then check the value of @status for details on the error
889 mono_image_open (const char *fname, MonoImageOpenStatus *status)
894 g_return_val_if_fail (fname != NULL, NULL);
896 absfname = canonicalize_path (fname);
899 * The easiest solution would be to do all the loading inside the mutex,
900 * but that would lead to scalability problems. So we let the loading
901 * happen outside the mutex, and if multiple threads happen to load
902 * the same image, we discard all but the first copy.
904 EnterCriticalSection (&images_mutex);
905 image = g_hash_table_lookup (loaded_images_hash, absfname);
909 mono_image_addref (image);
910 LeaveCriticalSection (&images_mutex);
913 LeaveCriticalSection (&images_mutex);
915 image = do_mono_image_open (fname, status, TRUE);
919 return register_image (image);
924 * @fname: filename that points to the module we want to open
925 * @status: An error condition is returned in this field
927 * Returns: An open image of type %MonoImage or NULL on error. if
928 * NULL, then check the value of @status for details on the error.
929 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
930 * It's just a PE file loader, used for FileVersionInfo. It also does
931 * not use the image cache.
934 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
936 g_return_val_if_fail (fname != NULL, NULL);
938 return(do_mono_image_open (fname, status, FALSE));
942 free_hash_table (gpointer key, gpointer val, gpointer user_data)
944 g_hash_table_destroy ((GHashTable*)val);
948 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
950 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
954 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
961 * @image: The image file we wish to add a reference to
963 * Increases the reference count of an image.
966 mono_image_addref (MonoImage *image)
968 InterlockedIncrement (&image->ref_count);
972 mono_dynamic_stream_reset (MonoDynamicStream* stream)
974 stream->alloc_size = stream->index = stream->offset = 0;
975 g_free (stream->data);
978 g_hash_table_destroy (stream->hash);
985 * @image: The image file we wish to close
987 * Closes an image file, deallocates all memory consumed and
988 * unmaps all possible sections of the file
991 mono_image_close (MonoImage *image)
996 g_return_if_fail (image != NULL);
998 EnterCriticalSection (&images_mutex);
999 /*g_print ("destroy image '%s' %p (dynamic: %d) refcount: %d\n", image->name, image, image->dynamic, image->ref_count);*/
1000 g_assert (image->ref_count > 0);
1001 if (--image->ref_count) {
1002 LeaveCriticalSection (&images_mutex);
1005 image2 = g_hash_table_lookup (loaded_images_hash, image->name);
1006 if (image == image2) {
1007 /* This is not true if we are called from mono_image_open () */
1008 g_hash_table_remove (loaded_images_hash, image->name);
1009 g_hash_table_remove (loaded_images_guid_hash, image->guid);
1010 /* Multiple images might have the same guid */
1011 build_guid_table ();
1013 if (image->assembly_name && (g_hash_table_lookup (loaded_images_hash, image->assembly_name) == image))
1014 g_hash_table_remove (loaded_images_hash, (char *) image->assembly_name);
1015 LeaveCriticalSection (&images_mutex);
1017 if (image->file_descr) {
1018 fclose (image->file_descr);
1019 image->file_descr = NULL;
1020 if (image->raw_data != NULL)
1021 mono_raw_buffer_free (image->raw_data);
1024 if (image->raw_data_allocated) {
1025 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1026 MonoCLIImageInfo *ii = image->image_info;
1028 if ((image->raw_metadata > image->raw_data) &&
1029 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1030 image->raw_metadata = NULL;
1032 for (i = 0; i < ii->cli_section_count; i++)
1033 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1034 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1035 ii->cli_sections [i] = NULL;
1037 g_free (image->raw_data);
1039 g_free (image->name);
1040 g_free (image->guid);
1041 g_free (image->files);
1043 g_hash_table_destroy (image->method_cache);
1044 g_hash_table_destroy (image->class_cache);
1045 g_hash_table_destroy (image->field_cache);
1046 g_hash_table_destroy (image->array_cache);
1047 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1048 g_hash_table_destroy (image->name_cache);
1049 g_hash_table_destroy (image->native_wrapper_cache);
1050 g_hash_table_destroy (image->managed_wrapper_cache);
1051 g_hash_table_destroy (image->delegate_begin_invoke_cache);
1052 g_hash_table_destroy (image->delegate_end_invoke_cache);
1053 g_hash_table_destroy (image->delegate_invoke_cache);
1054 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1055 g_hash_table_destroy (image->remoting_invoke_cache);
1056 g_hash_table_destroy (image->runtime_invoke_cache);
1057 g_hash_table_destroy (image->synchronized_cache);
1058 g_hash_table_destroy (image->unbox_wrapper_cache);
1059 g_hash_table_destroy (image->typespec_cache);
1060 g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1061 g_hash_table_destroy (image->memberref_signatures);
1062 g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1063 g_hash_table_destroy (image->helper_signatures);
1065 if (image->image_info){
1066 MonoCLIImageInfo *ii = image->image_info;
1068 if (ii->cli_section_tables)
1069 g_free (ii->cli_section_tables);
1070 if (ii->cli_sections)
1071 g_free (ii->cli_sections);
1072 g_free (image->image_info);
1075 for (i = 0; i < image->module_count; ++i) {
1076 if (image->modules [i])
1077 mono_image_close (image->modules [i]);
1079 /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1080 if (!image->dynamic) {
1081 mono_mempool_destroy (image->mempool);
1084 /* Dynamic images are GC_MALLOCed */
1085 struct _MonoDynamicImage *di = (struct _MonoDynamicImage*)image;
1087 g_free ((char*)image->module_name);
1089 g_hash_table_destroy (di->typespec);
1091 g_hash_table_destroy (di->typeref);
1093 g_hash_table_destroy (di->handleref);
1095 mono_g_hash_table_destroy (di->tokens);
1097 g_hash_table_destroy (di->blob_cache);
1098 g_list_free (di->array_methods);
1100 g_ptr_array_free (di->gen_params, TRUE);
1101 if (di->token_fixups)
1102 mono_g_hash_table_destroy (di->token_fixups);
1103 if (di->method_to_table_idx)
1104 g_hash_table_destroy (di->method_to_table_idx);
1105 if (di->field_to_table_idx)
1106 g_hash_table_destroy (di->field_to_table_idx);
1107 if (di->method_aux_hash)
1108 g_hash_table_destroy (di->method_aux_hash);
1109 g_free (di->strong_name);
1110 g_free (di->win32_res);
1111 /*g_print ("string heap destroy for image %p\n", di);*/
1112 mono_dynamic_stream_reset (&di->sheap);
1113 mono_dynamic_stream_reset (&di->code);
1114 mono_dynamic_stream_reset (&di->resources);
1115 mono_dynamic_stream_reset (&di->us);
1116 mono_dynamic_stream_reset (&di->blob);
1117 mono_dynamic_stream_reset (&di->tstream);
1118 mono_dynamic_stream_reset (&di->guid);
1119 for (i = 0; i < MONO_TABLE_NUM; ++i) {
1120 g_free (di->tables [i].values);
1122 mono_mempool_destroy (image->mempool);
1127 * mono_image_strerror:
1128 * @status: an code indicating the result from a recent operation
1130 * Returns: a string describing the error
1133 mono_image_strerror (MonoImageOpenStatus status)
1138 case MONO_IMAGE_ERROR_ERRNO:
1139 return strerror (errno);
1140 case MONO_IMAGE_IMAGE_INVALID:
1141 return "File does not contain a valid CIL image";
1142 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1143 return "An assembly was referenced, but could not be found";
1145 return "Internal error";
1149 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1150 guint32 lang_id, gunichar2 *name,
1151 MonoPEResourceDirEntry *entry,
1152 MonoPEResourceDir *root, guint32 level)
1154 gboolean is_string=entry->name_is_string;
1156 /* Level 0 holds a directory entry for each type of resource
1157 * (identified by ID or name).
1159 * Level 1 holds a directory entry for each named resource
1160 * item, and each "anonymous" item of a particular type of
1163 * Level 2 holds a directory entry for each language pointing to
1168 if((is_string==FALSE && entry->name_offset!=res_id) ||
1169 (is_string==TRUE)) {
1172 } else if (level==1) {
1175 is_string==TRUE && name!=lookup (entry->name_offset)) {
1179 } else if (level==2) {
1180 if ((is_string == FALSE &&
1181 entry->name_offset != lang_id &&
1183 (is_string == TRUE)) {
1187 g_assert_not_reached ();
1190 if(entry->is_dir==TRUE) {
1191 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+entry->dir_offset);
1192 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1195 entries=res_dir->res_named_entries + res_dir->res_id_entries;
1197 for(i=0; i<entries; i++) {
1198 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1201 ret=mono_image_walk_resource_tree (info, res_id,
1212 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+entry->dir_offset);
1219 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1221 MonoCLIImageInfo *info;
1222 MonoDotNetHeader *header;
1223 MonoPEDatadir *datadir;
1224 MonoPEDirEntry *rsrc;
1225 MonoPEResourceDir *resource_dir;
1226 MonoPEResourceDirEntry *res_entries;
1233 info=image->image_info;
1238 header=&info->cli_header;
1243 datadir=&header->datadir;
1248 rsrc=&datadir->pe_resource_table;
1253 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1254 if(resource_dir==NULL) {
1258 entries=resource_dir->res_named_entries + resource_dir->res_id_entries;
1259 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1261 for(i=0; i<entries; i++) {
1262 MonoPEResourceDirEntry *entry=&res_entries[i];
1265 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1266 name, entry, resource_dir,
1277 mono_image_get_entry_point (MonoImage *image)
1279 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1283 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1285 MonoCLIImageInfo *iinfo = image->image_info;
1286 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1289 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1292 data = mono_image_rva_map (image, ch->ch_resources.rva);
1297 *size = read32 (data);
1303 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1305 char *base_dir, *name;
1307 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1311 if (fileidx < 1 || fileidx > t->rows)
1314 if (image->files && image->files [fileidx - 1])
1315 return image->files [fileidx - 1];
1318 image->files = g_new0 (MonoImage*, t->rows);
1320 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1321 fname = mono_metadata_string_heap (image, fname_id);
1322 base_dir = g_path_get_dirname (image->name);
1323 name = g_build_filename (base_dir, fname, NULL);
1324 res = mono_image_open (name, NULL);
1327 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1328 res->assembly = image->assembly;
1329 for (i = 0; i < res->module_count; ++i) {
1330 if (res->modules [i] && !res->modules [i]->assembly)
1331 res->modules [i]->assembly = image->assembly;
1334 image->files [fileidx - 1] = res;
1342 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1344 MonoCLIImageInfo *iinfo = image->image_info;
1345 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1348 if (!de->size || !de->rva)
1350 data = mono_image_rva_map (image, de->rva);
1359 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1361 MonoCLIImageInfo *iinfo = image->image_info;
1362 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1363 const int top = iinfo->cli_section_count;
1364 MonoSectionTable *tables = iinfo->cli_section_tables;
1366 guint32 addr = de->rva;
1370 if (!de->size || !de->rva)
1372 for (i = 0; i < top; i++){
1373 if ((addr >= tables->st_virtual_address) &&
1374 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
1375 return tables->st_raw_data_ptr +
1376 (addr - tables->st_virtual_address);
1385 mono_image_get_public_key (MonoImage *image, guint32 *size)
1389 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1391 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1394 pubkey = mono_metadata_blob_heap (image, tok);
1395 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1402 mono_image_get_name (MonoImage *image)
1404 return image->assembly_name;
1408 mono_image_get_filename (MonoImage *image)
1413 const MonoTableInfo*
1414 mono_image_get_table_info (MonoImage *image, int table_id)
1416 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1418 return &image->tables [table_id];
1422 mono_image_get_table_rows (MonoImage *image, int table_id)
1424 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1426 return image->tables [table_id].rows;
1430 mono_table_info_get_rows (const MonoTableInfo *table)
1436 mono_image_get_assembly (MonoImage *image)
1438 return image->assembly;
1442 mono_image_is_dynamic (MonoImage *image)
1444 return image->dynamic;
1448 mono_image_has_authenticode_entry (MonoImage *image)
1450 MonoCLIImageInfo *iinfo = image->image_info;
1451 MonoDotNetHeader *header = &iinfo->cli_header;
1452 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
1453 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
1454 return ((de->rva != 0) && (de->size > 8));