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;
41 #define mono_images_lock() EnterCriticalSection (&images_mutex)
42 #define mono_images_unlock() LeaveCriticalSection (&images_mutex)
43 static CRITICAL_SECTION images_mutex;
46 mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
48 const int top = iinfo->cli_section_count;
49 MonoSectionTable *tables = iinfo->cli_section_tables;
52 for (i = 0; i < top; i++){
53 if ((addr >= tables->st_virtual_address) &&
54 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
55 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
59 return INVALID_ADDRESS;
63 mono_image_rva_map (MonoImage *image, guint32 addr)
65 MonoCLIImageInfo *iinfo = image->image_info;
66 const int top = iinfo->cli_section_count;
67 MonoSectionTable *tables = iinfo->cli_section_tables;
70 for (i = 0; i < top; i++){
71 if ((addr >= tables->st_virtual_address) &&
72 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
73 if (!iinfo->cli_sections [i]) {
74 if (!mono_image_ensure_section_idx (image, i))
77 return (char*)iinfo->cli_sections [i] +
78 (addr - tables->st_virtual_address);
86 canonicalize_path (const char *path)
88 gchar *abspath, *pos, *lastpos, *dest;
91 if (g_path_is_absolute (path)) {
92 abspath = g_strdup (path);
94 gchar *tmpdir = g_get_current_dir ();
95 abspath = g_build_filename (tmpdir, path, NULL);
99 abspath = g_strreverse (abspath);
102 dest = lastpos = abspath;
103 pos = strchr (lastpos, G_DIR_SEPARATOR);
105 while (pos != NULL) {
106 int len = pos - lastpos;
107 if (len == 1 && lastpos [0] == '.') {
109 } else if (len == 2 && lastpos [0] == '.' && lastpos [1] == '.') {
111 } else if (len > 0) {
115 if (dest != lastpos) strncpy (dest, lastpos, len + 1);
120 pos = strchr (lastpos, G_DIR_SEPARATOR);
123 if (dest != lastpos) strcpy (dest, lastpos);
124 return g_strreverse (abspath);
130 * Initialize the global variables used by this module.
133 mono_images_init (void)
135 InitializeCriticalSection (&images_mutex);
137 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
138 loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
139 loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
140 loaded_images_refonly_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
144 * mono_image_ensure_section_idx:
145 * @image: The image we are operating on
146 * @section: section number that we will load/map into memory
148 * This routine makes sure that we have an in-memory copy of
149 * an image section (.text, .rsrc, .data).
151 * Returns: TRUE on success
154 mono_image_ensure_section_idx (MonoImage *image, int section)
156 MonoCLIImageInfo *iinfo = image->image_info;
157 MonoSectionTable *sect;
160 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
162 if (iinfo->cli_sections [section] != NULL)
165 sect = &iinfo->cli_section_tables [section];
167 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
169 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
171 /* FIXME: we ignore the writable flag since we don't patch the binary */
172 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
177 * mono_image_ensure_section:
178 * @image: The image we are operating on
179 * @section: section name that we will load/map into memory
181 * This routine makes sure that we have an in-memory copy of
182 * an image section (.text, .rsrc, .data).
184 * Returns: TRUE on success
187 mono_image_ensure_section (MonoImage *image, const char *section)
189 MonoCLIImageInfo *ii = image->image_info;
192 for (i = 0; i < ii->cli_section_count; i++){
193 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
196 return mono_image_ensure_section_idx (image, i);
202 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
204 const int top = iinfo->cli_header.coff.coff_sections;
207 iinfo->cli_section_count = top;
208 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
209 iinfo->cli_sections = g_new0 (void *, top);
211 for (i = 0; i < top; i++){
212 MonoSectionTable *t = &iinfo->cli_section_tables [i];
214 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
216 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
217 offset += sizeof (MonoSectionTable);
219 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
220 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
221 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
222 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
223 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
224 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
225 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
226 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
227 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
228 t->st_flags = GUINT32_FROM_LE (t->st_flags);
230 /* consistency checks here */
237 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
241 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
242 if (offset == INVALID_ADDRESS)
245 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
247 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
249 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
250 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
251 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
252 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
253 SWAP32 (iinfo->cli_cli_header.ch_size);
254 SWAP32 (iinfo->cli_cli_header.ch_flags);
255 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
256 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
257 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
258 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
259 SWAPPDE (iinfo->cli_cli_header.ch_resources);
260 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
261 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
262 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
263 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
264 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
265 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
266 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
267 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
268 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
269 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
270 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
271 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
272 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
277 /* Catch new uses of the fields that are supposed to be zero */
279 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
280 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
281 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
282 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
283 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
284 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
285 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
286 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
287 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
290 * No need to scare people who are testing this, I am just
291 * labelling this as a LAMESPEC
293 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
301 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
303 guint32 offset, size;
309 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
310 if (offset == INVALID_ADDRESS)
313 size = iinfo->cli_cli_header.ch_metadata.size;
315 if (offset + size > image->raw_data_len)
317 image->raw_metadata = image->raw_data + offset;
319 ptr = image->raw_metadata;
321 if (strncmp (ptr, "BSJB", 4) == 0){
322 guint32 version_string_len;
325 image->md_version_major = read16 (ptr);
327 image->md_version_minor = read16 (ptr);
330 version_string_len = read32 (ptr);
332 image->version = g_strndup (ptr, version_string_len);
333 ptr += version_string_len;
334 pad = ptr - image->raw_metadata;
336 ptr += 4 - (pad % 4);
340 /* skip over flags */
343 streams = read16 (ptr);
346 for (i = 0; i < streams; i++){
347 if (strncmp (ptr + 8, "#~", 3) == 0){
348 image->heap_tables.data = image->raw_metadata + read32 (ptr);
349 image->heap_tables.size = read32 (ptr + 4);
351 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
352 image->heap_strings.data = image->raw_metadata + read32 (ptr);
353 image->heap_strings.size = read32 (ptr + 4);
355 } else if (strncmp (ptr + 8, "#US", 4) == 0){
356 image->heap_us.data = image->raw_metadata + read32 (ptr);
357 image->heap_us.size = read32 (ptr + 4);
359 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
360 image->heap_blob.data = image->raw_metadata + read32 (ptr);
361 image->heap_blob.size = read32 (ptr + 4);
363 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
364 image->heap_guid.data = image->raw_metadata + read32 (ptr);
365 image->heap_guid.size = read32 (ptr + 4);
367 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
368 g_print ("Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name);
371 g_message ("Unknown heap type: %s\n", ptr + 8);
372 ptr += 8 + strlen (ptr + 8) + 1;
374 pad = ptr - image->raw_metadata;
376 ptr += 4 - (pad % 4);
379 g_assert (image->heap_guid.data);
380 g_assert (image->heap_guid.size >= 16);
382 image->guid = mono_guid_to_string (image->heap_guid.data);
388 * Load representation of logical metadata tables, from the "#~" stream
391 load_tables (MonoImage *image)
393 const char *heap_tables = image->heap_tables.data;
395 guint64 valid_mask, sorted_mask;
396 int valid = 0, table;
399 heap_sizes = heap_tables [6];
400 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
401 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
402 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
404 valid_mask = read64 (heap_tables + 8);
405 sorted_mask = read64 (heap_tables + 16);
406 rows = (const guint32 *) (heap_tables + 24);
408 for (table = 0; table < 64; table++){
409 if ((valid_mask & ((guint64) 1 << table)) == 0){
410 if (table > MONO_TABLE_LAST)
412 image->tables [table].rows = 0;
415 if (table > MONO_TABLE_LAST) {
416 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
418 image->tables [table].rows = read32 (rows);
420 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
421 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
427 image->tables_base = (heap_tables + 24) + (4 * valid);
429 /* They must be the same */
430 g_assert ((const void *) image->tables_base == (const void *) rows);
432 mono_metadata_compute_table_bases (image);
437 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
439 if (!load_metadata_ptrs (image, iinfo))
442 return load_tables (image);
446 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
447 const char *name, guint32 index)
449 GHashTable *nspace_table;
450 GHashTable *name_cache = image->name_cache;
452 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
453 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
454 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
456 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
460 load_modules (MonoImage *image, MonoImageOpenStatus *status)
465 gboolean refonly = image->ref_only;
470 t = &image->tables [MONO_TABLE_MODULEREF];
471 image->modules = g_new0 (MonoImage *, t->rows);
472 image->module_count = t->rows;
473 base_dir = g_path_get_dirname (image->name);
474 for (i = 0; i < t->rows; i++){
477 guint32 cols [MONO_MODULEREF_SIZE];
479 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
480 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
481 module_ref = g_build_filename (base_dir, name, NULL);
482 image->modules [i] = mono_image_open_full (module_ref, status, refonly);
483 if (image->modules [i]) {
484 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
487 * FIXME: what do we do here? it could be a native dll...
488 * We should probably do lazy-loading of modules.
491 *status = MONO_IMAGE_OK;
499 load_class_names (MonoImage *image)
501 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
502 guint32 cols [MONO_TYPEDEF_SIZE];
505 guint32 i, visib, nspace_index;
506 GHashTable *name_cache2, *nspace_table;
508 /* Temporary hash table to avoid lookups in the nspace_table */
509 name_cache2 = g_hash_table_new (NULL, NULL);
511 for (i = 1; i <= t->rows; ++i) {
512 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
513 /* nested types are accessed from the nesting name */
514 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
515 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
517 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
518 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
520 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
521 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
523 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
524 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
525 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
528 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
531 /* Load type names from EXPORTEDTYPES table */
533 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
534 guint32 cols [MONO_EXP_TYPE_SIZE];
537 for (i = 0; i < t->rows; ++i) {
538 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
539 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
540 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
542 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
543 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
545 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
546 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
547 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
550 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
554 g_hash_table_destroy (name_cache2);
558 register_guid (gpointer key, gpointer value, gpointer user_data)
560 MonoImage *image = (MonoImage*)value;
562 if (!g_hash_table_lookup (loaded_images_guid_hash, image))
563 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
567 build_guid_table (gboolean refonly)
569 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
570 g_hash_table_foreach (loaded_images, register_guid, NULL);
574 mono_image_init (MonoImage *image)
576 image->mempool = mono_mempool_new ();
577 image->method_cache = g_hash_table_new (NULL, NULL);
578 image->class_cache = g_hash_table_new (NULL, NULL);
579 image->field_cache = g_hash_table_new (NULL, NULL);
580 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
581 image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
583 image->delegate_begin_invoke_cache =
584 g_hash_table_new ((GHashFunc)mono_signature_hash,
585 (GCompareFunc)mono_metadata_signature_equal);
586 image->delegate_end_invoke_cache =
587 g_hash_table_new ((GHashFunc)mono_signature_hash,
588 (GCompareFunc)mono_metadata_signature_equal);
589 image->delegate_invoke_cache =
590 g_hash_table_new ((GHashFunc)mono_signature_hash,
591 (GCompareFunc)mono_metadata_signature_equal);
592 image->runtime_invoke_cache =
593 g_hash_table_new ((GHashFunc)mono_signature_hash,
594 (GCompareFunc)mono_metadata_signature_equal);
596 image->managed_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
597 image->native_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
598 image->remoting_invoke_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
599 image->synchronized_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
600 image->unbox_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
602 image->typespec_cache = g_hash_table_new (NULL, NULL);
603 image->memberref_signatures = g_hash_table_new (NULL, NULL);
604 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
608 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
609 gboolean care_about_cli)
611 MonoCLIImageInfo *iinfo;
612 MonoDotNetHeader *header;
613 MonoMSDOSHeader msdos;
616 mono_image_init (image);
618 iinfo = image->image_info;
619 header = &iinfo->cli_header;
622 *status = MONO_IMAGE_IMAGE_INVALID;
624 if (offset + sizeof (msdos) > image->raw_data_len)
626 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
628 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
631 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
633 offset = msdos.pe_offset;
635 if (offset + sizeof (MonoDotNetHeader) > image->raw_data_len)
637 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
638 offset += sizeof (MonoDotNetHeader);
640 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
641 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
642 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
643 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
644 SWAP32 (header->coff.coff_time);
645 SWAP32 (header->coff.coff_symptr);
646 SWAP32 (header->coff.coff_symcount);
647 SWAP16 (header->coff.coff_machine);
648 SWAP16 (header->coff.coff_sections);
649 SWAP16 (header->coff.coff_opt_header_size);
650 SWAP16 (header->coff.coff_attributes);
652 SWAP32 (header->pe.pe_code_size);
653 SWAP32 (header->pe.pe_data_size);
654 SWAP32 (header->pe.pe_uninit_data_size);
655 SWAP32 (header->pe.pe_rva_entry_point);
656 SWAP32 (header->pe.pe_rva_code_base);
657 SWAP32 (header->pe.pe_rva_data_base);
658 SWAP16 (header->pe.pe_magic);
660 /* MonoPEHeaderNT: not used yet */
661 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
662 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
663 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
664 SWAP16 (header->nt.pe_os_major); /* must be 4 */
665 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
666 SWAP16 (header->nt.pe_user_major);
667 SWAP16 (header->nt.pe_user_minor);
668 SWAP16 (header->nt.pe_subsys_major);
669 SWAP16 (header->nt.pe_subsys_minor);
670 SWAP32 (header->nt.pe_reserved_1);
671 SWAP32 (header->nt.pe_image_size);
672 SWAP32 (header->nt.pe_header_size);
673 SWAP32 (header->nt.pe_checksum);
674 SWAP16 (header->nt.pe_subsys_required);
675 SWAP16 (header->nt.pe_dll_flags);
676 SWAP32 (header->nt.pe_stack_reserve);
677 SWAP32 (header->nt.pe_stack_commit);
678 SWAP32 (header->nt.pe_heap_reserve);
679 SWAP32 (header->nt.pe_heap_commit);
680 SWAP32 (header->nt.pe_loader_flags);
681 SWAP32 (header->nt.pe_data_dir_count);
683 /* MonoDotNetHeader: mostly unused */
684 SWAPPDE (header->datadir.pe_export_table);
685 SWAPPDE (header->datadir.pe_import_table);
686 SWAPPDE (header->datadir.pe_resource_table);
687 SWAPPDE (header->datadir.pe_exception_table);
688 SWAPPDE (header->datadir.pe_certificate_table);
689 SWAPPDE (header->datadir.pe_reloc_table);
690 SWAPPDE (header->datadir.pe_debug);
691 SWAPPDE (header->datadir.pe_copyright);
692 SWAPPDE (header->datadir.pe_global_ptr);
693 SWAPPDE (header->datadir.pe_tls_table);
694 SWAPPDE (header->datadir.pe_load_config_table);
695 SWAPPDE (header->datadir.pe_bound_import);
696 SWAPPDE (header->datadir.pe_iat);
697 SWAPPDE (header->datadir.pe_delay_import_desc);
698 SWAPPDE (header->datadir.pe_cli_header);
699 SWAPPDE (header->datadir.pe_reserved);
706 if (header->coff.coff_machine != 0x14c)
709 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
712 if (header->pesig[0] != 'P' || header->pesig[1] != 'E' || header->pe.pe_magic != 0x10B)
717 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
718 * which produces binaries with 7.0. From Sergey:
720 * The reason is that MSVC7 uses traditional compile/link
721 * sequence for CIL executables, and VS.NET (and Framework
722 * SDK) includes linker version 7, that puts 7.0 in this
723 * field. That's why it's currently not possible to load VC
724 * binaries with Mono. This field is pretty much meaningless
725 * anyway (what linker?).
727 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
732 * FIXME: byte swap all addresses here for header.
735 if (!load_section_tables (image, iinfo, offset))
738 if (care_about_cli == FALSE) {
742 /* Load the CLI header */
743 if (!load_cli_header (image, iinfo))
746 if (!load_metadata (image, iinfo))
749 load_class_names (image);
751 /* modules don't have an assembly table row */
752 if (image->tables [MONO_TABLE_ASSEMBLY].rows)
753 image->assembly_name = mono_metadata_string_heap (image,
754 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
755 0, MONO_ASSEMBLY_NAME));
757 image->module_name = mono_metadata_string_heap (image,
758 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
759 0, MONO_MODULE_NAME));
761 load_modules (image, status);
765 *status = MONO_IMAGE_OK;
770 mono_image_close (image);
775 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
776 gboolean care_about_cli, gboolean refonly)
778 MonoCLIImageInfo *iinfo;
781 struct stat stat_buf;
783 if ((filed = fopen (fname, "rb")) == NULL){
785 *status = MONO_IMAGE_ERROR_ERRNO;
789 if (fstat (fileno (filed), &stat_buf)) {
792 *status = MONO_IMAGE_ERROR_ERRNO;
795 image = g_new0 (MonoImage, 1);
796 image->file_descr = filed;
797 image->raw_data_len = stat_buf.st_size;
798 image->raw_data = mono_raw_buffer_load (fileno (filed), FALSE, 0, stat_buf.st_size);
799 iinfo = g_new0 (MonoCLIImageInfo, 1);
800 image->image_info = iinfo;
801 image->name = canonicalize_path (fname);
802 image->ref_only = refonly;
804 return do_mono_image_load (image, status, care_about_cli);
808 mono_image_loaded_full (const char *name, gboolean refonly)
811 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
814 res = g_hash_table_lookup (loaded_images, name);
815 mono_images_unlock ();
820 mono_image_loaded (const char *name)
822 return mono_image_loaded_full (name, FALSE);
826 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
829 GHashTable *loaded_images = refonly ? loaded_images_refonly_guid_hash : loaded_images_guid_hash;
832 res = g_hash_table_lookup (loaded_images, guid);
833 mono_images_unlock ();
838 mono_image_loaded_by_guid (const char *guid)
840 return mono_image_loaded_by_guid_full (guid, FALSE);
844 register_image (MonoImage *image)
847 GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
850 image2 = g_hash_table_lookup (loaded_images, image->name);
853 /* Somebody else beat us to it */
854 mono_image_addref (image2);
855 mono_images_unlock ();
856 mono_image_close (image);
859 g_hash_table_insert (loaded_images, image->name, image);
860 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
861 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);
862 g_hash_table_insert (image->ref_only ? loaded_images_refonly_guid_hash : loaded_images_guid_hash, image->guid, image);
863 mono_images_unlock ();
869 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
871 MonoCLIImageInfo *iinfo;
875 if (!data || !data_len) {
877 *status = MONO_IMAGE_IMAGE_INVALID;
882 datac = g_try_malloc (data_len);
885 *status = MONO_IMAGE_ERROR_ERRNO;
888 memcpy (datac, data, data_len);
891 image = g_new0 (MonoImage, 1);
892 image->raw_data = datac;
893 image->raw_data_len = data_len;
894 image->raw_data_allocated = need_copy;
895 image->name = g_strdup_printf ("data-%p", datac);
896 iinfo = g_new0 (MonoCLIImageInfo, 1);
897 image->image_info = iinfo;
898 image->ref_only = refonly;
900 image = do_mono_image_load (image, status, TRUE);
904 return register_image (image);
908 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
910 return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
914 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
917 GHashTable *loaded_images;
920 g_return_val_if_fail (fname != NULL, NULL);
922 absfname = canonicalize_path (fname);
925 * The easiest solution would be to do all the loading inside the mutex,
926 * but that would lead to scalability problems. So we let the loading
927 * happen outside the mutex, and if multiple threads happen to load
928 * the same image, we discard all but the first copy.
931 loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
932 image = g_hash_table_lookup (loaded_images, absfname);
936 mono_images_unlock ();
939 mono_images_unlock ();
941 image = do_mono_image_open (fname, status, TRUE, refonly);
945 return register_image (image);
950 * @fname: filename that points to the module we want to open
951 * @status: An error condition is returned in this field
953 * Returns: An open image of type %MonoImage or NULL on error.
954 * if NULL, then check the value of @status for details on the error
957 mono_image_open (const char *fname, MonoImageOpenStatus *status)
959 return mono_image_open_full (fname, status, FALSE);
964 * @fname: filename that points to the module we want to open
965 * @status: An error condition is returned in this field
967 * Returns: An open image of type %MonoImage or NULL on error. if
968 * NULL, then check the value of @status for details on the error.
969 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
970 * It's just a PE file loader, used for FileVersionInfo. It also does
971 * not use the image cache.
974 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
976 g_return_val_if_fail (fname != NULL, NULL);
978 return(do_mono_image_open (fname, status, FALSE, FALSE));
982 free_hash_table (gpointer key, gpointer val, gpointer user_data)
984 g_hash_table_destroy ((GHashTable*)val);
988 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
990 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
994 free_blob_cache_entry (gpointer key, gpointer val, gpointer user_data)
1000 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
1006 * mono_image_addref:
1007 * @image: The image file we wish to add a reference to
1009 * Increases the reference count of an image.
1012 mono_image_addref (MonoImage *image)
1014 InterlockedIncrement (&image->ref_count);
1018 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1020 stream->alloc_size = stream->index = stream->offset = 0;
1021 g_free (stream->data);
1022 stream->data = NULL;
1024 g_hash_table_destroy (stream->hash);
1025 stream->hash = NULL;
1031 * @image: The image file we wish to close
1033 * Closes an image file, deallocates all memory consumed and
1034 * unmaps all possible sections of the file
1037 mono_image_close (MonoImage *image)
1040 GHashTable *loaded_images, *loaded_images_guid;
1043 g_return_if_fail (image != NULL);
1045 if (InterlockedDecrement (&image->ref_count) > 0)
1048 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "Unloading image %s %p.", image->name, image);
1050 mono_images_lock ();
1051 loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1052 loaded_images_guid = image->ref_only ? loaded_images_refonly_guid_hash : loaded_images_guid_hash;
1053 image2 = g_hash_table_lookup (loaded_images, image->name);
1054 if (image == image2) {
1055 /* This is not true if we are called from mono_image_open () */
1056 g_hash_table_remove (loaded_images, image->name);
1057 g_hash_table_remove (loaded_images_guid, image->guid);
1058 /* Multiple images might have the same guid */
1059 build_guid_table (image->ref_only);
1061 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1062 g_hash_table_remove (loaded_images, (char *) image->assembly_name);
1063 mono_images_unlock ();
1065 if (image->file_descr) {
1066 fclose (image->file_descr);
1067 image->file_descr = NULL;
1068 if (image->raw_data != NULL)
1069 mono_raw_buffer_free (image->raw_data);
1072 if (image->raw_data_allocated) {
1073 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1074 MonoCLIImageInfo *ii = image->image_info;
1076 if ((image->raw_metadata > image->raw_data) &&
1077 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1078 image->raw_metadata = NULL;
1080 for (i = 0; i < ii->cli_section_count; i++)
1081 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1082 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1083 ii->cli_sections [i] = NULL;
1085 g_free (image->raw_data);
1087 g_free (image->name);
1088 g_free (image->guid);
1089 g_free (image->version);
1090 g_free (image->files);
1092 g_hash_table_destroy (image->method_cache);
1093 g_hash_table_destroy (image->class_cache);
1094 g_hash_table_destroy (image->field_cache);
1095 g_hash_table_destroy (image->array_cache);
1096 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1097 g_hash_table_destroy (image->name_cache);
1098 g_hash_table_destroy (image->native_wrapper_cache);
1099 g_hash_table_destroy (image->managed_wrapper_cache);
1100 g_hash_table_destroy (image->delegate_begin_invoke_cache);
1101 g_hash_table_destroy (image->delegate_end_invoke_cache);
1102 g_hash_table_destroy (image->delegate_invoke_cache);
1103 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1104 g_hash_table_destroy (image->remoting_invoke_cache);
1105 g_hash_table_destroy (image->runtime_invoke_cache);
1106 g_hash_table_destroy (image->synchronized_cache);
1107 g_hash_table_destroy (image->unbox_wrapper_cache);
1108 g_hash_table_destroy (image->typespec_cache);
1109 /* The ownership of signatures is not well defined */
1110 //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1111 g_hash_table_destroy (image->memberref_signatures);
1112 //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1113 g_hash_table_destroy (image->helper_signatures);
1115 if (image->interface_bitset) {
1116 mono_unload_interface_ids (image->interface_bitset);
1117 mono_bitset_free (image->interface_bitset);
1119 if (image->image_info){
1120 MonoCLIImageInfo *ii = image->image_info;
1122 if (ii->cli_section_tables)
1123 g_free (ii->cli_section_tables);
1124 if (ii->cli_sections)
1125 g_free (ii->cli_sections);
1126 g_free (image->image_info);
1129 for (i = 0; i < image->module_count; ++i) {
1130 if (image->modules [i])
1131 mono_image_close (image->modules [i]);
1133 /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1134 if (!image->dynamic) {
1135 mono_mempool_destroy (image->mempool);
1138 /* Dynamic images are GC_MALLOCed */
1139 struct _MonoDynamicImage *di = (struct _MonoDynamicImage*)image;
1141 g_free ((char*)image->module_name);
1143 g_hash_table_destroy (di->typespec);
1145 g_hash_table_destroy (di->typeref);
1147 g_hash_table_destroy (di->handleref);
1149 mono_g_hash_table_destroy (di->tokens);
1150 if (di->blob_cache) {
1151 g_hash_table_foreach (di->blob_cache, free_blob_cache_entry, NULL);
1152 g_hash_table_destroy (di->blob_cache);
1154 g_list_free (di->array_methods);
1156 g_ptr_array_free (di->gen_params, TRUE);
1157 if (di->token_fixups)
1158 mono_g_hash_table_destroy (di->token_fixups);
1159 if (di->method_to_table_idx)
1160 g_hash_table_destroy (di->method_to_table_idx);
1161 if (di->field_to_table_idx)
1162 g_hash_table_destroy (di->field_to_table_idx);
1163 if (di->method_aux_hash)
1164 g_hash_table_destroy (di->method_aux_hash);
1165 g_free (di->strong_name);
1166 g_free (di->win32_res);
1167 /*g_print ("string heap destroy for image %p\n", di);*/
1168 mono_dynamic_stream_reset (&di->sheap);
1169 mono_dynamic_stream_reset (&di->code);
1170 mono_dynamic_stream_reset (&di->resources);
1171 mono_dynamic_stream_reset (&di->us);
1172 mono_dynamic_stream_reset (&di->blob);
1173 mono_dynamic_stream_reset (&di->tstream);
1174 mono_dynamic_stream_reset (&di->guid);
1175 for (i = 0; i < MONO_TABLE_NUM; ++i) {
1176 g_free (di->tables [i].values);
1178 mono_mempool_destroy (image->mempool);
1183 * mono_image_strerror:
1184 * @status: an code indicating the result from a recent operation
1186 * Returns: a string describing the error
1189 mono_image_strerror (MonoImageOpenStatus status)
1194 case MONO_IMAGE_ERROR_ERRNO:
1195 return strerror (errno);
1196 case MONO_IMAGE_IMAGE_INVALID:
1197 return "File does not contain a valid CIL image";
1198 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1199 return "An assembly was referenced, but could not be found";
1201 return "Internal error";
1205 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1206 guint32 lang_id, gunichar2 *name,
1207 MonoPEResourceDirEntry *entry,
1208 MonoPEResourceDir *root, guint32 level)
1210 gboolean is_string=entry->name_is_string;
1212 /* Level 0 holds a directory entry for each type of resource
1213 * (identified by ID or name).
1215 * Level 1 holds a directory entry for each named resource
1216 * item, and each "anonymous" item of a particular type of
1219 * Level 2 holds a directory entry for each language pointing to
1224 if((is_string==FALSE && entry->name_offset!=res_id) ||
1225 (is_string==TRUE)) {
1228 } else if (level==1) {
1231 is_string==TRUE && name!=lookup (entry->name_offset)) {
1235 } else if (level==2) {
1236 if ((is_string == FALSE &&
1237 entry->name_offset != lang_id &&
1239 (is_string == TRUE)) {
1243 g_assert_not_reached ();
1246 if(entry->is_dir==TRUE) {
1247 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+entry->dir_offset);
1248 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1251 entries=res_dir->res_named_entries + res_dir->res_id_entries;
1253 for(i=0; i<entries; i++) {
1254 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1257 ret=mono_image_walk_resource_tree (info, res_id,
1268 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+entry->dir_offset);
1275 * mono_image_lookup_resource:
1276 * @image: the image to look up the resource in
1277 * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1278 * @lang_id: The language id.
1279 * @name: the resource name to lookup.
1281 * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1282 * of the given resource.
1285 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1287 MonoCLIImageInfo *info;
1288 MonoDotNetHeader *header;
1289 MonoPEDatadir *datadir;
1290 MonoPEDirEntry *rsrc;
1291 MonoPEResourceDir *resource_dir;
1292 MonoPEResourceDirEntry *res_entries;
1299 info=image->image_info;
1304 header=&info->cli_header;
1309 datadir=&header->datadir;
1314 rsrc=&datadir->pe_resource_table;
1319 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1320 if(resource_dir==NULL) {
1324 entries=resource_dir->res_named_entries + resource_dir->res_id_entries;
1325 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1327 for(i=0; i<entries; i++) {
1328 MonoPEResourceDirEntry *entry=&res_entries[i];
1331 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1332 name, entry, resource_dir,
1343 * mono_image_get_entry_point:
1344 * @image: the image where the entry point will be looked up.
1346 * Use this routine to determine the metadata token for method that
1347 * has been flagged as the entry point.
1349 * Returns: the token for the entry point method in the image
1352 mono_image_get_entry_point (MonoImage *image)
1354 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1358 * mono_image_get_resource:
1359 * @image: the image where the resource will be looked up.
1360 * @offset: The offset to add to the resource
1361 * @size: a pointer to an int where the size of the resource will be stored
1363 * This is a low-level routine that fetches a resource from the
1364 * metadata that starts at a given @offset. The @size parameter is
1365 * filled with the data field as encoded in the metadata.
1367 * Returns: the pointer to the resource whose offset is @offset.
1370 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1372 MonoCLIImageInfo *iinfo = image->image_info;
1373 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1376 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1379 data = mono_image_rva_map (image, ch->ch_resources.rva);
1384 *size = read32 (data);
1390 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1392 char *base_dir, *name;
1394 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1398 if (fileidx < 1 || fileidx > t->rows)
1401 if (image->files && image->files [fileidx - 1])
1402 return image->files [fileidx - 1];
1405 image->files = g_new0 (MonoImage*, t->rows);
1407 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1408 fname = mono_metadata_string_heap (image, fname_id);
1409 base_dir = g_path_get_dirname (image->name);
1410 name = g_build_filename (base_dir, fname, NULL);
1411 res = mono_image_open (name, NULL);
1414 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1415 res->assembly = image->assembly;
1416 for (i = 0; i < res->module_count; ++i) {
1417 if (res->modules [i] && !res->modules [i]->assembly)
1418 res->modules [i]->assembly = image->assembly;
1421 image->files [fileidx - 1] = res;
1429 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1431 MonoCLIImageInfo *iinfo = image->image_info;
1432 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1435 if (!de->size || !de->rva)
1437 data = mono_image_rva_map (image, de->rva);
1446 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1448 MonoCLIImageInfo *iinfo = image->image_info;
1449 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1450 const int top = iinfo->cli_section_count;
1451 MonoSectionTable *tables = iinfo->cli_section_tables;
1453 guint32 addr = de->rva;
1457 if (!de->size || !de->rva)
1459 for (i = 0; i < top; i++){
1460 if ((addr >= tables->st_virtual_address) &&
1461 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
1462 return tables->st_raw_data_ptr +
1463 (addr - tables->st_virtual_address);
1472 mono_image_get_public_key (MonoImage *image, guint32 *size)
1476 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1478 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1481 pubkey = mono_metadata_blob_heap (image, tok);
1482 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1489 mono_image_get_name (MonoImage *image)
1491 return image->assembly_name;
1495 mono_image_get_filename (MonoImage *image)
1501 mono_image_get_guid (MonoImage *image)
1506 const MonoTableInfo*
1507 mono_image_get_table_info (MonoImage *image, int table_id)
1509 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1511 return &image->tables [table_id];
1515 mono_image_get_table_rows (MonoImage *image, int table_id)
1517 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1519 return image->tables [table_id].rows;
1523 mono_table_info_get_rows (const MonoTableInfo *table)
1529 mono_image_get_assembly (MonoImage *image)
1531 return image->assembly;
1535 mono_image_is_dynamic (MonoImage *image)
1537 return image->dynamic;
1541 mono_image_has_authenticode_entry (MonoImage *image)
1543 MonoCLIImageInfo *iinfo = image->image_info;
1544 MonoDotNetHeader *header = &iinfo->cli_header;
1545 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
1546 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
1547 return ((de->rva != 0) && (de->size > 8));