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