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