2008-09-12 Mark Probst <mark.probst@gmail.com>
[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, gboolean has_entry_point, 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 = has_entry_point ? 0 : 1;
1095         image->has_entry_point = has_entry_point;
1096
1097         image = do_mono_image_load (image, status, TRUE);
1098         if (image == NULL)
1099                 return NULL;
1100
1101         return register_image (image);
1102 }
1103 #endif
1104
1105 MonoImage *
1106 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1107 {
1108         MonoImage *image;
1109         GHashTable *loaded_images;
1110         char *absfname;
1111         
1112         g_return_val_if_fail (fname != NULL, NULL);
1113         
1114 #ifdef PLATFORM_WIN32
1115         /* Load modules using LoadLibrary. */
1116         if (!refonly && coree_module_handle) {
1117                 HMODULE module_handle;
1118                 guint16 *fname_utf16;
1119                 DWORD last_error;
1120
1121                 absfname = mono_path_resolve_symlinks (fname);
1122                 fname_utf16 = NULL;
1123
1124                 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1125                 mono_images_lock ();
1126                 image = g_hash_table_lookup (loaded_images_hash, absfname);
1127                 if (image) {
1128                         g_assert (image->is_module_handle);
1129                         if (image->has_entry_point && image->ref_count == 0) {
1130                                 /* Increment reference count on images loaded outside of the runtime. */
1131                                 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1132                                 /* The image is already loaded because _CorDllMain removes images from the hash. */
1133                                 module_handle = LoadLibrary (fname_utf16);
1134                                 g_assert (module_handle == (HMODULE) image->raw_data);
1135                         }
1136                         mono_image_addref (image);
1137                         mono_images_unlock ();
1138                         if (fname_utf16)
1139                                 g_free (fname_utf16);
1140                         g_free (absfname);
1141                         return image;
1142                 }
1143
1144                 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1145                 module_handle = MonoLoadImage (fname_utf16);
1146                 if (status && module_handle == NULL)
1147                         last_error = GetLastError ();
1148
1149                 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1150                 image = g_hash_table_lookup (loaded_images_hash, absfname);
1151                 if (image)
1152                         mono_image_addref (image);
1153                 mono_images_unlock ();
1154
1155                 g_free (fname_utf16);
1156
1157                 if (module_handle == NULL) {
1158                         g_assert (!image);
1159                         g_free (absfname);
1160                         if (status) {
1161                                 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1162                                         *status = MONO_IMAGE_IMAGE_INVALID;
1163                                 else
1164                                         *status = MONO_IMAGE_ERROR_ERRNO;
1165                         }
1166                         return NULL;
1167                 }
1168
1169                 if (image) {
1170                         g_assert (image->is_module_handle);
1171                         g_assert (image->has_entry_point);
1172                         g_free (absfname);
1173                         return image;
1174                 }
1175
1176                 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1177         }
1178 #endif
1179
1180         absfname = mono_path_canonicalize (fname);
1181
1182         /*
1183          * The easiest solution would be to do all the loading inside the mutex,
1184          * but that would lead to scalability problems. So we let the loading
1185          * happen outside the mutex, and if multiple threads happen to load
1186          * the same image, we discard all but the first copy.
1187          */
1188         mono_images_lock ();
1189         loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1190         image = g_hash_table_lookup (loaded_images, absfname);
1191         g_free (absfname);
1192         
1193         if (image){
1194                 mono_image_addref (image);
1195                 mono_images_unlock ();
1196                 return image;
1197         }
1198         mono_images_unlock ();
1199
1200         image = do_mono_image_open (fname, status, TRUE, refonly);
1201         if (image == NULL)
1202                 return NULL;
1203
1204         return register_image (image);
1205 }
1206
1207 /**
1208  * mono_image_open:
1209  * @fname: filename that points to the module we want to open
1210  * @status: An error condition is returned in this field
1211  *
1212  * Returns: An open image of type %MonoImage or NULL on error. 
1213  * The caller holds a temporary reference to the returned image which should be cleared 
1214  * when no longer needed by calling mono_image_close ().
1215  * if NULL, then check the value of @status for details on the error
1216  */
1217 MonoImage *
1218 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1219 {
1220         return mono_image_open_full (fname, status, FALSE);
1221 }
1222
1223 /**
1224  * mono_pe_file_open:
1225  * @fname: filename that points to the module we want to open
1226  * @status: An error condition is returned in this field
1227  *
1228  * Returns: An open image of type %MonoImage or NULL on error.  if
1229  * NULL, then check the value of @status for details on the error.
1230  * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1231  * It's just a PE file loader, used for FileVersionInfo.  It also does
1232  * not use the image cache.
1233  */
1234 MonoImage *
1235 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1236 {
1237         g_return_val_if_fail (fname != NULL, NULL);
1238         
1239         return(do_mono_image_open (fname, status, FALSE, FALSE));
1240 }
1241
1242 void
1243 mono_image_fixup_vtable (MonoImage *image)
1244 {
1245 #ifdef PLATFORM_WIN32
1246         MonoCLIImageInfo *iinfo;
1247         MonoPEDirEntry *de;
1248         MonoVTableFixup *vtfixup;
1249         int count;
1250         gpointer slot;
1251         guint16 slot_type;
1252         int slot_count;
1253
1254         g_assert (image->is_module_handle);
1255
1256         iinfo = image->image_info;
1257         de = &iinfo->cli_cli_header.ch_vtable_fixups;
1258         if (!de->rva || !de->size)
1259                 return;
1260         vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1261         if (!vtfixup)
1262                 return;
1263         
1264         count = de->size / sizeof (MonoVTableFixup);
1265         while (count--) {
1266                 if (!vtfixup->rva || !vtfixup->count)
1267                         continue;
1268
1269                 slot = mono_image_rva_map (image, vtfixup->rva);
1270                 g_assert (slot);
1271                 slot_type = vtfixup->type;
1272                 slot_count = vtfixup->count;
1273                 if (slot_type & VTFIXUP_TYPE_32BIT)
1274                         while (slot_count--) {
1275                                 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1276                                 ((guint32*) slot)++;
1277                         }
1278                 else if (slot_type & VTFIXUP_TYPE_64BIT)
1279                         while (slot_count--) {
1280                                 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1281                                 ((guint64*) slot)++;
1282                         }
1283                 else
1284                         g_assert_not_reached();
1285
1286                 vtfixup++;
1287         }
1288 #else
1289         g_assert_not_reached();
1290 #endif
1291 }
1292
1293 static void
1294 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1295 {
1296         g_hash_table_destroy ((GHashTable*)val);
1297 }
1298
1299 /*
1300 static void
1301 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1302 {
1303         mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1304 }
1305 */
1306
1307 static void
1308 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
1309 {
1310         g_free (val);
1311 }
1312
1313 static void
1314 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1315 {
1316         g_slist_free ((GSList*)val);
1317 }
1318
1319 /**
1320  * mono_image_addref:
1321  * @image: The image file we wish to add a reference to
1322  *
1323  *  Increases the reference count of an image.
1324  */
1325 void
1326 mono_image_addref (MonoImage *image)
1327 {
1328         InterlockedIncrement (&image->ref_count);
1329 }       
1330
1331 void
1332 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1333 {
1334         stream->alloc_size = stream->index = stream->offset = 0;
1335         g_free (stream->data);
1336         stream->data = NULL;
1337         if (stream->hash) {
1338                 g_hash_table_destroy (stream->hash);
1339                 stream->hash = NULL;
1340         }
1341 }
1342
1343 /**
1344  * mono_image_close:
1345  * @image: The image file we wish to close
1346  *
1347  * Closes an image file, deallocates all memory consumed and
1348  * unmaps all possible sections of the file
1349  */
1350 void
1351 mono_image_close (MonoImage *image)
1352 {
1353         MonoImage *image2;
1354         GHashTable *loaded_images;
1355         int i;
1356
1357         g_return_if_fail (image != NULL);
1358
1359         if (InterlockedDecrement (&image->ref_count) > 0)
1360                 return;
1361
1362 #ifdef PLATFORM_WIN32
1363         if (image->is_module_handle && image->has_entry_point) {
1364                 mono_images_lock ();
1365                 if (image->ref_count == 0) {
1366                         /* Image will be closed by _CorDllMain. */
1367                         FreeLibrary ((HMODULE) image->raw_data);
1368                         mono_images_unlock ();
1369                         return;
1370                 }
1371                 mono_images_unlock ();
1372         }
1373 #endif
1374
1375         mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1376
1377         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1378
1379         mono_metadata_clean_for_image (image);
1380
1381         /*
1382          * The caches inside a MonoImage might refer to metadata which is stored in referenced 
1383          * assemblies, so we can't release these references in mono_assembly_close () since the
1384          * MonoImage might outlive its associated MonoAssembly.
1385          */
1386         if (image->references) {
1387                 int i;
1388
1389                 for (i = 0; image->references [i]; i++) {
1390                         if (image->references [i])
1391                                 mono_assembly_close (image->references [i]);
1392                 }
1393
1394                 g_free (image->references);
1395                 image->references = NULL;
1396         }
1397
1398         mono_images_lock ();
1399         loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1400         image2 = g_hash_table_lookup (loaded_images, image->name);
1401         if (image == image2) {
1402                 /* This is not true if we are called from mono_image_open () */
1403                 g_hash_table_remove (loaded_images, image->name);
1404         }
1405         if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1406                 g_hash_table_remove (loaded_images, (char *) image->assembly_name);     
1407
1408 #ifdef PLATFORM_WIN32
1409         if (image->is_module_handle && !image->has_entry_point)
1410                 FreeLibrary ((HMODULE) image->raw_data);
1411 #endif
1412
1413         mono_images_unlock ();
1414
1415         if (image->raw_buffer_used) {
1416                 if (image->raw_data != NULL)
1417                         mono_raw_buffer_free (image->raw_data);
1418         }
1419         
1420         if (image->raw_data_allocated) {
1421                 /* FIXME: do we need this? (image is disposed anyway) */
1422                 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1423                 MonoCLIImageInfo *ii = image->image_info;
1424
1425                 if ((image->raw_metadata > image->raw_data) &&
1426                         (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1427                         image->raw_metadata = NULL;
1428
1429                 for (i = 0; i < ii->cli_section_count; i++)
1430                         if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1431                                 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1432                                 ii->cli_sections [i] = NULL;
1433
1434                 g_free (image->raw_data);
1435         }
1436
1437         if (debug_assembly_unload) {
1438                 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1439         } else {
1440                 g_free (image->name);
1441                 g_free (image->guid);
1442                 g_free (image->version);
1443                 g_free (image->files);
1444         }
1445
1446         if (image->method_cache)
1447                 mono_value_hash_table_destroy (image->method_cache);
1448         if (image->methodref_cache)
1449                 g_hash_table_destroy (image->methodref_cache);
1450         mono_internal_hash_table_destroy (&image->class_cache);
1451         g_hash_table_destroy (image->field_cache);
1452         if (image->array_cache) {
1453                 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1454                 g_hash_table_destroy (image->array_cache);
1455         }
1456         if (image->ptr_cache)
1457                 g_hash_table_destroy (image->ptr_cache);
1458         if (image->name_cache) {
1459                 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1460                 g_hash_table_destroy (image->name_cache);
1461         }
1462         g_hash_table_destroy (image->native_wrapper_cache);
1463         g_hash_table_destroy (image->managed_wrapper_cache);
1464         g_hash_table_destroy (image->delegate_begin_invoke_cache);
1465         g_hash_table_destroy (image->delegate_end_invoke_cache);
1466         g_hash_table_destroy (image->delegate_invoke_cache);
1467         if (image->delegate_abstract_invoke_cache)
1468                 g_hash_table_destroy (image->delegate_abstract_invoke_cache);
1469         g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1470         g_hash_table_destroy (image->remoting_invoke_cache);
1471         g_hash_table_destroy (image->runtime_invoke_cache);
1472         g_hash_table_destroy (image->runtime_invoke_direct_cache);
1473         g_hash_table_destroy (image->synchronized_cache);
1474         g_hash_table_destroy (image->unbox_wrapper_cache);
1475         g_hash_table_destroy (image->cominterop_invoke_cache);
1476         g_hash_table_destroy (image->cominterop_wrapper_cache);
1477         g_hash_table_destroy (image->typespec_cache);
1478         g_hash_table_destroy (image->ldfld_wrapper_cache);
1479         g_hash_table_destroy (image->ldflda_wrapper_cache);
1480         g_hash_table_destroy (image->stfld_wrapper_cache);
1481         g_hash_table_destroy (image->isinst_cache);
1482         g_hash_table_destroy (image->castclass_cache);
1483         g_hash_table_destroy (image->proxy_isinst_cache);
1484         g_hash_table_destroy (image->thunk_invoke_cache);
1485         if (image->static_rgctx_invoke_cache)
1486                 g_hash_table_destroy (image->static_rgctx_invoke_cache);
1487
1488         /* The ownership of signatures is not well defined */
1489         //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1490         g_hash_table_destroy (image->memberref_signatures);
1491         //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1492         g_hash_table_destroy (image->helper_signatures);
1493         g_hash_table_destroy (image->method_signatures);
1494
1495         if (image->generic_class_cache)
1496                 g_hash_table_destroy (image->generic_class_cache);
1497
1498         if (image->rgctx_template_hash)
1499                 g_hash_table_destroy (image->rgctx_template_hash);
1500
1501         if (image->property_hash)
1502                 mono_property_hash_destroy (image->property_hash);
1503
1504         if (image->interface_bitset) {
1505                 mono_unload_interface_ids (image->interface_bitset);
1506                 mono_bitset_free (image->interface_bitset);
1507         }
1508         if (image->image_info){
1509                 MonoCLIImageInfo *ii = image->image_info;
1510
1511                 if (ii->cli_section_tables)
1512                         g_free (ii->cli_section_tables);
1513                 if (ii->cli_sections)
1514                         g_free (ii->cli_sections);
1515                 g_free (image->image_info);
1516         }
1517
1518         for (i = 0; i < image->module_count; ++i) {
1519                 if (image->modules [i])
1520                         mono_image_close (image->modules [i]);
1521         }
1522         if (image->modules)
1523                 g_free (image->modules);
1524         if (image->modules_loaded)
1525                 g_free (image->modules_loaded);
1526         if (image->references)
1527                 g_free (image->references);
1528         /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1529         if (!image->dynamic) {
1530                 if (debug_assembly_unload)
1531                         mono_mempool_invalidate (image->mempool);
1532                 else {
1533                         mono_mempool_destroy (image->mempool);
1534                         g_free (image);
1535                 }
1536         } else {
1537                 /* Dynamic images are GC_MALLOCed */
1538                 g_free ((char*)image->module_name);
1539                 mono_dynamic_image_free ((MonoDynamicImage*)image);
1540                 mono_mempool_destroy (image->mempool);
1541         }
1542
1543         mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1544 }
1545
1546 /** 
1547  * mono_image_strerror:
1548  * @status: an code indicating the result from a recent operation
1549  *
1550  * Returns: a string describing the error
1551  */
1552 const char *
1553 mono_image_strerror (MonoImageOpenStatus status)
1554 {
1555         switch (status){
1556         case MONO_IMAGE_OK:
1557                 return "success";
1558         case MONO_IMAGE_ERROR_ERRNO:
1559                 return strerror (errno);
1560         case MONO_IMAGE_IMAGE_INVALID:
1561                 return "File does not contain a valid CIL image";
1562         case MONO_IMAGE_MISSING_ASSEMBLYREF:
1563                 return "An assembly was referenced, but could not be found";
1564         }
1565         return "Internal error";
1566 }
1567
1568 static gpointer
1569 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1570                                guint32 lang_id, gunichar2 *name,
1571                                MonoPEResourceDirEntry *entry,
1572                                MonoPEResourceDir *root, guint32 level)
1573 {
1574         gboolean is_string, is_dir;
1575         guint32 name_offset, dir_offset;
1576
1577         /* Level 0 holds a directory entry for each type of resource
1578          * (identified by ID or name).
1579          *
1580          * Level 1 holds a directory entry for each named resource
1581          * item, and each "anonymous" item of a particular type of
1582          * resource.
1583          *
1584          * Level 2 holds a directory entry for each language pointing to
1585          * the actual data.
1586          */
1587         is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1588         name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1589
1590         is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1591         dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1592
1593         if(level==0) {
1594                 if((is_string==FALSE && name_offset!=res_id) ||
1595                    (is_string==TRUE)) {
1596                         return(NULL);
1597                 }
1598         } else if (level==1) {
1599 #if 0
1600                 if(name!=NULL &&
1601                    is_string==TRUE && name!=lookup (name_offset)) {
1602                         return(NULL);
1603                 }
1604 #endif
1605         } else if (level==2) {
1606                 if ((is_string == FALSE &&
1607                     name_offset != lang_id &&
1608                     lang_id != 0) ||
1609                    (is_string == TRUE)) {
1610                         return(NULL);
1611                 }
1612         } else {
1613                 g_assert_not_reached ();
1614         }
1615
1616         if(is_dir==TRUE) {
1617                 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1618                 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1619                 guint32 entries, i;
1620
1621                 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1622
1623                 for(i=0; i<entries; i++) {
1624                         MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1625                         gpointer ret;
1626                         
1627                         ret=mono_image_walk_resource_tree (info, res_id,
1628                                                            lang_id, name,
1629                                                            sub_entry, root,
1630                                                            level+1);
1631                         if(ret!=NULL) {
1632                                 return(ret);
1633                         }
1634                 }
1635
1636                 return(NULL);
1637         } else {
1638                 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
1639                 MonoPEResourceDataEntry *res;
1640
1641                 res = g_new0 (MonoPEResourceDataEntry, 1);
1642
1643                 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
1644                 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
1645                 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
1646                 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
1647
1648                 return (res);
1649         }
1650 }
1651
1652 /**
1653  * mono_image_lookup_resource:
1654  * @image: the image to look up the resource in
1655  * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1656  * @lang_id: The language id.
1657  * @name: the resource name to lookup.
1658  *
1659  * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1660  * of the given resource. The caller should free it using g_free () when no longer
1661  * needed.
1662  */
1663 gpointer
1664 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1665 {
1666         MonoCLIImageInfo *info;
1667         MonoDotNetHeader *header;
1668         MonoPEDatadir *datadir;
1669         MonoPEDirEntry *rsrc;
1670         MonoPEResourceDir *resource_dir;
1671         MonoPEResourceDirEntry *res_entries;
1672         guint32 entries, i;
1673
1674         if(image==NULL) {
1675                 return(NULL);
1676         }
1677
1678         info=image->image_info;
1679         if(info==NULL) {
1680                 return(NULL);
1681         }
1682
1683         header=&info->cli_header;
1684         if(header==NULL) {
1685                 return(NULL);
1686         }
1687
1688         datadir=&header->datadir;
1689         if(datadir==NULL) {
1690                 return(NULL);
1691         }
1692
1693         rsrc=&datadir->pe_resource_table;
1694         if(rsrc==NULL) {
1695                 return(NULL);
1696         }
1697
1698         resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1699         if(resource_dir==NULL) {
1700                 return(NULL);
1701         }
1702
1703         entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1704         res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1705         
1706         for(i=0; i<entries; i++) {
1707                 MonoPEResourceDirEntry *entry=&res_entries[i];
1708                 gpointer ret;
1709                 
1710                 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1711                                                    name, entry, resource_dir,
1712                                                    0);
1713                 if(ret!=NULL) {
1714                         return(ret);
1715                 }
1716         }
1717
1718         return(NULL);
1719 }
1720
1721 /** 
1722  * mono_image_get_entry_point:
1723  * @image: the image where the entry point will be looked up.
1724  *
1725  * Use this routine to determine the metadata token for method that
1726  * has been flagged as the entry point.
1727  *
1728  * Returns: the token for the entry point method in the image
1729  */
1730 guint32
1731 mono_image_get_entry_point (MonoImage *image)
1732 {
1733         return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1734 }
1735
1736 /**
1737  * mono_image_get_resource:
1738  * @image: the image where the resource will be looked up.
1739  * @offset: The offset to add to the resource
1740  * @size: a pointer to an int where the size of the resource will be stored
1741  *
1742  * This is a low-level routine that fetches a resource from the
1743  * metadata that starts at a given @offset.  The @size parameter is
1744  * filled with the data field as encoded in the metadata.
1745  *
1746  * Returns: the pointer to the resource whose offset is @offset.
1747  */
1748 const char*
1749 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1750 {
1751         MonoCLIImageInfo *iinfo = image->image_info;
1752         MonoCLIHeader *ch = &iinfo->cli_cli_header;
1753         const char* data;
1754
1755         if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1756                 return NULL;
1757         
1758         data = mono_image_rva_map (image, ch->ch_resources.rva);
1759         if (!data)
1760                 return NULL;
1761         data += offset;
1762         if (size)
1763                 *size = read32 (data);
1764         data += 4;
1765         return data;
1766 }
1767
1768 MonoImage*
1769 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1770 {
1771         char *base_dir, *name;
1772         MonoImage *res;
1773         MonoTableInfo  *t = &image->tables [MONO_TABLE_FILE];
1774         const char *fname;
1775         guint32 fname_id;
1776
1777         if (fileidx < 1 || fileidx > t->rows)
1778                 return NULL;
1779
1780         mono_loader_lock ();
1781         if (image->files && image->files [fileidx - 1]) {
1782                 mono_loader_unlock ();
1783                 return image->files [fileidx - 1];
1784         }
1785
1786         if (!image->files)
1787                 image->files = g_new0 (MonoImage*, t->rows);
1788
1789         fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1790         fname = mono_metadata_string_heap (image, fname_id);
1791         base_dir = g_path_get_dirname (image->name);
1792         name = g_build_filename (base_dir, fname, NULL);
1793         res = mono_image_open (name, NULL);
1794         if (res) {
1795                 int i;
1796                 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1797                 res->assembly = image->assembly;
1798                 for (i = 0; i < res->module_count; ++i) {
1799                         if (res->modules [i] && !res->modules [i]->assembly)
1800                                 res->modules [i]->assembly = image->assembly;
1801                 }
1802
1803                 image->files [fileidx - 1] = res;
1804 #ifdef PLATFORM_WIN32
1805                 if (res->is_module_handle)
1806                         mono_image_fixup_vtable (res);
1807 #endif
1808         }
1809         mono_loader_unlock ();
1810         g_free (name);
1811         g_free (base_dir);
1812         return res;
1813 }
1814
1815 /**
1816  * mono_image_get_strong_name:
1817  * @image: a MonoImage
1818  * @size: a guint32 pointer, or NULL.
1819  *
1820  * If the image has a strong name, and @size is not NULL, the value
1821  * pointed to by size will have the size of the strong name.
1822  *
1823  * Returns: NULL if the image does not have a strong name, or a
1824  * pointer to the public key.
1825  */
1826 const char*
1827 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1828 {
1829         MonoCLIImageInfo *iinfo = image->image_info;
1830         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1831         const char* data;
1832
1833         if (!de->size || !de->rva)
1834                 return NULL;
1835         data = mono_image_rva_map (image, de->rva);
1836         if (!data)
1837                 return NULL;
1838         if (size)
1839                 *size = de->size;
1840         return data;
1841 }
1842
1843 /**
1844  * mono_image_strong_name_position:
1845  * @image: a MonoImage
1846  * @size: a guint32 pointer, or NULL.
1847  *
1848  * If the image has a strong name, and @size is not NULL, the value
1849  * pointed to by size will have the size of the strong name.
1850  *
1851  * Returns: the position within the image file where the strong name
1852  * is stored.
1853  */
1854 guint32
1855 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1856 {
1857         MonoCLIImageInfo *iinfo = image->image_info;
1858         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1859         guint32 pos;
1860
1861         if (size)
1862                 *size = de->size;
1863         if (!de->size || !de->rva)
1864                 return 0;
1865         pos = mono_cli_rva_image_map (image, de->rva);
1866         return pos == INVALID_ADDRESS ? 0 : pos;
1867 }
1868
1869 /**
1870  * mono_image_get_public_key:
1871  * @image: a MonoImage
1872  * @size: a guint32 pointer, or NULL.
1873  *
1874  * This is used to obtain the public key in the @image.
1875  * 
1876  * If the image has a public key, and @size is not NULL, the value
1877  * pointed to by size will have the size of the public key.
1878  * 
1879  * Returns: NULL if the image does not have a public key, or a pointer
1880  * to the public key.
1881  */
1882 const char*
1883 mono_image_get_public_key (MonoImage *image, guint32 *size)
1884 {
1885         const char *pubkey;
1886         guint32 len, tok;
1887
1888         if (image->dynamic) {
1889                 if (size)
1890                         *size = ((MonoDynamicImage*)image)->public_key_len;
1891                 return (char*)((MonoDynamicImage*)image)->public_key;
1892         }
1893         if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1894                 return NULL;
1895         tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1896         if (!tok)
1897                 return NULL;
1898         pubkey = mono_metadata_blob_heap (image, tok);
1899         len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1900         if (size)
1901                 *size = len;
1902         return pubkey;
1903 }
1904
1905 /**
1906  * mono_image_get_name:
1907  * @name: a MonoImage
1908  *
1909  * Returns: the name of the assembly.
1910  */
1911 const char*
1912 mono_image_get_name (MonoImage *image)
1913 {
1914         return image->assembly_name;
1915 }
1916
1917 /**
1918  * mono_image_get_filename:
1919  * @image: a MonoImage
1920  *
1921  * Used to get the filename that hold the actual MonoImage
1922  *
1923  * Returns: the filename.
1924  */
1925 const char*
1926 mono_image_get_filename (MonoImage *image)
1927 {
1928         return image->name;
1929 }
1930
1931 const char*
1932 mono_image_get_guid (MonoImage *image)
1933 {
1934         return image->guid;
1935 }
1936
1937 const MonoTableInfo*
1938 mono_image_get_table_info (MonoImage *image, int table_id)
1939 {
1940         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1941                 return NULL;
1942         return &image->tables [table_id];
1943 }
1944
1945 int
1946 mono_image_get_table_rows (MonoImage *image, int table_id)
1947 {
1948         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1949                 return 0;
1950         return image->tables [table_id].rows;
1951 }
1952
1953 int
1954 mono_table_info_get_rows (const MonoTableInfo *table)
1955 {
1956         return table->rows;
1957 }
1958
1959 /**
1960  * mono_image_get_assembly:
1961  * @image: the MonoImage.
1962  *
1963  * Use this routine to get the assembly that owns this image.
1964  *
1965  * Returns: the assembly that holds this image.
1966  */
1967 MonoAssembly* 
1968 mono_image_get_assembly (MonoImage *image)
1969 {
1970         return image->assembly;
1971 }
1972
1973 /**
1974  * mono_image_is_dynamic:
1975  * @image: the MonoImage
1976  *
1977  * Determines if the given image was created dynamically through the
1978  * System.Reflection.Emit API
1979  *
1980  * Returns: TRUE if the image was created dynamically, FALSE if not.
1981  */
1982 gboolean
1983 mono_image_is_dynamic (MonoImage *image)
1984 {
1985         return image->dynamic;
1986 }
1987
1988 /**
1989  * mono_image_has_authenticode_entry:
1990  * @image: the MonoImage
1991  *
1992  * Use this routine to determine if the image has a Authenticode
1993  * Certificate Table.
1994  *
1995  * Returns: TRUE if the image contains an authenticode entry in the PE
1996  * directory.
1997  */
1998 gboolean
1999 mono_image_has_authenticode_entry (MonoImage *image)
2000 {
2001         MonoCLIImageInfo *iinfo = image->image_info;
2002         MonoDotNetHeader *header = &iinfo->cli_header;
2003         MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
2004         // the Authenticode "pre" (non ASN.1) header is 8 bytes long
2005         return ((de->rva != 0) && (de->size > 8));
2006 }