2009-07-11 Michael Barker <mike@middlesoft.co.uk>
[mono.git] / mono / metadata / image.c
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)
8  *
9  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
11  *
12  */
13 #include <config.h>
14 #include <stdio.h>
15 #include <glib.h>
16 #include <errno.h>
17 #include <time.h>
18 #include <string.h>
19 #include "image.h"
20 #include "cil-coff.h"
21 #include "mono-endian.h"
22 #include "tabledefs.h"
23 #include "tokentype.h"
24 #include "metadata-internals.h"
25 #include "profiler-private.h"
26 #include "loader.h"
27 #include "marshal.h"
28 #include "coree.h"
29 #include <mono/io-layer/io-layer.h>
30 #include <mono/utils/mono-logger.h>
31 #include <mono/utils/mono-path.h>
32 #include <mono/utils/mono-mmap.h>
33 #include <mono/utils/mono-io-portability.h>
34 #include <mono/metadata/class-internals.h>
35 #include <mono/metadata/assembly.h>
36 #include <mono/metadata/object-internals.h>
37 #include <mono/metadata/security-core-clr.h>
38 #include <mono/metadata/verify-internals.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #ifdef HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44
45 #define INVALID_ADDRESS 0xffffffff
46
47 /*
48  * Keeps track of the various assemblies loaded
49  */
50 static GHashTable *loaded_images_hash;
51 static GHashTable *loaded_images_refonly_hash;
52
53 static gboolean debug_assembly_unload = FALSE;
54
55 #define mono_images_lock() EnterCriticalSection (&images_mutex)
56 #define mono_images_unlock() LeaveCriticalSection (&images_mutex)
57 static CRITICAL_SECTION images_mutex;
58
59 /* returns offset relative to image->raw_data */
60 guint32
61 mono_cli_rva_image_map (MonoImage *image, guint32 addr)
62 {
63         MonoCLIImageInfo *iinfo = image->image_info;
64         const int top = iinfo->cli_section_count;
65         MonoSectionTable *tables = iinfo->cli_section_tables;
66         int i;
67         
68         for (i = 0; i < top; i++){
69                 if ((addr >= tables->st_virtual_address) &&
70                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
71 #ifdef PLATFORM_WIN32
72                         if (image->is_module_handle)
73                                 return addr;
74 #endif
75                         return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
76                 }
77                 tables++;
78         }
79         return INVALID_ADDRESS;
80 }
81
82 /**
83  * mono_images_rva_map:
84  * @image: a MonoImage
85  * @addr: relative virtual address (RVA)
86  *
87  * This is a low-level routine used by the runtime to map relative
88  * virtual address (RVA) into their location in memory. 
89  *
90  * Returns: the address in memory for the given RVA, or NULL if the
91  * RVA is not valid for this image. 
92  */
93 char *
94 mono_image_rva_map (MonoImage *image, guint32 addr)
95 {
96         MonoCLIImageInfo *iinfo = image->image_info;
97         const int top = iinfo->cli_section_count;
98         MonoSectionTable *tables = iinfo->cli_section_tables;
99         int i;
100         
101         for (i = 0; i < top; i++){
102                 if ((addr >= tables->st_virtual_address) &&
103                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
104                         if (!iinfo->cli_sections [i]) {
105                                 if (!mono_image_ensure_section_idx (image, i))
106                                         return NULL;
107                         }
108 #ifdef PLATFORM_WIN32
109                         if (image->is_module_handle)
110                                 return image->raw_data + addr;
111 #endif
112                         return (char*)iinfo->cli_sections [i] +
113                                 (addr - tables->st_virtual_address);
114                 }
115                 tables++;
116         }
117         return NULL;
118 }
119
120 /**
121  * mono_images_init:
122  *
123  *  Initialize the global variables used by this module.
124  */
125 void
126 mono_images_init (void)
127 {
128         InitializeCriticalSection (&images_mutex);
129
130         loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
131         loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
132
133         debug_assembly_unload = g_getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
134 }
135
136 /**
137  * mono_images_cleanup:
138  *
139  *  Free all resources used by this module.
140  */
141 void
142 mono_images_cleanup (void)
143 {
144         DeleteCriticalSection (&images_mutex);
145
146         g_hash_table_destroy (loaded_images_hash);
147         g_hash_table_destroy (loaded_images_refonly_hash);
148 }
149
150 /**
151  * mono_image_ensure_section_idx:
152  * @image: The image we are operating on
153  * @section: section number that we will load/map into memory
154  *
155  * This routine makes sure that we have an in-memory copy of
156  * an image section (.text, .rsrc, .data).
157  *
158  * Returns: TRUE on success
159  */
160 int
161 mono_image_ensure_section_idx (MonoImage *image, int section)
162 {
163         MonoCLIImageInfo *iinfo = image->image_info;
164         MonoSectionTable *sect;
165         gboolean writable;
166         
167         g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
168
169         if (iinfo->cli_sections [section] != NULL)
170                 return TRUE;
171
172         sect = &iinfo->cli_section_tables [section];
173         
174         writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
175
176         if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
177                 return FALSE;
178 #ifdef PLATFORM_WIN32
179         if (image->is_module_handle)
180                 iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address;
181         else
182 #endif
183         /* FIXME: we ignore the writable flag since we don't patch the binary */
184         iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
185         return TRUE;
186 }
187
188 /**
189  * mono_image_ensure_section:
190  * @image: The image we are operating on
191  * @section: section name that we will load/map into memory
192  *
193  * This routine makes sure that we have an in-memory copy of
194  * an image section (.text, .rsrc, .data).
195  *
196  * Returns: TRUE on success
197  */
198 int
199 mono_image_ensure_section (MonoImage *image, const char *section)
200 {
201         MonoCLIImageInfo *ii = image->image_info;
202         int i;
203         
204         for (i = 0; i < ii->cli_section_count; i++){
205                 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
206                         continue;
207                 
208                 return mono_image_ensure_section_idx (image, i);
209         }
210         return FALSE;
211 }
212
213 static int
214 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
215 {
216         const int top = iinfo->cli_header.coff.coff_sections;
217         int i;
218
219         iinfo->cli_section_count = top;
220         iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
221         iinfo->cli_sections = g_new0 (void *, top);
222         
223         for (i = 0; i < top; i++){
224                 MonoSectionTable *t = &iinfo->cli_section_tables [i];
225
226                 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
227                         return FALSE;
228                 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
229                 offset += sizeof (MonoSectionTable);
230
231 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
232                 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
233                 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
234                 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
235                 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
236                 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
237                 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
238                 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
239                 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
240                 t->st_flags = GUINT32_FROM_LE (t->st_flags);
241 #endif
242                 /* consistency checks here */
243         }
244
245         return TRUE;
246 }
247
248 static gboolean
249 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
250 {
251         guint32 offset;
252         
253         offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva);
254         if (offset == INVALID_ADDRESS)
255                 return FALSE;
256
257         if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
258                 return FALSE;
259         memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
260
261 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
262 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
263 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
264 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
265         SWAP32 (iinfo->cli_cli_header.ch_size);
266         SWAP32 (iinfo->cli_cli_header.ch_flags);
267         SWAP32 (iinfo->cli_cli_header.ch_entry_point);
268         SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
269         SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
270         SWAPPDE (iinfo->cli_cli_header.ch_metadata);
271         SWAPPDE (iinfo->cli_cli_header.ch_resources);
272         SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
273         SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
274         SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
275         SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
276         SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
277         SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
278         SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
279         SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
280         SWAPPDE (iinfo->cli_cli_header.ch_module_image);
281         SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
282         SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
283         SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
284         SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
285 #undef SWAP32
286 #undef SWAP16
287 #undef SWAPPDE
288 #endif
289         /* Catch new uses of the fields that are supposed to be zero */
290
291         if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
292             (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
293             (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
294             (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
295             (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
296             (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
297             (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
298             (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
299             (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
300
301                 /*
302                  * No need to scare people who are testing this, I am just
303                  * labelling this as a LAMESPEC
304                  */
305                 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
306
307         }
308             
309         return TRUE;
310 }
311
312 static gboolean
313 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
314 {
315         guint32 offset, size;
316         guint16 streams;
317         int i;
318         guint32 pad;
319         char *ptr;
320         
321         offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva);
322         if (offset == INVALID_ADDRESS)
323                 return FALSE;
324
325         size = iinfo->cli_cli_header.ch_metadata.size;
326
327         if (offset + size > image->raw_data_len)
328                 return FALSE;
329         image->raw_metadata = image->raw_data + offset;
330
331         ptr = image->raw_metadata;
332
333         if (strncmp (ptr, "BSJB", 4) == 0){
334                 guint32 version_string_len;
335
336                 ptr += 4;
337                 image->md_version_major = read16 (ptr);
338                 ptr += 2;
339                 image->md_version_minor = read16 (ptr);
340                 ptr += 6;
341
342                 version_string_len = read32 (ptr);
343                 ptr += 4;
344                 image->version = g_strndup (ptr, version_string_len);
345                 ptr += version_string_len;
346                 pad = ptr - image->raw_metadata;
347                 if (pad % 4)
348                         ptr += 4 - (pad % 4);
349         } else
350                 return FALSE;
351
352         /* skip over flags */
353         ptr += 2;
354         
355         streams = read16 (ptr);
356         ptr += 2;
357
358         for (i = 0; i < streams; i++){
359                 if (strncmp (ptr + 8, "#~", 3) == 0){
360                         image->heap_tables.data = image->raw_metadata + read32 (ptr);
361                         image->heap_tables.size = read32 (ptr + 4);
362                         ptr += 8 + 3;
363                 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
364                         image->heap_strings.data = image->raw_metadata + read32 (ptr);
365                         image->heap_strings.size = read32 (ptr + 4);
366                         ptr += 8 + 9;
367                 } else if (strncmp (ptr + 8, "#US", 4) == 0){
368                         image->heap_us.data = image->raw_metadata + read32 (ptr);
369                         image->heap_us.size = read32 (ptr + 4);
370                         ptr += 8 + 4;
371                 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
372                         image->heap_blob.data = image->raw_metadata + read32 (ptr);
373                         image->heap_blob.size = read32 (ptr + 4);
374                         ptr += 8 + 6;
375                 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
376                         image->heap_guid.data = image->raw_metadata + read32 (ptr);
377                         image->heap_guid.size = read32 (ptr + 4);
378                         ptr += 8 + 6;
379                 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
380                         image->heap_tables.data = image->raw_metadata + read32 (ptr);
381                         image->heap_tables.size = read32 (ptr + 4);
382                         ptr += 8 + 3;
383                         image->uncompressed_metadata = TRUE;
384                         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);
385                 } else {
386                         g_message ("Unknown heap type: %s\n", ptr + 8);
387                         ptr += 8 + strlen (ptr + 8) + 1;
388                 }
389                 pad = ptr - image->raw_metadata;
390                 if (pad % 4)
391                         ptr += 4 - (pad % 4);
392         }
393
394         g_assert (image->heap_guid.data);
395         g_assert (image->heap_guid.size >= 16);
396
397         image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
398
399         return TRUE;
400 }
401
402 /*
403  * Load representation of logical metadata tables, from the "#~" stream
404  */
405 static gboolean
406 load_tables (MonoImage *image)
407 {
408         const char *heap_tables = image->heap_tables.data;
409         const guint32 *rows;
410         guint64 valid_mask, sorted_mask;
411         int valid = 0, table;
412         int heap_sizes;
413         
414         heap_sizes = heap_tables [6];
415         image->idx_string_wide = ((heap_sizes & 0x01) == 1);
416         image->idx_guid_wide   = ((heap_sizes & 0x02) == 2);
417         image->idx_blob_wide   = ((heap_sizes & 0x04) == 4);
418         
419         valid_mask = read64 (heap_tables + 8);
420         sorted_mask = read64 (heap_tables + 16);
421         rows = (const guint32 *) (heap_tables + 24);
422         
423         for (table = 0; table < 64; table++){
424                 if ((valid_mask & ((guint64) 1 << table)) == 0){
425                         if (table > MONO_TABLE_LAST)
426                                 continue;
427                         image->tables [table].rows = 0;
428                         continue;
429                 }
430                 if (table > MONO_TABLE_LAST) {
431                         g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
432                 } else {
433                         image->tables [table].rows = read32 (rows);
434                 }
435                 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
436                         g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
437                 }*/
438                 rows++;
439                 valid++;
440         }
441
442         image->tables_base = (heap_tables + 24) + (4 * valid);
443
444         /* They must be the same */
445         g_assert ((const void *) image->tables_base == (const void *) rows);
446
447         mono_metadata_compute_table_bases (image);
448         return TRUE;
449 }
450
451 static gboolean
452 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
453 {
454         if (!load_metadata_ptrs (image, iinfo))
455                 return FALSE;
456
457         return load_tables (image);
458 }
459
460 void
461 mono_image_check_for_module_cctor (MonoImage *image)
462 {
463         MonoTableInfo *t, *mt;
464         t = &image->tables [MONO_TABLE_TYPEDEF];
465         mt = &image->tables [MONO_TABLE_METHOD];
466         if (mono_framework_version () == 1) {
467                 image->checked_module_cctor = TRUE;
468                 return;
469         }
470         if (image->dynamic) {
471                 /* FIXME: */
472                 image->checked_module_cctor = TRUE;
473                 return;
474         }
475         if (t->rows >= 1) {
476                 guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
477                 const char *name = mono_metadata_string_heap (image, nameidx);
478                 if (strcmp (name, "<Module>") == 0) {
479                         guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
480                         guint32 last_method;
481                         if (t->rows > 1)
482                                 last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
483                         else 
484                                 last_method = mt->rows;
485                         for (; first_method < last_method; first_method++) {
486                                 nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
487                                 name = mono_metadata_string_heap (image, nameidx);
488                                 if (strcmp (name, ".cctor") == 0) {
489                                         image->has_module_cctor = TRUE;
490                                         image->checked_module_cctor = TRUE;
491                                         return;
492                                 }
493                         }
494                 }
495         }
496         image->has_module_cctor = FALSE;
497         image->checked_module_cctor = TRUE;
498 }
499
500 static void
501 load_modules (MonoImage *image)
502 {
503         MonoTableInfo *t;
504
505         if (image->modules)
506                 return;
507
508         t = &image->tables [MONO_TABLE_MODULEREF];
509         image->modules = g_new0 (MonoImage *, t->rows);
510         image->modules_loaded = g_new0 (gboolean, t->rows);
511         image->module_count = t->rows;
512 }
513
514 /**
515  * mono_image_load_module:
516  *
517  *   Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
518  * it cannot be loaded.
519  */
520 MonoImage*
521 mono_image_load_module (MonoImage *image, int idx)
522 {
523         MonoTableInfo *t;
524         MonoTableInfo *file_table;
525         int i;
526         char *base_dir;
527         gboolean refonly = image->ref_only;
528         GList *list_iter, *valid_modules = NULL;
529         MonoImageOpenStatus status;
530
531         g_assert (idx <= image->module_count);
532         if (image->modules_loaded [idx - 1])
533                 return image->modules [idx - 1];
534
535         file_table = &image->tables [MONO_TABLE_FILE];
536         for (i = 0; i < file_table->rows; i++) {
537                 guint32 cols [MONO_FILE_SIZE];
538                 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
539                 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
540                         continue;
541                 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
542         }
543
544         t = &image->tables [MONO_TABLE_MODULEREF];
545         base_dir = g_path_get_dirname (image->name);
546
547         {
548                 char *module_ref;
549                 const char *name;
550                 guint32 cols [MONO_MODULEREF_SIZE];
551                 /* if there is no file table, we try to load the module... */
552                 int valid = file_table->rows == 0;
553
554                 mono_metadata_decode_row (t, idx - 1, cols, MONO_MODULEREF_SIZE);
555                 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
556                 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
557                         /* be safe with string dups, but we could just compare string indexes  */
558                         if (strcmp (list_iter->data, name) == 0) {
559                                 valid = TRUE;
560                                 break;
561                         }
562                 }
563                 if (valid) {
564                         module_ref = g_build_filename (base_dir, name, NULL);
565                         image->modules [idx - 1] = mono_image_open_full (module_ref, &status, refonly);
566                         if (image->modules [idx - 1]) {
567                                 mono_image_addref (image->modules [idx - 1]);
568                                 image->modules [idx - 1]->assembly = image->assembly;
569 #ifdef PLATFORM_WIN32
570                                 if (image->modules [idx - 1]->is_module_handle)
571                                         mono_image_fixup_vtable (image->modules [idx - 1]);
572 #endif
573                                 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
574                         }
575                         g_free (module_ref);
576                 }
577         }
578
579         image->modules_loaded [idx - 1] = TRUE;
580
581         g_free (base_dir);
582         g_list_free (valid_modules);
583
584         return image->modules [idx - 1];
585 }
586
587 static gpointer
588 class_key_extract (gpointer value)
589 {
590         MonoClass *class = value;
591
592         return GUINT_TO_POINTER (class->type_token);
593 }
594
595 static gpointer*
596 class_next_value (gpointer value)
597 {
598         MonoClass *class = value;
599
600         return (gpointer*)&class->next_class_cache;
601 }
602
603 void
604 mono_image_init (MonoImage *image)
605 {
606         image->mempool = mono_mempool_new_size (512);
607         mono_internal_hash_table_init (&image->class_cache,
608                                        g_direct_hash,
609                                        class_key_extract,
610                                        class_next_value);
611         image->field_cache = g_hash_table_new (NULL, NULL);
612
613         image->typespec_cache = g_hash_table_new (NULL, NULL);
614         image->memberref_signatures = g_hash_table_new (NULL, NULL);
615         image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
616         image->method_signatures = g_hash_table_new (NULL, NULL);
617
618         image->property_hash = mono_property_hash_new ();
619         InitializeCriticalSection (&image->lock);
620         InitializeCriticalSection (&image->szarray_cache_lock);
621 }
622
623 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
624 #define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
625 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
626 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
627 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
628 #else
629 #define SWAP64(x)
630 #define SWAP32(x)
631 #define SWAP16(x)
632 #define SWAPPDE(x)
633 #endif
634
635 /*
636  * Returns < 0 to indicate an error.
637  */
638 static int
639 do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
640 {
641         MonoDotNetHeader64 header64;
642
643 #ifdef PLATFORM_WIN32
644         if (!image->is_module_handle)
645 #endif
646         if (offset + sizeof (MonoDotNetHeader32) > image->raw_data_len)
647                 return -1;
648
649         memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
650
651         if (header->pesig [0] != 'P' || header->pesig [1] != 'E')
652                 return -1;
653
654         /* endian swap the fields common between PE and PE+ */
655         SWAP32 (header->coff.coff_time);
656         SWAP32 (header->coff.coff_symptr);
657         SWAP32 (header->coff.coff_symcount);
658         SWAP16 (header->coff.coff_machine);
659         SWAP16 (header->coff.coff_sections);
660         SWAP16 (header->coff.coff_opt_header_size);
661         SWAP16 (header->coff.coff_attributes);
662         /* MonoPEHeader */
663         SWAP32 (header->pe.pe_code_size);
664         SWAP32 (header->pe.pe_uninit_data_size);
665         SWAP32 (header->pe.pe_rva_entry_point);
666         SWAP32 (header->pe.pe_rva_code_base);
667         SWAP32 (header->pe.pe_rva_data_base);
668         SWAP16 (header->pe.pe_magic);
669
670         /* now we are ready for the basic tests */
671
672         if (header->pe.pe_magic == 0x10B) {
673                 offset += sizeof (MonoDotNetHeader);
674                 SWAP32 (header->pe.pe_data_size);
675                 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
676                         return -1;
677
678                 SWAP32  (header->nt.pe_image_base);     /* must be 0x400000 */
679                 SWAP32  (header->nt.pe_stack_reserve);
680                 SWAP32  (header->nt.pe_stack_commit);
681                 SWAP32  (header->nt.pe_heap_reserve);
682                 SWAP32  (header->nt.pe_heap_commit);
683         } else if (header->pe.pe_magic == 0x20B) {
684                 /* PE32+ file format */
685                 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
686                         return -1;
687                 memcpy (&header64, image->raw_data + offset, sizeof (MonoDotNetHeader64));
688                 offset += sizeof (MonoDotNetHeader64);
689                 /* copy the fields already swapped. the last field, pe_data_size, is missing */
690                 memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
691                 /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
692                  * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
693                  */
694                 SWAP64  (header64.nt.pe_image_base);
695                 header->nt.pe_image_base = header64.nt.pe_image_base;
696                 SWAP64  (header64.nt.pe_stack_reserve);
697                 header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
698                 SWAP64  (header64.nt.pe_stack_commit);
699                 header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
700                 SWAP64  (header64.nt.pe_heap_reserve);
701                 header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
702                 SWAP64  (header64.nt.pe_heap_commit);
703                 header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
704
705                 header->nt.pe_section_align = header64.nt.pe_section_align;
706                 header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
707                 header->nt.pe_os_major = header64.nt.pe_os_major;
708                 header->nt.pe_os_minor = header64.nt.pe_os_minor;
709                 header->nt.pe_user_major = header64.nt.pe_user_major;
710                 header->nt.pe_user_minor = header64.nt.pe_user_minor;
711                 header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
712                 header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
713                 header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
714                 header->nt.pe_image_size = header64.nt.pe_image_size;
715                 header->nt.pe_header_size = header64.nt.pe_header_size;
716                 header->nt.pe_checksum = header64.nt.pe_checksum;
717                 header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
718                 header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
719                 header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
720                 header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
721
722                 /* copy the datadir */
723                 memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
724         } else {
725                 return -1;
726         }
727
728         /* MonoPEHeaderNT: not used yet */
729         SWAP32  (header->nt.pe_section_align);       /* must be 8192 */
730         SWAP32  (header->nt.pe_file_alignment);      /* must be 512 or 4096 */
731         SWAP16  (header->nt.pe_os_major);            /* must be 4 */
732         SWAP16  (header->nt.pe_os_minor);            /* must be 0 */
733         SWAP16  (header->nt.pe_user_major);
734         SWAP16  (header->nt.pe_user_minor);
735         SWAP16  (header->nt.pe_subsys_major);
736         SWAP16  (header->nt.pe_subsys_minor);
737         SWAP32  (header->nt.pe_reserved_1);
738         SWAP32  (header->nt.pe_image_size);
739         SWAP32  (header->nt.pe_header_size);
740         SWAP32  (header->nt.pe_checksum);
741         SWAP16  (header->nt.pe_subsys_required);
742         SWAP16  (header->nt.pe_dll_flags);
743         SWAP32  (header->nt.pe_loader_flags);
744         SWAP32  (header->nt.pe_data_dir_count);
745
746         /* MonoDotNetHeader: mostly unused */
747         SWAPPDE (header->datadir.pe_export_table);
748         SWAPPDE (header->datadir.pe_import_table);
749         SWAPPDE (header->datadir.pe_resource_table);
750         SWAPPDE (header->datadir.pe_exception_table);
751         SWAPPDE (header->datadir.pe_certificate_table);
752         SWAPPDE (header->datadir.pe_reloc_table);
753         SWAPPDE (header->datadir.pe_debug);
754         SWAPPDE (header->datadir.pe_copyright);
755         SWAPPDE (header->datadir.pe_global_ptr);
756         SWAPPDE (header->datadir.pe_tls_table);
757         SWAPPDE (header->datadir.pe_load_config_table);
758         SWAPPDE (header->datadir.pe_bound_import);
759         SWAPPDE (header->datadir.pe_iat);
760         SWAPPDE (header->datadir.pe_delay_import_desc);
761         SWAPPDE (header->datadir.pe_cli_header);
762         SWAPPDE (header->datadir.pe_reserved);
763
764 #ifdef PLATFORM_WIN32
765         if (image->is_module_handle)
766                 image->raw_data_len = header->nt.pe_image_size;
767 #endif
768
769         return offset;
770 }
771
772 gboolean
773 mono_image_load_pe_data (MonoImage *image)
774 {
775         MonoCLIImageInfo *iinfo;
776         MonoDotNetHeader *header;
777         MonoMSDOSHeader msdos;
778         gint32 offset = 0;
779
780         iinfo = image->image_info;
781         header = &iinfo->cli_header;
782
783 #ifdef PLATFORM_WIN32
784         if (!image->is_module_handle)
785 #endif
786         if (offset + sizeof (msdos) > image->raw_data_len)
787                 goto invalid_image;
788         memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
789         
790         if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
791                 goto invalid_image;
792         
793         msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
794
795         offset = msdos.pe_offset;
796
797         offset = do_load_header (image, header, offset);
798         if (offset < 0)
799                 goto invalid_image;
800
801         /*
802          * this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
803          * we skip this test.
804         if (header->coff.coff_machine != 0x14c)
805                 goto invalid_image;
806         */
807
808 #if 0
809         /*
810          * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
811          * which produces binaries with 7.0.  From Sergey:
812          *
813          * The reason is that MSVC7 uses traditional compile/link
814          * sequence for CIL executables, and VS.NET (and Framework
815          * SDK) includes linker version 7, that puts 7.0 in this
816          * field.  That's why it's currently not possible to load VC
817          * binaries with Mono.  This field is pretty much meaningless
818          * anyway (what linker?).
819          */
820         if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
821                 goto invalid_image;
822 #endif
823
824         /*
825          * FIXME: byte swap all addresses here for header.
826          */
827         
828         if (!load_section_tables (image, iinfo, offset))
829                 goto invalid_image;
830
831         return TRUE;
832
833 invalid_image:
834         return FALSE;
835 }
836
837 gboolean
838 mono_image_load_cli_data (MonoImage *image)
839 {
840         MonoCLIImageInfo *iinfo;
841         MonoDotNetHeader *header;
842
843         iinfo = image->image_info;
844         header = &iinfo->cli_header;
845
846         /* Load the CLI header */
847         if (!load_cli_header (image, iinfo))
848                 return FALSE;
849
850         if (!load_metadata (image, iinfo))
851                 return FALSE;
852
853         return TRUE;
854 }
855
856 void
857 mono_image_load_names (MonoImage *image)
858 {
859         /* modules don't have an assembly table row */
860         if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
861                 image->assembly_name = mono_metadata_string_heap (image, 
862                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
863                                         0, MONO_ASSEMBLY_NAME));
864         }
865
866         image->module_name = mono_metadata_string_heap (image, 
867                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
868                                         0, MONO_MODULE_NAME));
869 }
870
871 static MonoImage *
872 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
873                     gboolean care_about_cli, gboolean care_about_pecoff)
874 {
875         MonoCLIImageInfo *iinfo;
876         MonoDotNetHeader *header;
877
878         mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
879
880         mono_image_init (image);
881
882         iinfo = image->image_info;
883         header = &iinfo->cli_header;
884                 
885         if (status)
886                 *status = MONO_IMAGE_IMAGE_INVALID;
887
888         if (care_about_pecoff == FALSE)
889                 goto done;
890
891         if (!mono_verifier_verify_pe_data (image, NULL))
892                 goto invalid_image;
893
894         if (!mono_image_load_pe_data (image))
895                 goto invalid_image;
896         
897         if (care_about_cli == FALSE) {
898                 goto done;
899         }
900
901         if (!mono_verifier_verify_cli_data (image, NULL))
902                 goto invalid_image;
903
904         if (!mono_image_load_cli_data (image))
905                 goto invalid_image;
906
907         if (!mono_verifier_verify_table_data (image, NULL))
908                 goto invalid_image;
909
910         mono_image_load_names (image);
911
912         load_modules (image);
913
914 done:
915         mono_profiler_module_loaded (image, MONO_PROFILE_OK);
916         if (status)
917                 *status = MONO_IMAGE_OK;
918
919         return image;
920
921 invalid_image:
922         mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
923         mono_image_close (image);
924                 return NULL;
925 }
926
927 static MonoImage *
928 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
929                     gboolean care_about_cli, gboolean care_about_pecoff, gboolean refonly)
930 {
931         MonoCLIImageInfo *iinfo;
932         MonoImage *image;
933         MonoFileMap *filed;
934
935         if ((filed = mono_file_map_open (fname)) == NULL){
936                 if (IS_PORTABILITY_SET) {
937                         gchar *ffname = mono_portability_find_file (fname, TRUE);
938                         if (ffname) {
939                                 filed = mono_file_map_open (ffname);
940                                 g_free (ffname);
941                         }
942                 }
943
944                 if (filed == NULL) {
945                         if (status)
946                                 *status = MONO_IMAGE_ERROR_ERRNO;
947                         return NULL;
948                 }
949         }
950
951         image = g_new0 (MonoImage, 1);
952         image->raw_buffer_used = TRUE;
953         image->raw_data_len = mono_file_map_size (filed);
954         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);
955         if (!image->raw_data) {
956                 mono_file_map_close (filed);
957                 g_free (image);
958                 if (status)
959                         *status = MONO_IMAGE_IMAGE_INVALID;
960                 return NULL;
961         }
962         iinfo = g_new0 (MonoCLIImageInfo, 1);
963         image->image_info = iinfo;
964         image->name = mono_path_resolve_symlinks (fname);
965         image->ref_only = refonly;
966         image->ref_count = 1;
967         /* if MONO_SECURITY_MODE_CORE_CLR is set then determine if this image is platform code */
968         image->core_clr_platform_code = mono_security_core_clr_determine_platform_image (image);
969
970         mono_file_map_close (filed);
971         return do_mono_image_load (image, status, care_about_cli, care_about_pecoff);
972 }
973
974 MonoImage *
975 mono_image_loaded_full (const char *name, gboolean refonly)
976 {
977         MonoImage *res;
978         GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
979         
980         mono_images_lock ();
981         res = g_hash_table_lookup (loaded_images, name);
982         mono_images_unlock ();
983         return res;
984 }
985
986 /**
987  * mono_image_loaded:
988  * @name: name of the image to load
989  *
990  * This routine ensures that the given image is loaded.
991  *
992  * Returns: the loaded MonoImage, or NULL on failure.
993  */
994 MonoImage *
995 mono_image_loaded (const char *name)
996 {
997         return mono_image_loaded_full (name, FALSE);
998 }
999
1000 typedef struct {
1001         MonoImage *res;
1002         const char* guid;
1003 } GuidData;
1004
1005 static void
1006 find_by_guid (gpointer key, gpointer val, gpointer user_data)
1007 {
1008         GuidData *data = user_data;
1009         MonoImage *image;
1010
1011         if (data->res)
1012                 return;
1013         image = val;
1014         if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
1015                 data->res = image;
1016 }
1017
1018 MonoImage *
1019 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
1020 {
1021         GuidData data;
1022         GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1023         data.res = NULL;
1024         data.guid = guid;
1025
1026         mono_images_lock ();
1027         g_hash_table_foreach (loaded_images, find_by_guid, &data);
1028         mono_images_unlock ();
1029         return data.res;
1030 }
1031
1032 MonoImage *
1033 mono_image_loaded_by_guid (const char *guid)
1034 {
1035         return mono_image_loaded_by_guid_full (guid, FALSE);
1036 }
1037
1038 static MonoImage *
1039 register_image (MonoImage *image)
1040 {
1041         MonoImage *image2;
1042         GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1043
1044         mono_images_lock ();
1045         image2 = g_hash_table_lookup (loaded_images, image->name);
1046
1047         if (image2) {
1048                 /* Somebody else beat us to it */
1049                 mono_image_addref (image2);
1050                 mono_images_unlock ();
1051                 mono_image_close (image);
1052                 return image2;
1053         }
1054         g_hash_table_insert (loaded_images, image->name, image);
1055         if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
1056                 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);      
1057         mono_images_unlock ();
1058
1059         return image;
1060 }
1061
1062 MonoImage *
1063 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1064 {
1065         MonoCLIImageInfo *iinfo;
1066         MonoImage *image;
1067         char *datac;
1068
1069         if (!data || !data_len) {
1070                 if (status)
1071                         *status = MONO_IMAGE_IMAGE_INVALID;
1072                 return NULL;
1073         }
1074         datac = data;
1075         if (need_copy) {
1076                 datac = g_try_malloc (data_len);
1077                 if (!datac) {
1078                         if (status)
1079                                 *status = MONO_IMAGE_ERROR_ERRNO;
1080                         return NULL;
1081                 }
1082                 memcpy (datac, data, data_len);
1083         }
1084
1085         image = g_new0 (MonoImage, 1);
1086         image->raw_data = datac;
1087         image->raw_data_len = data_len;
1088         image->raw_data_allocated = need_copy;
1089         image->name = g_strdup_printf ("data-%p", datac);
1090         iinfo = g_new0 (MonoCLIImageInfo, 1);
1091         image->image_info = iinfo;
1092         image->ref_only = refonly;
1093
1094         image = do_mono_image_load (image, status, TRUE, TRUE);
1095         if (image == NULL)
1096                 return NULL;
1097
1098         return register_image (image);
1099 }
1100
1101 MonoImage *
1102 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1103 {
1104         return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1105 }
1106
1107 #ifdef PLATFORM_WIN32
1108 /* fname is not duplicated. */
1109 MonoImage*
1110 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1111 {
1112         MonoImage* image;
1113         MonoCLIImageInfo* iinfo;
1114
1115         image = g_new0 (MonoImage, 1);
1116         image->raw_data = (char*) module_handle;
1117         image->is_module_handle = TRUE;
1118         iinfo = g_new0 (MonoCLIImageInfo, 1);
1119         image->image_info = iinfo;
1120         image->name = fname;
1121         image->ref_count = has_entry_point ? 0 : 1;
1122         image->has_entry_point = has_entry_point;
1123
1124         image = do_mono_image_load (image, status, TRUE, TRUE);
1125         if (image == NULL)
1126                 return NULL;
1127
1128         return register_image (image);
1129 }
1130 #endif
1131
1132 MonoImage *
1133 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1134 {
1135         MonoImage *image;
1136         GHashTable *loaded_images;
1137         char *absfname;
1138         
1139         g_return_val_if_fail (fname != NULL, NULL);
1140         
1141 #ifdef PLATFORM_WIN32
1142         /* Load modules using LoadLibrary. */
1143         if (!refonly && coree_module_handle) {
1144                 HMODULE module_handle;
1145                 guint16 *fname_utf16;
1146                 DWORD last_error;
1147
1148                 absfname = mono_path_resolve_symlinks (fname);
1149                 fname_utf16 = NULL;
1150
1151                 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1152                 mono_images_lock ();
1153                 image = g_hash_table_lookup (loaded_images_hash, absfname);
1154                 if (image) {
1155                         g_assert (image->is_module_handle);
1156                         if (image->has_entry_point && image->ref_count == 0) {
1157                                 /* Increment reference count on images loaded outside of the runtime. */
1158                                 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1159                                 /* The image is already loaded because _CorDllMain removes images from the hash. */
1160                                 module_handle = LoadLibrary (fname_utf16);
1161                                 g_assert (module_handle == (HMODULE) image->raw_data);
1162                         }
1163                         mono_image_addref (image);
1164                         mono_images_unlock ();
1165                         if (fname_utf16)
1166                                 g_free (fname_utf16);
1167                         g_free (absfname);
1168                         return image;
1169                 }
1170
1171                 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1172                 module_handle = MonoLoadImage (fname_utf16);
1173                 if (status && module_handle == NULL)
1174                         last_error = GetLastError ();
1175
1176                 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1177                 image = g_hash_table_lookup (loaded_images_hash, absfname);
1178                 if (image)
1179                         mono_image_addref (image);
1180                 mono_images_unlock ();
1181
1182                 g_free (fname_utf16);
1183
1184                 if (module_handle == NULL) {
1185                         g_assert (!image);
1186                         g_free (absfname);
1187                         if (status) {
1188                                 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1189                                         *status = MONO_IMAGE_IMAGE_INVALID;
1190                                 else
1191                                         *status = MONO_IMAGE_ERROR_ERRNO;
1192                         }
1193                         return NULL;
1194                 }
1195
1196                 if (image) {
1197                         g_assert (image->is_module_handle);
1198                         g_assert (image->has_entry_point);
1199                         g_free (absfname);
1200                         return image;
1201                 }
1202
1203                 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1204         }
1205 #endif
1206
1207         absfname = mono_path_canonicalize (fname);
1208
1209         /*
1210          * The easiest solution would be to do all the loading inside the mutex,
1211          * but that would lead to scalability problems. So we let the loading
1212          * happen outside the mutex, and if multiple threads happen to load
1213          * the same image, we discard all but the first copy.
1214          */
1215         mono_images_lock ();
1216         loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1217         image = g_hash_table_lookup (loaded_images, absfname);
1218         g_free (absfname);
1219         
1220         if (image){
1221                 mono_image_addref (image);
1222                 mono_images_unlock ();
1223                 return image;
1224         }
1225         mono_images_unlock ();
1226
1227         image = do_mono_image_open (fname, status, TRUE, TRUE, refonly);
1228         if (image == NULL)
1229                 return NULL;
1230
1231         return register_image (image);
1232 }
1233
1234 /**
1235  * mono_image_open:
1236  * @fname: filename that points to the module we want to open
1237  * @status: An error condition is returned in this field
1238  *
1239  * Returns: An open image of type %MonoImage or NULL on error. 
1240  * The caller holds a temporary reference to the returned image which should be cleared 
1241  * when no longer needed by calling mono_image_close ().
1242  * if NULL, then check the value of @status for details on the error
1243  */
1244 MonoImage *
1245 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1246 {
1247         return mono_image_open_full (fname, status, FALSE);
1248 }
1249
1250 /**
1251  * mono_pe_file_open:
1252  * @fname: filename that points to the module we want to open
1253  * @status: An error condition is returned in this field
1254  *
1255  * Returns: An open image of type %MonoImage or NULL on error.  if
1256  * NULL, then check the value of @status for details on the error.
1257  * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1258  * It's just a PE file loader, used for FileVersionInfo.  It also does
1259  * not use the image cache.
1260  */
1261 MonoImage *
1262 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1263 {
1264         g_return_val_if_fail (fname != NULL, NULL);
1265         
1266         return(do_mono_image_open (fname, status, FALSE, TRUE, FALSE));
1267 }
1268
1269 /**
1270  * mono_image_open_raw
1271  * @fname: filename that points to the module we want to open
1272  * @status: An error condition is returned in this field
1273  * 
1274  * Returns an image without loading neither pe or cli data.
1275  * 
1276  * Use mono_image_load_pe_data and mono_image_load_cli_data to load them.  
1277  */
1278 MonoImage *
1279 mono_image_open_raw (const char *fname, MonoImageOpenStatus *status)
1280 {
1281         g_return_val_if_fail (fname != NULL, NULL);
1282         
1283         return(do_mono_image_open (fname, status, FALSE, FALSE, FALSE));
1284 }
1285
1286 void
1287 mono_image_fixup_vtable (MonoImage *image)
1288 {
1289 #ifdef PLATFORM_WIN32
1290         MonoCLIImageInfo *iinfo;
1291         MonoPEDirEntry *de;
1292         MonoVTableFixup *vtfixup;
1293         int count;
1294         gpointer slot;
1295         guint16 slot_type;
1296         int slot_count;
1297
1298         g_assert (image->is_module_handle);
1299
1300         iinfo = image->image_info;
1301         de = &iinfo->cli_cli_header.ch_vtable_fixups;
1302         if (!de->rva || !de->size)
1303                 return;
1304         vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1305         if (!vtfixup)
1306                 return;
1307         
1308         count = de->size / sizeof (MonoVTableFixup);
1309         while (count--) {
1310                 if (!vtfixup->rva || !vtfixup->count)
1311                         continue;
1312
1313                 slot = mono_image_rva_map (image, vtfixup->rva);
1314                 g_assert (slot);
1315                 slot_type = vtfixup->type;
1316                 slot_count = vtfixup->count;
1317                 if (slot_type & VTFIXUP_TYPE_32BIT)
1318                         while (slot_count--) {
1319                                 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1320                                 slot = ((guint32*) slot) + 1;
1321                         }
1322                 else if (slot_type & VTFIXUP_TYPE_64BIT)
1323                         while (slot_count--) {
1324                                 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1325                                 slot = ((guint32*) slot) + 1;
1326                         }
1327                 else
1328                         g_assert_not_reached();
1329
1330                 vtfixup++;
1331         }
1332 #else
1333         g_assert_not_reached();
1334 #endif
1335 }
1336
1337 static void
1338 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1339 {
1340         g_hash_table_destroy ((GHashTable*)val);
1341 }
1342
1343 /*
1344 static void
1345 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1346 {
1347         mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1348 }
1349 */
1350
1351 static void
1352 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
1353 {
1354         g_free (val);
1355 }
1356
1357 static void
1358 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1359 {
1360         g_slist_free ((GSList*)val);
1361 }
1362
1363 /**
1364  * mono_image_addref:
1365  * @image: The image file we wish to add a reference to
1366  *
1367  *  Increases the reference count of an image.
1368  */
1369 void
1370 mono_image_addref (MonoImage *image)
1371 {
1372         InterlockedIncrement (&image->ref_count);
1373 }       
1374
1375 void
1376 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1377 {
1378         stream->alloc_size = stream->index = stream->offset = 0;
1379         g_free (stream->data);
1380         stream->data = NULL;
1381         if (stream->hash) {
1382                 g_hash_table_destroy (stream->hash);
1383                 stream->hash = NULL;
1384         }
1385 }
1386
1387 static inline void
1388 free_hash (GHashTable *hash)
1389 {
1390         if (hash)
1391                 g_hash_table_destroy (hash);
1392 }
1393
1394 /**
1395  * mono_image_close:
1396  * @image: The image file we wish to close
1397  *
1398  * Closes an image file, deallocates all memory consumed and
1399  * unmaps all possible sections of the file
1400  */
1401 void
1402 mono_image_close (MonoImage *image)
1403 {
1404         MonoImage *image2;
1405         GHashTable *loaded_images;
1406         int i;
1407
1408         g_return_if_fail (image != NULL);
1409
1410         if (InterlockedDecrement (&image->ref_count) > 0)
1411                 return;
1412
1413 #ifdef PLATFORM_WIN32
1414         if (image->is_module_handle && image->has_entry_point) {
1415                 mono_images_lock ();
1416                 if (image->ref_count == 0) {
1417                         /* Image will be closed by _CorDllMain. */
1418                         FreeLibrary ((HMODULE) image->raw_data);
1419                         mono_images_unlock ();
1420                         return;
1421                 }
1422                 mono_images_unlock ();
1423         }
1424 #endif
1425
1426         mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1427
1428         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1429
1430         mono_metadata_clean_for_image (image);
1431
1432         /*
1433          * The caches inside a MonoImage might refer to metadata which is stored in referenced 
1434          * assemblies, so we can't release these references in mono_assembly_close () since the
1435          * MonoImage might outlive its associated MonoAssembly.
1436          */
1437         if (image->references && !image->dynamic) {
1438                 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1439                 int i;
1440
1441                 for (i = 0; i < t->rows; i++) {
1442                         if (image->references [i])
1443                                 mono_assembly_close (image->references [i]);
1444                 }
1445
1446                 g_free (image->references);
1447                 image->references = NULL;
1448         }
1449
1450         mono_images_lock ();
1451         loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1452         image2 = g_hash_table_lookup (loaded_images, image->name);
1453         if (image == image2) {
1454                 /* This is not true if we are called from mono_image_open () */
1455                 g_hash_table_remove (loaded_images, image->name);
1456         }
1457         if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1458                 g_hash_table_remove (loaded_images, (char *) image->assembly_name);     
1459
1460 #ifdef PLATFORM_WIN32
1461         if (image->is_module_handle && !image->has_entry_point)
1462                 FreeLibrary ((HMODULE) image->raw_data);
1463 #endif
1464
1465         mono_images_unlock ();
1466
1467         if (image->raw_buffer_used) {
1468                 if (image->raw_data != NULL)
1469                         mono_file_unmap (image->raw_data, image->raw_data_handle);
1470         }
1471         
1472         if (image->raw_data_allocated) {
1473                 /* FIXME: do we need this? (image is disposed anyway) */
1474                 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1475                 MonoCLIImageInfo *ii = image->image_info;
1476
1477                 if ((image->raw_metadata > image->raw_data) &&
1478                         (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1479                         image->raw_metadata = NULL;
1480
1481                 for (i = 0; i < ii->cli_section_count; i++)
1482                         if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1483                                 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1484                                 ii->cli_sections [i] = NULL;
1485
1486                 g_free (image->raw_data);
1487         }
1488
1489         if (debug_assembly_unload) {
1490                 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1491         } else {
1492                 g_free (image->name);
1493                 g_free (image->guid);
1494                 g_free (image->version);
1495                 g_free (image->files);
1496         }
1497
1498         if (image->method_cache)
1499                 mono_value_hash_table_destroy (image->method_cache);
1500         if (image->methodref_cache)
1501                 g_hash_table_destroy (image->methodref_cache);
1502         mono_internal_hash_table_destroy (&image->class_cache);
1503         g_hash_table_destroy (image->field_cache);
1504         if (image->array_cache) {
1505                 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1506                 g_hash_table_destroy (image->array_cache);
1507         }
1508         if (image->szarray_cache)
1509                 g_hash_table_destroy (image->szarray_cache);
1510         if (image->ptr_cache)
1511                 g_hash_table_destroy (image->ptr_cache);
1512         if (image->name_cache) {
1513                 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1514                 g_hash_table_destroy (image->name_cache);
1515         }
1516
1517         free_hash (image->native_wrapper_cache);
1518         free_hash (image->managed_wrapper_cache);
1519         free_hash (image->delegate_begin_invoke_cache);
1520         free_hash (image->delegate_end_invoke_cache);
1521         free_hash (image->delegate_invoke_cache);
1522         free_hash (image->delegate_abstract_invoke_cache);
1523         if (image->remoting_invoke_cache)
1524                 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1525         free_hash (image->remoting_invoke_cache);
1526         free_hash (image->runtime_invoke_cache);
1527         free_hash (image->runtime_invoke_direct_cache);
1528         free_hash (image->runtime_invoke_vcall_cache);
1529         free_hash (image->synchronized_cache);
1530         free_hash (image->unbox_wrapper_cache);
1531         free_hash (image->cominterop_invoke_cache);
1532         free_hash (image->cominterop_wrapper_cache);
1533         free_hash (image->typespec_cache);
1534         free_hash (image->ldfld_wrapper_cache);
1535         free_hash (image->ldflda_wrapper_cache);
1536         free_hash (image->stfld_wrapper_cache);
1537         free_hash (image->isinst_cache);
1538         free_hash (image->castclass_cache);
1539         free_hash (image->proxy_isinst_cache);
1540         free_hash (image->thunk_invoke_cache);
1541
1542         /* The ownership of signatures is not well defined */
1543         //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1544         g_hash_table_destroy (image->memberref_signatures);
1545         //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1546         g_hash_table_destroy (image->helper_signatures);
1547         g_hash_table_destroy (image->method_signatures);
1548
1549         if (image->generic_class_cache)
1550                 g_hash_table_destroy (image->generic_class_cache);
1551
1552         if (image->rgctx_template_hash)
1553                 g_hash_table_destroy (image->rgctx_template_hash);
1554
1555         if (image->property_hash)
1556                 mono_property_hash_destroy (image->property_hash);
1557
1558         if (image->interface_bitset) {
1559                 mono_unload_interface_ids (image->interface_bitset);
1560                 mono_bitset_free (image->interface_bitset);
1561         }
1562         if (image->image_info){
1563                 MonoCLIImageInfo *ii = image->image_info;
1564
1565                 if (ii->cli_section_tables)
1566                         g_free (ii->cli_section_tables);
1567                 if (ii->cli_sections)
1568                         g_free (ii->cli_sections);
1569                 g_free (image->image_info);
1570         }
1571
1572         for (i = 0; i < image->module_count; ++i) {
1573                 if (image->modules [i])
1574                         mono_image_close (image->modules [i]);
1575         }
1576         if (image->modules)
1577                 g_free (image->modules);
1578         if (image->modules_loaded)
1579                 g_free (image->modules_loaded);
1580         if (image->references)
1581                 g_free (image->references);
1582         mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
1583
1584         DeleteCriticalSection (&image->szarray_cache_lock);
1585         DeleteCriticalSection (&image->lock);
1586
1587         /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1588         if (!image->dynamic) {
1589                 if (debug_assembly_unload)
1590                         mono_mempool_invalidate (image->mempool);
1591                 else {
1592                         mono_mempool_destroy (image->mempool);
1593                         g_free (image);
1594                 }
1595         } else {
1596                 /* Dynamic images are GC_MALLOCed */
1597                 g_free ((char*)image->module_name);
1598                 mono_dynamic_image_free ((MonoDynamicImage*)image);
1599                 if (debug_assembly_unload)
1600                         mono_mempool_invalidate (image->mempool);
1601                 else
1602                         mono_mempool_destroy (image->mempool);
1603         }
1604
1605         mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1606 }
1607
1608 /** 
1609  * mono_image_strerror:
1610  * @status: an code indicating the result from a recent operation
1611  *
1612  * Returns: a string describing the error
1613  */
1614 const char *
1615 mono_image_strerror (MonoImageOpenStatus status)
1616 {
1617         switch (status){
1618         case MONO_IMAGE_OK:
1619                 return "success";
1620         case MONO_IMAGE_ERROR_ERRNO:
1621                 return strerror (errno);
1622         case MONO_IMAGE_IMAGE_INVALID:
1623                 return "File does not contain a valid CIL image";
1624         case MONO_IMAGE_MISSING_ASSEMBLYREF:
1625                 return "An assembly was referenced, but could not be found";
1626         }
1627         return "Internal error";
1628 }
1629
1630 static gpointer
1631 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1632                                guint32 lang_id, gunichar2 *name,
1633                                MonoPEResourceDirEntry *entry,
1634                                MonoPEResourceDir *root, guint32 level)
1635 {
1636         gboolean is_string, is_dir;
1637         guint32 name_offset, dir_offset;
1638
1639         /* Level 0 holds a directory entry for each type of resource
1640          * (identified by ID or name).
1641          *
1642          * Level 1 holds a directory entry for each named resource
1643          * item, and each "anonymous" item of a particular type of
1644          * resource.
1645          *
1646          * Level 2 holds a directory entry for each language pointing to
1647          * the actual data.
1648          */
1649         is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1650         name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1651
1652         is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1653         dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1654
1655         if(level==0) {
1656                 if (is_string)
1657                         return NULL;
1658         } else if (level==1) {
1659                 if (res_id != name_offset)
1660                         return NULL;
1661 #if 0
1662                 if(name!=NULL &&
1663                    is_string==TRUE && name!=lookup (name_offset)) {
1664                         return(NULL);
1665                 }
1666 #endif
1667         } else if (level==2) {
1668                 if (is_string == TRUE || (is_string == FALSE && lang_id != 0 && name_offset != lang_id))
1669                         return NULL;
1670         } else {
1671                 g_assert_not_reached ();
1672         }
1673
1674         if(is_dir==TRUE) {
1675                 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1676                 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1677                 guint32 entries, i;
1678
1679                 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1680
1681                 for(i=0; i<entries; i++) {
1682                         MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1683                         gpointer ret;
1684                         
1685                         ret=mono_image_walk_resource_tree (info, res_id,
1686                                                            lang_id, name,
1687                                                            sub_entry, root,
1688                                                            level+1);
1689                         if(ret!=NULL) {
1690                                 return(ret);
1691                         }
1692                 }
1693
1694                 return(NULL);
1695         } else {
1696                 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
1697                 MonoPEResourceDataEntry *res;
1698
1699                 res = g_new0 (MonoPEResourceDataEntry, 1);
1700
1701                 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
1702                 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
1703                 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
1704                 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
1705
1706                 return (res);
1707         }
1708 }
1709
1710 /**
1711  * mono_image_lookup_resource:
1712  * @image: the image to look up the resource in
1713  * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1714  * @lang_id: The language id.
1715  * @name: the resource name to lookup.
1716  *
1717  * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1718  * of the given resource. The caller should free it using g_free () when no longer
1719  * needed.
1720  */
1721 gpointer
1722 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1723 {
1724         MonoCLIImageInfo *info;
1725         MonoDotNetHeader *header;
1726         MonoPEDatadir *datadir;
1727         MonoPEDirEntry *rsrc;
1728         MonoPEResourceDir *resource_dir;
1729         MonoPEResourceDirEntry *res_entries;
1730         guint32 entries, i;
1731
1732         if(image==NULL) {
1733                 return(NULL);
1734         }
1735
1736         mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
1737
1738         info=image->image_info;
1739         if(info==NULL) {
1740                 return(NULL);
1741         }
1742
1743         header=&info->cli_header;
1744         if(header==NULL) {
1745                 return(NULL);
1746         }
1747
1748         datadir=&header->datadir;
1749         if(datadir==NULL) {
1750                 return(NULL);
1751         }
1752
1753         rsrc=&datadir->pe_resource_table;
1754         if(rsrc==NULL) {
1755                 return(NULL);
1756         }
1757
1758         resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1759         if(resource_dir==NULL) {
1760                 return(NULL);
1761         }
1762
1763         entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1764         res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1765         
1766         for(i=0; i<entries; i++) {
1767                 MonoPEResourceDirEntry *entry=&res_entries[i];
1768                 gpointer ret;
1769                 
1770                 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1771                                                    name, entry, resource_dir,
1772                                                    0);
1773                 if(ret!=NULL) {
1774                         return(ret);
1775                 }
1776         }
1777
1778         return(NULL);
1779 }
1780
1781 /** 
1782  * mono_image_get_entry_point:
1783  * @image: the image where the entry point will be looked up.
1784  *
1785  * Use this routine to determine the metadata token for method that
1786  * has been flagged as the entry point.
1787  *
1788  * Returns: the token for the entry point method in the image
1789  */
1790 guint32
1791 mono_image_get_entry_point (MonoImage *image)
1792 {
1793         return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1794 }
1795
1796 /**
1797  * mono_image_get_resource:
1798  * @image: the image where the resource will be looked up.
1799  * @offset: The offset to add to the resource
1800  * @size: a pointer to an int where the size of the resource will be stored
1801  *
1802  * This is a low-level routine that fetches a resource from the
1803  * metadata that starts at a given @offset.  The @size parameter is
1804  * filled with the data field as encoded in the metadata.
1805  *
1806  * Returns: the pointer to the resource whose offset is @offset.
1807  */
1808 const char*
1809 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1810 {
1811         MonoCLIImageInfo *iinfo = image->image_info;
1812         MonoCLIHeader *ch = &iinfo->cli_cli_header;
1813         const char* data;
1814
1815         if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1816                 return NULL;
1817         
1818         data = mono_image_rva_map (image, ch->ch_resources.rva);
1819         if (!data)
1820                 return NULL;
1821         data += offset;
1822         if (size)
1823                 *size = read32 (data);
1824         data += 4;
1825         return data;
1826 }
1827
1828 MonoImage*
1829 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1830 {
1831         char *base_dir, *name;
1832         MonoImage *res;
1833         MonoTableInfo  *t = &image->tables [MONO_TABLE_FILE];
1834         const char *fname;
1835         guint32 fname_id;
1836
1837         if (fileidx < 1 || fileidx > t->rows)
1838                 return NULL;
1839
1840         mono_loader_lock ();
1841         if (image->files && image->files [fileidx - 1]) {
1842                 mono_loader_unlock ();
1843                 return image->files [fileidx - 1];
1844         }
1845
1846         if (!image->files)
1847                 image->files = g_new0 (MonoImage*, t->rows);
1848
1849         fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1850         fname = mono_metadata_string_heap (image, fname_id);
1851         base_dir = g_path_get_dirname (image->name);
1852         name = g_build_filename (base_dir, fname, NULL);
1853         res = mono_image_open (name, NULL);
1854         if (res) {
1855                 int i;
1856                 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1857                 res->assembly = image->assembly;
1858                 for (i = 0; i < res->module_count; ++i) {
1859                         if (res->modules [i] && !res->modules [i]->assembly)
1860                                 res->modules [i]->assembly = image->assembly;
1861                 }
1862
1863                 image->files [fileidx - 1] = res;
1864 #ifdef PLATFORM_WIN32
1865                 if (res->is_module_handle)
1866                         mono_image_fixup_vtable (res);
1867 #endif
1868         }
1869         mono_loader_unlock ();
1870         g_free (name);
1871         g_free (base_dir);
1872         return res;
1873 }
1874
1875 /**
1876  * mono_image_get_strong_name:
1877  * @image: a MonoImage
1878  * @size: a guint32 pointer, or NULL.
1879  *
1880  * If the image has a strong name, and @size is not NULL, the value
1881  * pointed to by size will have the size of the strong name.
1882  *
1883  * Returns: NULL if the image does not have a strong name, or a
1884  * pointer to the public key.
1885  */
1886 const char*
1887 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1888 {
1889         MonoCLIImageInfo *iinfo = image->image_info;
1890         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1891         const char* data;
1892
1893         if (!de->size || !de->rva)
1894                 return NULL;
1895         data = mono_image_rva_map (image, de->rva);
1896         if (!data)
1897                 return NULL;
1898         if (size)
1899                 *size = de->size;
1900         return data;
1901 }
1902
1903 /**
1904  * mono_image_strong_name_position:
1905  * @image: a MonoImage
1906  * @size: a guint32 pointer, or NULL.
1907  *
1908  * If the image has a strong name, and @size is not NULL, the value
1909  * pointed to by size will have the size of the strong name.
1910  *
1911  * Returns: the position within the image file where the strong name
1912  * is stored.
1913  */
1914 guint32
1915 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1916 {
1917         MonoCLIImageInfo *iinfo = image->image_info;
1918         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1919         guint32 pos;
1920
1921         if (size)
1922                 *size = de->size;
1923         if (!de->size || !de->rva)
1924                 return 0;
1925         pos = mono_cli_rva_image_map (image, de->rva);
1926         return pos == INVALID_ADDRESS ? 0 : pos;
1927 }
1928
1929 /**
1930  * mono_image_get_public_key:
1931  * @image: a MonoImage
1932  * @size: a guint32 pointer, or NULL.
1933  *
1934  * This is used to obtain the public key in the @image.
1935  * 
1936  * If the image has a public key, and @size is not NULL, the value
1937  * pointed to by size will have the size of the public key.
1938  * 
1939  * Returns: NULL if the image does not have a public key, or a pointer
1940  * to the public key.
1941  */
1942 const char*
1943 mono_image_get_public_key (MonoImage *image, guint32 *size)
1944 {
1945         const char *pubkey;
1946         guint32 len, tok;
1947
1948         if (image->dynamic) {
1949                 if (size)
1950                         *size = ((MonoDynamicImage*)image)->public_key_len;
1951                 return (char*)((MonoDynamicImage*)image)->public_key;
1952         }
1953         if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1954                 return NULL;
1955         tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1956         if (!tok)
1957                 return NULL;
1958         pubkey = mono_metadata_blob_heap (image, tok);
1959         len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1960         if (size)
1961                 *size = len;
1962         return pubkey;
1963 }
1964
1965 /**
1966  * mono_image_get_name:
1967  * @name: a MonoImage
1968  *
1969  * Returns: the name of the assembly.
1970  */
1971 const char*
1972 mono_image_get_name (MonoImage *image)
1973 {
1974         return image->assembly_name;
1975 }
1976
1977 /**
1978  * mono_image_get_filename:
1979  * @image: a MonoImage
1980  *
1981  * Used to get the filename that hold the actual MonoImage
1982  *
1983  * Returns: the filename.
1984  */
1985 const char*
1986 mono_image_get_filename (MonoImage *image)
1987 {
1988         return image->name;
1989 }
1990
1991 const char*
1992 mono_image_get_guid (MonoImage *image)
1993 {
1994         return image->guid;
1995 }
1996
1997 const MonoTableInfo*
1998 mono_image_get_table_info (MonoImage *image, int table_id)
1999 {
2000         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2001                 return NULL;
2002         return &image->tables [table_id];
2003 }
2004
2005 int
2006 mono_image_get_table_rows (MonoImage *image, int table_id)
2007 {
2008         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2009                 return 0;
2010         return image->tables [table_id].rows;
2011 }
2012
2013 int
2014 mono_table_info_get_rows (const MonoTableInfo *table)
2015 {
2016         return table->rows;
2017 }
2018
2019 /**
2020  * mono_image_get_assembly:
2021  * @image: the MonoImage.
2022  *
2023  * Use this routine to get the assembly that owns this image.
2024  *
2025  * Returns: the assembly that holds this image.
2026  */
2027 MonoAssembly* 
2028 mono_image_get_assembly (MonoImage *image)
2029 {
2030         return image->assembly;
2031 }
2032
2033 /**
2034  * mono_image_is_dynamic:
2035  * @image: the MonoImage
2036  *
2037  * Determines if the given image was created dynamically through the
2038  * System.Reflection.Emit API
2039  *
2040  * Returns: TRUE if the image was created dynamically, FALSE if not.
2041  */
2042 gboolean
2043 mono_image_is_dynamic (MonoImage *image)
2044 {
2045         return image->dynamic;
2046 }
2047
2048 /**
2049  * mono_image_has_authenticode_entry:
2050  * @image: the MonoImage
2051  *
2052  * Use this routine to determine if the image has a Authenticode
2053  * Certificate Table.
2054  *
2055  * Returns: TRUE if the image contains an authenticode entry in the PE
2056  * directory.
2057  */
2058 gboolean
2059 mono_image_has_authenticode_entry (MonoImage *image)
2060 {
2061         MonoCLIImageInfo *iinfo = image->image_info;
2062         MonoDotNetHeader *header = &iinfo->cli_header;
2063         MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
2064         // the Authenticode "pre" (non ASN.1) header is 8 bytes long
2065         return ((de->rva != 0) && (de->size > 8));
2066 }
2067
2068 gpointer
2069 mono_image_alloc (MonoImage *image, guint size)
2070 {
2071         gpointer res;
2072
2073         mono_perfcounters->loader_bytes += size;
2074         mono_image_lock (image);
2075         res = mono_mempool_alloc (image->mempool, size);
2076         mono_image_unlock (image);
2077
2078         return res;
2079 }
2080
2081 gpointer
2082 mono_image_alloc0 (MonoImage *image, guint size)
2083 {
2084         gpointer res;
2085
2086         mono_perfcounters->loader_bytes += size;
2087         mono_image_lock (image);
2088         res = mono_mempool_alloc0 (image->mempool, size);
2089         mono_image_unlock (image);
2090
2091         return res;
2092 }
2093
2094 char*
2095 mono_image_strdup (MonoImage *image, const char *s)
2096 {
2097         char *res;
2098
2099         mono_perfcounters->loader_bytes += strlen (s);
2100         mono_image_lock (image);
2101         res = mono_mempool_strdup (image->mempool, s);
2102         mono_image_unlock (image);
2103
2104         return res;
2105 }
2106
2107 GList*
2108 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
2109 {
2110         GList *new_list;
2111         
2112         new_list = mono_image_alloc (image, sizeof (GList));
2113         new_list->data = data;
2114         new_list->prev = list ? list->prev : NULL;
2115     new_list->next = list;
2116
2117     if (new_list->prev)
2118             new_list->prev->next = new_list;
2119     if (list)
2120             list->prev = new_list;
2121
2122         return new_list;
2123 }
2124
2125 GSList*
2126 g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
2127 {
2128         GSList *new_list;
2129
2130         new_list = mono_image_alloc (image, sizeof (GSList));
2131         new_list->data = data;
2132         new_list->next = NULL;
2133
2134         return g_slist_concat (list, new_list);
2135 }
2136
2137 void
2138 mono_image_lock (MonoImage *image)
2139 {
2140         mono_locks_acquire (&image->lock, ImageDataLock);
2141 }
2142
2143 void
2144 mono_image_unlock (MonoImage *image)
2145 {
2146         mono_locks_release (&image->lock, ImageDataLock);
2147 }
2148
2149
2150 /**
2151  * mono_image_property_lookup:
2152  *
2153  * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
2154  *
2155  * LOCKING: Takes the image lock
2156  */
2157 gpointer 
2158 mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
2159 {
2160         gpointer res;
2161
2162         mono_image_lock (image);
2163         res = mono_property_hash_lookup (image->property_hash, subject, property);
2164         mono_image_unlock (image);
2165
2166         return res;
2167 }
2168
2169 /**
2170  * mono_image_property_insert:
2171  *
2172  * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2173  *
2174  * LOCKING: Takes the image lock
2175  */
2176 void
2177 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
2178 {
2179         mono_image_lock (image);
2180         mono_property_hash_insert (image->property_hash, subject, property, value);
2181         mono_image_unlock (image);
2182 }
2183
2184 /**
2185  * mono_image_property_remove:
2186  *
2187  * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2188  *
2189  * LOCKING: Takes the image lock
2190  */
2191 void
2192 mono_image_property_remove (MonoImage *image, gpointer subject)
2193 {
2194         mono_image_lock (image);
2195         mono_property_hash_remove_object (image->property_hash, subject);
2196         mono_image_unlock (image);
2197 }