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