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