update the man page too match last changes
[mono.git] / mono / metadata / image.c
blobd86a2614af5b9a44c3001b34dbfd35b3e67eb3bf
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 * (C) 2001-2003 Ximian, Inc. http://www.ximian.com
12 #include <config.h>
13 #include <stdio.h>
14 #include <glib.h>
15 #include <errno.h>
16 #include <time.h>
17 #include <string.h>
18 #include "image.h"
19 #include "cil-coff.h"
20 #include "rawbuffer.h"
21 #include "mono-endian.h"
22 #include "tabledefs.h"
23 #include "tokentype.h"
24 #include "metadata-internals.h"
25 #include "loader.h"
26 #include <mono/io-layer/io-layer.h>
27 #include <mono/utils/mono-logger.h>
28 #include <mono/utils/mono-path.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
33 #define INVALID_ADDRESS 0xffffffff
36 * Keeps track of the various assemblies loaded
38 static GHashTable *loaded_images_hash;
39 static GHashTable *loaded_images_guid_hash;
40 static GHashTable *loaded_images_refonly_hash;
41 static GHashTable *loaded_images_refonly_guid_hash;
43 static gboolean debug_assembly_unload = FALSE;
45 #define mono_images_lock() EnterCriticalSection (&images_mutex)
46 #define mono_images_unlock() LeaveCriticalSection (&images_mutex)
47 static CRITICAL_SECTION images_mutex;
49 guint32
50 mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
52 const int top = iinfo->cli_section_count;
53 MonoSectionTable *tables = iinfo->cli_section_tables;
54 int i;
56 for (i = 0; i < top; i++){
57 if ((addr >= tables->st_virtual_address) &&
58 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
59 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
61 tables++;
63 return INVALID_ADDRESS;
66 /**
67 * mono_images_rva_map:
68 * @image: a MonoImage
69 * @addr: relative virtual address (RVA)
71 * This is a low-level routine used by the runtime to map relative
72 * virtual address (RVA) into their location in memory.
74 * Returns: the address in memory for the given RVA, or NULL if the
75 * RVA is not valid for this image.
77 char *
78 mono_image_rva_map (MonoImage *image, guint32 addr)
80 MonoCLIImageInfo *iinfo = image->image_info;
81 const int top = iinfo->cli_section_count;
82 MonoSectionTable *tables = iinfo->cli_section_tables;
83 int i;
85 for (i = 0; i < top; i++){
86 if ((addr >= tables->st_virtual_address) &&
87 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
88 if (!iinfo->cli_sections [i]) {
89 if (!mono_image_ensure_section_idx (image, i))
90 return NULL;
92 return (char*)iinfo->cli_sections [i] +
93 (addr - tables->st_virtual_address);
95 tables++;
97 return NULL;
101 * mono_images_init:
103 * Initialize the global variables used by this module.
105 void
106 mono_images_init (void)
108 InitializeCriticalSection (&images_mutex);
110 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
111 loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
112 loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
113 loaded_images_refonly_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
115 debug_assembly_unload = getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
119 * mono_images_cleanup:
121 * Free all resources used by this module.
123 void
124 mono_images_cleanup (void)
126 DeleteCriticalSection (&images_mutex);
128 g_hash_table_destroy (loaded_images_hash);
129 g_hash_table_destroy (loaded_images_guid_hash);
130 g_hash_table_destroy (loaded_images_refonly_hash);
131 g_hash_table_destroy (loaded_images_refonly_guid_hash);
135 * mono_image_ensure_section_idx:
136 * @image: The image we are operating on
137 * @section: section number that we will load/map into memory
139 * This routine makes sure that we have an in-memory copy of
140 * an image section (.text, .rsrc, .data).
142 * Returns: TRUE on success
145 mono_image_ensure_section_idx (MonoImage *image, int section)
147 MonoCLIImageInfo *iinfo = image->image_info;
148 MonoSectionTable *sect;
149 gboolean writable;
151 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
153 if (iinfo->cli_sections [section] != NULL)
154 return TRUE;
156 sect = &iinfo->cli_section_tables [section];
158 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
160 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
161 return FALSE;
162 /* FIXME: we ignore the writable flag since we don't patch the binary */
163 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
164 return TRUE;
168 * mono_image_ensure_section:
169 * @image: The image we are operating on
170 * @section: section name that we will load/map into memory
172 * This routine makes sure that we have an in-memory copy of
173 * an image section (.text, .rsrc, .data).
175 * Returns: TRUE on success
178 mono_image_ensure_section (MonoImage *image, const char *section)
180 MonoCLIImageInfo *ii = image->image_info;
181 int i;
183 for (i = 0; i < ii->cli_section_count; i++){
184 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
185 continue;
187 return mono_image_ensure_section_idx (image, i);
189 return FALSE;
192 static int
193 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
195 const int top = iinfo->cli_header.coff.coff_sections;
196 int i;
198 iinfo->cli_section_count = top;
199 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
200 iinfo->cli_sections = g_new0 (void *, top);
202 for (i = 0; i < top; i++){
203 MonoSectionTable *t = &iinfo->cli_section_tables [i];
205 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
206 return FALSE;
207 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
208 offset += sizeof (MonoSectionTable);
210 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
211 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
212 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
213 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
214 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
215 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
216 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
217 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
218 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
219 t->st_flags = GUINT32_FROM_LE (t->st_flags);
220 #endif
221 /* consistency checks here */
224 return TRUE;
227 static gboolean
228 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
230 guint32 offset;
232 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
233 if (offset == INVALID_ADDRESS)
234 return FALSE;
236 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
237 return FALSE;
238 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
240 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
241 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
242 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
243 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
244 SWAP32 (iinfo->cli_cli_header.ch_size);
245 SWAP32 (iinfo->cli_cli_header.ch_flags);
246 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
247 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
248 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
249 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
250 SWAPPDE (iinfo->cli_cli_header.ch_resources);
251 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
252 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
253 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
254 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
255 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
256 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
257 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
258 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
259 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
260 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
261 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
262 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
263 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
264 #undef SWAP32
265 #undef SWAP16
266 #undef SWAPPDE
267 #endif
268 /* Catch new uses of the fields that are supposed to be zero */
270 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
271 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
272 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
273 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
274 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
275 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
276 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
277 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
278 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
281 * No need to scare people who are testing this, I am just
282 * labelling this as a LAMESPEC
284 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
288 return TRUE;
291 static gboolean
292 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
294 guint32 offset, size;
295 guint16 streams;
296 int i;
297 guint32 pad;
298 char *ptr;
300 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
301 if (offset == INVALID_ADDRESS)
302 return FALSE;
304 size = iinfo->cli_cli_header.ch_metadata.size;
306 if (offset + size > image->raw_data_len)
307 return FALSE;
308 image->raw_metadata = image->raw_data + offset;
310 ptr = image->raw_metadata;
312 if (strncmp (ptr, "BSJB", 4) == 0){
313 guint32 version_string_len;
315 ptr += 4;
316 image->md_version_major = read16 (ptr);
317 ptr += 4;
318 image->md_version_minor = read16 (ptr);
319 ptr += 4;
321 version_string_len = read32 (ptr);
322 ptr += 4;
323 image->version = g_strndup (ptr, version_string_len);
324 ptr += version_string_len;
325 pad = ptr - image->raw_metadata;
326 if (pad % 4)
327 ptr += 4 - (pad % 4);
328 } else
329 return FALSE;
331 /* skip over flags */
332 ptr += 2;
334 streams = read16 (ptr);
335 ptr += 2;
337 for (i = 0; i < streams; i++){
338 if (strncmp (ptr + 8, "#~", 3) == 0){
339 image->heap_tables.data = image->raw_metadata + read32 (ptr);
340 image->heap_tables.size = read32 (ptr + 4);
341 ptr += 8 + 3;
342 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
343 image->heap_strings.data = image->raw_metadata + read32 (ptr);
344 image->heap_strings.size = read32 (ptr + 4);
345 ptr += 8 + 9;
346 } else if (strncmp (ptr + 8, "#US", 4) == 0){
347 image->heap_us.data = image->raw_metadata + read32 (ptr);
348 image->heap_us.size = read32 (ptr + 4);
349 ptr += 8 + 4;
350 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
351 image->heap_blob.data = image->raw_metadata + read32 (ptr);
352 image->heap_blob.size = read32 (ptr + 4);
353 ptr += 8 + 6;
354 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
355 image->heap_guid.data = image->raw_metadata + read32 (ptr);
356 image->heap_guid.size = read32 (ptr + 4);
357 ptr += 8 + 6;
358 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
359 image->heap_tables.data = image->raw_metadata + read32 (ptr);
360 image->heap_tables.size = read32 (ptr + 4);
361 ptr += 8 + 3;
362 image->uncompressed_metadata = TRUE;
363 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);
364 } else {
365 g_message ("Unknown heap type: %s\n", ptr + 8);
366 ptr += 8 + strlen (ptr + 8) + 1;
368 pad = ptr - image->raw_metadata;
369 if (pad % 4)
370 ptr += 4 - (pad % 4);
373 g_assert (image->heap_guid.data);
374 g_assert (image->heap_guid.size >= 16);
376 image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
378 return TRUE;
382 * Load representation of logical metadata tables, from the "#~" stream
384 static gboolean
385 load_tables (MonoImage *image)
387 const char *heap_tables = image->heap_tables.data;
388 const guint32 *rows;
389 guint64 valid_mask, sorted_mask;
390 int valid = 0, table;
391 int heap_sizes;
393 heap_sizes = heap_tables [6];
394 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
395 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
396 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
398 valid_mask = read64 (heap_tables + 8);
399 sorted_mask = read64 (heap_tables + 16);
400 rows = (const guint32 *) (heap_tables + 24);
402 for (table = 0; table < 64; table++){
403 if ((valid_mask & ((guint64) 1 << table)) == 0){
404 if (table > MONO_TABLE_LAST)
405 continue;
406 image->tables [table].rows = 0;
407 continue;
409 if (table > MONO_TABLE_LAST) {
410 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
411 } else {
412 image->tables [table].rows = read32 (rows);
414 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
415 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
417 rows++;
418 valid++;
421 image->tables_base = (heap_tables + 24) + (4 * valid);
423 /* They must be the same */
424 g_assert ((const void *) image->tables_base == (const void *) rows);
426 mono_metadata_compute_table_bases (image);
427 return TRUE;
430 static gboolean
431 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
433 if (!load_metadata_ptrs (image, iinfo))
434 return FALSE;
436 return load_tables (image);
439 void
440 mono_image_check_for_module_cctor (MonoImage *image)
442 MonoTableInfo *t, *mt;
443 t = &image->tables [MONO_TABLE_TYPEDEF];
444 mt = &image->tables [MONO_TABLE_METHOD];
445 if (mono_get_runtime_info ()->framework_version [0] == '1') {
446 image->checked_module_cctor = TRUE;
447 return;
449 if (t->rows >= 1) {
450 guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
451 const char *name = mono_metadata_string_heap (image, nameidx);
452 if (strcmp (name, "<Module>") == 0) {
453 guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
454 guint32 last_method;
455 if (t->rows > 1)
456 last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
457 else
458 last_method = mt->rows;
459 for (; first_method < last_method; first_method++) {
460 nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
461 name = mono_metadata_string_heap (image, nameidx);
462 if (strcmp (name, ".cctor") == 0) {
463 image->has_module_cctor = TRUE;
464 image->checked_module_cctor = TRUE;
465 return;
470 image->has_module_cctor = FALSE;
471 image->checked_module_cctor = TRUE;
474 static void
475 load_modules (MonoImage *image, MonoImageOpenStatus *status)
477 MonoTableInfo *t;
478 MonoTableInfo *file_table;
479 int i;
480 char *base_dir;
481 gboolean refonly = image->ref_only;
482 GList *list_iter, *valid_modules = NULL;
484 if (image->modules)
485 return;
487 file_table = &image->tables [MONO_TABLE_FILE];
488 for (i = 0; i < file_table->rows; i++) {
489 guint32 cols [MONO_FILE_SIZE];
490 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
491 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
492 continue;
493 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
496 t = &image->tables [MONO_TABLE_MODULEREF];
497 image->modules = g_new0 (MonoImage *, t->rows);
498 image->module_count = t->rows;
499 base_dir = g_path_get_dirname (image->name);
500 for (i = 0; i < t->rows; i++){
501 char *module_ref;
502 const char *name;
503 guint32 cols [MONO_MODULEREF_SIZE];
504 /* if there is no file table, we try to load the module... */
505 int valid = file_table->rows == 0;
507 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
508 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
509 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
510 /* be safe with string dups, but we could just compare string indexes */
511 if (strcmp (list_iter->data, name) == 0) {
512 valid = TRUE;
513 break;
516 if (!valid)
517 continue;
518 module_ref = g_build_filename (base_dir, name, NULL);
519 image->modules [i] = mono_image_open_full (module_ref, status, refonly);
520 if (image->modules [i]) {
521 mono_image_addref (image->modules [i]);
522 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
525 * FIXME: We should probably do lazy-loading of modules.
527 if (status)
528 *status = MONO_IMAGE_OK;
529 g_free (module_ref);
532 g_free (base_dir);
533 g_list_free (valid_modules);
536 static void
537 register_guid (gpointer key, gpointer value, gpointer user_data)
539 MonoImage *image = (MonoImage*)value;
541 if (!g_hash_table_lookup (loaded_images_guid_hash, image))
542 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
545 static void
546 build_guid_table (gboolean refonly)
548 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
549 g_hash_table_foreach (loaded_images, register_guid, NULL);
552 void
553 mono_image_init (MonoImage *image)
555 image->mempool = mono_mempool_new ();
556 image->method_cache = g_hash_table_new (NULL, NULL);
557 image->class_cache = g_hash_table_new (NULL, NULL);
558 image->field_cache = g_hash_table_new (NULL, NULL);
560 image->delegate_begin_invoke_cache =
561 g_hash_table_new ((GHashFunc)mono_signature_hash,
562 (GCompareFunc)mono_metadata_signature_equal);
563 image->delegate_end_invoke_cache =
564 g_hash_table_new ((GHashFunc)mono_signature_hash,
565 (GCompareFunc)mono_metadata_signature_equal);
566 image->delegate_invoke_cache =
567 g_hash_table_new ((GHashFunc)mono_signature_hash,
568 (GCompareFunc)mono_metadata_signature_equal);
569 image->runtime_invoke_cache =
570 g_hash_table_new ((GHashFunc)mono_signature_hash,
571 (GCompareFunc)mono_metadata_signature_equal);
573 image->managed_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
574 image->native_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
575 image->remoting_invoke_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
576 image->cominterop_invoke_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
577 image->cominterop_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
578 image->synchronized_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
579 image->unbox_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
581 image->ldfld_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
582 image->ldflda_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
583 image->ldfld_remote_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
584 image->stfld_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
585 image->stfld_remote_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
586 image->isinst_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
587 image->castclass_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
588 image->proxy_isinst_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
590 image->typespec_cache = g_hash_table_new (NULL, NULL);
591 image->memberref_signatures = g_hash_table_new (NULL, NULL);
592 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
593 image->method_signatures = g_hash_table_new (NULL, NULL);
596 static MonoImage *
597 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
598 gboolean care_about_cli)
600 MonoCLIImageInfo *iinfo;
601 MonoDotNetHeader *header;
602 MonoMSDOSHeader msdos;
603 guint32 offset = 0;
605 mono_image_init (image);
607 iinfo = image->image_info;
608 header = &iinfo->cli_header;
610 if (status)
611 *status = MONO_IMAGE_IMAGE_INVALID;
613 if (offset + sizeof (msdos) > image->raw_data_len)
614 goto invalid_image;
615 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
617 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
618 goto invalid_image;
620 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
622 offset = msdos.pe_offset;
624 if (offset + sizeof (MonoDotNetHeader) > image->raw_data_len)
625 goto invalid_image;
626 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
627 offset += sizeof (MonoDotNetHeader);
629 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
630 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
631 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
632 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
633 SWAP32 (header->coff.coff_time);
634 SWAP32 (header->coff.coff_symptr);
635 SWAP32 (header->coff.coff_symcount);
636 SWAP16 (header->coff.coff_machine);
637 SWAP16 (header->coff.coff_sections);
638 SWAP16 (header->coff.coff_opt_header_size);
639 SWAP16 (header->coff.coff_attributes);
640 /* MonoPEHeader */
641 SWAP32 (header->pe.pe_code_size);
642 SWAP32 (header->pe.pe_data_size);
643 SWAP32 (header->pe.pe_uninit_data_size);
644 SWAP32 (header->pe.pe_rva_entry_point);
645 SWAP32 (header->pe.pe_rva_code_base);
646 SWAP32 (header->pe.pe_rva_data_base);
647 SWAP16 (header->pe.pe_magic);
649 /* MonoPEHeaderNT: not used yet */
650 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
651 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
652 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
653 SWAP16 (header->nt.pe_os_major); /* must be 4 */
654 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
655 SWAP16 (header->nt.pe_user_major);
656 SWAP16 (header->nt.pe_user_minor);
657 SWAP16 (header->nt.pe_subsys_major);
658 SWAP16 (header->nt.pe_subsys_minor);
659 SWAP32 (header->nt.pe_reserved_1);
660 SWAP32 (header->nt.pe_image_size);
661 SWAP32 (header->nt.pe_header_size);
662 SWAP32 (header->nt.pe_checksum);
663 SWAP16 (header->nt.pe_subsys_required);
664 SWAP16 (header->nt.pe_dll_flags);
665 SWAP32 (header->nt.pe_stack_reserve);
666 SWAP32 (header->nt.pe_stack_commit);
667 SWAP32 (header->nt.pe_heap_reserve);
668 SWAP32 (header->nt.pe_heap_commit);
669 SWAP32 (header->nt.pe_loader_flags);
670 SWAP32 (header->nt.pe_data_dir_count);
672 /* MonoDotNetHeader: mostly unused */
673 SWAPPDE (header->datadir.pe_export_table);
674 SWAPPDE (header->datadir.pe_import_table);
675 SWAPPDE (header->datadir.pe_resource_table);
676 SWAPPDE (header->datadir.pe_exception_table);
677 SWAPPDE (header->datadir.pe_certificate_table);
678 SWAPPDE (header->datadir.pe_reloc_table);
679 SWAPPDE (header->datadir.pe_debug);
680 SWAPPDE (header->datadir.pe_copyright);
681 SWAPPDE (header->datadir.pe_global_ptr);
682 SWAPPDE (header->datadir.pe_tls_table);
683 SWAPPDE (header->datadir.pe_load_config_table);
684 SWAPPDE (header->datadir.pe_bound_import);
685 SWAPPDE (header->datadir.pe_iat);
686 SWAPPDE (header->datadir.pe_delay_import_desc);
687 SWAPPDE (header->datadir.pe_cli_header);
688 SWAPPDE (header->datadir.pe_reserved);
690 #undef SWAP32
691 #undef SWAP16
692 #undef SWAPPDE
693 #endif
695 if (header->coff.coff_machine != 0x14c)
696 goto invalid_image;
698 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
699 goto invalid_image;
701 if (header->pesig[0] != 'P' || header->pesig[1] != 'E' || header->pe.pe_magic != 0x10B)
702 goto invalid_image;
704 #if 0
706 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
707 * which produces binaries with 7.0. From Sergey:
709 * The reason is that MSVC7 uses traditional compile/link
710 * sequence for CIL executables, and VS.NET (and Framework
711 * SDK) includes linker version 7, that puts 7.0 in this
712 * field. That's why it's currently not possible to load VC
713 * binaries with Mono. This field is pretty much meaningless
714 * anyway (what linker?).
716 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
717 goto invalid_image;
718 #endif
721 * FIXME: byte swap all addresses here for header.
724 if (!load_section_tables (image, iinfo, offset))
725 goto invalid_image;
727 if (care_about_cli == FALSE) {
728 goto done;
731 /* Load the CLI header */
732 if (!load_cli_header (image, iinfo))
733 goto invalid_image;
735 if (!load_metadata (image, iinfo))
736 goto invalid_image;
738 /* modules don't have an assembly table row */
739 if (image->tables [MONO_TABLE_ASSEMBLY].rows)
740 image->assembly_name = mono_metadata_string_heap (image,
741 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
742 0, MONO_ASSEMBLY_NAME));
744 image->module_name = mono_metadata_string_heap (image,
745 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
746 0, MONO_MODULE_NAME));
748 load_modules (image, status);
750 done:
751 if (status)
752 *status = MONO_IMAGE_OK;
754 return image;
756 invalid_image:
757 mono_image_close (image);
758 return NULL;
761 static MonoImage *
762 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
763 gboolean care_about_cli, gboolean refonly)
765 MonoCLIImageInfo *iinfo;
766 MonoImage *image;
767 FILE *filed;
768 struct stat stat_buf;
770 if ((filed = fopen (fname, "rb")) == NULL){
771 if (status)
772 *status = MONO_IMAGE_ERROR_ERRNO;
773 return NULL;
776 if (fstat (fileno (filed), &stat_buf)) {
777 fclose (filed);
778 if (status)
779 *status = MONO_IMAGE_ERROR_ERRNO;
780 return NULL;
782 image = g_new0 (MonoImage, 1);
783 image->file_descr = filed;
784 image->raw_data_len = stat_buf.st_size;
785 image->raw_data = mono_raw_buffer_load (fileno (filed), FALSE, 0, stat_buf.st_size);
786 iinfo = g_new0 (MonoCLIImageInfo, 1);
787 image->image_info = iinfo;
788 image->name = mono_path_resolve_symlinks (fname);
789 image->ref_only = refonly;
790 image->ref_count = 1;
792 return do_mono_image_load (image, status, care_about_cli);
795 MonoImage *
796 mono_image_loaded_full (const char *name, gboolean refonly)
798 MonoImage *res;
799 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
801 mono_images_lock ();
802 res = g_hash_table_lookup (loaded_images, name);
803 mono_images_unlock ();
804 return res;
808 * mono_image_loaded:
809 * @name: name of the image to load
811 * This routine ensures that the given image is loaded.
813 * Returns: the loaded MonoImage, or NULL on failure.
815 MonoImage *
816 mono_image_loaded (const char *name)
818 return mono_image_loaded_full (name, FALSE);
821 MonoImage *
822 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
824 MonoImage *res;
825 GHashTable *loaded_images = refonly ? loaded_images_refonly_guid_hash : loaded_images_guid_hash;
827 mono_images_lock ();
828 res = g_hash_table_lookup (loaded_images, guid);
829 mono_images_unlock ();
830 return res;
833 MonoImage *
834 mono_image_loaded_by_guid (const char *guid)
836 return mono_image_loaded_by_guid_full (guid, FALSE);
839 static MonoImage *
840 register_image (MonoImage *image)
842 MonoImage *image2;
843 GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
845 mono_images_lock ();
846 image2 = g_hash_table_lookup (loaded_images, image->name);
848 if (image2) {
849 /* Somebody else beat us to it */
850 mono_image_addref (image2);
851 mono_images_unlock ();
852 mono_image_close (image);
853 return image2;
855 g_hash_table_insert (loaded_images, image->name, image);
856 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
857 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);
858 g_hash_table_insert (image->ref_only ? loaded_images_refonly_guid_hash : loaded_images_guid_hash, image->guid, image);
859 mono_images_unlock ();
861 return image;
864 MonoImage *
865 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
867 MonoCLIImageInfo *iinfo;
868 MonoImage *image;
869 char *datac;
871 if (!data || !data_len) {
872 if (status)
873 *status = MONO_IMAGE_IMAGE_INVALID;
874 return NULL;
876 datac = data;
877 if (need_copy) {
878 datac = g_try_malloc (data_len);
879 if (!datac) {
880 if (status)
881 *status = MONO_IMAGE_ERROR_ERRNO;
882 return NULL;
884 memcpy (datac, data, data_len);
887 image = g_new0 (MonoImage, 1);
888 image->raw_data = datac;
889 image->raw_data_len = data_len;
890 image->raw_data_allocated = need_copy;
891 image->name = g_strdup_printf ("data-%p", datac);
892 iinfo = g_new0 (MonoCLIImageInfo, 1);
893 image->image_info = iinfo;
894 image->ref_only = refonly;
896 image = do_mono_image_load (image, status, TRUE);
897 if (image == NULL)
898 return NULL;
900 return register_image (image);
903 MonoImage *
904 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
906 return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
909 MonoImage *
910 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
912 MonoImage *image;
913 GHashTable *loaded_images;
914 char *absfname;
916 g_return_val_if_fail (fname != NULL, NULL);
918 absfname = mono_path_canonicalize (fname);
921 * The easiest solution would be to do all the loading inside the mutex,
922 * but that would lead to scalability problems. So we let the loading
923 * happen outside the mutex, and if multiple threads happen to load
924 * the same image, we discard all but the first copy.
926 mono_images_lock ();
927 loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
928 image = g_hash_table_lookup (loaded_images, absfname);
929 g_free (absfname);
931 if (image){
932 mono_image_addref (image);
933 mono_images_unlock ();
934 return image;
936 mono_images_unlock ();
938 image = do_mono_image_open (fname, status, TRUE, refonly);
939 if (image == NULL)
940 return NULL;
942 return register_image (image);
946 * mono_image_open:
947 * @fname: filename that points to the module we want to open
948 * @status: An error condition is returned in this field
950 * Returns: An open image of type %MonoImage or NULL on error.
951 * The caller holds a temporary reference to the returned image which should be cleared
952 * when no longer needed by calling mono_image_close ().
953 * if NULL, then check the value of @status for details on the error
955 MonoImage *
956 mono_image_open (const char *fname, MonoImageOpenStatus *status)
958 return mono_image_open_full (fname, status, FALSE);
962 * mono_pe_file_open:
963 * @fname: filename that points to the module we want to open
964 * @status: An error condition is returned in this field
966 * Returns: An open image of type %MonoImage or NULL on error. if
967 * NULL, then check the value of @status for details on the error.
968 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
969 * It's just a PE file loader, used for FileVersionInfo. It also does
970 * not use the image cache.
972 MonoImage *
973 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
975 g_return_val_if_fail (fname != NULL, NULL);
977 return(do_mono_image_open (fname, status, FALSE, FALSE));
980 static void
981 free_hash_table (gpointer key, gpointer val, gpointer user_data)
983 g_hash_table_destroy ((GHashTable*)val);
987 static void
988 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
990 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
994 static void
995 free_blob_cache_entry (gpointer key, gpointer val, gpointer user_data)
997 g_free (key);
1000 static void
1001 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
1003 g_free (val);
1006 static void
1007 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1009 g_slist_free ((GSList*)val);
1013 * mono_image_addref:
1014 * @image: The image file we wish to add a reference to
1016 * Increases the reference count of an image.
1018 void
1019 mono_image_addref (MonoImage *image)
1021 InterlockedIncrement (&image->ref_count);
1024 void
1025 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1027 stream->alloc_size = stream->index = stream->offset = 0;
1028 g_free (stream->data);
1029 stream->data = NULL;
1030 if (stream->hash) {
1031 g_hash_table_destroy (stream->hash);
1032 stream->hash = NULL;
1037 * mono_image_close:
1038 * @image: The image file we wish to close
1040 * Closes an image file, deallocates all memory consumed and
1041 * unmaps all possible sections of the file
1043 void
1044 mono_image_close (MonoImage *image)
1046 MonoImage *image2;
1047 GHashTable *loaded_images, *loaded_images_guid;
1048 int i;
1050 g_return_if_fail (image != NULL);
1052 if (InterlockedDecrement (&image->ref_count) > 0)
1053 return;
1055 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1057 mono_images_lock ();
1058 loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1059 loaded_images_guid = image->ref_only ? loaded_images_refonly_guid_hash : loaded_images_guid_hash;
1060 image2 = g_hash_table_lookup (loaded_images, image->name);
1061 if (image == image2) {
1062 /* This is not true if we are called from mono_image_open () */
1063 g_hash_table_remove (loaded_images, image->name);
1064 g_hash_table_remove (loaded_images_guid, image->guid);
1066 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1067 g_hash_table_remove (loaded_images, (char *) image->assembly_name);
1069 /* Multiple images might have the same guid */
1070 build_guid_table (image->ref_only);
1072 mono_images_unlock ();
1074 if (image->file_descr) {
1075 fclose (image->file_descr);
1076 image->file_descr = NULL;
1077 if (image->raw_data != NULL)
1078 mono_raw_buffer_free (image->raw_data);
1081 if (image->raw_data_allocated) {
1082 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1083 MonoCLIImageInfo *ii = image->image_info;
1085 if ((image->raw_metadata > image->raw_data) &&
1086 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1087 image->raw_metadata = NULL;
1089 for (i = 0; i < ii->cli_section_count; i++)
1090 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1091 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1092 ii->cli_sections [i] = NULL;
1094 g_free (image->raw_data);
1097 if (debug_assembly_unload) {
1098 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1099 } else {
1100 g_free (image->name);
1101 g_free (image->guid);
1102 g_free (image->version);
1103 g_free (image->files);
1106 g_hash_table_destroy (image->method_cache);
1107 g_hash_table_destroy (image->class_cache);
1108 g_hash_table_destroy (image->field_cache);
1109 if (image->array_cache) {
1110 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1111 g_hash_table_destroy (image->array_cache);
1113 if (image->ptr_cache)
1114 g_hash_table_destroy (image->ptr_cache);
1115 if (image->name_cache) {
1116 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1117 g_hash_table_destroy (image->name_cache);
1119 g_hash_table_destroy (image->native_wrapper_cache);
1120 g_hash_table_destroy (image->managed_wrapper_cache);
1121 g_hash_table_destroy (image->delegate_begin_invoke_cache);
1122 g_hash_table_destroy (image->delegate_end_invoke_cache);
1123 g_hash_table_destroy (image->delegate_invoke_cache);
1124 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1125 g_hash_table_destroy (image->remoting_invoke_cache);
1126 g_hash_table_destroy (image->runtime_invoke_cache);
1127 g_hash_table_destroy (image->synchronized_cache);
1128 g_hash_table_destroy (image->unbox_wrapper_cache);
1129 g_hash_table_destroy (image->cominterop_invoke_cache);
1130 g_hash_table_destroy (image->cominterop_wrapper_cache);
1131 g_hash_table_destroy (image->typespec_cache);
1132 g_hash_table_destroy (image->ldfld_wrapper_cache);
1133 g_hash_table_destroy (image->ldflda_wrapper_cache);
1134 g_hash_table_destroy (image->ldfld_remote_wrapper_cache);
1135 g_hash_table_destroy (image->stfld_wrapper_cache);
1136 g_hash_table_destroy (image->stfld_remote_wrapper_cache);
1137 g_hash_table_destroy (image->isinst_cache);
1138 g_hash_table_destroy (image->castclass_cache);
1139 g_hash_table_destroy (image->proxy_isinst_cache);
1141 /* The ownership of signatures is not well defined */
1142 //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1143 g_hash_table_destroy (image->memberref_signatures);
1144 //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1145 g_hash_table_destroy (image->helper_signatures);
1146 g_hash_table_destroy (image->method_signatures);
1148 if (image->interface_bitset) {
1149 mono_unload_interface_ids (image->interface_bitset);
1150 mono_bitset_free (image->interface_bitset);
1152 if (image->image_info){
1153 MonoCLIImageInfo *ii = image->image_info;
1155 if (ii->cli_section_tables)
1156 g_free (ii->cli_section_tables);
1157 if (ii->cli_sections)
1158 g_free (ii->cli_sections);
1159 g_free (image->image_info);
1162 for (i = 0; i < image->module_count; ++i) {
1163 if (image->modules [i])
1164 mono_image_close (image->modules [i]);
1166 if (image->modules)
1167 g_free (image->modules);
1168 if (image->references)
1169 g_free (image->references);
1170 /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1171 if (!image->dynamic) {
1172 if (debug_assembly_unload)
1173 mono_mempool_invalidate (image->mempool);
1174 else {
1175 mono_mempool_destroy (image->mempool);
1176 g_free (image);
1178 } else {
1179 /* Dynamic images are GC_MALLOCed */
1180 struct _MonoDynamicImage *di = (struct _MonoDynamicImage*)image;
1181 int i;
1182 g_free ((char*)image->module_name);
1183 if (di->typespec)
1184 g_hash_table_destroy (di->typespec);
1185 if (di->typeref)
1186 g_hash_table_destroy (di->typeref);
1187 if (di->handleref)
1188 g_hash_table_destroy (di->handleref);
1189 if (di->tokens)
1190 mono_g_hash_table_destroy (di->tokens);
1191 if (di->blob_cache) {
1192 g_hash_table_foreach (di->blob_cache, free_blob_cache_entry, NULL);
1193 g_hash_table_destroy (di->blob_cache);
1195 g_list_free (di->array_methods);
1196 if (di->gen_params)
1197 g_ptr_array_free (di->gen_params, TRUE);
1198 if (di->token_fixups)
1199 mono_g_hash_table_destroy (di->token_fixups);
1200 if (di->method_to_table_idx)
1201 g_hash_table_destroy (di->method_to_table_idx);
1202 if (di->field_to_table_idx)
1203 g_hash_table_destroy (di->field_to_table_idx);
1204 if (di->method_aux_hash)
1205 g_hash_table_destroy (di->method_aux_hash);
1206 g_free (di->strong_name);
1207 g_free (di->win32_res);
1208 /*g_print ("string heap destroy for image %p\n", di);*/
1209 mono_dynamic_stream_reset (&di->sheap);
1210 mono_dynamic_stream_reset (&di->code);
1211 mono_dynamic_stream_reset (&di->resources);
1212 mono_dynamic_stream_reset (&di->us);
1213 mono_dynamic_stream_reset (&di->blob);
1214 mono_dynamic_stream_reset (&di->tstream);
1215 mono_dynamic_stream_reset (&di->guid);
1216 for (i = 0; i < MONO_TABLE_NUM; ++i) {
1217 g_free (di->tables [i].values);
1219 mono_mempool_destroy (image->mempool);
1223 /**
1224 * mono_image_strerror:
1225 * @status: an code indicating the result from a recent operation
1227 * Returns: a string describing the error
1229 const char *
1230 mono_image_strerror (MonoImageOpenStatus status)
1232 switch (status){
1233 case MONO_IMAGE_OK:
1234 return "success";
1235 case MONO_IMAGE_ERROR_ERRNO:
1236 return strerror (errno);
1237 case MONO_IMAGE_IMAGE_INVALID:
1238 return "File does not contain a valid CIL image";
1239 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1240 return "An assembly was referenced, but could not be found";
1242 return "Internal error";
1245 static gpointer
1246 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1247 guint32 lang_id, gunichar2 *name,
1248 MonoPEResourceDirEntry *entry,
1249 MonoPEResourceDir *root, guint32 level)
1251 gboolean is_string, is_dir;
1252 guint32 name_offset, dir_offset;
1254 /* Level 0 holds a directory entry for each type of resource
1255 * (identified by ID or name).
1257 * Level 1 holds a directory entry for each named resource
1258 * item, and each "anonymous" item of a particular type of
1259 * resource.
1261 * Level 2 holds a directory entry for each language pointing to
1262 * the actual data.
1264 name_offset = GUINT32_FROM_LE (entry->name_offset) & 0x7fffffff;
1265 dir_offset = GUINT32_FROM_LE (entry->dir_offset) & 0x7fffffff;
1267 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
1268 is_string = (GUINT32_FROM_LE (entry->name_offset) & 0x80000000) != 0;
1269 is_dir = (GUINT32_FROM_LE (entry->dir_offset) & 0x80000000) != 0;
1270 #else
1271 is_string = entry->name_is_string;
1272 is_dir = entry->is_dir;
1273 #endif
1275 if(level==0) {
1276 if((is_string==FALSE && name_offset!=res_id) ||
1277 (is_string==TRUE)) {
1278 return(NULL);
1280 } else if (level==1) {
1281 #if 0
1282 if(name!=NULL &&
1283 is_string==TRUE && name!=lookup (name_offset)) {
1284 return(NULL);
1286 #endif
1287 } else if (level==2) {
1288 if ((is_string == FALSE &&
1289 name_offset != lang_id &&
1290 lang_id != 0) ||
1291 (is_string == TRUE)) {
1292 return(NULL);
1294 } else {
1295 g_assert_not_reached ();
1298 if(is_dir==TRUE) {
1299 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1300 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1301 guint32 entries, i;
1303 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1305 for(i=0; i<entries; i++) {
1306 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1307 gpointer ret;
1309 ret=mono_image_walk_resource_tree (info, res_id,
1310 lang_id, name,
1311 sub_entry, root,
1312 level+1);
1313 if(ret!=NULL) {
1314 return(ret);
1318 return(NULL);
1319 } else {
1320 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
1321 MonoPEResourceDataEntry *res;
1323 res = g_new0 (MonoPEResourceDataEntry, 1);
1325 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
1326 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
1327 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
1328 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
1330 return (res);
1335 * mono_image_lookup_resource:
1336 * @image: the image to look up the resource in
1337 * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1338 * @lang_id: The language id.
1339 * @name: the resource name to lookup.
1341 * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1342 * of the given resource. The caller should free it using g_free () when no longer
1343 * needed.
1345 gpointer
1346 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1348 MonoCLIImageInfo *info;
1349 MonoDotNetHeader *header;
1350 MonoPEDatadir *datadir;
1351 MonoPEDirEntry *rsrc;
1352 MonoPEResourceDir *resource_dir;
1353 MonoPEResourceDirEntry *res_entries;
1354 guint32 entries, i;
1356 if(image==NULL) {
1357 return(NULL);
1360 info=image->image_info;
1361 if(info==NULL) {
1362 return(NULL);
1365 header=&info->cli_header;
1366 if(header==NULL) {
1367 return(NULL);
1370 datadir=&header->datadir;
1371 if(datadir==NULL) {
1372 return(NULL);
1375 rsrc=&datadir->pe_resource_table;
1376 if(rsrc==NULL) {
1377 return(NULL);
1380 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1381 if(resource_dir==NULL) {
1382 return(NULL);
1385 entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1386 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1388 for(i=0; i<entries; i++) {
1389 MonoPEResourceDirEntry *entry=&res_entries[i];
1390 gpointer ret;
1392 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1393 name, entry, resource_dir,
1395 if(ret!=NULL) {
1396 return(ret);
1400 return(NULL);
1403 /**
1404 * mono_image_get_entry_point:
1405 * @image: the image where the entry point will be looked up.
1407 * Use this routine to determine the metadata token for method that
1408 * has been flagged as the entry point.
1410 * Returns: the token for the entry point method in the image
1412 guint32
1413 mono_image_get_entry_point (MonoImage *image)
1415 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1419 * mono_image_get_resource:
1420 * @image: the image where the resource will be looked up.
1421 * @offset: The offset to add to the resource
1422 * @size: a pointer to an int where the size of the resource will be stored
1424 * This is a low-level routine that fetches a resource from the
1425 * metadata that starts at a given @offset. The @size parameter is
1426 * filled with the data field as encoded in the metadata.
1428 * Returns: the pointer to the resource whose offset is @offset.
1430 const char*
1431 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1433 MonoCLIImageInfo *iinfo = image->image_info;
1434 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1435 const char* data;
1437 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1438 return NULL;
1440 data = mono_image_rva_map (image, ch->ch_resources.rva);
1441 if (!data)
1442 return NULL;
1443 data += offset;
1444 if (size)
1445 *size = read32 (data);
1446 data += 4;
1447 return data;
1450 MonoImage*
1451 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1453 char *base_dir, *name;
1454 MonoImage *res;
1455 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1456 const char *fname;
1457 guint32 fname_id;
1459 if (fileidx < 1 || fileidx > t->rows)
1460 return NULL;
1462 if (image->files && image->files [fileidx - 1])
1463 return image->files [fileidx - 1];
1465 if (!image->files)
1466 image->files = g_new0 (MonoImage*, t->rows);
1468 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1469 fname = mono_metadata_string_heap (image, fname_id);
1470 base_dir = g_path_get_dirname (image->name);
1471 name = g_build_filename (base_dir, fname, NULL);
1472 res = mono_image_open (name, NULL);
1473 if (res) {
1474 int i;
1475 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1476 res->assembly = image->assembly;
1477 for (i = 0; i < res->module_count; ++i) {
1478 if (res->modules [i] && !res->modules [i]->assembly)
1479 res->modules [i]->assembly = image->assembly;
1482 image->files [fileidx - 1] = res;
1484 g_free (name);
1485 g_free (base_dir);
1486 return res;
1490 * mono_image_get_strong_name:
1491 * @image: a MonoImage
1492 * @size: a guint32 pointer, or NULL.
1494 * If the image has a strong name, and @size is not NULL, the value
1495 * pointed to by size will have the size of the strong name.
1497 * Returns: NULL if the image does not have a strong name, or a
1498 * pointer to the public key.
1500 const char*
1501 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1503 MonoCLIImageInfo *iinfo = image->image_info;
1504 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1505 const char* data;
1507 if (!de->size || !de->rva)
1508 return NULL;
1509 data = mono_image_rva_map (image, de->rva);
1510 if (!data)
1511 return NULL;
1512 if (size)
1513 *size = de->size;
1514 return data;
1518 * mono_image_strong_name_position:
1519 * @image: a MonoImage
1520 * @size: a guint32 pointer, or NULL.
1522 * If the image has a strong name, and @size is not NULL, the value
1523 * pointed to by size will have the size of the strong name.
1525 * Returns: the position within the image file where the strong name
1526 * is stored.
1528 guint32
1529 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1531 MonoCLIImageInfo *iinfo = image->image_info;
1532 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1533 const int top = iinfo->cli_section_count;
1534 MonoSectionTable *tables = iinfo->cli_section_tables;
1535 int i;
1536 guint32 addr = de->rva;
1538 if (size)
1539 *size = de->size;
1540 if (!de->size || !de->rva)
1541 return 0;
1542 for (i = 0; i < top; i++){
1543 if ((addr >= tables->st_virtual_address) &&
1544 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
1545 return tables->st_raw_data_ptr +
1546 (addr - tables->st_virtual_address);
1548 tables++;
1551 return 0;
1555 * mono_image_get_public_key:
1556 * @image: a MonoImage
1557 * @size: a guint32 pointer, or NULL.
1559 * This is used to obtain the public key in the @image.
1561 * If the image has a public key, and @size is not NULL, the value
1562 * pointed to by size will have the size of the public key.
1564 * Returns: NULL if the image does not have a public key, or a pointer
1565 * to the public key.
1567 const char*
1568 mono_image_get_public_key (MonoImage *image, guint32 *size)
1570 const char *pubkey;
1571 guint32 len, tok;
1572 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1573 return NULL;
1574 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1575 if (!tok)
1576 return NULL;
1577 pubkey = mono_metadata_blob_heap (image, tok);
1578 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1579 if (size)
1580 *size = len;
1581 return pubkey;
1585 * mono_image_get_name:
1586 * @name: a MonoImage
1588 * Returns: the name of the assembly.
1590 const char*
1591 mono_image_get_name (MonoImage *image)
1593 return image->assembly_name;
1597 * mono_image_get_filename:
1598 * @image: a MonoImage
1600 * Used to get the filename that hold the actual MonoImage
1602 * Returns: the filename.
1604 const char*
1605 mono_image_get_filename (MonoImage *image)
1607 return image->name;
1610 const char*
1611 mono_image_get_guid (MonoImage *image)
1613 return image->guid;
1616 const MonoTableInfo*
1617 mono_image_get_table_info (MonoImage *image, int table_id)
1619 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1620 return NULL;
1621 return &image->tables [table_id];
1625 mono_image_get_table_rows (MonoImage *image, int table_id)
1627 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1628 return 0;
1629 return image->tables [table_id].rows;
1633 mono_table_info_get_rows (const MonoTableInfo *table)
1635 return table->rows;
1639 * mono_image_get_assembly:
1640 * @image: the MonoImage.
1642 * Use this routine to get the assembly that owns this image.
1644 * Returns: the assembly that holds this image.
1646 MonoAssembly*
1647 mono_image_get_assembly (MonoImage *image)
1649 return image->assembly;
1653 * mono_image_is_dynamic:
1654 * @image: the MonoImage
1656 * Determines if the given image was created dynamically through the
1657 * System.Reflection.Emit API
1659 * Returns: TRUE if the image was created dynamically, FALSE if not.
1661 gboolean
1662 mono_image_is_dynamic (MonoImage *image)
1664 return image->dynamic;
1668 * mono_image_has_authenticode_entry:
1669 * @image: the MonoImage
1671 * Use this routine to determine if the image has a Authenticode
1672 * Certificate Table.
1674 * Returns: TRUE if the image contains an authenticode entry in the PE
1675 * directory.
1677 gboolean
1678 mono_image_has_authenticode_entry (MonoImage *image)
1680 MonoCLIImageInfo *iinfo = image->image_info;
1681 MonoDotNetHeader *header = &iinfo->cli_header;
1682 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
1683 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
1684 return ((de->rva != 0) && (de->size > 8));