Merge pull request #2202 from mono/revert-2090-mono-4.2.0-branch-bug25480
[mono-project.git] / mono / metadata / image.c
blob8f0ea296690c1ecf43935cc46ece5b96b5f9c6f9
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-internal.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/utils/atomic.h>
35 #include <mono/metadata/class-internals.h>
36 #include <mono/metadata/assembly.h>
37 #include <mono/metadata/object-internals.h>
38 #include <mono/metadata/security-core-clr.h>
39 #include <mono/metadata/verify-internals.h>
40 #include <mono/metadata/verify.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
47 #define INVALID_ADDRESS 0xffffffff
50 * Keeps track of the various assemblies loaded
52 static GHashTable *loaded_images_hash;
53 static GHashTable *loaded_images_refonly_hash;
55 static gboolean debug_assembly_unload = FALSE;
57 #define mono_images_lock() if (mutex_inited) mono_mutex_lock (&images_mutex)
58 #define mono_images_unlock() if (mutex_inited) mono_mutex_unlock (&images_mutex)
59 static gboolean mutex_inited;
60 static mono_mutex_t images_mutex;
62 typedef struct ImageUnloadHook ImageUnloadHook;
63 struct ImageUnloadHook {
64 MonoImageUnloadFunc func;
65 gpointer user_data;
68 static GSList *image_unload_hooks;
70 void
71 mono_install_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data)
73 ImageUnloadHook *hook;
75 g_return_if_fail (func != NULL);
77 hook = g_new0 (ImageUnloadHook, 1);
78 hook->func = func;
79 hook->user_data = user_data;
80 image_unload_hooks = g_slist_prepend (image_unload_hooks, hook);
83 void
84 mono_remove_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data)
86 GSList *l;
87 ImageUnloadHook *hook;
89 for (l = image_unload_hooks; l; l = l->next) {
90 hook = l->data;
92 if (hook->func == func && hook->user_data == user_data) {
93 g_free (hook);
94 image_unload_hooks = g_slist_delete_link (image_unload_hooks, l);
95 break;
100 static void
101 mono_image_invoke_unload_hook (MonoImage *image)
103 GSList *l;
104 ImageUnloadHook *hook;
106 for (l = image_unload_hooks; l; l = l->next) {
107 hook = l->data;
109 hook->func (image, hook->user_data);
113 /* returns offset relative to image->raw_data */
114 guint32
115 mono_cli_rva_image_map (MonoImage *image, guint32 addr)
117 MonoCLIImageInfo *iinfo = image->image_info;
118 const int top = iinfo->cli_section_count;
119 MonoSectionTable *tables = iinfo->cli_section_tables;
120 int i;
122 if (image->metadata_only)
123 return addr;
125 for (i = 0; i < top; i++){
126 if ((addr >= tables->st_virtual_address) &&
127 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
128 #ifdef HOST_WIN32
129 if (image->is_module_handle)
130 return addr;
131 #endif
132 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
134 tables++;
136 return INVALID_ADDRESS;
140 * mono_images_rva_map:
141 * @image: a MonoImage
142 * @addr: relative virtual address (RVA)
144 * This is a low-level routine used by the runtime to map relative
145 * virtual address (RVA) into their location in memory.
147 * Returns: the address in memory for the given RVA, or NULL if the
148 * RVA is not valid for this image.
150 char *
151 mono_image_rva_map (MonoImage *image, guint32 addr)
153 MonoCLIImageInfo *iinfo = image->image_info;
154 const int top = iinfo->cli_section_count;
155 MonoSectionTable *tables = iinfo->cli_section_tables;
156 int i;
158 #ifdef HOST_WIN32
159 if (image->is_module_handle) {
160 if (addr && addr < image->raw_data_len)
161 return image->raw_data + addr;
162 else
163 return NULL;
165 #endif
167 for (i = 0; i < top; i++){
168 if ((addr >= tables->st_virtual_address) &&
169 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
170 if (!iinfo->cli_sections [i]) {
171 if (!mono_image_ensure_section_idx (image, i))
172 return NULL;
174 return (char*)iinfo->cli_sections [i] +
175 (addr - tables->st_virtual_address);
177 tables++;
179 return NULL;
183 * mono_images_init:
185 * Initialize the global variables used by this module.
187 void
188 mono_images_init (void)
190 mono_mutex_init_recursive (&images_mutex);
192 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
193 loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
195 debug_assembly_unload = g_getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
197 mutex_inited = TRUE;
201 * mono_images_cleanup:
203 * Free all resources used by this module.
205 void
206 mono_images_cleanup (void)
208 GHashTableIter iter;
209 MonoImage *image;
211 mono_mutex_destroy (&images_mutex);
213 g_hash_table_iter_init (&iter, loaded_images_hash);
214 while (g_hash_table_iter_next (&iter, NULL, (void**)&image))
215 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Assembly image '%s' still loaded at shutdown.", image->name);
217 g_hash_table_destroy (loaded_images_hash);
218 g_hash_table_destroy (loaded_images_refonly_hash);
220 mutex_inited = FALSE;
224 * mono_image_ensure_section_idx:
225 * @image: The image we are operating on
226 * @section: section number that we will load/map into memory
228 * This routine makes sure that we have an in-memory copy of
229 * an image section (.text, .rsrc, .data).
231 * Returns: TRUE on success
234 mono_image_ensure_section_idx (MonoImage *image, int section)
236 MonoCLIImageInfo *iinfo = image->image_info;
237 MonoSectionTable *sect;
239 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
241 if (iinfo->cli_sections [section] != NULL)
242 return TRUE;
244 sect = &iinfo->cli_section_tables [section];
246 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
247 return FALSE;
248 #ifdef HOST_WIN32
249 if (image->is_module_handle)
250 iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address;
251 else
252 #endif
253 /* FIXME: we ignore the writable flag since we don't patch the binary */
254 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
255 return TRUE;
259 * mono_image_ensure_section:
260 * @image: The image we are operating on
261 * @section: section name that we will load/map into memory
263 * This routine makes sure that we have an in-memory copy of
264 * an image section (.text, .rsrc, .data).
266 * Returns: TRUE on success
269 mono_image_ensure_section (MonoImage *image, const char *section)
271 MonoCLIImageInfo *ii = image->image_info;
272 int i;
274 for (i = 0; i < ii->cli_section_count; i++){
275 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
276 continue;
278 return mono_image_ensure_section_idx (image, i);
280 return FALSE;
283 static int
284 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
286 const int top = iinfo->cli_header.coff.coff_sections;
287 int i;
289 iinfo->cli_section_count = top;
290 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
291 iinfo->cli_sections = g_new0 (void *, top);
293 for (i = 0; i < top; i++){
294 MonoSectionTable *t = &iinfo->cli_section_tables [i];
296 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
297 return FALSE;
298 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
299 offset += sizeof (MonoSectionTable);
301 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
302 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
303 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
304 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
305 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
306 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
307 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
308 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
309 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
310 t->st_flags = GUINT32_FROM_LE (t->st_flags);
311 #endif
312 /* consistency checks here */
315 return TRUE;
318 static gboolean
319 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
321 guint32 offset;
323 offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva);
324 if (offset == INVALID_ADDRESS)
325 return FALSE;
327 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
328 return FALSE;
329 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
331 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
332 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
333 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
334 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
335 SWAP32 (iinfo->cli_cli_header.ch_size);
336 SWAP32 (iinfo->cli_cli_header.ch_flags);
337 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
338 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
339 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
340 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
341 SWAPPDE (iinfo->cli_cli_header.ch_resources);
342 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
343 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
344 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
345 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
346 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
347 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
348 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
349 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
350 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
351 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
352 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
353 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
354 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
355 #undef SWAP32
356 #undef SWAP16
357 #undef SWAPPDE
358 #endif
359 /* Catch new uses of the fields that are supposed to be zero */
361 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
362 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
363 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
364 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
365 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
366 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
367 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
368 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
369 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
372 * No need to scare people who are testing this, I am just
373 * labelling this as a LAMESPEC
375 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
379 return TRUE;
382 static gboolean
383 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
385 guint32 offset, size;
386 guint16 streams;
387 int i;
388 guint32 pad;
389 char *ptr;
391 offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva);
392 if (offset == INVALID_ADDRESS)
393 return FALSE;
395 size = iinfo->cli_cli_header.ch_metadata.size;
397 if (offset + size > image->raw_data_len)
398 return FALSE;
399 image->raw_metadata = image->raw_data + offset;
401 /* 24.2.1: Metadata root starts here */
402 ptr = image->raw_metadata;
404 if (strncmp (ptr, "BSJB", 4) == 0){
405 guint32 version_string_len;
407 ptr += 4;
408 image->md_version_major = read16 (ptr);
409 ptr += 2;
410 image->md_version_minor = read16 (ptr);
411 ptr += 6;
413 version_string_len = read32 (ptr);
414 ptr += 4;
415 image->version = g_strndup (ptr, version_string_len);
416 ptr += version_string_len;
417 pad = ptr - image->raw_metadata;
418 if (pad % 4)
419 ptr += 4 - (pad % 4);
420 } else
421 return FALSE;
423 /* skip over flags */
424 ptr += 2;
426 streams = read16 (ptr);
427 ptr += 2;
429 for (i = 0; i < streams; i++){
430 if (strncmp (ptr + 8, "#~", 3) == 0){
431 image->heap_tables.data = image->raw_metadata + read32 (ptr);
432 image->heap_tables.size = read32 (ptr + 4);
433 ptr += 8 + 3;
434 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
435 image->heap_strings.data = image->raw_metadata + read32 (ptr);
436 image->heap_strings.size = read32 (ptr + 4);
437 ptr += 8 + 9;
438 } else if (strncmp (ptr + 8, "#US", 4) == 0){
439 image->heap_us.data = image->raw_metadata + read32 (ptr);
440 image->heap_us.size = read32 (ptr + 4);
441 ptr += 8 + 4;
442 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
443 image->heap_blob.data = image->raw_metadata + read32 (ptr);
444 image->heap_blob.size = read32 (ptr + 4);
445 ptr += 8 + 6;
446 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
447 image->heap_guid.data = image->raw_metadata + read32 (ptr);
448 image->heap_guid.size = read32 (ptr + 4);
449 ptr += 8 + 6;
450 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
451 image->heap_tables.data = image->raw_metadata + read32 (ptr);
452 image->heap_tables.size = read32 (ptr + 4);
453 ptr += 8 + 3;
454 image->uncompressed_metadata = TRUE;
455 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);
456 } else if (strncmp (ptr + 8, "#Pdb", 5) == 0) {
457 image->heap_pdb.data = image->raw_metadata + read32 (ptr);
458 image->heap_pdb.size = read32 (ptr + 4);
459 ptr += 8 + 5;
460 } else {
461 g_message ("Unknown heap type: %s\n", ptr + 8);
462 ptr += 8 + strlen (ptr + 8) + 1;
464 pad = ptr - image->raw_metadata;
465 if (pad % 4)
466 ptr += 4 - (pad % 4);
469 g_assert (image->heap_guid.data);
470 g_assert (image->heap_guid.size >= 16);
472 image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
474 return TRUE;
478 * Load representation of logical metadata tables, from the "#~" stream
480 static gboolean
481 load_tables (MonoImage *image)
483 const char *heap_tables = image->heap_tables.data;
484 const guint32 *rows;
485 guint64 valid_mask;
486 int valid = 0, table;
487 int heap_sizes;
489 heap_sizes = heap_tables [6];
490 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
491 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
492 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
494 valid_mask = read64 (heap_tables + 8);
495 rows = (const guint32 *) (heap_tables + 24);
497 for (table = 0; table < 64; table++){
498 if ((valid_mask & ((guint64) 1 << table)) == 0){
499 if (table > MONO_TABLE_LAST)
500 continue;
501 image->tables [table].rows = 0;
502 continue;
504 if (table > MONO_TABLE_LAST) {
505 g_warning("bits in valid must be zero above 0x37 (II - 23.1.6)");
506 } else {
507 image->tables [table].rows = read32 (rows);
509 rows++;
510 valid++;
513 image->tables_base = (heap_tables + 24) + (4 * valid);
515 /* They must be the same */
516 g_assert ((const void *) image->tables_base == (const void *) rows);
518 mono_metadata_compute_table_bases (image);
519 return TRUE;
522 static gboolean
523 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
525 if (!load_metadata_ptrs (image, iinfo))
526 return FALSE;
528 return load_tables (image);
531 void
532 mono_image_check_for_module_cctor (MonoImage *image)
534 MonoTableInfo *t, *mt;
535 t = &image->tables [MONO_TABLE_TYPEDEF];
536 mt = &image->tables [MONO_TABLE_METHOD];
537 if (image_is_dynamic (image)) {
538 /* FIXME: */
539 image->checked_module_cctor = TRUE;
540 return;
542 if (t->rows >= 1) {
543 guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
544 const char *name = mono_metadata_string_heap (image, nameidx);
545 if (strcmp (name, "<Module>") == 0) {
546 guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
547 guint32 last_method;
548 if (t->rows > 1)
549 last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
550 else
551 last_method = mt->rows;
552 for (; first_method < last_method; first_method++) {
553 nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
554 name = mono_metadata_string_heap (image, nameidx);
555 if (strcmp (name, ".cctor") == 0) {
556 image->has_module_cctor = TRUE;
557 image->checked_module_cctor = TRUE;
558 return;
563 image->has_module_cctor = FALSE;
564 image->checked_module_cctor = TRUE;
567 static void
568 load_modules (MonoImage *image)
570 MonoTableInfo *t;
572 if (image->modules)
573 return;
575 t = &image->tables [MONO_TABLE_MODULEREF];
576 image->modules = g_new0 (MonoImage *, t->rows);
577 image->modules_loaded = g_new0 (gboolean, t->rows);
578 image->module_count = t->rows;
582 * mono_image_load_module:
584 * Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
585 * it cannot be loaded.
587 MonoImage*
588 mono_image_load_module (MonoImage *image, int idx)
590 MonoTableInfo *t;
591 MonoTableInfo *file_table;
592 int i;
593 char *base_dir;
594 gboolean refonly = image->ref_only;
595 GList *list_iter, *valid_modules = NULL;
596 MonoImageOpenStatus status;
598 if ((image->module_count == 0) || (idx > image->module_count || idx <= 0))
599 return NULL;
600 if (image->modules_loaded [idx - 1])
601 return image->modules [idx - 1];
603 file_table = &image->tables [MONO_TABLE_FILE];
604 for (i = 0; i < file_table->rows; i++) {
605 guint32 cols [MONO_FILE_SIZE];
606 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
607 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
608 continue;
609 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
612 t = &image->tables [MONO_TABLE_MODULEREF];
613 base_dir = g_path_get_dirname (image->name);
616 char *module_ref;
617 const char *name;
618 guint32 cols [MONO_MODULEREF_SIZE];
619 /* if there is no file table, we try to load the module... */
620 int valid = file_table->rows == 0;
622 mono_metadata_decode_row (t, idx - 1, cols, MONO_MODULEREF_SIZE);
623 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
624 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
625 /* be safe with string dups, but we could just compare string indexes */
626 if (strcmp (list_iter->data, name) == 0) {
627 valid = TRUE;
628 break;
631 if (valid) {
632 module_ref = g_build_filename (base_dir, name, NULL);
633 image->modules [idx - 1] = mono_image_open_full (module_ref, &status, refonly);
634 if (image->modules [idx - 1]) {
635 mono_image_addref (image->modules [idx - 1]);
636 image->modules [idx - 1]->assembly = image->assembly;
637 #ifdef HOST_WIN32
638 if (image->modules [idx - 1]->is_module_handle)
639 mono_image_fixup_vtable (image->modules [idx - 1]);
640 #endif
641 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
643 g_free (module_ref);
647 image->modules_loaded [idx - 1] = TRUE;
649 g_free (base_dir);
650 g_list_free (valid_modules);
652 return image->modules [idx - 1];
655 static gpointer
656 class_key_extract (gpointer value)
658 MonoClass *class = value;
660 return GUINT_TO_POINTER (class->type_token);
663 static gpointer*
664 class_next_value (gpointer value)
666 MonoClass *class = value;
668 return (gpointer*)&class->next_class_cache;
671 void
672 mono_image_init (MonoImage *image)
674 mono_mutex_init_recursive (&image->lock);
675 mono_mutex_init_recursive (&image->szarray_cache_lock);
677 image->mempool = mono_mempool_new_size (512);
678 mono_internal_hash_table_init (&image->class_cache,
679 g_direct_hash,
680 class_key_extract,
681 class_next_value);
682 image->field_cache = mono_conc_hashtable_new (&image->lock, NULL, NULL);
684 image->typespec_cache = g_hash_table_new (NULL, NULL);
685 image->memberref_signatures = g_hash_table_new (NULL, NULL);
686 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
687 image->method_signatures = g_hash_table_new (NULL, NULL);
689 image->property_hash = mono_property_hash_new ();
692 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
693 #define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
694 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
695 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
696 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
697 #else
698 #define SWAP64(x)
699 #define SWAP32(x)
700 #define SWAP16(x)
701 #define SWAPPDE(x)
702 #endif
705 * Returns < 0 to indicate an error.
707 static int
708 do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
710 MonoDotNetHeader64 header64;
712 #ifdef HOST_WIN32
713 if (!image->is_module_handle)
714 #endif
715 if (offset + sizeof (MonoDotNetHeader32) > image->raw_data_len)
716 return -1;
718 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
720 if (header->pesig [0] != 'P' || header->pesig [1] != 'E')
721 return -1;
723 /* endian swap the fields common between PE and PE+ */
724 SWAP32 (header->coff.coff_time);
725 SWAP32 (header->coff.coff_symptr);
726 SWAP32 (header->coff.coff_symcount);
727 SWAP16 (header->coff.coff_machine);
728 SWAP16 (header->coff.coff_sections);
729 SWAP16 (header->coff.coff_opt_header_size);
730 SWAP16 (header->coff.coff_attributes);
731 /* MonoPEHeader */
732 SWAP32 (header->pe.pe_code_size);
733 SWAP32 (header->pe.pe_uninit_data_size);
734 SWAP32 (header->pe.pe_rva_entry_point);
735 SWAP32 (header->pe.pe_rva_code_base);
736 SWAP32 (header->pe.pe_rva_data_base);
737 SWAP16 (header->pe.pe_magic);
739 /* now we are ready for the basic tests */
741 if (header->pe.pe_magic == 0x10B) {
742 offset += sizeof (MonoDotNetHeader);
743 SWAP32 (header->pe.pe_data_size);
744 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
745 return -1;
747 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
748 SWAP32 (header->nt.pe_stack_reserve);
749 SWAP32 (header->nt.pe_stack_commit);
750 SWAP32 (header->nt.pe_heap_reserve);
751 SWAP32 (header->nt.pe_heap_commit);
752 } else if (header->pe.pe_magic == 0x20B) {
753 /* PE32+ file format */
754 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
755 return -1;
756 memcpy (&header64, image->raw_data + offset, sizeof (MonoDotNetHeader64));
757 offset += sizeof (MonoDotNetHeader64);
758 /* copy the fields already swapped. the last field, pe_data_size, is missing */
759 memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
760 /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
761 * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
763 SWAP64 (header64.nt.pe_image_base);
764 header->nt.pe_image_base = header64.nt.pe_image_base;
765 SWAP64 (header64.nt.pe_stack_reserve);
766 header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
767 SWAP64 (header64.nt.pe_stack_commit);
768 header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
769 SWAP64 (header64.nt.pe_heap_reserve);
770 header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
771 SWAP64 (header64.nt.pe_heap_commit);
772 header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
774 header->nt.pe_section_align = header64.nt.pe_section_align;
775 header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
776 header->nt.pe_os_major = header64.nt.pe_os_major;
777 header->nt.pe_os_minor = header64.nt.pe_os_minor;
778 header->nt.pe_user_major = header64.nt.pe_user_major;
779 header->nt.pe_user_minor = header64.nt.pe_user_minor;
780 header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
781 header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
782 header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
783 header->nt.pe_image_size = header64.nt.pe_image_size;
784 header->nt.pe_header_size = header64.nt.pe_header_size;
785 header->nt.pe_checksum = header64.nt.pe_checksum;
786 header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
787 header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
788 header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
789 header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
791 /* copy the datadir */
792 memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
793 } else {
794 return -1;
797 /* MonoPEHeaderNT: not used yet */
798 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
799 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
800 SWAP16 (header->nt.pe_os_major); /* must be 4 */
801 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
802 SWAP16 (header->nt.pe_user_major);
803 SWAP16 (header->nt.pe_user_minor);
804 SWAP16 (header->nt.pe_subsys_major);
805 SWAP16 (header->nt.pe_subsys_minor);
806 SWAP32 (header->nt.pe_reserved_1);
807 SWAP32 (header->nt.pe_image_size);
808 SWAP32 (header->nt.pe_header_size);
809 SWAP32 (header->nt.pe_checksum);
810 SWAP16 (header->nt.pe_subsys_required);
811 SWAP16 (header->nt.pe_dll_flags);
812 SWAP32 (header->nt.pe_loader_flags);
813 SWAP32 (header->nt.pe_data_dir_count);
815 /* MonoDotNetHeader: mostly unused */
816 SWAPPDE (header->datadir.pe_export_table);
817 SWAPPDE (header->datadir.pe_import_table);
818 SWAPPDE (header->datadir.pe_resource_table);
819 SWAPPDE (header->datadir.pe_exception_table);
820 SWAPPDE (header->datadir.pe_certificate_table);
821 SWAPPDE (header->datadir.pe_reloc_table);
822 SWAPPDE (header->datadir.pe_debug);
823 SWAPPDE (header->datadir.pe_copyright);
824 SWAPPDE (header->datadir.pe_global_ptr);
825 SWAPPDE (header->datadir.pe_tls_table);
826 SWAPPDE (header->datadir.pe_load_config_table);
827 SWAPPDE (header->datadir.pe_bound_import);
828 SWAPPDE (header->datadir.pe_iat);
829 SWAPPDE (header->datadir.pe_delay_import_desc);
830 SWAPPDE (header->datadir.pe_cli_header);
831 SWAPPDE (header->datadir.pe_reserved);
833 #ifdef HOST_WIN32
834 if (image->is_module_handle)
835 image->raw_data_len = header->nt.pe_image_size;
836 #endif
838 return offset;
841 gboolean
842 mono_image_load_pe_data (MonoImage *image)
844 MonoCLIImageInfo *iinfo;
845 MonoDotNetHeader *header;
846 MonoMSDOSHeader msdos;
847 gint32 offset = 0;
849 iinfo = image->image_info;
850 header = &iinfo->cli_header;
852 #ifdef HOST_WIN32
853 if (!image->is_module_handle)
854 #endif
855 if (offset + sizeof (msdos) > image->raw_data_len)
856 goto invalid_image;
857 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
859 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
860 goto invalid_image;
862 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
864 offset = msdos.pe_offset;
866 offset = do_load_header (image, header, offset);
867 if (offset < 0)
868 goto invalid_image;
871 * this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
872 * we skip this test.
873 if (header->coff.coff_machine != 0x14c)
874 goto invalid_image;
877 #if 0
879 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
880 * which produces binaries with 7.0. From Sergey:
882 * The reason is that MSVC7 uses traditional compile/link
883 * sequence for CIL executables, and VS.NET (and Framework
884 * SDK) includes linker version 7, that puts 7.0 in this
885 * field. That's why it's currently not possible to load VC
886 * binaries with Mono. This field is pretty much meaningless
887 * anyway (what linker?).
889 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
890 goto invalid_image;
891 #endif
894 * FIXME: byte swap all addresses here for header.
897 if (!load_section_tables (image, iinfo, offset))
898 goto invalid_image;
900 return TRUE;
902 invalid_image:
903 return FALSE;
906 gboolean
907 mono_image_load_cli_data (MonoImage *image)
909 MonoCLIImageInfo *iinfo;
911 iinfo = image->image_info;
913 /* Load the CLI header */
914 if (!load_cli_header (image, iinfo))
915 return FALSE;
917 if (!load_metadata (image, iinfo))
918 return FALSE;
920 return TRUE;
923 void
924 mono_image_load_names (MonoImage *image)
926 /* modules don't have an assembly table row */
927 if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
928 image->assembly_name = mono_metadata_string_heap (image,
929 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
930 0, MONO_ASSEMBLY_NAME));
933 /* Portable pdb images don't have a MODULE row */
934 if (image->tables [MONO_TABLE_MODULE].rows) {
935 image->module_name = mono_metadata_string_heap (image,
936 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
937 0, MONO_MODULE_NAME));
941 static MonoImage *
942 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
943 gboolean care_about_cli, gboolean care_about_pecoff)
945 MonoCLIImageInfo *iinfo;
946 MonoDotNetHeader *header;
947 GSList *errors = NULL;
949 mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
951 mono_image_init (image);
953 iinfo = image->image_info;
954 header = &iinfo->cli_header;
956 if (status)
957 *status = MONO_IMAGE_IMAGE_INVALID;
959 if (care_about_pecoff == FALSE)
960 goto done;
962 if (!image->metadata_only) {
963 if (!mono_verifier_verify_pe_data (image, &errors))
964 goto invalid_image;
966 if (!mono_image_load_pe_data (image))
967 goto invalid_image;
970 if (care_about_cli == FALSE) {
971 goto done;
974 if (!mono_verifier_verify_cli_data (image, &errors))
975 goto invalid_image;
977 if (!mono_image_load_cli_data (image))
978 goto invalid_image;
980 if (!mono_verifier_verify_table_data (image, &errors))
981 goto invalid_image;
983 mono_image_load_names (image);
985 load_modules (image);
987 done:
988 mono_profiler_module_loaded (image, MONO_PROFILE_OK);
989 if (status)
990 *status = MONO_IMAGE_OK;
992 return image;
994 invalid_image:
995 if (errors) {
996 MonoVerifyInfo *info = errors->data;
997 g_warning ("Could not load image %s due to %s", image->name, info->message);
998 mono_free_verify_list (errors);
1000 mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
1001 mono_image_close (image);
1002 return NULL;
1005 static MonoImage *
1006 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
1007 gboolean care_about_cli, gboolean care_about_pecoff, gboolean refonly, gboolean metadata_only)
1009 MonoCLIImageInfo *iinfo;
1010 MonoImage *image;
1011 MonoFileMap *filed;
1013 if ((filed = mono_file_map_open (fname)) == NULL){
1014 if (IS_PORTABILITY_SET) {
1015 gchar *ffname = mono_portability_find_file (fname, TRUE);
1016 if (ffname) {
1017 filed = mono_file_map_open (ffname);
1018 g_free (ffname);
1022 if (filed == NULL) {
1023 if (status)
1024 *status = MONO_IMAGE_ERROR_ERRNO;
1025 return NULL;
1029 image = g_new0 (MonoImage, 1);
1030 image->raw_buffer_used = TRUE;
1031 image->raw_data_len = mono_file_map_size (filed);
1032 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);
1033 #if defined(HAVE_MMAP) && !defined (HOST_WIN32)
1034 if (!image->raw_data) {
1035 image->fileio_used = TRUE;
1036 image->raw_data = mono_file_map_fileio (image->raw_data_len, MONO_MMAP_READ|MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, &image->raw_data_handle);
1038 #endif
1039 if (!image->raw_data) {
1040 mono_file_map_close (filed);
1041 g_free (image);
1042 if (status)
1043 *status = MONO_IMAGE_IMAGE_INVALID;
1044 return NULL;
1046 iinfo = g_new0 (MonoCLIImageInfo, 1);
1047 image->image_info = iinfo;
1048 image->name = mono_path_resolve_symlinks (fname);
1049 image->ref_only = refonly;
1050 image->metadata_only = metadata_only;
1051 image->ref_count = 1;
1052 /* if MONO_SECURITY_MODE_CORE_CLR is set then determine if this image is platform code */
1053 image->core_clr_platform_code = mono_security_core_clr_determine_platform_image (image);
1055 mono_file_map_close (filed);
1056 return do_mono_image_load (image, status, care_about_cli, care_about_pecoff);
1059 MonoImage *
1060 mono_image_loaded_full (const char *name, gboolean refonly)
1062 MonoImage *res;
1063 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1065 mono_images_lock ();
1066 res = g_hash_table_lookup (loaded_images, name);
1067 mono_images_unlock ();
1068 return res;
1072 * mono_image_loaded:
1073 * @name: name of the image to load
1075 * This routine ensures that the given image is loaded.
1077 * Returns: the loaded MonoImage, or NULL on failure.
1079 MonoImage *
1080 mono_image_loaded (const char *name)
1082 return mono_image_loaded_full (name, FALSE);
1085 typedef struct {
1086 MonoImage *res;
1087 const char* guid;
1088 } GuidData;
1090 static void
1091 find_by_guid (gpointer key, gpointer val, gpointer user_data)
1093 GuidData *data = user_data;
1094 MonoImage *image;
1096 if (data->res)
1097 return;
1098 image = val;
1099 if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
1100 data->res = image;
1103 MonoImage *
1104 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
1106 GuidData data;
1107 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1108 data.res = NULL;
1109 data.guid = guid;
1111 mono_images_lock ();
1112 g_hash_table_foreach (loaded_images, find_by_guid, &data);
1113 mono_images_unlock ();
1114 return data.res;
1117 MonoImage *
1118 mono_image_loaded_by_guid (const char *guid)
1120 return mono_image_loaded_by_guid_full (guid, FALSE);
1123 static MonoImage *
1124 register_image (MonoImage *image)
1126 MonoImage *image2;
1127 GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1129 mono_images_lock ();
1130 image2 = g_hash_table_lookup (loaded_images, image->name);
1132 if (image2) {
1133 /* Somebody else beat us to it */
1134 mono_image_addref (image2);
1135 mono_images_unlock ();
1136 mono_image_close (image);
1137 return image2;
1139 g_hash_table_insert (loaded_images, image->name, image);
1140 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
1141 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);
1142 mono_images_unlock ();
1144 return image;
1147 MonoImage *
1148 mono_image_open_from_data_internal (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly, gboolean metadata_only, const char *name)
1150 MonoCLIImageInfo *iinfo;
1151 MonoImage *image;
1152 char *datac;
1154 if (!data || !data_len) {
1155 if (status)
1156 *status = MONO_IMAGE_IMAGE_INVALID;
1157 return NULL;
1159 datac = data;
1160 if (need_copy) {
1161 datac = g_try_malloc (data_len);
1162 if (!datac) {
1163 if (status)
1164 *status = MONO_IMAGE_ERROR_ERRNO;
1165 return NULL;
1167 memcpy (datac, data, data_len);
1170 image = g_new0 (MonoImage, 1);
1171 image->raw_data = datac;
1172 image->raw_data_len = data_len;
1173 image->raw_data_allocated = need_copy;
1174 image->name = (name == NULL) ? g_strdup_printf ("data-%p", datac) : g_strdup(name);
1175 iinfo = g_new0 (MonoCLIImageInfo, 1);
1176 image->image_info = iinfo;
1177 image->ref_only = refonly;
1178 image->metadata_only = metadata_only;
1180 image = do_mono_image_load (image, status, TRUE, TRUE);
1181 if (image == NULL)
1182 return NULL;
1184 return register_image (image);
1187 MonoImage *
1188 mono_image_open_from_data_with_name (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly, const char *name)
1190 return mono_image_open_from_data_internal (data, data_len, need_copy, status, refonly, FALSE, name);
1193 MonoImage *
1194 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1196 return mono_image_open_from_data_with_name (data, data_len, need_copy, status, refonly, NULL);
1199 MonoImage *
1200 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1202 return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1205 #ifdef HOST_WIN32
1206 /* fname is not duplicated. */
1207 MonoImage*
1208 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1210 MonoImage* image;
1211 MonoCLIImageInfo* iinfo;
1213 image = g_new0 (MonoImage, 1);
1214 image->raw_data = (char*) module_handle;
1215 image->is_module_handle = TRUE;
1216 iinfo = g_new0 (MonoCLIImageInfo, 1);
1217 image->image_info = iinfo;
1218 image->name = fname;
1219 image->ref_count = has_entry_point ? 0 : 1;
1220 image->has_entry_point = has_entry_point;
1222 image = do_mono_image_load (image, status, TRUE, TRUE);
1223 if (image == NULL)
1224 return NULL;
1226 return register_image (image);
1228 #endif
1230 MonoImage *
1231 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1233 MonoImage *image;
1234 GHashTable *loaded_images;
1235 char *absfname;
1237 g_return_val_if_fail (fname != NULL, NULL);
1239 #ifdef HOST_WIN32
1240 /* Load modules using LoadLibrary. */
1241 if (!refonly && coree_module_handle) {
1242 HMODULE module_handle;
1243 guint16 *fname_utf16;
1244 DWORD last_error;
1246 absfname = mono_path_resolve_symlinks (fname);
1247 fname_utf16 = NULL;
1249 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1250 mono_images_lock ();
1251 image = g_hash_table_lookup (loaded_images_hash, absfname);
1252 if (image) {
1253 g_assert (image->is_module_handle);
1254 if (image->has_entry_point && image->ref_count == 0) {
1255 /* Increment reference count on images loaded outside of the runtime. */
1256 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1257 /* The image is already loaded because _CorDllMain removes images from the hash. */
1258 module_handle = LoadLibrary (fname_utf16);
1259 g_assert (module_handle == (HMODULE) image->raw_data);
1261 mono_image_addref (image);
1262 mono_images_unlock ();
1263 if (fname_utf16)
1264 g_free (fname_utf16);
1265 g_free (absfname);
1266 return image;
1269 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1270 module_handle = MonoLoadImage (fname_utf16);
1271 if (status && module_handle == NULL)
1272 last_error = GetLastError ();
1274 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1275 image = g_hash_table_lookup (loaded_images_hash, absfname);
1276 if (image)
1277 mono_image_addref (image);
1278 mono_images_unlock ();
1280 g_free (fname_utf16);
1282 if (module_handle == NULL) {
1283 g_assert (!image);
1284 g_free (absfname);
1285 if (status) {
1286 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1287 *status = MONO_IMAGE_IMAGE_INVALID;
1288 else {
1289 if (last_error == ERROR_FILE_NOT_FOUND || last_error == ERROR_PATH_NOT_FOUND)
1290 errno = ENOENT;
1291 else
1292 errno = 0;
1295 return NULL;
1298 if (image) {
1299 g_assert (image->is_module_handle);
1300 g_assert (image->has_entry_point);
1301 g_free (absfname);
1302 return image;
1305 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1307 #endif
1309 absfname = mono_path_canonicalize (fname);
1312 * The easiest solution would be to do all the loading inside the mutex,
1313 * but that would lead to scalability problems. So we let the loading
1314 * happen outside the mutex, and if multiple threads happen to load
1315 * the same image, we discard all but the first copy.
1317 mono_images_lock ();
1318 loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1319 image = g_hash_table_lookup (loaded_images, absfname);
1320 g_free (absfname);
1322 if (image){
1323 mono_image_addref (image);
1324 mono_images_unlock ();
1325 return image;
1327 mono_images_unlock ();
1329 image = do_mono_image_open (fname, status, TRUE, TRUE, refonly, FALSE);
1330 if (image == NULL)
1331 return NULL;
1333 return register_image (image);
1337 * mono_image_open:
1338 * @fname: filename that points to the module we want to open
1339 * @status: An error condition is returned in this field
1341 * Returns: An open image of type %MonoImage or NULL on error.
1342 * The caller holds a temporary reference to the returned image which should be cleared
1343 * when no longer needed by calling mono_image_close ().
1344 * if NULL, then check the value of @status for details on the error
1346 MonoImage *
1347 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1349 return mono_image_open_full (fname, status, FALSE);
1353 * mono_pe_file_open:
1354 * @fname: filename that points to the module we want to open
1355 * @status: An error condition is returned in this field
1357 * Returns: An open image of type %MonoImage or NULL on error. if
1358 * NULL, then check the value of @status for details on the error.
1359 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1360 * It's just a PE file loader, used for FileVersionInfo. It also does
1361 * not use the image cache.
1363 MonoImage *
1364 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1366 g_return_val_if_fail (fname != NULL, NULL);
1368 return do_mono_image_open (fname, status, FALSE, TRUE, FALSE, FALSE);
1372 * mono_image_open_raw
1373 * @fname: filename that points to the module we want to open
1374 * @status: An error condition is returned in this field
1376 * Returns an image without loading neither pe or cli data.
1378 * Use mono_image_load_pe_data and mono_image_load_cli_data to load them.
1380 MonoImage *
1381 mono_image_open_raw (const char *fname, MonoImageOpenStatus *status)
1383 g_return_val_if_fail (fname != NULL, NULL);
1385 return do_mono_image_open (fname, status, FALSE, FALSE, FALSE, FALSE);
1389 * mono_image_open_metadata_only:
1391 * Open an image which contains metadata only without a PE header.
1393 MonoImage *
1394 mono_image_open_metadata_only (const char *fname, MonoImageOpenStatus *status)
1396 return do_mono_image_open (fname, status, TRUE, TRUE, FALSE, TRUE);
1399 void
1400 mono_image_fixup_vtable (MonoImage *image)
1402 #ifdef HOST_WIN32
1403 MonoCLIImageInfo *iinfo;
1404 MonoPEDirEntry *de;
1405 MonoVTableFixup *vtfixup;
1406 int count;
1407 gpointer slot;
1408 guint16 slot_type;
1409 int slot_count;
1411 g_assert (image->is_module_handle);
1413 iinfo = image->image_info;
1414 de = &iinfo->cli_cli_header.ch_vtable_fixups;
1415 if (!de->rva || !de->size)
1416 return;
1417 vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1418 if (!vtfixup)
1419 return;
1421 count = de->size / sizeof (MonoVTableFixup);
1422 while (count--) {
1423 if (!vtfixup->rva || !vtfixup->count)
1424 continue;
1426 slot = mono_image_rva_map (image, vtfixup->rva);
1427 g_assert (slot);
1428 slot_type = vtfixup->type;
1429 slot_count = vtfixup->count;
1430 if (slot_type & VTFIXUP_TYPE_32BIT)
1431 while (slot_count--) {
1432 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1433 slot = ((guint32*) slot) + 1;
1435 else if (slot_type & VTFIXUP_TYPE_64BIT)
1436 while (slot_count--) {
1437 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1438 slot = ((guint32*) slot) + 1;
1440 else
1441 g_assert_not_reached();
1443 vtfixup++;
1445 #else
1446 g_assert_not_reached();
1447 #endif
1450 static void
1451 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1453 g_hash_table_destroy ((GHashTable*)val);
1457 static void
1458 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1460 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1464 static void
1465 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1467 g_slist_free ((GSList*)val);
1471 * mono_image_addref:
1472 * @image: The image file we wish to add a reference to
1474 * Increases the reference count of an image.
1476 void
1477 mono_image_addref (MonoImage *image)
1479 InterlockedIncrement (&image->ref_count);
1482 void
1483 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1485 stream->alloc_size = stream->index = stream->offset = 0;
1486 g_free (stream->data);
1487 stream->data = NULL;
1488 if (stream->hash) {
1489 g_hash_table_destroy (stream->hash);
1490 stream->hash = NULL;
1494 static inline void
1495 free_hash (GHashTable *hash)
1497 if (hash)
1498 g_hash_table_destroy (hash);
1502 * Returns whether mono_image_close_finish() must be called as well.
1503 * We must unload images in two steps because clearing the domain in
1504 * SGen requires the class metadata to be intact, but we need to free
1505 * the mono_g_hash_tables in case a collection occurs during domain
1506 * unloading and the roots would trip up the GC.
1508 gboolean
1509 mono_image_close_except_pools (MonoImage *image)
1511 MonoImage *image2;
1512 GHashTable *loaded_images;
1513 int i;
1515 g_return_val_if_fail (image != NULL, FALSE);
1518 * Atomically decrement the refcount and remove ourselves from the hash tables, so
1519 * register_image () can't grab an image which is being closed.
1521 mono_images_lock ();
1523 if (InterlockedDecrement (&image->ref_count) > 0) {
1524 mono_images_unlock ();
1525 return FALSE;
1528 loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1529 image2 = g_hash_table_lookup (loaded_images, image->name);
1530 if (image == image2) {
1531 /* This is not true if we are called from mono_image_open () */
1532 g_hash_table_remove (loaded_images, image->name);
1534 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1535 g_hash_table_remove (loaded_images, (char *) image->assembly_name);
1537 mono_images_unlock ();
1539 #ifdef HOST_WIN32
1540 if (image->is_module_handle && image->has_entry_point) {
1541 mono_images_lock ();
1542 if (image->ref_count == 0) {
1543 /* Image will be closed by _CorDllMain. */
1544 FreeLibrary ((HMODULE) image->raw_data);
1545 mono_images_unlock ();
1546 return FALSE;
1548 mono_images_unlock ();
1550 #endif
1552 mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1554 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1556 mono_image_invoke_unload_hook (image);
1558 mono_metadata_clean_for_image (image);
1561 * The caches inside a MonoImage might refer to metadata which is stored in referenced
1562 * assemblies, so we can't release these references in mono_assembly_close () since the
1563 * MonoImage might outlive its associated MonoAssembly.
1565 if (image->references && !image_is_dynamic (image)) {
1566 for (i = 0; i < image->nreferences; i++) {
1567 if (image->references [i] && image->references [i] != REFERENCE_MISSING) {
1568 if (!mono_assembly_close_except_image_pools (image->references [i]))
1569 image->references [i] = NULL;
1572 } else {
1573 if (image->references) {
1574 g_free (image->references);
1575 image->references = NULL;
1579 #ifdef HOST_WIN32
1580 mono_images_lock ();
1581 if (image->is_module_handle && !image->has_entry_point)
1582 FreeLibrary ((HMODULE) image->raw_data);
1583 mono_images_unlock ();
1584 #endif
1586 if (image->raw_buffer_used) {
1587 if (image->raw_data != NULL) {
1588 #ifndef HOST_WIN32
1589 if (image->fileio_used)
1590 mono_file_unmap_fileio (image->raw_data, image->raw_data_handle);
1591 else
1592 #endif
1593 mono_file_unmap (image->raw_data, image->raw_data_handle);
1597 if (image->raw_data_allocated) {
1598 /* FIXME: do we need this? (image is disposed anyway) */
1599 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1600 MonoCLIImageInfo *ii = image->image_info;
1602 if ((image->raw_metadata > image->raw_data) &&
1603 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1604 image->raw_metadata = NULL;
1606 for (i = 0; i < ii->cli_section_count; i++)
1607 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1608 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1609 ii->cli_sections [i] = NULL;
1611 g_free (image->raw_data);
1614 if (debug_assembly_unload) {
1615 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1616 } else {
1617 g_free (image->name);
1618 g_free (image->guid);
1619 g_free (image->version);
1620 g_free (image->files);
1623 if (image->method_cache)
1624 g_hash_table_destroy (image->method_cache);
1625 if (image->methodref_cache)
1626 g_hash_table_destroy (image->methodref_cache);
1627 mono_internal_hash_table_destroy (&image->class_cache);
1628 mono_conc_hashtable_destroy (image->field_cache);
1629 if (image->array_cache) {
1630 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1631 g_hash_table_destroy (image->array_cache);
1633 if (image->szarray_cache)
1634 g_hash_table_destroy (image->szarray_cache);
1635 if (image->ptr_cache)
1636 g_hash_table_destroy (image->ptr_cache);
1637 if (image->name_cache) {
1638 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1639 g_hash_table_destroy (image->name_cache);
1642 free_hash (image->native_wrapper_cache);
1643 free_hash (image->native_wrapper_aot_cache);
1644 free_hash (image->native_wrapper_check_cache);
1645 free_hash (image->native_wrapper_aot_check_cache);
1646 free_hash (image->native_func_wrapper_cache);
1647 free_hash (image->managed_wrapper_cache);
1648 free_hash (image->delegate_begin_invoke_cache);
1649 free_hash (image->delegate_end_invoke_cache);
1650 free_hash (image->delegate_invoke_cache);
1651 free_hash (image->delegate_abstract_invoke_cache);
1652 free_hash (image->delegate_bound_static_invoke_cache);
1653 free_hash (image->delegate_invoke_generic_cache);
1654 free_hash (image->delegate_begin_invoke_generic_cache);
1655 free_hash (image->delegate_end_invoke_generic_cache);
1656 free_hash (image->synchronized_generic_cache);
1657 free_hash (image->remoting_invoke_cache);
1658 free_hash (image->runtime_invoke_cache);
1659 free_hash (image->runtime_invoke_vtype_cache);
1660 free_hash (image->runtime_invoke_direct_cache);
1661 free_hash (image->runtime_invoke_vcall_cache);
1662 free_hash (image->synchronized_cache);
1663 free_hash (image->unbox_wrapper_cache);
1664 free_hash (image->cominterop_invoke_cache);
1665 free_hash (image->cominterop_wrapper_cache);
1666 free_hash (image->typespec_cache);
1667 free_hash (image->ldfld_wrapper_cache);
1668 free_hash (image->ldflda_wrapper_cache);
1669 free_hash (image->stfld_wrapper_cache);
1670 free_hash (image->isinst_cache);
1671 free_hash (image->castclass_cache);
1672 free_hash (image->proxy_isinst_cache);
1673 free_hash (image->thunk_invoke_cache);
1674 free_hash (image->var_cache_slow);
1675 free_hash (image->mvar_cache_slow);
1676 free_hash (image->var_cache_constrained);
1677 free_hash (image->mvar_cache_constrained);
1678 free_hash (image->wrapper_param_names);
1679 free_hash (image->pinvoke_scopes);
1680 free_hash (image->pinvoke_scope_filenames);
1681 for (i = 0; i < image->gshared_types_len; ++i)
1682 free_hash (image->gshared_types [i]);
1683 g_free (image->gshared_types);
1685 /* The ownership of signatures is not well defined */
1686 g_hash_table_destroy (image->memberref_signatures);
1687 g_hash_table_destroy (image->helper_signatures);
1688 g_hash_table_destroy (image->method_signatures);
1690 if (image->rgctx_template_hash)
1691 g_hash_table_destroy (image->rgctx_template_hash);
1693 if (image->property_hash)
1694 mono_property_hash_destroy (image->property_hash);
1697 reflection_info_unregister_classes is only required by dynamic images, which will not be properly
1698 cleared during shutdown as we don't perform regular appdomain unload for the root one.
1700 g_assert (!image->reflection_info_unregister_classes || mono_runtime_is_shutting_down ());
1701 image->reflection_info_unregister_classes = NULL;
1703 if (image->interface_bitset) {
1704 mono_unload_interface_ids (image->interface_bitset);
1705 mono_bitset_free (image->interface_bitset);
1707 if (image->image_info){
1708 MonoCLIImageInfo *ii = image->image_info;
1710 if (ii->cli_section_tables)
1711 g_free (ii->cli_section_tables);
1712 if (ii->cli_sections)
1713 g_free (ii->cli_sections);
1714 g_free (image->image_info);
1717 for (i = 0; i < image->module_count; ++i) {
1718 if (image->modules [i]) {
1719 if (!mono_image_close_except_pools (image->modules [i]))
1720 image->modules [i] = NULL;
1723 if (image->modules_loaded)
1724 g_free (image->modules_loaded);
1726 mono_mutex_destroy (&image->szarray_cache_lock);
1727 mono_mutex_destroy (&image->lock);
1729 /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1730 if (image_is_dynamic (image)) {
1731 /* Dynamic images are GC_MALLOCed */
1732 g_free ((char*)image->module_name);
1733 mono_dynamic_image_free ((MonoDynamicImage*)image);
1736 mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1738 return TRUE;
1741 void
1742 mono_image_close_finish (MonoImage *image)
1744 int i;
1746 if (image->references && !image_is_dynamic (image)) {
1747 for (i = 0; i < image->nreferences; i++) {
1748 if (image->references [i] && image->references [i] != REFERENCE_MISSING)
1749 mono_assembly_close_finish (image->references [i]);
1752 g_free (image->references);
1753 image->references = NULL;
1756 for (i = 0; i < image->module_count; ++i) {
1757 if (image->modules [i])
1758 mono_image_close_finish (image->modules [i]);
1760 if (image->modules)
1761 g_free (image->modules);
1763 #ifndef DISABLE_PERFCOUNTERS
1764 mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
1765 #endif
1767 if (!image_is_dynamic (image)) {
1768 if (debug_assembly_unload)
1769 mono_mempool_invalidate (image->mempool);
1770 else {
1771 mono_mempool_destroy (image->mempool);
1772 g_free (image);
1774 } else {
1775 if (debug_assembly_unload)
1776 mono_mempool_invalidate (image->mempool);
1777 else {
1778 mono_mempool_destroy (image->mempool);
1779 mono_dynamic_image_free_image ((MonoDynamicImage*)image);
1785 * mono_image_close:
1786 * @image: The image file we wish to close
1788 * Closes an image file, deallocates all memory consumed and
1789 * unmaps all possible sections of the file
1791 void
1792 mono_image_close (MonoImage *image)
1794 if (mono_image_close_except_pools (image))
1795 mono_image_close_finish (image);
1798 /**
1799 * mono_image_strerror:
1800 * @status: an code indicating the result from a recent operation
1802 * Returns: a string describing the error
1804 const char *
1805 mono_image_strerror (MonoImageOpenStatus status)
1807 switch (status){
1808 case MONO_IMAGE_OK:
1809 return "success";
1810 case MONO_IMAGE_ERROR_ERRNO:
1811 return strerror (errno);
1812 case MONO_IMAGE_IMAGE_INVALID:
1813 return "File does not contain a valid CIL image";
1814 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1815 return "An assembly was referenced, but could not be found";
1817 return "Internal error";
1820 static gpointer
1821 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1822 guint32 lang_id, gunichar2 *name,
1823 MonoPEResourceDirEntry *entry,
1824 MonoPEResourceDir *root, guint32 level)
1826 gboolean is_string, is_dir;
1827 guint32 name_offset, dir_offset;
1829 /* Level 0 holds a directory entry for each type of resource
1830 * (identified by ID or name).
1832 * Level 1 holds a directory entry for each named resource
1833 * item, and each "anonymous" item of a particular type of
1834 * resource.
1836 * Level 2 holds a directory entry for each language pointing to
1837 * the actual data.
1839 is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1840 name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1842 is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1843 dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1845 if(level==0) {
1846 if (is_string)
1847 return NULL;
1848 } else if (level==1) {
1849 if (res_id != name_offset)
1850 return NULL;
1851 #if 0
1852 if(name!=NULL &&
1853 is_string==TRUE && name!=lookup (name_offset)) {
1854 return(NULL);
1856 #endif
1857 } else if (level==2) {
1858 if (is_string == TRUE || (is_string == FALSE && lang_id != 0 && name_offset != lang_id))
1859 return NULL;
1860 } else {
1861 g_assert_not_reached ();
1864 if(is_dir==TRUE) {
1865 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1866 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1867 guint32 entries, i;
1869 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1871 for(i=0; i<entries; i++) {
1872 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1873 gpointer ret;
1875 ret=mono_image_walk_resource_tree (info, res_id,
1876 lang_id, name,
1877 sub_entry, root,
1878 level+1);
1879 if(ret!=NULL) {
1880 return(ret);
1884 return(NULL);
1885 } else {
1886 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
1887 MonoPEResourceDataEntry *res;
1889 res = g_new0 (MonoPEResourceDataEntry, 1);
1891 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
1892 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
1893 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
1894 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
1896 return (res);
1901 * mono_image_lookup_resource:
1902 * @image: the image to look up the resource in
1903 * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1904 * @lang_id: The language id.
1905 * @name: the resource name to lookup.
1907 * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1908 * of the given resource. The caller should free it using g_free () when no longer
1909 * needed.
1911 gpointer
1912 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1914 MonoCLIImageInfo *info;
1915 MonoDotNetHeader *header;
1916 MonoPEDatadir *datadir;
1917 MonoPEDirEntry *rsrc;
1918 MonoPEResourceDir *resource_dir;
1919 MonoPEResourceDirEntry *res_entries;
1920 guint32 entries, i;
1922 if(image==NULL) {
1923 return(NULL);
1926 mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
1928 info=image->image_info;
1929 if(info==NULL) {
1930 return(NULL);
1933 header=&info->cli_header;
1934 if(header==NULL) {
1935 return(NULL);
1938 datadir=&header->datadir;
1939 if(datadir==NULL) {
1940 return(NULL);
1943 rsrc=&datadir->pe_resource_table;
1944 if(rsrc==NULL) {
1945 return(NULL);
1948 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1949 if(resource_dir==NULL) {
1950 return(NULL);
1953 entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1954 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1956 for(i=0; i<entries; i++) {
1957 MonoPEResourceDirEntry *entry=&res_entries[i];
1958 gpointer ret;
1960 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1961 name, entry, resource_dir,
1963 if(ret!=NULL) {
1964 return(ret);
1968 return(NULL);
1971 /**
1972 * mono_image_get_entry_point:
1973 * @image: the image where the entry point will be looked up.
1975 * Use this routine to determine the metadata token for method that
1976 * has been flagged as the entry point.
1978 * Returns: the token for the entry point method in the image
1980 guint32
1981 mono_image_get_entry_point (MonoImage *image)
1983 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1987 * mono_image_get_resource:
1988 * @image: the image where the resource will be looked up.
1989 * @offset: The offset to add to the resource
1990 * @size: a pointer to an int where the size of the resource will be stored
1992 * This is a low-level routine that fetches a resource from the
1993 * metadata that starts at a given @offset. The @size parameter is
1994 * filled with the data field as encoded in the metadata.
1996 * Returns: the pointer to the resource whose offset is @offset.
1998 const char*
1999 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
2001 MonoCLIImageInfo *iinfo = image->image_info;
2002 MonoCLIHeader *ch = &iinfo->cli_cli_header;
2003 const char* data;
2005 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
2006 return NULL;
2008 data = mono_image_rva_map (image, ch->ch_resources.rva);
2009 if (!data)
2010 return NULL;
2011 data += offset;
2012 if (size)
2013 *size = read32 (data);
2014 data += 4;
2015 return data;
2018 MonoImage*
2019 mono_image_load_file_for_image (MonoImage *image, int fileidx)
2021 char *base_dir, *name;
2022 MonoImage *res;
2023 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
2024 const char *fname;
2025 guint32 fname_id;
2027 if (fileidx < 1 || fileidx > t->rows)
2028 return NULL;
2030 mono_image_lock (image);
2031 if (image->files && image->files [fileidx - 1]) {
2032 mono_image_unlock (image);
2033 return image->files [fileidx - 1];
2035 mono_image_unlock (image);
2037 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
2038 fname = mono_metadata_string_heap (image, fname_id);
2039 base_dir = g_path_get_dirname (image->name);
2040 name = g_build_filename (base_dir, fname, NULL);
2041 res = mono_image_open (name, NULL);
2042 if (!res)
2043 goto done;
2045 mono_image_lock (image);
2046 if (image->files && image->files [fileidx - 1]) {
2047 MonoImage *old = res;
2048 res = image->files [fileidx - 1];
2049 mono_image_unlock (image);
2050 mono_image_close (old);
2051 } else {
2052 int i;
2053 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
2054 res->assembly = image->assembly;
2055 for (i = 0; i < res->module_count; ++i) {
2056 if (res->modules [i] && !res->modules [i]->assembly)
2057 res->modules [i]->assembly = image->assembly;
2060 if (!image->files)
2061 image->files = g_new0 (MonoImage*, t->rows);
2062 image->files [fileidx - 1] = res;
2063 mono_image_unlock (image);
2064 /* vtable fixup can't happen with the image lock held */
2065 #ifdef HOST_WIN32
2066 if (res->is_module_handle)
2067 mono_image_fixup_vtable (res);
2068 #endif
2071 done:
2072 g_free (name);
2073 g_free (base_dir);
2074 return res;
2078 * mono_image_get_strong_name:
2079 * @image: a MonoImage
2080 * @size: a guint32 pointer, or NULL.
2082 * If the image has a strong name, and @size is not NULL, the value
2083 * pointed to by size will have the size of the strong name.
2085 * Returns: NULL if the image does not have a strong name, or a
2086 * pointer to the public key.
2088 const char*
2089 mono_image_get_strong_name (MonoImage *image, guint32 *size)
2091 MonoCLIImageInfo *iinfo = image->image_info;
2092 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
2093 const char* data;
2095 if (!de->size || !de->rva)
2096 return NULL;
2097 data = mono_image_rva_map (image, de->rva);
2098 if (!data)
2099 return NULL;
2100 if (size)
2101 *size = de->size;
2102 return data;
2106 * mono_image_strong_name_position:
2107 * @image: a MonoImage
2108 * @size: a guint32 pointer, or NULL.
2110 * If the image has a strong name, and @size is not NULL, the value
2111 * pointed to by size will have the size of the strong name.
2113 * Returns: the position within the image file where the strong name
2114 * is stored.
2116 guint32
2117 mono_image_strong_name_position (MonoImage *image, guint32 *size)
2119 MonoCLIImageInfo *iinfo = image->image_info;
2120 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
2121 guint32 pos;
2123 if (size)
2124 *size = de->size;
2125 if (!de->size || !de->rva)
2126 return 0;
2127 pos = mono_cli_rva_image_map (image, de->rva);
2128 return pos == INVALID_ADDRESS ? 0 : pos;
2132 * mono_image_get_public_key:
2133 * @image: a MonoImage
2134 * @size: a guint32 pointer, or NULL.
2136 * This is used to obtain the public key in the @image.
2138 * If the image has a public key, and @size is not NULL, the value
2139 * pointed to by size will have the size of the public key.
2141 * Returns: NULL if the image does not have a public key, or a pointer
2142 * to the public key.
2144 const char*
2145 mono_image_get_public_key (MonoImage *image, guint32 *size)
2147 const char *pubkey;
2148 guint32 len, tok;
2150 if (image_is_dynamic (image)) {
2151 if (size)
2152 *size = ((MonoDynamicImage*)image)->public_key_len;
2153 return (char*)((MonoDynamicImage*)image)->public_key;
2155 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
2156 return NULL;
2157 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
2158 if (!tok)
2159 return NULL;
2160 pubkey = mono_metadata_blob_heap (image, tok);
2161 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
2162 if (size)
2163 *size = len;
2164 return pubkey;
2168 * mono_image_get_name:
2169 * @name: a MonoImage
2171 * Returns: the name of the assembly.
2173 const char*
2174 mono_image_get_name (MonoImage *image)
2176 return image->assembly_name;
2180 * mono_image_get_filename:
2181 * @image: a MonoImage
2183 * Used to get the filename that hold the actual MonoImage
2185 * Returns: the filename.
2187 const char*
2188 mono_image_get_filename (MonoImage *image)
2190 return image->name;
2193 const char*
2194 mono_image_get_guid (MonoImage *image)
2196 return image->guid;
2199 const MonoTableInfo*
2200 mono_image_get_table_info (MonoImage *image, int table_id)
2202 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2203 return NULL;
2204 return &image->tables [table_id];
2208 mono_image_get_table_rows (MonoImage *image, int table_id)
2210 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2211 return 0;
2212 return image->tables [table_id].rows;
2216 mono_table_info_get_rows (const MonoTableInfo *table)
2218 return table->rows;
2222 * mono_image_get_assembly:
2223 * @image: the MonoImage.
2225 * Use this routine to get the assembly that owns this image.
2227 * Returns: the assembly that holds this image.
2229 MonoAssembly*
2230 mono_image_get_assembly (MonoImage *image)
2232 return image->assembly;
2236 * mono_image_is_dynamic:
2237 * @image: the MonoImage
2239 * Determines if the given image was created dynamically through the
2240 * System.Reflection.Emit API
2242 * Returns: TRUE if the image was created dynamically, FALSE if not.
2244 gboolean
2245 mono_image_is_dynamic (MonoImage *image)
2247 return image_is_dynamic (image);
2251 * mono_image_has_authenticode_entry:
2252 * @image: the MonoImage
2254 * Use this routine to determine if the image has a Authenticode
2255 * Certificate Table.
2257 * Returns: TRUE if the image contains an authenticode entry in the PE
2258 * directory.
2260 gboolean
2261 mono_image_has_authenticode_entry (MonoImage *image)
2263 MonoCLIImageInfo *iinfo = image->image_info;
2264 MonoDotNetHeader *header = &iinfo->cli_header;
2265 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
2266 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
2267 return ((de->rva != 0) && (de->size > 8));
2270 gpointer
2271 mono_image_alloc (MonoImage *image, guint size)
2273 gpointer res;
2275 #ifndef DISABLE_PERFCOUNTERS
2276 mono_perfcounters->loader_bytes += size;
2277 #endif
2278 mono_image_lock (image);
2279 res = mono_mempool_alloc (image->mempool, size);
2280 mono_image_unlock (image);
2282 return res;
2285 gpointer
2286 mono_image_alloc0 (MonoImage *image, guint size)
2288 gpointer res;
2290 #ifndef DISABLE_PERFCOUNTERS
2291 mono_perfcounters->loader_bytes += size;
2292 #endif
2293 mono_image_lock (image);
2294 res = mono_mempool_alloc0 (image->mempool, size);
2295 mono_image_unlock (image);
2297 return res;
2300 char*
2301 mono_image_strdup (MonoImage *image, const char *s)
2303 char *res;
2305 #ifndef DISABLE_PERFCOUNTERS
2306 mono_perfcounters->loader_bytes += strlen (s);
2307 #endif
2308 mono_image_lock (image);
2309 res = mono_mempool_strdup (image->mempool, s);
2310 mono_image_unlock (image);
2312 return res;
2315 GList*
2316 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
2318 GList *new_list;
2320 new_list = mono_image_alloc (image, sizeof (GList));
2321 new_list->data = data;
2322 new_list->prev = list ? list->prev : NULL;
2323 new_list->next = list;
2325 if (new_list->prev)
2326 new_list->prev->next = new_list;
2327 if (list)
2328 list->prev = new_list;
2330 return new_list;
2333 GSList*
2334 g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
2336 GSList *new_list;
2338 new_list = mono_image_alloc (image, sizeof (GSList));
2339 new_list->data = data;
2340 new_list->next = NULL;
2342 return g_slist_concat (list, new_list);
2345 void
2346 mono_image_lock (MonoImage *image)
2348 mono_locks_acquire (&image->lock, ImageDataLock);
2351 void
2352 mono_image_unlock (MonoImage *image)
2354 mono_locks_release (&image->lock, ImageDataLock);
2359 * mono_image_property_lookup:
2361 * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
2363 * LOCKING: Takes the image lock
2365 gpointer
2366 mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
2368 gpointer res;
2370 mono_image_lock (image);
2371 res = mono_property_hash_lookup (image->property_hash, subject, property);
2372 mono_image_unlock (image);
2374 return res;
2378 * mono_image_property_insert:
2380 * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2382 * LOCKING: Takes the image lock
2384 void
2385 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
2387 mono_image_lock (image);
2388 mono_property_hash_insert (image->property_hash, subject, property, value);
2389 mono_image_unlock (image);
2393 * mono_image_property_remove:
2395 * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2397 * LOCKING: Takes the image lock
2399 void
2400 mono_image_property_remove (MonoImage *image, gpointer subject)
2402 mono_image_lock (image);
2403 mono_property_hash_remove_object (image->property_hash, subject);
2404 mono_image_unlock (image);
2407 void
2408 mono_image_append_class_to_reflection_info_set (MonoClass *class)
2410 MonoImage *image = class->image;
2411 g_assert (image_is_dynamic (image));
2412 mono_image_lock (image);
2413 image->reflection_info_unregister_classes = g_slist_prepend_mempool (image->mempool, image->reflection_info_unregister_classes, class);
2414 mono_image_unlock (image);