2009-03-11 Zoltan Varga <vargaz@gmail.com>
[mono-debugger.git] / mono / metadata / image.c
blobd6a479d814ae3d8a91c7b7338fd6ca441eb24a8b
1 /*
2 * image.c: Routines for manipulating an image stored in an
3 * extended PE/COFF file.
4 *
5 * Authors:
6 * Miguel de Icaza (miguel@ximian.com)
7 * Paolo Molaro (lupus@ximian.com)
9 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
13 #include <config.h>
14 #include <stdio.h>
15 #include <glib.h>
16 #include <errno.h>
17 #include <time.h>
18 #include <string.h>
19 #include "image.h"
20 #include "cil-coff.h"
21 #include "mono-endian.h"
22 #include "tabledefs.h"
23 #include "tokentype.h"
24 #include "metadata-internals.h"
25 #include "profiler-private.h"
26 #include "loader.h"
27 #include "marshal.h"
28 #include "coree.h"
29 #include <mono/io-layer/io-layer.h>
30 #include <mono/utils/mono-logger.h>
31 #include <mono/utils/mono-path.h>
32 #include <mono/utils/mono-mmap.h>
33 #include <mono/utils/mono-io-portability.h>
34 #include <mono/metadata/class-internals.h>
35 #include <mono/metadata/assembly.h>
36 #include <mono/metadata/object-internals.h>
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #ifdef HAVE_UNISTD_H
40 #include <unistd.h>
41 #endif
43 #define INVALID_ADDRESS 0xffffffff
46 * Keeps track of the various assemblies loaded
48 static GHashTable *loaded_images_hash;
49 static GHashTable *loaded_images_refonly_hash;
51 static gboolean debug_assembly_unload = FALSE;
53 #define mono_images_lock() EnterCriticalSection (&images_mutex)
54 #define mono_images_unlock() LeaveCriticalSection (&images_mutex)
55 static CRITICAL_SECTION images_mutex;
57 /* returns offset relative to image->raw_data */
58 guint32
59 mono_cli_rva_image_map (MonoImage *image, guint32 addr)
61 MonoCLIImageInfo *iinfo = image->image_info;
62 const int top = iinfo->cli_section_count;
63 MonoSectionTable *tables = iinfo->cli_section_tables;
64 int i;
66 for (i = 0; i < top; i++){
67 if ((addr >= tables->st_virtual_address) &&
68 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
69 #ifdef PLATFORM_WIN32
70 if (image->is_module_handle)
71 return addr;
72 #endif
73 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
75 tables++;
77 return INVALID_ADDRESS;
80 /**
81 * mono_images_rva_map:
82 * @image: a MonoImage
83 * @addr: relative virtual address (RVA)
85 * This is a low-level routine used by the runtime to map relative
86 * virtual address (RVA) into their location in memory.
88 * Returns: the address in memory for the given RVA, or NULL if the
89 * RVA is not valid for this image.
91 char *
92 mono_image_rva_map (MonoImage *image, guint32 addr)
94 MonoCLIImageInfo *iinfo = image->image_info;
95 const int top = iinfo->cli_section_count;
96 MonoSectionTable *tables = iinfo->cli_section_tables;
97 int i;
99 for (i = 0; i < top; i++){
100 if ((addr >= tables->st_virtual_address) &&
101 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
102 if (!iinfo->cli_sections [i]) {
103 if (!mono_image_ensure_section_idx (image, i))
104 return NULL;
106 #ifdef PLATFORM_WIN32
107 if (image->is_module_handle)
108 return image->raw_data + addr;
109 #endif
110 return (char*)iinfo->cli_sections [i] +
111 (addr - tables->st_virtual_address);
113 tables++;
115 return NULL;
119 * mono_images_init:
121 * Initialize the global variables used by this module.
123 void
124 mono_images_init (void)
126 InitializeCriticalSection (&images_mutex);
128 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
129 loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
131 debug_assembly_unload = getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
135 * mono_images_cleanup:
137 * Free all resources used by this module.
139 void
140 mono_images_cleanup (void)
142 DeleteCriticalSection (&images_mutex);
144 g_hash_table_destroy (loaded_images_hash);
145 g_hash_table_destroy (loaded_images_refonly_hash);
149 * mono_image_ensure_section_idx:
150 * @image: The image we are operating on
151 * @section: section number that we will load/map into memory
153 * This routine makes sure that we have an in-memory copy of
154 * an image section (.text, .rsrc, .data).
156 * Returns: TRUE on success
159 mono_image_ensure_section_idx (MonoImage *image, int section)
161 MonoCLIImageInfo *iinfo = image->image_info;
162 MonoSectionTable *sect;
163 gboolean writable;
165 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
167 if (iinfo->cli_sections [section] != NULL)
168 return TRUE;
170 sect = &iinfo->cli_section_tables [section];
172 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
174 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
175 return FALSE;
176 #ifdef PLATFORM_WIN32
177 if (image->is_module_handle)
178 iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address;
179 else
180 #endif
181 /* FIXME: we ignore the writable flag since we don't patch the binary */
182 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
183 return TRUE;
187 * mono_image_ensure_section:
188 * @image: The image we are operating on
189 * @section: section name that we will load/map into memory
191 * This routine makes sure that we have an in-memory copy of
192 * an image section (.text, .rsrc, .data).
194 * Returns: TRUE on success
197 mono_image_ensure_section (MonoImage *image, const char *section)
199 MonoCLIImageInfo *ii = image->image_info;
200 int i;
202 for (i = 0; i < ii->cli_section_count; i++){
203 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
204 continue;
206 return mono_image_ensure_section_idx (image, i);
208 return FALSE;
211 static int
212 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
214 const int top = iinfo->cli_header.coff.coff_sections;
215 int i;
217 iinfo->cli_section_count = top;
218 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
219 iinfo->cli_sections = g_new0 (void *, top);
221 for (i = 0; i < top; i++){
222 MonoSectionTable *t = &iinfo->cli_section_tables [i];
224 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
225 return FALSE;
226 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
227 offset += sizeof (MonoSectionTable);
229 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
230 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
231 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
232 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
233 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
234 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
235 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
236 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
237 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
238 t->st_flags = GUINT32_FROM_LE (t->st_flags);
239 #endif
240 /* consistency checks here */
243 return TRUE;
246 static gboolean
247 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
249 guint32 offset;
251 offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva);
252 if (offset == INVALID_ADDRESS)
253 return FALSE;
255 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
256 return FALSE;
257 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
259 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
260 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
261 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
262 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
263 SWAP32 (iinfo->cli_cli_header.ch_size);
264 SWAP32 (iinfo->cli_cli_header.ch_flags);
265 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
266 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
267 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
268 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
269 SWAPPDE (iinfo->cli_cli_header.ch_resources);
270 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
271 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
272 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
273 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
274 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
275 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
276 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
277 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
278 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
279 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
280 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
281 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
282 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
283 #undef SWAP32
284 #undef SWAP16
285 #undef SWAPPDE
286 #endif
287 /* Catch new uses of the fields that are supposed to be zero */
289 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
290 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
291 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
292 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
293 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
294 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
295 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
296 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
297 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
300 * No need to scare people who are testing this, I am just
301 * labelling this as a LAMESPEC
303 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
307 return TRUE;
310 static gboolean
311 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
313 guint32 offset, size;
314 guint16 streams;
315 int i;
316 guint32 pad;
317 char *ptr;
319 offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva);
320 if (offset == INVALID_ADDRESS)
321 return FALSE;
323 size = iinfo->cli_cli_header.ch_metadata.size;
325 if (offset + size > image->raw_data_len)
326 return FALSE;
327 image->raw_metadata = image->raw_data + offset;
329 ptr = image->raw_metadata;
331 if (strncmp (ptr, "BSJB", 4) == 0){
332 guint32 version_string_len;
334 ptr += 4;
335 image->md_version_major = read16 (ptr);
336 ptr += 4;
337 image->md_version_minor = read16 (ptr);
338 ptr += 4;
340 version_string_len = read32 (ptr);
341 ptr += 4;
342 image->version = g_strndup (ptr, version_string_len);
343 ptr += version_string_len;
344 pad = ptr - image->raw_metadata;
345 if (pad % 4)
346 ptr += 4 - (pad % 4);
347 } else
348 return FALSE;
350 /* skip over flags */
351 ptr += 2;
353 streams = read16 (ptr);
354 ptr += 2;
356 for (i = 0; i < streams; i++){
357 if (strncmp (ptr + 8, "#~", 3) == 0){
358 image->heap_tables.data = image->raw_metadata + read32 (ptr);
359 image->heap_tables.size = read32 (ptr + 4);
360 ptr += 8 + 3;
361 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
362 image->heap_strings.data = image->raw_metadata + read32 (ptr);
363 image->heap_strings.size = read32 (ptr + 4);
364 ptr += 8 + 9;
365 } else if (strncmp (ptr + 8, "#US", 4) == 0){
366 image->heap_us.data = image->raw_metadata + read32 (ptr);
367 image->heap_us.size = read32 (ptr + 4);
368 ptr += 8 + 4;
369 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
370 image->heap_blob.data = image->raw_metadata + read32 (ptr);
371 image->heap_blob.size = read32 (ptr + 4);
372 ptr += 8 + 6;
373 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
374 image->heap_guid.data = image->raw_metadata + read32 (ptr);
375 image->heap_guid.size = read32 (ptr + 4);
376 ptr += 8 + 6;
377 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
378 image->heap_tables.data = image->raw_metadata + read32 (ptr);
379 image->heap_tables.size = read32 (ptr + 4);
380 ptr += 8 + 3;
381 image->uncompressed_metadata = TRUE;
382 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).\n", image->name);
383 } else {
384 g_message ("Unknown heap type: %s\n", ptr + 8);
385 ptr += 8 + strlen (ptr + 8) + 1;
387 pad = ptr - image->raw_metadata;
388 if (pad % 4)
389 ptr += 4 - (pad % 4);
392 g_assert (image->heap_guid.data);
393 g_assert (image->heap_guid.size >= 16);
395 image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
397 return TRUE;
401 * Load representation of logical metadata tables, from the "#~" stream
403 static gboolean
404 load_tables (MonoImage *image)
406 const char *heap_tables = image->heap_tables.data;
407 const guint32 *rows;
408 guint64 valid_mask, sorted_mask;
409 int valid = 0, table;
410 int heap_sizes;
412 heap_sizes = heap_tables [6];
413 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
414 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
415 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
417 valid_mask = read64 (heap_tables + 8);
418 sorted_mask = read64 (heap_tables + 16);
419 rows = (const guint32 *) (heap_tables + 24);
421 for (table = 0; table < 64; table++){
422 if ((valid_mask & ((guint64) 1 << table)) == 0){
423 if (table > MONO_TABLE_LAST)
424 continue;
425 image->tables [table].rows = 0;
426 continue;
428 if (table > MONO_TABLE_LAST) {
429 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
430 } else {
431 image->tables [table].rows = read32 (rows);
433 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
434 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
436 rows++;
437 valid++;
440 image->tables_base = (heap_tables + 24) + (4 * valid);
442 /* They must be the same */
443 g_assert ((const void *) image->tables_base == (const void *) rows);
445 mono_metadata_compute_table_bases (image);
446 return TRUE;
449 static gboolean
450 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
452 if (!load_metadata_ptrs (image, iinfo))
453 return FALSE;
455 return load_tables (image);
458 void
459 mono_image_check_for_module_cctor (MonoImage *image)
461 MonoTableInfo *t, *mt;
462 t = &image->tables [MONO_TABLE_TYPEDEF];
463 mt = &image->tables [MONO_TABLE_METHOD];
464 if (mono_framework_version () == 1) {
465 image->checked_module_cctor = TRUE;
466 return;
468 if (image->dynamic) {
469 /* FIXME: */
470 image->checked_module_cctor = TRUE;
471 return;
473 if (t->rows >= 1) {
474 guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
475 const char *name = mono_metadata_string_heap (image, nameidx);
476 if (strcmp (name, "<Module>") == 0) {
477 guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
478 guint32 last_method;
479 if (t->rows > 1)
480 last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
481 else
482 last_method = mt->rows;
483 for (; first_method < last_method; first_method++) {
484 nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
485 name = mono_metadata_string_heap (image, nameidx);
486 if (strcmp (name, ".cctor") == 0) {
487 image->has_module_cctor = TRUE;
488 image->checked_module_cctor = TRUE;
489 return;
494 image->has_module_cctor = FALSE;
495 image->checked_module_cctor = TRUE;
498 static void
499 load_modules (MonoImage *image)
501 MonoTableInfo *t;
503 if (image->modules)
504 return;
506 t = &image->tables [MONO_TABLE_MODULEREF];
507 image->modules = g_new0 (MonoImage *, t->rows);
508 image->modules_loaded = g_new0 (gboolean, t->rows);
509 image->module_count = t->rows;
513 * mono_image_load_module:
515 * Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
516 * it cannot be loaded.
518 MonoImage*
519 mono_image_load_module (MonoImage *image, int idx)
521 MonoTableInfo *t;
522 MonoTableInfo *file_table;
523 int i;
524 char *base_dir;
525 gboolean refonly = image->ref_only;
526 GList *list_iter, *valid_modules = NULL;
527 MonoImageOpenStatus status;
529 g_assert (idx <= image->module_count);
530 if (image->modules_loaded [idx - 1])
531 return image->modules [idx - 1];
533 file_table = &image->tables [MONO_TABLE_FILE];
534 for (i = 0; i < file_table->rows; i++) {
535 guint32 cols [MONO_FILE_SIZE];
536 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
537 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
538 continue;
539 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
542 t = &image->tables [MONO_TABLE_MODULEREF];
543 base_dir = g_path_get_dirname (image->name);
546 char *module_ref;
547 const char *name;
548 guint32 cols [MONO_MODULEREF_SIZE];
549 /* if there is no file table, we try to load the module... */
550 int valid = file_table->rows == 0;
552 mono_metadata_decode_row (t, idx - 1, cols, MONO_MODULEREF_SIZE);
553 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
554 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
555 /* be safe with string dups, but we could just compare string indexes */
556 if (strcmp (list_iter->data, name) == 0) {
557 valid = TRUE;
558 break;
561 if (valid) {
562 module_ref = g_build_filename (base_dir, name, NULL);
563 image->modules [idx - 1] = mono_image_open_full (module_ref, &status, refonly);
564 if (image->modules [idx - 1]) {
565 mono_image_addref (image->modules [idx - 1]);
566 image->modules [idx - 1]->assembly = image->assembly;
567 #ifdef PLATFORM_WIN32
568 if (image->modules [idx - 1]->is_module_handle)
569 mono_image_fixup_vtable (image->modules [idx - 1]);
570 #endif
571 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
573 g_free (module_ref);
577 image->modules_loaded [idx - 1] = TRUE;
579 g_free (base_dir);
580 g_list_free (valid_modules);
582 return image->modules [idx - 1];
585 static gpointer
586 class_key_extract (gpointer value)
588 MonoClass *class = value;
590 return GUINT_TO_POINTER (class->type_token);
593 static gpointer*
594 class_next_value (gpointer value)
596 MonoClass *class = value;
598 return (gpointer*)&class->next_class_cache;
601 void
602 mono_image_init (MonoImage *image)
604 image->mempool = mono_mempool_new_size (512);
605 mono_internal_hash_table_init (&image->class_cache,
606 g_direct_hash,
607 class_key_extract,
608 class_next_value);
609 image->field_cache = g_hash_table_new (NULL, NULL);
611 image->typespec_cache = g_hash_table_new (NULL, NULL);
612 image->memberref_signatures = g_hash_table_new (NULL, NULL);
613 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
614 image->method_signatures = g_hash_table_new (NULL, NULL);
616 image->property_hash = mono_property_hash_new ();
617 InitializeCriticalSection (&image->lock);
618 InitializeCriticalSection (&image->szarray_cache_lock);
621 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
622 #define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
623 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
624 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
625 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
626 #else
627 #define SWAP64(x)
628 #define SWAP32(x)
629 #define SWAP16(x)
630 #define SWAPPDE(x)
631 #endif
634 * Returns < 0 to indicate an error.
636 static int
637 do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
639 MonoDotNetHeader64 header64;
641 #ifdef PLATFORM_WIN32
642 if (!image->is_module_handle)
643 #endif
644 if (offset + sizeof (MonoDotNetHeader32) > image->raw_data_len)
645 return -1;
647 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
649 if (header->pesig [0] != 'P' || header->pesig [1] != 'E')
650 return -1;
652 /* endian swap the fields common between PE and PE+ */
653 SWAP32 (header->coff.coff_time);
654 SWAP32 (header->coff.coff_symptr);
655 SWAP32 (header->coff.coff_symcount);
656 SWAP16 (header->coff.coff_machine);
657 SWAP16 (header->coff.coff_sections);
658 SWAP16 (header->coff.coff_opt_header_size);
659 SWAP16 (header->coff.coff_attributes);
660 /* MonoPEHeader */
661 SWAP32 (header->pe.pe_code_size);
662 SWAP32 (header->pe.pe_uninit_data_size);
663 SWAP32 (header->pe.pe_rva_entry_point);
664 SWAP32 (header->pe.pe_rva_code_base);
665 SWAP32 (header->pe.pe_rva_data_base);
666 SWAP16 (header->pe.pe_magic);
668 /* now we are ready for the basic tests */
670 if (header->pe.pe_magic == 0x10B) {
671 offset += sizeof (MonoDotNetHeader);
672 SWAP32 (header->pe.pe_data_size);
673 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
674 return -1;
676 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
677 SWAP32 (header->nt.pe_stack_reserve);
678 SWAP32 (header->nt.pe_stack_commit);
679 SWAP32 (header->nt.pe_heap_reserve);
680 SWAP32 (header->nt.pe_heap_commit);
681 } else if (header->pe.pe_magic == 0x20B) {
682 /* PE32+ file format */
683 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
684 return -1;
685 memcpy (&header64, image->raw_data + offset, sizeof (MonoDotNetHeader64));
686 offset += sizeof (MonoDotNetHeader64);
687 /* copy the fields already swapped. the last field, pe_data_size, is missing */
688 memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
689 /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
690 * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
692 SWAP64 (header64.nt.pe_image_base);
693 header->nt.pe_image_base = header64.nt.pe_image_base;
694 SWAP64 (header64.nt.pe_stack_reserve);
695 header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
696 SWAP64 (header64.nt.pe_stack_commit);
697 header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
698 SWAP64 (header64.nt.pe_heap_reserve);
699 header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
700 SWAP64 (header64.nt.pe_heap_commit);
701 header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
703 header->nt.pe_section_align = header64.nt.pe_section_align;
704 header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
705 header->nt.pe_os_major = header64.nt.pe_os_major;
706 header->nt.pe_os_minor = header64.nt.pe_os_minor;
707 header->nt.pe_user_major = header64.nt.pe_user_major;
708 header->nt.pe_user_minor = header64.nt.pe_user_minor;
709 header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
710 header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
711 header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
712 header->nt.pe_image_size = header64.nt.pe_image_size;
713 header->nt.pe_header_size = header64.nt.pe_header_size;
714 header->nt.pe_checksum = header64.nt.pe_checksum;
715 header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
716 header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
717 header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
718 header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
720 /* copy the datadir */
721 memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
722 } else {
723 return -1;
726 /* MonoPEHeaderNT: not used yet */
727 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
728 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
729 SWAP16 (header->nt.pe_os_major); /* must be 4 */
730 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
731 SWAP16 (header->nt.pe_user_major);
732 SWAP16 (header->nt.pe_user_minor);
733 SWAP16 (header->nt.pe_subsys_major);
734 SWAP16 (header->nt.pe_subsys_minor);
735 SWAP32 (header->nt.pe_reserved_1);
736 SWAP32 (header->nt.pe_image_size);
737 SWAP32 (header->nt.pe_header_size);
738 SWAP32 (header->nt.pe_checksum);
739 SWAP16 (header->nt.pe_subsys_required);
740 SWAP16 (header->nt.pe_dll_flags);
741 SWAP32 (header->nt.pe_loader_flags);
742 SWAP32 (header->nt.pe_data_dir_count);
744 /* MonoDotNetHeader: mostly unused */
745 SWAPPDE (header->datadir.pe_export_table);
746 SWAPPDE (header->datadir.pe_import_table);
747 SWAPPDE (header->datadir.pe_resource_table);
748 SWAPPDE (header->datadir.pe_exception_table);
749 SWAPPDE (header->datadir.pe_certificate_table);
750 SWAPPDE (header->datadir.pe_reloc_table);
751 SWAPPDE (header->datadir.pe_debug);
752 SWAPPDE (header->datadir.pe_copyright);
753 SWAPPDE (header->datadir.pe_global_ptr);
754 SWAPPDE (header->datadir.pe_tls_table);
755 SWAPPDE (header->datadir.pe_load_config_table);
756 SWAPPDE (header->datadir.pe_bound_import);
757 SWAPPDE (header->datadir.pe_iat);
758 SWAPPDE (header->datadir.pe_delay_import_desc);
759 SWAPPDE (header->datadir.pe_cli_header);
760 SWAPPDE (header->datadir.pe_reserved);
762 #ifdef PLATFORM_WIN32
763 if (image->is_module_handle)
764 image->raw_data_len = header->nt.pe_image_size;
765 #endif
767 return offset;
770 static MonoImage *
771 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
772 gboolean care_about_cli)
774 MonoCLIImageInfo *iinfo;
775 MonoDotNetHeader *header;
776 MonoMSDOSHeader msdos;
777 gint32 offset = 0;
779 mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
781 mono_image_init (image);
783 iinfo = image->image_info;
784 header = &iinfo->cli_header;
786 if (status)
787 *status = MONO_IMAGE_IMAGE_INVALID;
789 #ifdef PLATFORM_WIN32
790 if (!image->is_module_handle)
791 #endif
792 if (offset + sizeof (msdos) > image->raw_data_len)
793 goto invalid_image;
794 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
796 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
797 goto invalid_image;
799 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
801 offset = msdos.pe_offset;
803 offset = do_load_header (image, header, offset);
804 if (offset < 0)
805 goto invalid_image;
808 * this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
809 * we skip this test.
810 if (header->coff.coff_machine != 0x14c)
811 goto invalid_image;
814 #if 0
816 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
817 * which produces binaries with 7.0. From Sergey:
819 * The reason is that MSVC7 uses traditional compile/link
820 * sequence for CIL executables, and VS.NET (and Framework
821 * SDK) includes linker version 7, that puts 7.0 in this
822 * field. That's why it's currently not possible to load VC
823 * binaries with Mono. This field is pretty much meaningless
824 * anyway (what linker?).
826 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
827 goto invalid_image;
828 #endif
831 * FIXME: byte swap all addresses here for header.
834 if (!load_section_tables (image, iinfo, offset))
835 goto invalid_image;
837 if (care_about_cli == FALSE) {
838 goto done;
841 /* Load the CLI header */
842 if (!load_cli_header (image, iinfo))
843 goto invalid_image;
845 if (!load_metadata (image, iinfo))
846 goto invalid_image;
848 /* modules don't have an assembly table row */
849 if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
850 image->assembly_name = mono_metadata_string_heap (image,
851 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
852 0, MONO_ASSEMBLY_NAME));
855 image->module_name = mono_metadata_string_heap (image,
856 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
857 0, MONO_MODULE_NAME));
859 load_modules (image);
861 done:
862 mono_profiler_module_loaded (image, MONO_PROFILE_OK);
863 if (status)
864 *status = MONO_IMAGE_OK;
866 return image;
868 invalid_image:
869 mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
870 mono_image_close (image);
871 return NULL;
874 static MonoImage *
875 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
876 gboolean care_about_cli, gboolean refonly)
878 MonoCLIImageInfo *iinfo;
879 MonoImage *image;
880 MonoFileMap *filed;
882 if ((filed = mono_file_map_open (fname)) == NULL){
883 if (IS_PORTABILITY_SET) {
884 gchar *ffname = mono_portability_find_file (fname, TRUE);
885 if (ffname) {
886 filed = mono_file_map_open (ffname);
887 g_free (ffname);
891 if (filed == NULL) {
892 if (status)
893 *status = MONO_IMAGE_ERROR_ERRNO;
894 return NULL;
898 image = g_new0 (MonoImage, 1);
899 image->raw_buffer_used = TRUE;
900 image->raw_data_len = mono_file_map_size (filed);
901 image->raw_data = mono_file_map (image->raw_data_len, MONO_MMAP_READ|MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, &image->raw_data_handle);
902 if (!image->raw_data) {
903 mono_file_map_close (filed);
904 g_free (image);
905 if (status)
906 *status = MONO_IMAGE_IMAGE_INVALID;
907 return NULL;
909 iinfo = g_new0 (MonoCLIImageInfo, 1);
910 image->image_info = iinfo;
911 image->name = mono_path_resolve_symlinks (fname);
912 image->ref_only = refonly;
913 image->ref_count = 1;
915 mono_file_map_close (filed);
916 return do_mono_image_load (image, status, care_about_cli);
919 MonoImage *
920 mono_image_loaded_full (const char *name, gboolean refonly)
922 MonoImage *res;
923 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
925 mono_images_lock ();
926 res = g_hash_table_lookup (loaded_images, name);
927 mono_images_unlock ();
928 return res;
932 * mono_image_loaded:
933 * @name: name of the image to load
935 * This routine ensures that the given image is loaded.
937 * Returns: the loaded MonoImage, or NULL on failure.
939 MonoImage *
940 mono_image_loaded (const char *name)
942 return mono_image_loaded_full (name, FALSE);
945 typedef struct {
946 MonoImage *res;
947 const char* guid;
948 } GuidData;
950 static void
951 find_by_guid (gpointer key, gpointer val, gpointer user_data)
953 GuidData *data = user_data;
954 MonoImage *image;
956 if (data->res)
957 return;
958 image = val;
959 if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
960 data->res = image;
963 MonoImage *
964 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
966 GuidData data;
967 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
968 data.res = NULL;
969 data.guid = guid;
971 mono_images_lock ();
972 g_hash_table_foreach (loaded_images, find_by_guid, &data);
973 mono_images_unlock ();
974 return data.res;
977 MonoImage *
978 mono_image_loaded_by_guid (const char *guid)
980 return mono_image_loaded_by_guid_full (guid, FALSE);
983 static MonoImage *
984 register_image (MonoImage *image)
986 MonoImage *image2;
987 GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
989 mono_images_lock ();
990 image2 = g_hash_table_lookup (loaded_images, image->name);
992 if (image2) {
993 /* Somebody else beat us to it */
994 mono_image_addref (image2);
995 mono_images_unlock ();
996 mono_image_close (image);
997 return image2;
999 g_hash_table_insert (loaded_images, image->name, image);
1000 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
1001 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);
1002 mono_images_unlock ();
1004 return image;
1007 MonoImage *
1008 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1010 MonoCLIImageInfo *iinfo;
1011 MonoImage *image;
1012 char *datac;
1014 if (!data || !data_len) {
1015 if (status)
1016 *status = MONO_IMAGE_IMAGE_INVALID;
1017 return NULL;
1019 datac = data;
1020 if (need_copy) {
1021 datac = g_try_malloc (data_len);
1022 if (!datac) {
1023 if (status)
1024 *status = MONO_IMAGE_ERROR_ERRNO;
1025 return NULL;
1027 memcpy (datac, data, data_len);
1030 image = g_new0 (MonoImage, 1);
1031 image->raw_data = datac;
1032 image->raw_data_len = data_len;
1033 image->raw_data_allocated = need_copy;
1034 image->name = g_strdup_printf ("data-%p", datac);
1035 iinfo = g_new0 (MonoCLIImageInfo, 1);
1036 image->image_info = iinfo;
1037 image->ref_only = refonly;
1039 image = do_mono_image_load (image, status, TRUE);
1040 if (image == NULL)
1041 return NULL;
1043 return register_image (image);
1046 MonoImage *
1047 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1049 return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1052 #ifdef PLATFORM_WIN32
1053 /* fname is not duplicated. */
1054 MonoImage*
1055 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1057 MonoImage* image;
1058 MonoCLIImageInfo* iinfo;
1060 image = g_new0 (MonoImage, 1);
1061 image->raw_data = (char*) module_handle;
1062 image->is_module_handle = TRUE;
1063 iinfo = g_new0 (MonoCLIImageInfo, 1);
1064 image->image_info = iinfo;
1065 image->name = fname;
1066 image->ref_count = has_entry_point ? 0 : 1;
1067 image->has_entry_point = has_entry_point;
1069 image = do_mono_image_load (image, status, TRUE);
1070 if (image == NULL)
1071 return NULL;
1073 return register_image (image);
1075 #endif
1077 MonoImage *
1078 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1080 MonoImage *image;
1081 GHashTable *loaded_images;
1082 char *absfname;
1084 g_return_val_if_fail (fname != NULL, NULL);
1086 #ifdef PLATFORM_WIN32
1087 /* Load modules using LoadLibrary. */
1088 if (!refonly && coree_module_handle) {
1089 HMODULE module_handle;
1090 guint16 *fname_utf16;
1091 DWORD last_error;
1093 absfname = mono_path_resolve_symlinks (fname);
1094 fname_utf16 = NULL;
1096 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1097 mono_images_lock ();
1098 image = g_hash_table_lookup (loaded_images_hash, absfname);
1099 if (image) {
1100 g_assert (image->is_module_handle);
1101 if (image->has_entry_point && image->ref_count == 0) {
1102 /* Increment reference count on images loaded outside of the runtime. */
1103 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1104 /* The image is already loaded because _CorDllMain removes images from the hash. */
1105 module_handle = LoadLibrary (fname_utf16);
1106 g_assert (module_handle == (HMODULE) image->raw_data);
1108 mono_image_addref (image);
1109 mono_images_unlock ();
1110 if (fname_utf16)
1111 g_free (fname_utf16);
1112 g_free (absfname);
1113 return image;
1116 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1117 module_handle = MonoLoadImage (fname_utf16);
1118 if (status && module_handle == NULL)
1119 last_error = GetLastError ();
1121 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1122 image = g_hash_table_lookup (loaded_images_hash, absfname);
1123 if (image)
1124 mono_image_addref (image);
1125 mono_images_unlock ();
1127 g_free (fname_utf16);
1129 if (module_handle == NULL) {
1130 g_assert (!image);
1131 g_free (absfname);
1132 if (status) {
1133 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1134 *status = MONO_IMAGE_IMAGE_INVALID;
1135 else
1136 *status = MONO_IMAGE_ERROR_ERRNO;
1138 return NULL;
1141 if (image) {
1142 g_assert (image->is_module_handle);
1143 g_assert (image->has_entry_point);
1144 g_free (absfname);
1145 return image;
1148 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1150 #endif
1152 absfname = mono_path_canonicalize (fname);
1155 * The easiest solution would be to do all the loading inside the mutex,
1156 * but that would lead to scalability problems. So we let the loading
1157 * happen outside the mutex, and if multiple threads happen to load
1158 * the same image, we discard all but the first copy.
1160 mono_images_lock ();
1161 loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1162 image = g_hash_table_lookup (loaded_images, absfname);
1163 g_free (absfname);
1165 if (image){
1166 mono_image_addref (image);
1167 mono_images_unlock ();
1168 return image;
1170 mono_images_unlock ();
1172 image = do_mono_image_open (fname, status, TRUE, refonly);
1173 if (image == NULL)
1174 return NULL;
1176 return register_image (image);
1180 * mono_image_open:
1181 * @fname: filename that points to the module we want to open
1182 * @status: An error condition is returned in this field
1184 * Returns: An open image of type %MonoImage or NULL on error.
1185 * The caller holds a temporary reference to the returned image which should be cleared
1186 * when no longer needed by calling mono_image_close ().
1187 * if NULL, then check the value of @status for details on the error
1189 MonoImage *
1190 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1192 return mono_image_open_full (fname, status, FALSE);
1196 * mono_pe_file_open:
1197 * @fname: filename that points to the module we want to open
1198 * @status: An error condition is returned in this field
1200 * Returns: An open image of type %MonoImage or NULL on error. if
1201 * NULL, then check the value of @status for details on the error.
1202 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1203 * It's just a PE file loader, used for FileVersionInfo. It also does
1204 * not use the image cache.
1206 MonoImage *
1207 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1209 g_return_val_if_fail (fname != NULL, NULL);
1211 return(do_mono_image_open (fname, status, FALSE, FALSE));
1214 void
1215 mono_image_fixup_vtable (MonoImage *image)
1217 #ifdef PLATFORM_WIN32
1218 MonoCLIImageInfo *iinfo;
1219 MonoPEDirEntry *de;
1220 MonoVTableFixup *vtfixup;
1221 int count;
1222 gpointer slot;
1223 guint16 slot_type;
1224 int slot_count;
1226 g_assert (image->is_module_handle);
1228 iinfo = image->image_info;
1229 de = &iinfo->cli_cli_header.ch_vtable_fixups;
1230 if (!de->rva || !de->size)
1231 return;
1232 vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1233 if (!vtfixup)
1234 return;
1236 count = de->size / sizeof (MonoVTableFixup);
1237 while (count--) {
1238 if (!vtfixup->rva || !vtfixup->count)
1239 continue;
1241 slot = mono_image_rva_map (image, vtfixup->rva);
1242 g_assert (slot);
1243 slot_type = vtfixup->type;
1244 slot_count = vtfixup->count;
1245 if (slot_type & VTFIXUP_TYPE_32BIT)
1246 while (slot_count--) {
1247 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1248 ((guint32*) slot)++;
1250 else if (slot_type & VTFIXUP_TYPE_64BIT)
1251 while (slot_count--) {
1252 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1253 ((guint64*) slot)++;
1255 else
1256 g_assert_not_reached();
1258 vtfixup++;
1260 #else
1261 g_assert_not_reached();
1262 #endif
1265 static void
1266 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1268 g_hash_table_destroy ((GHashTable*)val);
1272 static void
1273 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1275 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1279 static void
1280 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
1282 g_free (val);
1285 static void
1286 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1288 g_slist_free ((GSList*)val);
1292 * mono_image_addref:
1293 * @image: The image file we wish to add a reference to
1295 * Increases the reference count of an image.
1297 void
1298 mono_image_addref (MonoImage *image)
1300 InterlockedIncrement (&image->ref_count);
1303 void
1304 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1306 stream->alloc_size = stream->index = stream->offset = 0;
1307 g_free (stream->data);
1308 stream->data = NULL;
1309 if (stream->hash) {
1310 g_hash_table_destroy (stream->hash);
1311 stream->hash = NULL;
1315 static inline void
1316 free_hash (GHashTable *hash)
1318 if (hash)
1319 g_hash_table_destroy (hash);
1323 * mono_image_close:
1324 * @image: The image file we wish to close
1326 * Closes an image file, deallocates all memory consumed and
1327 * unmaps all possible sections of the file
1329 void
1330 mono_image_close (MonoImage *image)
1332 MonoImage *image2;
1333 GHashTable *loaded_images;
1334 int i;
1336 g_return_if_fail (image != NULL);
1338 if (InterlockedDecrement (&image->ref_count) > 0)
1339 return;
1341 #ifdef PLATFORM_WIN32
1342 if (image->is_module_handle && image->has_entry_point) {
1343 mono_images_lock ();
1344 if (image->ref_count == 0) {
1345 /* Image will be closed by _CorDllMain. */
1346 FreeLibrary ((HMODULE) image->raw_data);
1347 mono_images_unlock ();
1348 return;
1350 mono_images_unlock ();
1352 #endif
1354 mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1356 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1358 mono_metadata_clean_for_image (image);
1361 * The caches inside a MonoImage might refer to metadata which is stored in referenced
1362 * assemblies, so we can't release these references in mono_assembly_close () since the
1363 * MonoImage might outlive its associated MonoAssembly.
1365 if (image->references && !image->dynamic) {
1366 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1367 int i;
1369 for (i = 0; i < t->rows; i++) {
1370 if (image->references [i])
1371 mono_assembly_close (image->references [i]);
1374 g_free (image->references);
1375 image->references = NULL;
1378 mono_images_lock ();
1379 loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1380 image2 = g_hash_table_lookup (loaded_images, image->name);
1381 if (image == image2) {
1382 /* This is not true if we are called from mono_image_open () */
1383 g_hash_table_remove (loaded_images, image->name);
1385 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1386 g_hash_table_remove (loaded_images, (char *) image->assembly_name);
1388 #ifdef PLATFORM_WIN32
1389 if (image->is_module_handle && !image->has_entry_point)
1390 FreeLibrary ((HMODULE) image->raw_data);
1391 #endif
1393 mono_images_unlock ();
1395 if (image->raw_buffer_used) {
1396 if (image->raw_data != NULL)
1397 mono_file_unmap (image->raw_data, image->raw_data_handle);
1400 if (image->raw_data_allocated) {
1401 /* FIXME: do we need this? (image is disposed anyway) */
1402 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1403 MonoCLIImageInfo *ii = image->image_info;
1405 if ((image->raw_metadata > image->raw_data) &&
1406 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1407 image->raw_metadata = NULL;
1409 for (i = 0; i < ii->cli_section_count; i++)
1410 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1411 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1412 ii->cli_sections [i] = NULL;
1414 g_free (image->raw_data);
1417 if (debug_assembly_unload) {
1418 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1419 } else {
1420 g_free (image->name);
1421 g_free (image->guid);
1422 g_free (image->version);
1423 g_free (image->files);
1426 if (image->method_cache)
1427 mono_value_hash_table_destroy (image->method_cache);
1428 if (image->methodref_cache)
1429 g_hash_table_destroy (image->methodref_cache);
1430 mono_internal_hash_table_destroy (&image->class_cache);
1431 g_hash_table_destroy (image->field_cache);
1432 if (image->array_cache) {
1433 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1434 g_hash_table_destroy (image->array_cache);
1436 if (image->szarray_cache)
1437 g_hash_table_destroy (image->szarray_cache);
1438 if (image->ptr_cache)
1439 g_hash_table_destroy (image->ptr_cache);
1440 if (image->name_cache) {
1441 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1442 g_hash_table_destroy (image->name_cache);
1445 free_hash (image->native_wrapper_cache);
1446 free_hash (image->managed_wrapper_cache);
1447 free_hash (image->delegate_begin_invoke_cache);
1448 free_hash (image->delegate_end_invoke_cache);
1449 free_hash (image->delegate_invoke_cache);
1450 free_hash (image->delegate_abstract_invoke_cache);
1451 if (image->remoting_invoke_cache)
1452 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1453 free_hash (image->remoting_invoke_cache);
1454 free_hash (image->runtime_invoke_cache);
1455 free_hash (image->runtime_invoke_direct_cache);
1456 free_hash (image->runtime_invoke_vcall_cache);
1457 free_hash (image->synchronized_cache);
1458 free_hash (image->unbox_wrapper_cache);
1459 free_hash (image->cominterop_invoke_cache);
1460 free_hash (image->cominterop_wrapper_cache);
1461 free_hash (image->typespec_cache);
1462 free_hash (image->ldfld_wrapper_cache);
1463 free_hash (image->ldflda_wrapper_cache);
1464 free_hash (image->stfld_wrapper_cache);
1465 free_hash (image->isinst_cache);
1466 free_hash (image->castclass_cache);
1467 free_hash (image->proxy_isinst_cache);
1468 free_hash (image->thunk_invoke_cache);
1469 free_hash (image->static_rgctx_invoke_cache);
1471 /* The ownership of signatures is not well defined */
1472 //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1473 g_hash_table_destroy (image->memberref_signatures);
1474 //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1475 g_hash_table_destroy (image->helper_signatures);
1476 g_hash_table_destroy (image->method_signatures);
1478 if (image->generic_class_cache)
1479 g_hash_table_destroy (image->generic_class_cache);
1481 if (image->rgctx_template_hash)
1482 g_hash_table_destroy (image->rgctx_template_hash);
1484 if (image->property_hash)
1485 mono_property_hash_destroy (image->property_hash);
1487 if (image->interface_bitset) {
1488 mono_unload_interface_ids (image->interface_bitset);
1489 mono_bitset_free (image->interface_bitset);
1491 if (image->image_info){
1492 MonoCLIImageInfo *ii = image->image_info;
1494 if (ii->cli_section_tables)
1495 g_free (ii->cli_section_tables);
1496 if (ii->cli_sections)
1497 g_free (ii->cli_sections);
1498 g_free (image->image_info);
1501 for (i = 0; i < image->module_count; ++i) {
1502 if (image->modules [i])
1503 mono_image_close (image->modules [i]);
1505 if (image->modules)
1506 g_free (image->modules);
1507 if (image->modules_loaded)
1508 g_free (image->modules_loaded);
1509 if (image->references)
1510 g_free (image->references);
1511 mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
1513 DeleteCriticalSection (&image->szarray_cache_lock);
1514 DeleteCriticalSection (&image->lock);
1516 /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1517 if (!image->dynamic) {
1518 if (debug_assembly_unload)
1519 mono_mempool_invalidate (image->mempool);
1520 else {
1521 mono_mempool_destroy (image->mempool);
1522 g_free (image);
1524 } else {
1525 /* Dynamic images are GC_MALLOCed */
1526 g_free ((char*)image->module_name);
1527 mono_dynamic_image_free ((MonoDynamicImage*)image);
1528 mono_mempool_destroy (image->mempool);
1531 mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1534 /**
1535 * mono_image_strerror:
1536 * @status: an code indicating the result from a recent operation
1538 * Returns: a string describing the error
1540 const char *
1541 mono_image_strerror (MonoImageOpenStatus status)
1543 switch (status){
1544 case MONO_IMAGE_OK:
1545 return "success";
1546 case MONO_IMAGE_ERROR_ERRNO:
1547 return strerror (errno);
1548 case MONO_IMAGE_IMAGE_INVALID:
1549 return "File does not contain a valid CIL image";
1550 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1551 return "An assembly was referenced, but could not be found";
1553 return "Internal error";
1556 static gpointer
1557 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1558 guint32 lang_id, gunichar2 *name,
1559 MonoPEResourceDirEntry *entry,
1560 MonoPEResourceDir *root, guint32 level)
1562 gboolean is_string, is_dir;
1563 guint32 name_offset, dir_offset;
1565 /* Level 0 holds a directory entry for each type of resource
1566 * (identified by ID or name).
1568 * Level 1 holds a directory entry for each named resource
1569 * item, and each "anonymous" item of a particular type of
1570 * resource.
1572 * Level 2 holds a directory entry for each language pointing to
1573 * the actual data.
1575 is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1576 name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1578 is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1579 dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1581 if(level==0) {
1582 if (is_string)
1583 return NULL;
1584 } else if (level==1) {
1585 if (res_id != name_offset)
1586 return NULL;
1587 #if 0
1588 if(name!=NULL &&
1589 is_string==TRUE && name!=lookup (name_offset)) {
1590 return(NULL);
1592 #endif
1593 } else if (level==2) {
1594 if (is_string == TRUE || (is_string == FALSE && lang_id != 0 && name_offset != lang_id))
1595 return NULL;
1596 } else {
1597 g_assert_not_reached ();
1600 if(is_dir==TRUE) {
1601 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1602 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1603 guint32 entries, i;
1605 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1607 for(i=0; i<entries; i++) {
1608 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1609 gpointer ret;
1611 ret=mono_image_walk_resource_tree (info, res_id,
1612 lang_id, name,
1613 sub_entry, root,
1614 level+1);
1615 if(ret!=NULL) {
1616 return(ret);
1620 return(NULL);
1621 } else {
1622 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
1623 MonoPEResourceDataEntry *res;
1625 res = g_new0 (MonoPEResourceDataEntry, 1);
1627 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
1628 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
1629 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
1630 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
1632 return (res);
1637 * mono_image_lookup_resource:
1638 * @image: the image to look up the resource in
1639 * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1640 * @lang_id: The language id.
1641 * @name: the resource name to lookup.
1643 * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1644 * of the given resource. The caller should free it using g_free () when no longer
1645 * needed.
1647 gpointer
1648 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1650 MonoCLIImageInfo *info;
1651 MonoDotNetHeader *header;
1652 MonoPEDatadir *datadir;
1653 MonoPEDirEntry *rsrc;
1654 MonoPEResourceDir *resource_dir;
1655 MonoPEResourceDirEntry *res_entries;
1656 guint32 entries, i;
1658 if(image==NULL) {
1659 return(NULL);
1662 mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
1664 info=image->image_info;
1665 if(info==NULL) {
1666 return(NULL);
1669 header=&info->cli_header;
1670 if(header==NULL) {
1671 return(NULL);
1674 datadir=&header->datadir;
1675 if(datadir==NULL) {
1676 return(NULL);
1679 rsrc=&datadir->pe_resource_table;
1680 if(rsrc==NULL) {
1681 return(NULL);
1684 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1685 if(resource_dir==NULL) {
1686 return(NULL);
1689 entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1690 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1692 for(i=0; i<entries; i++) {
1693 MonoPEResourceDirEntry *entry=&res_entries[i];
1694 gpointer ret;
1696 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1697 name, entry, resource_dir,
1699 if(ret!=NULL) {
1700 return(ret);
1704 return(NULL);
1707 /**
1708 * mono_image_get_entry_point:
1709 * @image: the image where the entry point will be looked up.
1711 * Use this routine to determine the metadata token for method that
1712 * has been flagged as the entry point.
1714 * Returns: the token for the entry point method in the image
1716 guint32
1717 mono_image_get_entry_point (MonoImage *image)
1719 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1723 * mono_image_get_resource:
1724 * @image: the image where the resource will be looked up.
1725 * @offset: The offset to add to the resource
1726 * @size: a pointer to an int where the size of the resource will be stored
1728 * This is a low-level routine that fetches a resource from the
1729 * metadata that starts at a given @offset. The @size parameter is
1730 * filled with the data field as encoded in the metadata.
1732 * Returns: the pointer to the resource whose offset is @offset.
1734 const char*
1735 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1737 MonoCLIImageInfo *iinfo = image->image_info;
1738 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1739 const char* data;
1741 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1742 return NULL;
1744 data = mono_image_rva_map (image, ch->ch_resources.rva);
1745 if (!data)
1746 return NULL;
1747 data += offset;
1748 if (size)
1749 *size = read32 (data);
1750 data += 4;
1751 return data;
1754 MonoImage*
1755 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1757 char *base_dir, *name;
1758 MonoImage *res;
1759 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1760 const char *fname;
1761 guint32 fname_id;
1763 if (fileidx < 1 || fileidx > t->rows)
1764 return NULL;
1766 mono_loader_lock ();
1767 if (image->files && image->files [fileidx - 1]) {
1768 mono_loader_unlock ();
1769 return image->files [fileidx - 1];
1772 if (!image->files)
1773 image->files = g_new0 (MonoImage*, t->rows);
1775 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1776 fname = mono_metadata_string_heap (image, fname_id);
1777 base_dir = g_path_get_dirname (image->name);
1778 name = g_build_filename (base_dir, fname, NULL);
1779 res = mono_image_open (name, NULL);
1780 if (res) {
1781 int i;
1782 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1783 res->assembly = image->assembly;
1784 for (i = 0; i < res->module_count; ++i) {
1785 if (res->modules [i] && !res->modules [i]->assembly)
1786 res->modules [i]->assembly = image->assembly;
1789 image->files [fileidx - 1] = res;
1790 #ifdef PLATFORM_WIN32
1791 if (res->is_module_handle)
1792 mono_image_fixup_vtable (res);
1793 #endif
1795 mono_loader_unlock ();
1796 g_free (name);
1797 g_free (base_dir);
1798 return res;
1802 * mono_image_get_strong_name:
1803 * @image: a MonoImage
1804 * @size: a guint32 pointer, or NULL.
1806 * If the image has a strong name, and @size is not NULL, the value
1807 * pointed to by size will have the size of the strong name.
1809 * Returns: NULL if the image does not have a strong name, or a
1810 * pointer to the public key.
1812 const char*
1813 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1815 MonoCLIImageInfo *iinfo = image->image_info;
1816 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1817 const char* data;
1819 if (!de->size || !de->rva)
1820 return NULL;
1821 data = mono_image_rva_map (image, de->rva);
1822 if (!data)
1823 return NULL;
1824 if (size)
1825 *size = de->size;
1826 return data;
1830 * mono_image_strong_name_position:
1831 * @image: a MonoImage
1832 * @size: a guint32 pointer, or NULL.
1834 * If the image has a strong name, and @size is not NULL, the value
1835 * pointed to by size will have the size of the strong name.
1837 * Returns: the position within the image file where the strong name
1838 * is stored.
1840 guint32
1841 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1843 MonoCLIImageInfo *iinfo = image->image_info;
1844 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1845 guint32 pos;
1847 if (size)
1848 *size = de->size;
1849 if (!de->size || !de->rva)
1850 return 0;
1851 pos = mono_cli_rva_image_map (image, de->rva);
1852 return pos == INVALID_ADDRESS ? 0 : pos;
1856 * mono_image_get_public_key:
1857 * @image: a MonoImage
1858 * @size: a guint32 pointer, or NULL.
1860 * This is used to obtain the public key in the @image.
1862 * If the image has a public key, and @size is not NULL, the value
1863 * pointed to by size will have the size of the public key.
1865 * Returns: NULL if the image does not have a public key, or a pointer
1866 * to the public key.
1868 const char*
1869 mono_image_get_public_key (MonoImage *image, guint32 *size)
1871 const char *pubkey;
1872 guint32 len, tok;
1874 if (image->dynamic) {
1875 if (size)
1876 *size = ((MonoDynamicImage*)image)->public_key_len;
1877 return (char*)((MonoDynamicImage*)image)->public_key;
1879 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1880 return NULL;
1881 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1882 if (!tok)
1883 return NULL;
1884 pubkey = mono_metadata_blob_heap (image, tok);
1885 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1886 if (size)
1887 *size = len;
1888 return pubkey;
1892 * mono_image_get_name:
1893 * @name: a MonoImage
1895 * Returns: the name of the assembly.
1897 const char*
1898 mono_image_get_name (MonoImage *image)
1900 return image->assembly_name;
1904 * mono_image_get_filename:
1905 * @image: a MonoImage
1907 * Used to get the filename that hold the actual MonoImage
1909 * Returns: the filename.
1911 const char*
1912 mono_image_get_filename (MonoImage *image)
1914 return image->name;
1917 const char*
1918 mono_image_get_guid (MonoImage *image)
1920 return image->guid;
1923 const MonoTableInfo*
1924 mono_image_get_table_info (MonoImage *image, int table_id)
1926 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1927 return NULL;
1928 return &image->tables [table_id];
1932 mono_image_get_table_rows (MonoImage *image, int table_id)
1934 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1935 return 0;
1936 return image->tables [table_id].rows;
1940 mono_table_info_get_rows (const MonoTableInfo *table)
1942 return table->rows;
1946 * mono_image_get_assembly:
1947 * @image: the MonoImage.
1949 * Use this routine to get the assembly that owns this image.
1951 * Returns: the assembly that holds this image.
1953 MonoAssembly*
1954 mono_image_get_assembly (MonoImage *image)
1956 return image->assembly;
1960 * mono_image_is_dynamic:
1961 * @image: the MonoImage
1963 * Determines if the given image was created dynamically through the
1964 * System.Reflection.Emit API
1966 * Returns: TRUE if the image was created dynamically, FALSE if not.
1968 gboolean
1969 mono_image_is_dynamic (MonoImage *image)
1971 return image->dynamic;
1975 * mono_image_has_authenticode_entry:
1976 * @image: the MonoImage
1978 * Use this routine to determine if the image has a Authenticode
1979 * Certificate Table.
1981 * Returns: TRUE if the image contains an authenticode entry in the PE
1982 * directory.
1984 gboolean
1985 mono_image_has_authenticode_entry (MonoImage *image)
1987 MonoCLIImageInfo *iinfo = image->image_info;
1988 MonoDotNetHeader *header = &iinfo->cli_header;
1989 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
1990 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
1991 return ((de->rva != 0) && (de->size > 8));
1994 gpointer
1995 mono_image_alloc (MonoImage *image, guint size)
1997 gpointer res;
1999 mono_perfcounters->loader_bytes += size;
2000 mono_image_lock (image);
2001 res = mono_mempool_alloc (image->mempool, size);
2002 mono_image_unlock (image);
2004 return res;
2007 gpointer
2008 mono_image_alloc0 (MonoImage *image, guint size)
2010 gpointer res;
2012 mono_perfcounters->loader_bytes += size;
2013 mono_image_lock (image);
2014 res = mono_mempool_alloc0 (image->mempool, size);
2015 mono_image_unlock (image);
2017 return res;
2020 char*
2021 mono_image_strdup (MonoImage *image, const char *s)
2023 char *res;
2025 mono_perfcounters->loader_bytes += strlen (s);
2026 mono_image_lock (image);
2027 res = mono_mempool_strdup (image->mempool, s);
2028 mono_image_unlock (image);
2030 return res;
2033 GList*
2034 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
2036 GList *new_list;
2038 new_list = mono_image_alloc (image, sizeof (GList));
2039 new_list->data = data;
2040 new_list->prev = list ? list->prev : NULL;
2041 new_list->next = list;
2043 if (new_list->prev)
2044 new_list->prev->next = new_list;
2045 if (list)
2046 list->prev = new_list;
2048 return new_list;
2051 GSList*
2052 g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
2054 GSList *new_list;
2056 new_list = mono_image_alloc (image, sizeof (GSList));
2057 new_list->data = data;
2058 new_list->next = NULL;
2060 return g_slist_concat (list, new_list);
2063 void
2064 mono_image_lock (MonoImage *image)
2066 mono_locks_acquire (&image->lock, ImageDataLock);
2069 void
2070 mono_image_unlock (MonoImage *image)
2072 mono_locks_release (&image->lock, ImageDataLock);
2077 * mono_image_property_lookup:
2079 * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
2081 * LOCKING: Takes the image lock
2083 gpointer
2084 mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
2086 gpointer res;
2088 mono_image_lock (image);
2089 res = mono_property_hash_lookup (image->property_hash, subject, property);
2090 mono_image_unlock (image);
2092 return res;
2096 * mono_image_property_insert:
2098 * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2100 * LOCKING: Takes the image lock
2102 void
2103 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
2105 mono_image_lock (image);
2106 mono_property_hash_insert (image->property_hash, subject, property, value);
2107 mono_image_unlock (image);
2111 * mono_image_property_remove:
2113 * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2115 * LOCKING: Takes the image lock
2117 void
2118 mono_image_property_remove (MonoImage *image, gpointer subject)
2120 mono_image_lock (image);
2121 mono_property_hash_remove_object (image->property_hash, subject);
2122 mono_image_unlock (image);