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 <mono/utils/mono-path.h>
29 #include <sys/types.h>
33 #define INVALID_ADDRESS 0xffffffff
36 * Keeps track of the various assemblies loaded
38 static GHashTable *loaded_images_hash;
39 static GHashTable *loaded_images_guid_hash;
40 static GHashTable *loaded_images_refonly_hash;
41 static GHashTable *loaded_images_refonly_guid_hash;
43 static gboolean debug_assembly_unload = FALSE;
45 #define mono_images_lock() EnterCriticalSection (&images_mutex)
46 #define mono_images_unlock() LeaveCriticalSection (&images_mutex)
47 static CRITICAL_SECTION images_mutex;
50 mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
52 const int top = iinfo->cli_section_count;
53 MonoSectionTable *tables = iinfo->cli_section_tables;
56 for (i = 0; i < top; i++){
57 if ((addr >= tables->st_virtual_address) &&
58 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
59 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
63 return INVALID_ADDRESS;
67 mono_image_rva_map (MonoImage *image, guint32 addr)
69 MonoCLIImageInfo *iinfo = image->image_info;
70 const int top = iinfo->cli_section_count;
71 MonoSectionTable *tables = iinfo->cli_section_tables;
74 for (i = 0; i < top; i++){
75 if ((addr >= tables->st_virtual_address) &&
76 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
77 if (!iinfo->cli_sections [i]) {
78 if (!mono_image_ensure_section_idx (image, i))
81 return (char*)iinfo->cli_sections [i] +
82 (addr - tables->st_virtual_address);
92 * Initialize the global variables used by this module.
95 mono_images_init (void)
97 InitializeCriticalSection (&images_mutex);
99 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
100 loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
101 loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
102 loaded_images_refonly_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
104 debug_assembly_unload = getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
108 * mono_images_cleanup:
110 * Free all resources used by this module.
113 mono_images_cleanup (void)
115 DeleteCriticalSection (&images_mutex);
117 g_hash_table_destroy (loaded_images_hash);
118 g_hash_table_destroy (loaded_images_guid_hash);
119 g_hash_table_destroy (loaded_images_refonly_hash);
120 g_hash_table_destroy (loaded_images_refonly_guid_hash);
124 * mono_image_ensure_section_idx:
125 * @image: The image we are operating on
126 * @section: section number that we will load/map into memory
128 * This routine makes sure that we have an in-memory copy of
129 * an image section (.text, .rsrc, .data).
131 * Returns: TRUE on success
134 mono_image_ensure_section_idx (MonoImage *image, int section)
136 MonoCLIImageInfo *iinfo = image->image_info;
137 MonoSectionTable *sect;
140 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
142 if (iinfo->cli_sections [section] != NULL)
145 sect = &iinfo->cli_section_tables [section];
147 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
149 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
151 /* FIXME: we ignore the writable flag since we don't patch the binary */
152 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
157 * mono_image_ensure_section:
158 * @image: The image we are operating on
159 * @section: section name that we will load/map into memory
161 * This routine makes sure that we have an in-memory copy of
162 * an image section (.text, .rsrc, .data).
164 * Returns: TRUE on success
167 mono_image_ensure_section (MonoImage *image, const char *section)
169 MonoCLIImageInfo *ii = image->image_info;
172 for (i = 0; i < ii->cli_section_count; i++){
173 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
176 return mono_image_ensure_section_idx (image, i);
182 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
184 const int top = iinfo->cli_header.coff.coff_sections;
187 iinfo->cli_section_count = top;
188 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
189 iinfo->cli_sections = g_new0 (void *, top);
191 for (i = 0; i < top; i++){
192 MonoSectionTable *t = &iinfo->cli_section_tables [i];
194 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
196 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
197 offset += sizeof (MonoSectionTable);
199 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
200 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
201 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
202 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
203 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
204 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
205 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
206 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
207 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
208 t->st_flags = GUINT32_FROM_LE (t->st_flags);
210 /* consistency checks here */
217 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
221 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
222 if (offset == INVALID_ADDRESS)
225 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
227 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
229 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
230 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
231 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
232 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
233 SWAP32 (iinfo->cli_cli_header.ch_size);
234 SWAP32 (iinfo->cli_cli_header.ch_flags);
235 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
236 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
237 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
238 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
239 SWAPPDE (iinfo->cli_cli_header.ch_resources);
240 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
241 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
242 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
243 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
244 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
245 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
246 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
247 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
248 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
249 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
250 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
251 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
252 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
257 /* Catch new uses of the fields that are supposed to be zero */
259 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
260 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
261 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
262 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
263 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
264 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
265 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
266 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
267 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
270 * No need to scare people who are testing this, I am just
271 * labelling this as a LAMESPEC
273 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
281 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
283 guint32 offset, size;
289 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
290 if (offset == INVALID_ADDRESS)
293 size = iinfo->cli_cli_header.ch_metadata.size;
295 if (offset + size > image->raw_data_len)
297 image->raw_metadata = image->raw_data + offset;
299 ptr = image->raw_metadata;
301 if (strncmp (ptr, "BSJB", 4) == 0){
302 guint32 version_string_len;
305 image->md_version_major = read16 (ptr);
307 image->md_version_minor = read16 (ptr);
310 version_string_len = read32 (ptr);
312 image->version = g_strndup (ptr, version_string_len);
313 ptr += version_string_len;
314 pad = ptr - image->raw_metadata;
316 ptr += 4 - (pad % 4);
320 /* skip over flags */
323 streams = read16 (ptr);
326 for (i = 0; i < streams; i++){
327 if (strncmp (ptr + 8, "#~", 3) == 0){
328 image->heap_tables.data = image->raw_metadata + read32 (ptr);
329 image->heap_tables.size = read32 (ptr + 4);
331 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
332 image->heap_strings.data = image->raw_metadata + read32 (ptr);
333 image->heap_strings.size = read32 (ptr + 4);
335 } else if (strncmp (ptr + 8, "#US", 4) == 0){
336 image->heap_us.data = image->raw_metadata + read32 (ptr);
337 image->heap_us.size = read32 (ptr + 4);
339 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
340 image->heap_blob.data = image->raw_metadata + read32 (ptr);
341 image->heap_blob.size = read32 (ptr + 4);
343 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
344 image->heap_guid.data = image->raw_metadata + read32 (ptr);
345 image->heap_guid.size = read32 (ptr + 4);
347 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
348 g_print ("Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name);
351 g_message ("Unknown heap type: %s\n", ptr + 8);
352 ptr += 8 + strlen (ptr + 8) + 1;
354 pad = ptr - image->raw_metadata;
356 ptr += 4 - (pad % 4);
359 g_assert (image->heap_guid.data);
360 g_assert (image->heap_guid.size >= 16);
362 image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
368 * Load representation of logical metadata tables, from the "#~" stream
371 load_tables (MonoImage *image)
373 const char *heap_tables = image->heap_tables.data;
375 guint64 valid_mask, sorted_mask;
376 int valid = 0, table;
379 heap_sizes = heap_tables [6];
380 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
381 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
382 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
384 valid_mask = read64 (heap_tables + 8);
385 sorted_mask = read64 (heap_tables + 16);
386 rows = (const guint32 *) (heap_tables + 24);
388 for (table = 0; table < 64; table++){
389 if ((valid_mask & ((guint64) 1 << table)) == 0){
390 if (table > MONO_TABLE_LAST)
392 image->tables [table].rows = 0;
395 if (table > MONO_TABLE_LAST) {
396 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
398 image->tables [table].rows = read32 (rows);
400 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
401 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
407 image->tables_base = (heap_tables + 24) + (4 * valid);
409 /* They must be the same */
410 g_assert ((const void *) image->tables_base == (const void *) rows);
412 mono_metadata_compute_table_bases (image);
417 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
419 if (!load_metadata_ptrs (image, iinfo))
422 return load_tables (image);
426 load_modules (MonoImage *image, MonoImageOpenStatus *status)
429 MonoTableInfo *file_table;
432 gboolean refonly = image->ref_only;
433 GList *list_iter, *valid_modules = NULL;
438 file_table = &image->tables [MONO_TABLE_FILE];
439 for (i = 0; i < file_table->rows; i++) {
440 guint32 cols [MONO_FILE_SIZE];
441 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
442 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
444 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
447 t = &image->tables [MONO_TABLE_MODULEREF];
448 image->modules = g_new0 (MonoImage *, t->rows);
449 image->module_count = t->rows;
450 base_dir = g_path_get_dirname (image->name);
451 for (i = 0; i < t->rows; i++){
454 guint32 cols [MONO_MODULEREF_SIZE];
457 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
458 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
459 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
460 /* be safe with string dups, but we could just compare string indexes */
461 if (strcmp (list_iter->data, name) == 0) {
468 module_ref = g_build_filename (base_dir, name, NULL);
469 image->modules [i] = mono_image_open_full (module_ref, status, refonly);
470 if (image->modules [i]) {
471 mono_image_addref (image->modules [i]);
472 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
475 * FIXME: We should probably do lazy-loading of modules.
478 *status = MONO_IMAGE_OK;
483 g_list_free (valid_modules);
487 register_guid (gpointer key, gpointer value, gpointer user_data)
489 MonoImage *image = (MonoImage*)value;
491 if (!g_hash_table_lookup (loaded_images_guid_hash, image))
492 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
496 build_guid_table (gboolean refonly)
498 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
499 g_hash_table_foreach (loaded_images, register_guid, NULL);
503 mono_image_init (MonoImage *image)
505 image->mempool = mono_mempool_new ();
506 image->method_cache = g_hash_table_new (NULL, NULL);
507 image->class_cache = g_hash_table_new (NULL, NULL);
508 image->field_cache = g_hash_table_new (NULL, NULL);
510 image->delegate_begin_invoke_cache =
511 g_hash_table_new ((GHashFunc)mono_signature_hash,
512 (GCompareFunc)mono_metadata_signature_equal);
513 image->delegate_end_invoke_cache =
514 g_hash_table_new ((GHashFunc)mono_signature_hash,
515 (GCompareFunc)mono_metadata_signature_equal);
516 image->delegate_invoke_cache =
517 g_hash_table_new ((GHashFunc)mono_signature_hash,
518 (GCompareFunc)mono_metadata_signature_equal);
519 image->runtime_invoke_cache =
520 g_hash_table_new ((GHashFunc)mono_signature_hash,
521 (GCompareFunc)mono_metadata_signature_equal);
523 image->managed_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
524 image->native_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
525 image->remoting_invoke_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
526 image->cominterop_invoke_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
527 image->cominterop_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
528 image->synchronized_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
529 image->unbox_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
531 image->ldfld_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
532 image->ldflda_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
533 image->ldfld_remote_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
534 image->stfld_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
535 image->stfld_remote_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
536 image->isinst_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
537 image->castclass_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
538 image->proxy_isinst_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
540 image->typespec_cache = g_hash_table_new (NULL, NULL);
541 image->memberref_signatures = g_hash_table_new (NULL, NULL);
542 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
543 image->method_signatures = g_hash_table_new (NULL, NULL);
547 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
548 gboolean care_about_cli)
550 MonoCLIImageInfo *iinfo;
551 MonoDotNetHeader *header;
552 MonoMSDOSHeader msdos;
555 mono_image_init (image);
557 iinfo = image->image_info;
558 header = &iinfo->cli_header;
561 *status = MONO_IMAGE_IMAGE_INVALID;
563 if (offset + sizeof (msdos) > image->raw_data_len)
565 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
567 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
570 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
572 offset = msdos.pe_offset;
574 if (offset + sizeof (MonoDotNetHeader) > image->raw_data_len)
576 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
577 offset += sizeof (MonoDotNetHeader);
579 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
580 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
581 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
582 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
583 SWAP32 (header->coff.coff_time);
584 SWAP32 (header->coff.coff_symptr);
585 SWAP32 (header->coff.coff_symcount);
586 SWAP16 (header->coff.coff_machine);
587 SWAP16 (header->coff.coff_sections);
588 SWAP16 (header->coff.coff_opt_header_size);
589 SWAP16 (header->coff.coff_attributes);
591 SWAP32 (header->pe.pe_code_size);
592 SWAP32 (header->pe.pe_data_size);
593 SWAP32 (header->pe.pe_uninit_data_size);
594 SWAP32 (header->pe.pe_rva_entry_point);
595 SWAP32 (header->pe.pe_rva_code_base);
596 SWAP32 (header->pe.pe_rva_data_base);
597 SWAP16 (header->pe.pe_magic);
599 /* MonoPEHeaderNT: not used yet */
600 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
601 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
602 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
603 SWAP16 (header->nt.pe_os_major); /* must be 4 */
604 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
605 SWAP16 (header->nt.pe_user_major);
606 SWAP16 (header->nt.pe_user_minor);
607 SWAP16 (header->nt.pe_subsys_major);
608 SWAP16 (header->nt.pe_subsys_minor);
609 SWAP32 (header->nt.pe_reserved_1);
610 SWAP32 (header->nt.pe_image_size);
611 SWAP32 (header->nt.pe_header_size);
612 SWAP32 (header->nt.pe_checksum);
613 SWAP16 (header->nt.pe_subsys_required);
614 SWAP16 (header->nt.pe_dll_flags);
615 SWAP32 (header->nt.pe_stack_reserve);
616 SWAP32 (header->nt.pe_stack_commit);
617 SWAP32 (header->nt.pe_heap_reserve);
618 SWAP32 (header->nt.pe_heap_commit);
619 SWAP32 (header->nt.pe_loader_flags);
620 SWAP32 (header->nt.pe_data_dir_count);
622 /* MonoDotNetHeader: mostly unused */
623 SWAPPDE (header->datadir.pe_export_table);
624 SWAPPDE (header->datadir.pe_import_table);
625 SWAPPDE (header->datadir.pe_resource_table);
626 SWAPPDE (header->datadir.pe_exception_table);
627 SWAPPDE (header->datadir.pe_certificate_table);
628 SWAPPDE (header->datadir.pe_reloc_table);
629 SWAPPDE (header->datadir.pe_debug);
630 SWAPPDE (header->datadir.pe_copyright);
631 SWAPPDE (header->datadir.pe_global_ptr);
632 SWAPPDE (header->datadir.pe_tls_table);
633 SWAPPDE (header->datadir.pe_load_config_table);
634 SWAPPDE (header->datadir.pe_bound_import);
635 SWAPPDE (header->datadir.pe_iat);
636 SWAPPDE (header->datadir.pe_delay_import_desc);
637 SWAPPDE (header->datadir.pe_cli_header);
638 SWAPPDE (header->datadir.pe_reserved);
645 if (header->coff.coff_machine != 0x14c)
648 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
651 if (header->pesig[0] != 'P' || header->pesig[1] != 'E' || header->pe.pe_magic != 0x10B)
656 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
657 * which produces binaries with 7.0. From Sergey:
659 * The reason is that MSVC7 uses traditional compile/link
660 * sequence for CIL executables, and VS.NET (and Framework
661 * SDK) includes linker version 7, that puts 7.0 in this
662 * field. That's why it's currently not possible to load VC
663 * binaries with Mono. This field is pretty much meaningless
664 * anyway (what linker?).
666 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
671 * FIXME: byte swap all addresses here for header.
674 if (!load_section_tables (image, iinfo, offset))
677 if (care_about_cli == FALSE) {
681 /* Load the CLI header */
682 if (!load_cli_header (image, iinfo))
685 if (!load_metadata (image, iinfo))
688 /* modules don't have an assembly table row */
689 if (image->tables [MONO_TABLE_ASSEMBLY].rows)
690 image->assembly_name = mono_metadata_string_heap (image,
691 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
692 0, MONO_ASSEMBLY_NAME));
694 image->module_name = mono_metadata_string_heap (image,
695 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
696 0, MONO_MODULE_NAME));
698 load_modules (image, status);
702 *status = MONO_IMAGE_OK;
707 mono_image_close (image);
712 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
713 gboolean care_about_cli, gboolean refonly)
715 MonoCLIImageInfo *iinfo;
718 struct stat stat_buf;
720 if ((filed = fopen (fname, "rb")) == NULL){
722 *status = MONO_IMAGE_ERROR_ERRNO;
726 if (fstat (fileno (filed), &stat_buf)) {
729 *status = MONO_IMAGE_ERROR_ERRNO;
732 image = g_new0 (MonoImage, 1);
733 image->file_descr = filed;
734 image->raw_data_len = stat_buf.st_size;
735 image->raw_data = mono_raw_buffer_load (fileno (filed), FALSE, 0, stat_buf.st_size);
736 iinfo = g_new0 (MonoCLIImageInfo, 1);
737 image->image_info = iinfo;
738 image->name = mono_path_resolve_symlinks (fname);
739 image->ref_only = refonly;
740 image->ref_count = 1;
742 return do_mono_image_load (image, status, care_about_cli);
746 mono_image_loaded_full (const char *name, gboolean refonly)
749 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
752 res = g_hash_table_lookup (loaded_images, name);
753 mono_images_unlock ();
758 mono_image_loaded (const char *name)
760 return mono_image_loaded_full (name, FALSE);
764 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
767 GHashTable *loaded_images = refonly ? loaded_images_refonly_guid_hash : loaded_images_guid_hash;
770 res = g_hash_table_lookup (loaded_images, guid);
771 mono_images_unlock ();
776 mono_image_loaded_by_guid (const char *guid)
778 return mono_image_loaded_by_guid_full (guid, FALSE);
782 register_image (MonoImage *image)
785 GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
788 image2 = g_hash_table_lookup (loaded_images, image->name);
791 /* Somebody else beat us to it */
792 mono_image_addref (image2);
793 mono_images_unlock ();
794 mono_image_close (image);
797 g_hash_table_insert (loaded_images, image->name, image);
798 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
799 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);
800 g_hash_table_insert (image->ref_only ? loaded_images_refonly_guid_hash : loaded_images_guid_hash, image->guid, image);
801 mono_images_unlock ();
807 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
809 MonoCLIImageInfo *iinfo;
813 if (!data || !data_len) {
815 *status = MONO_IMAGE_IMAGE_INVALID;
820 datac = g_try_malloc (data_len);
823 *status = MONO_IMAGE_ERROR_ERRNO;
826 memcpy (datac, data, data_len);
829 image = g_new0 (MonoImage, 1);
830 image->raw_data = datac;
831 image->raw_data_len = data_len;
832 image->raw_data_allocated = need_copy;
833 image->name = g_strdup_printf ("data-%p", datac);
834 iinfo = g_new0 (MonoCLIImageInfo, 1);
835 image->image_info = iinfo;
836 image->ref_only = refonly;
838 image = do_mono_image_load (image, status, TRUE);
842 return register_image (image);
846 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
848 return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
852 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
855 GHashTable *loaded_images;
858 g_return_val_if_fail (fname != NULL, NULL);
860 absfname = mono_path_canonicalize (fname);
863 * The easiest solution would be to do all the loading inside the mutex,
864 * but that would lead to scalability problems. So we let the loading
865 * happen outside the mutex, and if multiple threads happen to load
866 * the same image, we discard all but the first copy.
869 loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
870 image = g_hash_table_lookup (loaded_images, absfname);
874 mono_image_addref (image);
875 mono_images_unlock ();
878 mono_images_unlock ();
880 image = do_mono_image_open (fname, status, TRUE, refonly);
884 return register_image (image);
889 * @fname: filename that points to the module we want to open
890 * @status: An error condition is returned in this field
892 * Returns: An open image of type %MonoImage or NULL on error.
893 * The caller holds a temporary reference to the returned image which should be cleared
894 * when no longer needed by calling mono_image_close ().
895 * if NULL, then check the value of @status for details on the error
898 mono_image_open (const char *fname, MonoImageOpenStatus *status)
900 return mono_image_open_full (fname, status, FALSE);
905 * @fname: filename that points to the module we want to open
906 * @status: An error condition is returned in this field
908 * Returns: An open image of type %MonoImage or NULL on error. if
909 * NULL, then check the value of @status for details on the error.
910 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
911 * It's just a PE file loader, used for FileVersionInfo. It also does
912 * not use the image cache.
915 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
917 g_return_val_if_fail (fname != NULL, NULL);
919 return(do_mono_image_open (fname, status, FALSE, FALSE));
923 free_hash_table (gpointer key, gpointer val, gpointer user_data)
925 g_hash_table_destroy ((GHashTable*)val);
930 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
932 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
937 free_blob_cache_entry (gpointer key, gpointer val, gpointer user_data)
943 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
949 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
951 g_slist_free ((GSList*)val);
956 * @image: The image file we wish to add a reference to
958 * Increases the reference count of an image.
961 mono_image_addref (MonoImage *image)
963 InterlockedIncrement (&image->ref_count);
967 mono_dynamic_stream_reset (MonoDynamicStream* stream)
969 stream->alloc_size = stream->index = stream->offset = 0;
970 g_free (stream->data);
973 g_hash_table_destroy (stream->hash);
980 * @image: The image file we wish to close
982 * Closes an image file, deallocates all memory consumed and
983 * unmaps all possible sections of the file
986 mono_image_close (MonoImage *image)
989 GHashTable *loaded_images, *loaded_images_guid;
992 g_return_if_fail (image != NULL);
994 if (InterlockedDecrement (&image->ref_count) > 0)
997 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1000 loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1001 loaded_images_guid = image->ref_only ? loaded_images_refonly_guid_hash : loaded_images_guid_hash;
1002 image2 = g_hash_table_lookup (loaded_images, image->name);
1003 if (image == image2) {
1004 /* This is not true if we are called from mono_image_open () */
1005 g_hash_table_remove (loaded_images, image->name);
1006 g_hash_table_remove (loaded_images_guid, image->guid);
1008 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1009 g_hash_table_remove (loaded_images, (char *) image->assembly_name);
1011 /* Multiple images might have the same guid */
1012 build_guid_table (image->ref_only);
1014 mono_images_unlock ();
1016 if (image->file_descr) {
1017 fclose (image->file_descr);
1018 image->file_descr = NULL;
1019 if (image->raw_data != NULL)
1020 mono_raw_buffer_free (image->raw_data);
1023 if (image->raw_data_allocated) {
1024 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1025 MonoCLIImageInfo *ii = image->image_info;
1027 if ((image->raw_metadata > image->raw_data) &&
1028 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1029 image->raw_metadata = NULL;
1031 for (i = 0; i < ii->cli_section_count; i++)
1032 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1033 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1034 ii->cli_sections [i] = NULL;
1036 g_free (image->raw_data);
1039 if (debug_assembly_unload) {
1040 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1042 g_free (image->name);
1043 g_free (image->guid);
1044 g_free (image->version);
1045 g_free (image->files);
1048 g_hash_table_destroy (image->method_cache);
1049 g_hash_table_destroy (image->class_cache);
1050 g_hash_table_destroy (image->field_cache);
1051 if (image->array_cache) {
1052 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1053 g_hash_table_destroy (image->array_cache);
1055 if (image->ptr_cache)
1056 g_hash_table_destroy (image->ptr_cache);
1057 if (image->name_cache) {
1058 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1059 g_hash_table_destroy (image->name_cache);
1061 g_hash_table_destroy (image->native_wrapper_cache);
1062 g_hash_table_destroy (image->managed_wrapper_cache);
1063 g_hash_table_destroy (image->delegate_begin_invoke_cache);
1064 g_hash_table_destroy (image->delegate_end_invoke_cache);
1065 g_hash_table_destroy (image->delegate_invoke_cache);
1066 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1067 g_hash_table_destroy (image->remoting_invoke_cache);
1068 g_hash_table_destroy (image->runtime_invoke_cache);
1069 g_hash_table_destroy (image->synchronized_cache);
1070 g_hash_table_destroy (image->unbox_wrapper_cache);
1071 g_hash_table_destroy (image->cominterop_invoke_cache);
1072 g_hash_table_destroy (image->cominterop_wrapper_cache);
1073 g_hash_table_destroy (image->typespec_cache);
1074 g_hash_table_destroy (image->ldfld_wrapper_cache);
1075 g_hash_table_destroy (image->ldflda_wrapper_cache);
1076 g_hash_table_destroy (image->ldfld_remote_wrapper_cache);
1077 g_hash_table_destroy (image->stfld_wrapper_cache);
1078 g_hash_table_destroy (image->stfld_remote_wrapper_cache);
1079 g_hash_table_destroy (image->isinst_cache);
1080 g_hash_table_destroy (image->castclass_cache);
1081 g_hash_table_destroy (image->proxy_isinst_cache);
1083 /* The ownership of signatures is not well defined */
1084 //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1085 g_hash_table_destroy (image->memberref_signatures);
1086 //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1087 g_hash_table_destroy (image->helper_signatures);
1088 g_hash_table_destroy (image->method_signatures);
1090 if (image->interface_bitset) {
1091 mono_unload_interface_ids (image->interface_bitset);
1092 mono_bitset_free (image->interface_bitset);
1094 if (image->image_info){
1095 MonoCLIImageInfo *ii = image->image_info;
1097 if (ii->cli_section_tables)
1098 g_free (ii->cli_section_tables);
1099 if (ii->cli_sections)
1100 g_free (ii->cli_sections);
1101 g_free (image->image_info);
1104 for (i = 0; i < image->module_count; ++i) {
1105 if (image->modules [i])
1106 mono_image_close (image->modules [i]);
1109 g_free (image->modules);
1110 if (image->references)
1111 g_free (image->references);
1112 /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1113 if (!image->dynamic) {
1114 if (debug_assembly_unload)
1115 mono_mempool_invalidate (image->mempool);
1117 mono_mempool_destroy (image->mempool);
1121 /* Dynamic images are GC_MALLOCed */
1122 struct _MonoDynamicImage *di = (struct _MonoDynamicImage*)image;
1124 g_free ((char*)image->module_name);
1126 g_hash_table_destroy (di->typespec);
1128 g_hash_table_destroy (di->typeref);
1130 g_hash_table_destroy (di->handleref);
1132 mono_g_hash_table_destroy (di->tokens);
1133 if (di->blob_cache) {
1134 g_hash_table_foreach (di->blob_cache, free_blob_cache_entry, NULL);
1135 g_hash_table_destroy (di->blob_cache);
1137 g_list_free (di->array_methods);
1139 g_ptr_array_free (di->gen_params, TRUE);
1140 if (di->token_fixups)
1141 mono_g_hash_table_destroy (di->token_fixups);
1142 if (di->method_to_table_idx)
1143 g_hash_table_destroy (di->method_to_table_idx);
1144 if (di->field_to_table_idx)
1145 g_hash_table_destroy (di->field_to_table_idx);
1146 if (di->method_aux_hash)
1147 g_hash_table_destroy (di->method_aux_hash);
1148 g_free (di->strong_name);
1149 g_free (di->win32_res);
1150 /*g_print ("string heap destroy for image %p\n", di);*/
1151 mono_dynamic_stream_reset (&di->sheap);
1152 mono_dynamic_stream_reset (&di->code);
1153 mono_dynamic_stream_reset (&di->resources);
1154 mono_dynamic_stream_reset (&di->us);
1155 mono_dynamic_stream_reset (&di->blob);
1156 mono_dynamic_stream_reset (&di->tstream);
1157 mono_dynamic_stream_reset (&di->guid);
1158 for (i = 0; i < MONO_TABLE_NUM; ++i) {
1159 g_free (di->tables [i].values);
1161 mono_mempool_destroy (image->mempool);
1166 * mono_image_strerror:
1167 * @status: an code indicating the result from a recent operation
1169 * Returns: a string describing the error
1172 mono_image_strerror (MonoImageOpenStatus status)
1177 case MONO_IMAGE_ERROR_ERRNO:
1178 return strerror (errno);
1179 case MONO_IMAGE_IMAGE_INVALID:
1180 return "File does not contain a valid CIL image";
1181 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1182 return "An assembly was referenced, but could not be found";
1184 return "Internal error";
1188 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1189 guint32 lang_id, gunichar2 *name,
1190 MonoPEResourceDirEntry *entry,
1191 MonoPEResourceDir *root, guint32 level)
1193 gboolean is_string=entry->name_is_string;
1195 /* Level 0 holds a directory entry for each type of resource
1196 * (identified by ID or name).
1198 * Level 1 holds a directory entry for each named resource
1199 * item, and each "anonymous" item of a particular type of
1202 * Level 2 holds a directory entry for each language pointing to
1207 if((is_string==FALSE && entry->name_offset!=res_id) ||
1208 (is_string==TRUE)) {
1211 } else if (level==1) {
1214 is_string==TRUE && name!=lookup (entry->name_offset)) {
1218 } else if (level==2) {
1219 if ((is_string == FALSE &&
1220 entry->name_offset != lang_id &&
1222 (is_string == TRUE)) {
1226 g_assert_not_reached ();
1229 if(entry->is_dir==TRUE) {
1230 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+entry->dir_offset);
1231 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1234 entries=res_dir->res_named_entries + res_dir->res_id_entries;
1236 for(i=0; i<entries; i++) {
1237 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1240 ret=mono_image_walk_resource_tree (info, res_id,
1251 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+entry->dir_offset);
1258 * mono_image_lookup_resource:
1259 * @image: the image to look up the resource in
1260 * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1261 * @lang_id: The language id.
1262 * @name: the resource name to lookup.
1264 * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1265 * of the given resource.
1268 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1270 MonoCLIImageInfo *info;
1271 MonoDotNetHeader *header;
1272 MonoPEDatadir *datadir;
1273 MonoPEDirEntry *rsrc;
1274 MonoPEResourceDir *resource_dir;
1275 MonoPEResourceDirEntry *res_entries;
1282 info=image->image_info;
1287 header=&info->cli_header;
1292 datadir=&header->datadir;
1297 rsrc=&datadir->pe_resource_table;
1302 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1303 if(resource_dir==NULL) {
1307 entries=resource_dir->res_named_entries + resource_dir->res_id_entries;
1308 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1310 for(i=0; i<entries; i++) {
1311 MonoPEResourceDirEntry *entry=&res_entries[i];
1314 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1315 name, entry, resource_dir,
1326 * mono_image_get_entry_point:
1327 * @image: the image where the entry point will be looked up.
1329 * Use this routine to determine the metadata token for method that
1330 * has been flagged as the entry point.
1332 * Returns: the token for the entry point method in the image
1335 mono_image_get_entry_point (MonoImage *image)
1337 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1341 * mono_image_get_resource:
1342 * @image: the image where the resource will be looked up.
1343 * @offset: The offset to add to the resource
1344 * @size: a pointer to an int where the size of the resource will be stored
1346 * This is a low-level routine that fetches a resource from the
1347 * metadata that starts at a given @offset. The @size parameter is
1348 * filled with the data field as encoded in the metadata.
1350 * Returns: the pointer to the resource whose offset is @offset.
1353 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1355 MonoCLIImageInfo *iinfo = image->image_info;
1356 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1359 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1362 data = mono_image_rva_map (image, ch->ch_resources.rva);
1367 *size = read32 (data);
1373 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1375 char *base_dir, *name;
1377 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1381 if (fileidx < 1 || fileidx > t->rows)
1384 if (image->files && image->files [fileidx - 1])
1385 return image->files [fileidx - 1];
1388 image->files = g_new0 (MonoImage*, t->rows);
1390 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1391 fname = mono_metadata_string_heap (image, fname_id);
1392 base_dir = g_path_get_dirname (image->name);
1393 name = g_build_filename (base_dir, fname, NULL);
1394 res = mono_image_open (name, NULL);
1397 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1398 res->assembly = image->assembly;
1399 for (i = 0; i < res->module_count; ++i) {
1400 if (res->modules [i] && !res->modules [i]->assembly)
1401 res->modules [i]->assembly = image->assembly;
1404 image->files [fileidx - 1] = res;
1412 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1414 MonoCLIImageInfo *iinfo = image->image_info;
1415 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1418 if (!de->size || !de->rva)
1420 data = mono_image_rva_map (image, de->rva);
1429 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1431 MonoCLIImageInfo *iinfo = image->image_info;
1432 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1433 const int top = iinfo->cli_section_count;
1434 MonoSectionTable *tables = iinfo->cli_section_tables;
1436 guint32 addr = de->rva;
1440 if (!de->size || !de->rva)
1442 for (i = 0; i < top; i++){
1443 if ((addr >= tables->st_virtual_address) &&
1444 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
1445 return tables->st_raw_data_ptr +
1446 (addr - tables->st_virtual_address);
1455 mono_image_get_public_key (MonoImage *image, guint32 *size)
1459 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1461 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1464 pubkey = mono_metadata_blob_heap (image, tok);
1465 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1472 mono_image_get_name (MonoImage *image)
1474 return image->assembly_name;
1478 mono_image_get_filename (MonoImage *image)
1484 mono_image_get_guid (MonoImage *image)
1489 const MonoTableInfo*
1490 mono_image_get_table_info (MonoImage *image, int table_id)
1492 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1494 return &image->tables [table_id];
1498 mono_image_get_table_rows (MonoImage *image, int table_id)
1500 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1502 return image->tables [table_id].rows;
1506 mono_table_info_get_rows (const MonoTableInfo *table)
1512 mono_image_get_assembly (MonoImage *image)
1514 return image->assembly;
1518 mono_image_is_dynamic (MonoImage *image)
1520 return image->dynamic;
1524 mono_image_has_authenticode_entry (MonoImage *image)
1526 MonoCLIImageInfo *iinfo = image->image_info;
1527 MonoDotNetHeader *header = &iinfo->cli_header;
1528 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
1529 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
1530 return ((de->rva != 0) && (de->size > 8));