2009-02-19 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 }
619
620 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
621 #define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
622 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
623 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
624 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
625 #else
626 #define SWAP64(x)
627 #define SWAP32(x)
628 #define SWAP16(x)
629 #define SWAPPDE(x)
630 #endif
631
632 /*
633  * Returns < 0 to indicate an error.
634  */
635 static int
636 do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
637 {
638         MonoDotNetHeader64 header64;
639
640 #ifdef PLATFORM_WIN32
641         if (!image->is_module_handle)
642 #endif
643         if (offset + sizeof (MonoDotNetHeader32) > image->raw_data_len)
644                 return -1;
645
646         memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
647
648         if (header->pesig [0] != 'P' || header->pesig [1] != 'E')
649                 return -1;
650
651         /* endian swap the fields common between PE and PE+ */
652         SWAP32 (header->coff.coff_time);
653         SWAP32 (header->coff.coff_symptr);
654         SWAP32 (header->coff.coff_symcount);
655         SWAP16 (header->coff.coff_machine);
656         SWAP16 (header->coff.coff_sections);
657         SWAP16 (header->coff.coff_opt_header_size);
658         SWAP16 (header->coff.coff_attributes);
659         /* MonoPEHeader */
660         SWAP32 (header->pe.pe_code_size);
661         SWAP32 (header->pe.pe_uninit_data_size);
662         SWAP32 (header->pe.pe_rva_entry_point);
663         SWAP32 (header->pe.pe_rva_code_base);
664         SWAP32 (header->pe.pe_rva_data_base);
665         SWAP16 (header->pe.pe_magic);
666
667         /* now we are ready for the basic tests */
668
669         if (header->pe.pe_magic == 0x10B) {
670                 offset += sizeof (MonoDotNetHeader);
671                 SWAP32 (header->pe.pe_data_size);
672                 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
673                         return -1;
674
675                 SWAP32  (header->nt.pe_image_base);     /* must be 0x400000 */
676                 SWAP32  (header->nt.pe_stack_reserve);
677                 SWAP32  (header->nt.pe_stack_commit);
678                 SWAP32  (header->nt.pe_heap_reserve);
679                 SWAP32  (header->nt.pe_heap_commit);
680         } else if (header->pe.pe_magic == 0x20B) {
681                 /* PE32+ file format */
682                 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
683                         return -1;
684                 memcpy (&header64, image->raw_data + offset, sizeof (MonoDotNetHeader64));
685                 offset += sizeof (MonoDotNetHeader64);
686                 /* copy the fields already swapped. the last field, pe_data_size, is missing */
687                 memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
688                 /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
689                  * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
690                  */
691                 SWAP64  (header64.nt.pe_image_base);
692                 header->nt.pe_image_base = header64.nt.pe_image_base;
693                 SWAP64  (header64.nt.pe_stack_reserve);
694                 header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
695                 SWAP64  (header64.nt.pe_stack_commit);
696                 header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
697                 SWAP64  (header64.nt.pe_heap_reserve);
698                 header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
699                 SWAP64  (header64.nt.pe_heap_commit);
700                 header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
701
702                 header->nt.pe_section_align = header64.nt.pe_section_align;
703                 header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
704                 header->nt.pe_os_major = header64.nt.pe_os_major;
705                 header->nt.pe_os_minor = header64.nt.pe_os_minor;
706                 header->nt.pe_user_major = header64.nt.pe_user_major;
707                 header->nt.pe_user_minor = header64.nt.pe_user_minor;
708                 header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
709                 header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
710                 header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
711                 header->nt.pe_image_size = header64.nt.pe_image_size;
712                 header->nt.pe_header_size = header64.nt.pe_header_size;
713                 header->nt.pe_checksum = header64.nt.pe_checksum;
714                 header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
715                 header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
716                 header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
717                 header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
718
719                 /* copy the datadir */
720                 memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
721         } else {
722                 return -1;
723         }
724
725         /* MonoPEHeaderNT: not used yet */
726         SWAP32  (header->nt.pe_section_align);       /* must be 8192 */
727         SWAP32  (header->nt.pe_file_alignment);      /* must be 512 or 4096 */
728         SWAP16  (header->nt.pe_os_major);            /* must be 4 */
729         SWAP16  (header->nt.pe_os_minor);            /* must be 0 */
730         SWAP16  (header->nt.pe_user_major);
731         SWAP16  (header->nt.pe_user_minor);
732         SWAP16  (header->nt.pe_subsys_major);
733         SWAP16  (header->nt.pe_subsys_minor);
734         SWAP32  (header->nt.pe_reserved_1);
735         SWAP32  (header->nt.pe_image_size);
736         SWAP32  (header->nt.pe_header_size);
737         SWAP32  (header->nt.pe_checksum);
738         SWAP16  (header->nt.pe_subsys_required);
739         SWAP16  (header->nt.pe_dll_flags);
740         SWAP32  (header->nt.pe_loader_flags);
741         SWAP32  (header->nt.pe_data_dir_count);
742
743         /* MonoDotNetHeader: mostly unused */
744         SWAPPDE (header->datadir.pe_export_table);
745         SWAPPDE (header->datadir.pe_import_table);
746         SWAPPDE (header->datadir.pe_resource_table);
747         SWAPPDE (header->datadir.pe_exception_table);
748         SWAPPDE (header->datadir.pe_certificate_table);
749         SWAPPDE (header->datadir.pe_reloc_table);
750         SWAPPDE (header->datadir.pe_debug);
751         SWAPPDE (header->datadir.pe_copyright);
752         SWAPPDE (header->datadir.pe_global_ptr);
753         SWAPPDE (header->datadir.pe_tls_table);
754         SWAPPDE (header->datadir.pe_load_config_table);
755         SWAPPDE (header->datadir.pe_bound_import);
756         SWAPPDE (header->datadir.pe_iat);
757         SWAPPDE (header->datadir.pe_delay_import_desc);
758         SWAPPDE (header->datadir.pe_cli_header);
759         SWAPPDE (header->datadir.pe_reserved);
760
761 #ifdef PLATFORM_WIN32
762         if (image->is_module_handle)
763                 image->raw_data_len = header->nt.pe_image_size;
764 #endif
765
766         return offset;
767 }
768
769 static MonoImage *
770 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
771                     gboolean care_about_cli)
772 {
773         MonoCLIImageInfo *iinfo;
774         MonoDotNetHeader *header;
775         MonoMSDOSHeader msdos;
776         gint32 offset = 0;
777
778         mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
779
780         mono_image_init (image);
781
782         iinfo = image->image_info;
783         header = &iinfo->cli_header;
784                 
785         if (status)
786                 *status = MONO_IMAGE_IMAGE_INVALID;
787
788 #ifdef PLATFORM_WIN32
789         if (!image->is_module_handle)
790 #endif
791         if (offset + sizeof (msdos) > image->raw_data_len)
792                 goto invalid_image;
793         memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
794         
795         if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
796                 goto invalid_image;
797         
798         msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
799
800         offset = msdos.pe_offset;
801
802         offset = do_load_header (image, header, offset);
803         if (offset < 0)
804                 goto invalid_image;
805
806         /*
807          * this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
808          * we skip this test.
809         if (header->coff.coff_machine != 0x14c)
810                 goto invalid_image;
811         */
812
813 #if 0
814         /*
815          * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
816          * which produces binaries with 7.0.  From Sergey:
817          *
818          * The reason is that MSVC7 uses traditional compile/link
819          * sequence for CIL executables, and VS.NET (and Framework
820          * SDK) includes linker version 7, that puts 7.0 in this
821          * field.  That's why it's currently not possible to load VC
822          * binaries with Mono.  This field is pretty much meaningless
823          * anyway (what linker?).
824          */
825         if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
826                 goto invalid_image;
827 #endif
828
829         /*
830          * FIXME: byte swap all addresses here for header.
831          */
832         
833         if (!load_section_tables (image, iinfo, offset))
834                 goto invalid_image;
835         
836         if (care_about_cli == FALSE) {
837                 goto done;
838         }
839         
840         /* Load the CLI header */
841         if (!load_cli_header (image, iinfo))
842                 goto invalid_image;
843
844         if (!load_metadata (image, iinfo))
845                 goto invalid_image;
846
847         /* modules don't have an assembly table row */
848         if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
849                 image->assembly_name = mono_metadata_string_heap (image, 
850                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
851                                         0, MONO_ASSEMBLY_NAME));
852         }
853
854         image->module_name = mono_metadata_string_heap (image, 
855                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
856                                         0, MONO_MODULE_NAME));
857
858         load_modules (image);
859
860 done:
861         mono_profiler_module_loaded (image, MONO_PROFILE_OK);
862         if (status)
863                 *status = MONO_IMAGE_OK;
864
865         return image;
866
867 invalid_image:
868         mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
869         mono_image_close (image);
870                 return NULL;
871 }
872
873 static MonoImage *
874 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
875                     gboolean care_about_cli, gboolean refonly)
876 {
877         MonoCLIImageInfo *iinfo;
878         MonoImage *image;
879         MonoFileMap *filed;
880
881         if ((filed = mono_file_map_open (fname)) == NULL){
882                 if (IS_PORTABILITY_SET) {
883                         gchar *ffname = mono_portability_find_file (fname, TRUE);
884                         if (ffname) {
885                                 filed = mono_file_map_open (ffname);
886                                 g_free (ffname);
887                         }
888                 }
889
890                 if (filed == NULL) {
891                         if (status)
892                                 *status = MONO_IMAGE_ERROR_ERRNO;
893                         return NULL;
894                 }
895         }
896
897         image = g_new0 (MonoImage, 1);
898         image->raw_buffer_used = TRUE;
899         image->raw_data_len = mono_file_map_size (filed);
900         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);
901         if (!image->raw_data) {
902                 mono_file_map_close (filed);
903                 g_free (image);
904                 if (status)
905                         *status = MONO_IMAGE_IMAGE_INVALID;
906                 return NULL;
907         }
908         iinfo = g_new0 (MonoCLIImageInfo, 1);
909         image->image_info = iinfo;
910         image->name = mono_path_resolve_symlinks (fname);
911         image->ref_only = refonly;
912         image->ref_count = 1;
913
914         mono_file_map_close (filed);
915         return do_mono_image_load (image, status, care_about_cli);
916 }
917
918 MonoImage *
919 mono_image_loaded_full (const char *name, gboolean refonly)
920 {
921         MonoImage *res;
922         GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
923         
924         mono_images_lock ();
925         res = g_hash_table_lookup (loaded_images, name);
926         mono_images_unlock ();
927         return res;
928 }
929
930 /**
931  * mono_image_loaded:
932  * @name: name of the image to load
933  *
934  * This routine ensures that the given image is loaded.
935  *
936  * Returns: the loaded MonoImage, or NULL on failure.
937  */
938 MonoImage *
939 mono_image_loaded (const char *name)
940 {
941         return mono_image_loaded_full (name, FALSE);
942 }
943
944 typedef struct {
945         MonoImage *res;
946         const char* guid;
947 } GuidData;
948
949 static void
950 find_by_guid (gpointer key, gpointer val, gpointer user_data)
951 {
952         GuidData *data = user_data;
953         MonoImage *image;
954
955         if (data->res)
956                 return;
957         image = val;
958         if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
959                 data->res = image;
960 }
961
962 MonoImage *
963 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
964 {
965         GuidData data;
966         GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
967         data.res = NULL;
968         data.guid = guid;
969
970         mono_images_lock ();
971         g_hash_table_foreach (loaded_images, find_by_guid, &data);
972         mono_images_unlock ();
973         return data.res;
974 }
975
976 MonoImage *
977 mono_image_loaded_by_guid (const char *guid)
978 {
979         return mono_image_loaded_by_guid_full (guid, FALSE);
980 }
981
982 static MonoImage *
983 register_image (MonoImage *image)
984 {
985         MonoImage *image2;
986         GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
987
988         mono_images_lock ();
989         image2 = g_hash_table_lookup (loaded_images, image->name);
990
991         if (image2) {
992                 /* Somebody else beat us to it */
993                 mono_image_addref (image2);
994                 mono_images_unlock ();
995                 mono_image_close (image);
996                 return image2;
997         }
998         g_hash_table_insert (loaded_images, image->name, image);
999         if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
1000                 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);      
1001         mono_images_unlock ();
1002
1003         return image;
1004 }
1005
1006 MonoImage *
1007 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1008 {
1009         MonoCLIImageInfo *iinfo;
1010         MonoImage *image;
1011         char *datac;
1012
1013         if (!data || !data_len) {
1014                 if (status)
1015                         *status = MONO_IMAGE_IMAGE_INVALID;
1016                 return NULL;
1017         }
1018         datac = data;
1019         if (need_copy) {
1020                 datac = g_try_malloc (data_len);
1021                 if (!datac) {
1022                         if (status)
1023                                 *status = MONO_IMAGE_ERROR_ERRNO;
1024                         return NULL;
1025                 }
1026                 memcpy (datac, data, data_len);
1027         }
1028
1029         image = g_new0 (MonoImage, 1);
1030         image->raw_data = datac;
1031         image->raw_data_len = data_len;
1032         image->raw_data_allocated = need_copy;
1033         image->name = g_strdup_printf ("data-%p", datac);
1034         iinfo = g_new0 (MonoCLIImageInfo, 1);
1035         image->image_info = iinfo;
1036         image->ref_only = refonly;
1037
1038         image = do_mono_image_load (image, status, TRUE);
1039         if (image == NULL)
1040                 return NULL;
1041
1042         return register_image (image);
1043 }
1044
1045 MonoImage *
1046 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1047 {
1048         return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1049 }
1050
1051 #ifdef PLATFORM_WIN32
1052 /* fname is not duplicated. */
1053 MonoImage*
1054 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1055 {
1056         MonoImage* image;
1057         MonoCLIImageInfo* iinfo;
1058
1059         image = g_new0 (MonoImage, 1);
1060         image->raw_data = (char*) module_handle;
1061         image->is_module_handle = TRUE;
1062         iinfo = g_new0 (MonoCLIImageInfo, 1);
1063         image->image_info = iinfo;
1064         image->name = fname;
1065         image->ref_count = has_entry_point ? 0 : 1;
1066         image->has_entry_point = has_entry_point;
1067
1068         image = do_mono_image_load (image, status, TRUE);
1069         if (image == NULL)
1070                 return NULL;
1071
1072         return register_image (image);
1073 }
1074 #endif
1075
1076 MonoImage *
1077 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1078 {
1079         MonoImage *image;
1080         GHashTable *loaded_images;
1081         char *absfname;
1082         
1083         g_return_val_if_fail (fname != NULL, NULL);
1084         
1085 #ifdef PLATFORM_WIN32
1086         /* Load modules using LoadLibrary. */
1087         if (!refonly && coree_module_handle) {
1088                 HMODULE module_handle;
1089                 guint16 *fname_utf16;
1090                 DWORD last_error;
1091
1092                 absfname = mono_path_resolve_symlinks (fname);
1093                 fname_utf16 = NULL;
1094
1095                 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1096                 mono_images_lock ();
1097                 image = g_hash_table_lookup (loaded_images_hash, absfname);
1098                 if (image) {
1099                         g_assert (image->is_module_handle);
1100                         if (image->has_entry_point && image->ref_count == 0) {
1101                                 /* Increment reference count on images loaded outside of the runtime. */
1102                                 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1103                                 /* The image is already loaded because _CorDllMain removes images from the hash. */
1104                                 module_handle = LoadLibrary (fname_utf16);
1105                                 g_assert (module_handle == (HMODULE) image->raw_data);
1106                         }
1107                         mono_image_addref (image);
1108                         mono_images_unlock ();
1109                         if (fname_utf16)
1110                                 g_free (fname_utf16);
1111                         g_free (absfname);
1112                         return image;
1113                 }
1114
1115                 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1116                 module_handle = MonoLoadImage (fname_utf16);
1117                 if (status && module_handle == NULL)
1118                         last_error = GetLastError ();
1119
1120                 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1121                 image = g_hash_table_lookup (loaded_images_hash, absfname);
1122                 if (image)
1123                         mono_image_addref (image);
1124                 mono_images_unlock ();
1125
1126                 g_free (fname_utf16);
1127
1128                 if (module_handle == NULL) {
1129                         g_assert (!image);
1130                         g_free (absfname);
1131                         if (status) {
1132                                 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1133                                         *status = MONO_IMAGE_IMAGE_INVALID;
1134                                 else
1135                                         *status = MONO_IMAGE_ERROR_ERRNO;
1136                         }
1137                         return NULL;
1138                 }
1139
1140                 if (image) {
1141                         g_assert (image->is_module_handle);
1142                         g_assert (image->has_entry_point);
1143                         g_free (absfname);
1144                         return image;
1145                 }
1146
1147                 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1148         }
1149 #endif
1150
1151         absfname = mono_path_canonicalize (fname);
1152
1153         /*
1154          * The easiest solution would be to do all the loading inside the mutex,
1155          * but that would lead to scalability problems. So we let the loading
1156          * happen outside the mutex, and if multiple threads happen to load
1157          * the same image, we discard all but the first copy.
1158          */
1159         mono_images_lock ();
1160         loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1161         image = g_hash_table_lookup (loaded_images, absfname);
1162         g_free (absfname);
1163         
1164         if (image){
1165                 mono_image_addref (image);
1166                 mono_images_unlock ();
1167                 return image;
1168         }
1169         mono_images_unlock ();
1170
1171         image = do_mono_image_open (fname, status, TRUE, refonly);
1172         if (image == NULL)
1173                 return NULL;
1174
1175         return register_image (image);
1176 }
1177
1178 /**
1179  * mono_image_open:
1180  * @fname: filename that points to the module we want to open
1181  * @status: An error condition is returned in this field
1182  *
1183  * Returns: An open image of type %MonoImage or NULL on error. 
1184  * The caller holds a temporary reference to the returned image which should be cleared 
1185  * when no longer needed by calling mono_image_close ().
1186  * if NULL, then check the value of @status for details on the error
1187  */
1188 MonoImage *
1189 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1190 {
1191         return mono_image_open_full (fname, status, FALSE);
1192 }
1193
1194 /**
1195  * mono_pe_file_open:
1196  * @fname: filename that points to the module we want to open
1197  * @status: An error condition is returned in this field
1198  *
1199  * Returns: An open image of type %MonoImage or NULL on error.  if
1200  * NULL, then check the value of @status for details on the error.
1201  * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1202  * It's just a PE file loader, used for FileVersionInfo.  It also does
1203  * not use the image cache.
1204  */
1205 MonoImage *
1206 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1207 {
1208         g_return_val_if_fail (fname != NULL, NULL);
1209         
1210         return(do_mono_image_open (fname, status, FALSE, FALSE));
1211 }
1212
1213 void
1214 mono_image_fixup_vtable (MonoImage *image)
1215 {
1216 #ifdef PLATFORM_WIN32
1217         MonoCLIImageInfo *iinfo;
1218         MonoPEDirEntry *de;
1219         MonoVTableFixup *vtfixup;
1220         int count;
1221         gpointer slot;
1222         guint16 slot_type;
1223         int slot_count;
1224
1225         g_assert (image->is_module_handle);
1226
1227         iinfo = image->image_info;
1228         de = &iinfo->cli_cli_header.ch_vtable_fixups;
1229         if (!de->rva || !de->size)
1230                 return;
1231         vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1232         if (!vtfixup)
1233                 return;
1234         
1235         count = de->size / sizeof (MonoVTableFixup);
1236         while (count--) {
1237                 if (!vtfixup->rva || !vtfixup->count)
1238                         continue;
1239
1240                 slot = mono_image_rva_map (image, vtfixup->rva);
1241                 g_assert (slot);
1242                 slot_type = vtfixup->type;
1243                 slot_count = vtfixup->count;
1244                 if (slot_type & VTFIXUP_TYPE_32BIT)
1245                         while (slot_count--) {
1246                                 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1247                                 ((guint32*) slot)++;
1248                         }
1249                 else if (slot_type & VTFIXUP_TYPE_64BIT)
1250                         while (slot_count--) {
1251                                 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1252                                 ((guint64*) slot)++;
1253                         }
1254                 else
1255                         g_assert_not_reached();
1256
1257                 vtfixup++;
1258         }
1259 #else
1260         g_assert_not_reached();
1261 #endif
1262 }
1263
1264 static void
1265 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1266 {
1267         g_hash_table_destroy ((GHashTable*)val);
1268 }
1269
1270 /*
1271 static void
1272 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1273 {
1274         mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1275 }
1276 */
1277
1278 static void
1279 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
1280 {
1281         g_free (val);
1282 }
1283
1284 static void
1285 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1286 {
1287         g_slist_free ((GSList*)val);
1288 }
1289
1290 /**
1291  * mono_image_addref:
1292  * @image: The image file we wish to add a reference to
1293  *
1294  *  Increases the reference count of an image.
1295  */
1296 void
1297 mono_image_addref (MonoImage *image)
1298 {
1299         InterlockedIncrement (&image->ref_count);
1300 }       
1301
1302 void
1303 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1304 {
1305         stream->alloc_size = stream->index = stream->offset = 0;
1306         g_free (stream->data);
1307         stream->data = NULL;
1308         if (stream->hash) {
1309                 g_hash_table_destroy (stream->hash);
1310                 stream->hash = NULL;
1311         }
1312 }
1313
1314 static inline void
1315 free_hash (GHashTable *hash)
1316 {
1317         if (hash)
1318                 g_hash_table_destroy (hash);
1319 }
1320
1321 /**
1322  * mono_image_close:
1323  * @image: The image file we wish to close
1324  *
1325  * Closes an image file, deallocates all memory consumed and
1326  * unmaps all possible sections of the file
1327  */
1328 void
1329 mono_image_close (MonoImage *image)
1330 {
1331         MonoImage *image2;
1332         GHashTable *loaded_images;
1333         int i;
1334
1335         g_return_if_fail (image != NULL);
1336
1337         if (InterlockedDecrement (&image->ref_count) > 0)
1338                 return;
1339
1340 #ifdef PLATFORM_WIN32
1341         if (image->is_module_handle && image->has_entry_point) {
1342                 mono_images_lock ();
1343                 if (image->ref_count == 0) {
1344                         /* Image will be closed by _CorDllMain. */
1345                         FreeLibrary ((HMODULE) image->raw_data);
1346                         mono_images_unlock ();
1347                         return;
1348                 }
1349                 mono_images_unlock ();
1350         }
1351 #endif
1352
1353         mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1354
1355         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1356
1357         mono_metadata_clean_for_image (image);
1358
1359         /*
1360          * The caches inside a MonoImage might refer to metadata which is stored in referenced 
1361          * assemblies, so we can't release these references in mono_assembly_close () since the
1362          * MonoImage might outlive its associated MonoAssembly.
1363          */
1364         if (image->references && !image->dynamic) {
1365                 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1366                 int i;
1367
1368                 for (i = 0; i < t->rows; i++) {
1369                         if (image->references [i])
1370                                 mono_assembly_close (image->references [i]);
1371                 }
1372
1373                 g_free (image->references);
1374                 image->references = NULL;
1375         }
1376
1377         mono_images_lock ();
1378         loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1379         image2 = g_hash_table_lookup (loaded_images, image->name);
1380         if (image == image2) {
1381                 /* This is not true if we are called from mono_image_open () */
1382                 g_hash_table_remove (loaded_images, image->name);
1383         }
1384         if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1385                 g_hash_table_remove (loaded_images, (char *) image->assembly_name);     
1386
1387 #ifdef PLATFORM_WIN32
1388         if (image->is_module_handle && !image->has_entry_point)
1389                 FreeLibrary ((HMODULE) image->raw_data);
1390 #endif
1391
1392         mono_images_unlock ();
1393
1394         if (image->raw_buffer_used) {
1395                 if (image->raw_data != NULL)
1396                         mono_file_unmap (image->raw_data, image->raw_data_handle);
1397         }
1398         
1399         if (image->raw_data_allocated) {
1400                 /* FIXME: do we need this? (image is disposed anyway) */
1401                 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1402                 MonoCLIImageInfo *ii = image->image_info;
1403
1404                 if ((image->raw_metadata > image->raw_data) &&
1405                         (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1406                         image->raw_metadata = NULL;
1407
1408                 for (i = 0; i < ii->cli_section_count; i++)
1409                         if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1410                                 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1411                                 ii->cli_sections [i] = NULL;
1412
1413                 g_free (image->raw_data);
1414         }
1415
1416         if (debug_assembly_unload) {
1417                 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1418         } else {
1419                 g_free (image->name);
1420                 g_free (image->guid);
1421                 g_free (image->version);
1422                 g_free (image->files);
1423         }
1424
1425         if (image->method_cache)
1426                 mono_value_hash_table_destroy (image->method_cache);
1427         if (image->methodref_cache)
1428                 g_hash_table_destroy (image->methodref_cache);
1429         mono_internal_hash_table_destroy (&image->class_cache);
1430         g_hash_table_destroy (image->field_cache);
1431         if (image->array_cache) {
1432                 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1433                 g_hash_table_destroy (image->array_cache);
1434         }
1435         if (image->ptr_cache)
1436                 g_hash_table_destroy (image->ptr_cache);
1437         if (image->name_cache) {
1438                 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1439                 g_hash_table_destroy (image->name_cache);
1440         }
1441
1442         free_hash (image->native_wrapper_cache);
1443         free_hash (image->managed_wrapper_cache);
1444         free_hash (image->delegate_begin_invoke_cache);
1445         free_hash (image->delegate_end_invoke_cache);
1446         free_hash (image->delegate_invoke_cache);
1447         free_hash (image->delegate_abstract_invoke_cache);
1448         if (image->remoting_invoke_cache)
1449                 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1450         free_hash (image->remoting_invoke_cache);
1451         free_hash (image->runtime_invoke_cache);
1452         free_hash (image->runtime_invoke_direct_cache);
1453         free_hash (image->synchronized_cache);
1454         free_hash (image->unbox_wrapper_cache);
1455         free_hash (image->cominterop_invoke_cache);
1456         free_hash (image->cominterop_wrapper_cache);
1457         free_hash (image->typespec_cache);
1458         free_hash (image->ldfld_wrapper_cache);
1459         free_hash (image->ldflda_wrapper_cache);
1460         free_hash (image->stfld_wrapper_cache);
1461         free_hash (image->isinst_cache);
1462         free_hash (image->castclass_cache);
1463         free_hash (image->proxy_isinst_cache);
1464         free_hash (image->thunk_invoke_cache);
1465         free_hash (image->static_rgctx_invoke_cache);
1466
1467         /* The ownership of signatures is not well defined */
1468         //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1469         g_hash_table_destroy (image->memberref_signatures);
1470         //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1471         g_hash_table_destroy (image->helper_signatures);
1472         g_hash_table_destroy (image->method_signatures);
1473
1474         if (image->generic_class_cache)
1475                 g_hash_table_destroy (image->generic_class_cache);
1476
1477         if (image->rgctx_template_hash)
1478                 g_hash_table_destroy (image->rgctx_template_hash);
1479
1480         if (image->property_hash)
1481                 mono_property_hash_destroy (image->property_hash);
1482
1483         if (image->interface_bitset) {
1484                 mono_unload_interface_ids (image->interface_bitset);
1485                 mono_bitset_free (image->interface_bitset);
1486         }
1487         if (image->image_info){
1488                 MonoCLIImageInfo *ii = image->image_info;
1489
1490                 if (ii->cli_section_tables)
1491                         g_free (ii->cli_section_tables);
1492                 if (ii->cli_sections)
1493                         g_free (ii->cli_sections);
1494                 g_free (image->image_info);
1495         }
1496
1497         for (i = 0; i < image->module_count; ++i) {
1498                 if (image->modules [i])
1499                         mono_image_close (image->modules [i]);
1500         }
1501         if (image->modules)
1502                 g_free (image->modules);
1503         if (image->modules_loaded)
1504                 g_free (image->modules_loaded);
1505         if (image->references)
1506                 g_free (image->references);
1507         mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
1508
1509         DeleteCriticalSection (&image->lock);
1510
1511         /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1512         if (!image->dynamic) {
1513                 if (debug_assembly_unload)
1514                         mono_mempool_invalidate (image->mempool);
1515                 else {
1516                         mono_mempool_destroy (image->mempool);
1517                         g_free (image);
1518                 }
1519         } else {
1520                 /* Dynamic images are GC_MALLOCed */
1521                 g_free ((char*)image->module_name);
1522                 mono_dynamic_image_free ((MonoDynamicImage*)image);
1523                 mono_mempool_destroy (image->mempool);
1524         }
1525
1526         mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1527 }
1528
1529 /** 
1530  * mono_image_strerror:
1531  * @status: an code indicating the result from a recent operation
1532  *
1533  * Returns: a string describing the error
1534  */
1535 const char *
1536 mono_image_strerror (MonoImageOpenStatus status)
1537 {
1538         switch (status){
1539         case MONO_IMAGE_OK:
1540                 return "success";
1541         case MONO_IMAGE_ERROR_ERRNO:
1542                 return strerror (errno);
1543         case MONO_IMAGE_IMAGE_INVALID:
1544                 return "File does not contain a valid CIL image";
1545         case MONO_IMAGE_MISSING_ASSEMBLYREF:
1546                 return "An assembly was referenced, but could not be found";
1547         }
1548         return "Internal error";
1549 }
1550
1551 static gpointer
1552 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1553                                guint32 lang_id, gunichar2 *name,
1554                                MonoPEResourceDirEntry *entry,
1555                                MonoPEResourceDir *root, guint32 level)
1556 {
1557         gboolean is_string, is_dir;
1558         guint32 name_offset, dir_offset;
1559
1560         /* Level 0 holds a directory entry for each type of resource
1561          * (identified by ID or name).
1562          *
1563          * Level 1 holds a directory entry for each named resource
1564          * item, and each "anonymous" item of a particular type of
1565          * resource.
1566          *
1567          * Level 2 holds a directory entry for each language pointing to
1568          * the actual data.
1569          */
1570         is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1571         name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1572
1573         is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1574         dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1575
1576         if(level==0) {
1577                 if((is_string==FALSE && name_offset!=res_id) ||
1578                    (is_string==TRUE)) {
1579                         return(NULL);
1580                 }
1581         } else if (level==1) {
1582 #if 0
1583                 if(name!=NULL &&
1584                    is_string==TRUE && name!=lookup (name_offset)) {
1585                         return(NULL);
1586                 }
1587 #endif
1588         } else if (level==2) {
1589                 if ((is_string == FALSE &&
1590                     name_offset != lang_id &&
1591                     lang_id != 0) ||
1592                    (is_string == TRUE)) {
1593                         return(NULL);
1594                 }
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         info=image->image_info;
1662         if(info==NULL) {
1663                 return(NULL);
1664         }
1665
1666         header=&info->cli_header;
1667         if(header==NULL) {
1668                 return(NULL);
1669         }
1670
1671         datadir=&header->datadir;
1672         if(datadir==NULL) {
1673                 return(NULL);
1674         }
1675
1676         rsrc=&datadir->pe_resource_table;
1677         if(rsrc==NULL) {
1678                 return(NULL);
1679         }
1680
1681         resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1682         if(resource_dir==NULL) {
1683                 return(NULL);
1684         }
1685
1686         entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1687         res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1688         
1689         for(i=0; i<entries; i++) {
1690                 MonoPEResourceDirEntry *entry=&res_entries[i];
1691                 gpointer ret;
1692                 
1693                 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1694                                                    name, entry, resource_dir,
1695                                                    0);
1696                 if(ret!=NULL) {
1697                         return(ret);
1698                 }
1699         }
1700
1701         return(NULL);
1702 }
1703
1704 /** 
1705  * mono_image_get_entry_point:
1706  * @image: the image where the entry point will be looked up.
1707  *
1708  * Use this routine to determine the metadata token for method that
1709  * has been flagged as the entry point.
1710  *
1711  * Returns: the token for the entry point method in the image
1712  */
1713 guint32
1714 mono_image_get_entry_point (MonoImage *image)
1715 {
1716         return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1717 }
1718
1719 /**
1720  * mono_image_get_resource:
1721  * @image: the image where the resource will be looked up.
1722  * @offset: The offset to add to the resource
1723  * @size: a pointer to an int where the size of the resource will be stored
1724  *
1725  * This is a low-level routine that fetches a resource from the
1726  * metadata that starts at a given @offset.  The @size parameter is
1727  * filled with the data field as encoded in the metadata.
1728  *
1729  * Returns: the pointer to the resource whose offset is @offset.
1730  */
1731 const char*
1732 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1733 {
1734         MonoCLIImageInfo *iinfo = image->image_info;
1735         MonoCLIHeader *ch = &iinfo->cli_cli_header;
1736         const char* data;
1737
1738         if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1739                 return NULL;
1740         
1741         data = mono_image_rva_map (image, ch->ch_resources.rva);
1742         if (!data)
1743                 return NULL;
1744         data += offset;
1745         if (size)
1746                 *size = read32 (data);
1747         data += 4;
1748         return data;
1749 }
1750
1751 MonoImage*
1752 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1753 {
1754         char *base_dir, *name;
1755         MonoImage *res;
1756         MonoTableInfo  *t = &image->tables [MONO_TABLE_FILE];
1757         const char *fname;
1758         guint32 fname_id;
1759
1760         if (fileidx < 1 || fileidx > t->rows)
1761                 return NULL;
1762
1763         mono_loader_lock ();
1764         if (image->files && image->files [fileidx - 1]) {
1765                 mono_loader_unlock ();
1766                 return image->files [fileidx - 1];
1767         }
1768
1769         if (!image->files)
1770                 image->files = g_new0 (MonoImage*, t->rows);
1771
1772         fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1773         fname = mono_metadata_string_heap (image, fname_id);
1774         base_dir = g_path_get_dirname (image->name);
1775         name = g_build_filename (base_dir, fname, NULL);
1776         res = mono_image_open (name, NULL);
1777         if (res) {
1778                 int i;
1779                 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1780                 res->assembly = image->assembly;
1781                 for (i = 0; i < res->module_count; ++i) {
1782                         if (res->modules [i] && !res->modules [i]->assembly)
1783                                 res->modules [i]->assembly = image->assembly;
1784                 }
1785
1786                 image->files [fileidx - 1] = res;
1787 #ifdef PLATFORM_WIN32
1788                 if (res->is_module_handle)
1789                         mono_image_fixup_vtable (res);
1790 #endif
1791         }
1792         mono_loader_unlock ();
1793         g_free (name);
1794         g_free (base_dir);
1795         return res;
1796 }
1797
1798 /**
1799  * mono_image_get_strong_name:
1800  * @image: a MonoImage
1801  * @size: a guint32 pointer, or NULL.
1802  *
1803  * If the image has a strong name, and @size is not NULL, the value
1804  * pointed to by size will have the size of the strong name.
1805  *
1806  * Returns: NULL if the image does not have a strong name, or a
1807  * pointer to the public key.
1808  */
1809 const char*
1810 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1811 {
1812         MonoCLIImageInfo *iinfo = image->image_info;
1813         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1814         const char* data;
1815
1816         if (!de->size || !de->rva)
1817                 return NULL;
1818         data = mono_image_rva_map (image, de->rva);
1819         if (!data)
1820                 return NULL;
1821         if (size)
1822                 *size = de->size;
1823         return data;
1824 }
1825
1826 /**
1827  * mono_image_strong_name_position:
1828  * @image: a MonoImage
1829  * @size: a guint32 pointer, or NULL.
1830  *
1831  * If the image has a strong name, and @size is not NULL, the value
1832  * pointed to by size will have the size of the strong name.
1833  *
1834  * Returns: the position within the image file where the strong name
1835  * is stored.
1836  */
1837 guint32
1838 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1839 {
1840         MonoCLIImageInfo *iinfo = image->image_info;
1841         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1842         guint32 pos;
1843
1844         if (size)
1845                 *size = de->size;
1846         if (!de->size || !de->rva)
1847                 return 0;
1848         pos = mono_cli_rva_image_map (image, de->rva);
1849         return pos == INVALID_ADDRESS ? 0 : pos;
1850 }
1851
1852 /**
1853  * mono_image_get_public_key:
1854  * @image: a MonoImage
1855  * @size: a guint32 pointer, or NULL.
1856  *
1857  * This is used to obtain the public key in the @image.
1858  * 
1859  * If the image has a public key, and @size is not NULL, the value
1860  * pointed to by size will have the size of the public key.
1861  * 
1862  * Returns: NULL if the image does not have a public key, or a pointer
1863  * to the public key.
1864  */
1865 const char*
1866 mono_image_get_public_key (MonoImage *image, guint32 *size)
1867 {
1868         const char *pubkey;
1869         guint32 len, tok;
1870
1871         if (image->dynamic) {
1872                 if (size)
1873                         *size = ((MonoDynamicImage*)image)->public_key_len;
1874                 return (char*)((MonoDynamicImage*)image)->public_key;
1875         }
1876         if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1877                 return NULL;
1878         tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1879         if (!tok)
1880                 return NULL;
1881         pubkey = mono_metadata_blob_heap (image, tok);
1882         len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1883         if (size)
1884                 *size = len;
1885         return pubkey;
1886 }
1887
1888 /**
1889  * mono_image_get_name:
1890  * @name: a MonoImage
1891  *
1892  * Returns: the name of the assembly.
1893  */
1894 const char*
1895 mono_image_get_name (MonoImage *image)
1896 {
1897         return image->assembly_name;
1898 }
1899
1900 /**
1901  * mono_image_get_filename:
1902  * @image: a MonoImage
1903  *
1904  * Used to get the filename that hold the actual MonoImage
1905  *
1906  * Returns: the filename.
1907  */
1908 const char*
1909 mono_image_get_filename (MonoImage *image)
1910 {
1911         return image->name;
1912 }
1913
1914 const char*
1915 mono_image_get_guid (MonoImage *image)
1916 {
1917         return image->guid;
1918 }
1919
1920 const MonoTableInfo*
1921 mono_image_get_table_info (MonoImage *image, int table_id)
1922 {
1923         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1924                 return NULL;
1925         return &image->tables [table_id];
1926 }
1927
1928 int
1929 mono_image_get_table_rows (MonoImage *image, int table_id)
1930 {
1931         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1932                 return 0;
1933         return image->tables [table_id].rows;
1934 }
1935
1936 int
1937 mono_table_info_get_rows (const MonoTableInfo *table)
1938 {
1939         return table->rows;
1940 }
1941
1942 /**
1943  * mono_image_get_assembly:
1944  * @image: the MonoImage.
1945  *
1946  * Use this routine to get the assembly that owns this image.
1947  *
1948  * Returns: the assembly that holds this image.
1949  */
1950 MonoAssembly* 
1951 mono_image_get_assembly (MonoImage *image)
1952 {
1953         return image->assembly;
1954 }
1955
1956 /**
1957  * mono_image_is_dynamic:
1958  * @image: the MonoImage
1959  *
1960  * Determines if the given image was created dynamically through the
1961  * System.Reflection.Emit API
1962  *
1963  * Returns: TRUE if the image was created dynamically, FALSE if not.
1964  */
1965 gboolean
1966 mono_image_is_dynamic (MonoImage *image)
1967 {
1968         return image->dynamic;
1969 }
1970
1971 /**
1972  * mono_image_has_authenticode_entry:
1973  * @image: the MonoImage
1974  *
1975  * Use this routine to determine if the image has a Authenticode
1976  * Certificate Table.
1977  *
1978  * Returns: TRUE if the image contains an authenticode entry in the PE
1979  * directory.
1980  */
1981 gboolean
1982 mono_image_has_authenticode_entry (MonoImage *image)
1983 {
1984         MonoCLIImageInfo *iinfo = image->image_info;
1985         MonoDotNetHeader *header = &iinfo->cli_header;
1986         MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
1987         // the Authenticode "pre" (non ASN.1) header is 8 bytes long
1988         return ((de->rva != 0) && (de->size > 8));
1989 }
1990
1991 gpointer
1992 mono_image_alloc (MonoImage *image, guint size)
1993 {
1994         gpointer res;
1995
1996         mono_perfcounters->loader_bytes += size;
1997         mono_image_lock (image);
1998         res = mono_mempool_alloc (image->mempool, size);
1999         mono_image_unlock (image);
2000
2001         return res;
2002 }
2003
2004 gpointer
2005 mono_image_alloc0 (MonoImage *image, guint size)
2006 {
2007         gpointer res;
2008
2009         mono_perfcounters->loader_bytes += size;
2010         mono_image_lock (image);
2011         res = mono_mempool_alloc0 (image->mempool, size);
2012         mono_image_unlock (image);
2013
2014         return res;
2015 }
2016
2017 char*
2018 mono_image_strdup (MonoImage *image, const char *s)
2019 {
2020         char *res;
2021
2022         mono_perfcounters->loader_bytes += strlen (s);
2023         mono_image_lock (image);
2024         res = mono_mempool_strdup (image->mempool, s);
2025         mono_image_unlock (image);
2026
2027         return res;
2028 }
2029
2030 GList*
2031 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
2032 {
2033         GList *new_list;
2034         
2035         new_list = mono_image_alloc (image, sizeof (GList));
2036         new_list->data = data;
2037         new_list->prev = list ? list->prev : NULL;
2038     new_list->next = list;
2039
2040     if (new_list->prev)
2041             new_list->prev->next = new_list;
2042     if (list)
2043             list->prev = new_list;
2044
2045         return new_list;
2046 }
2047
2048 GSList*
2049 g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
2050 {
2051         GSList *new_list;
2052
2053         new_list = mono_image_alloc (image, sizeof (GSList));
2054         new_list->data = data;
2055         new_list->next = NULL;
2056
2057         return g_slist_concat (list, new_list);
2058 }
2059
2060 void
2061 mono_image_lock (MonoImage *image)
2062 {
2063         EnterCriticalSection (&image->lock);
2064 }
2065
2066 void
2067 mono_image_unlock (MonoImage *image)
2068 {
2069         LeaveCriticalSection (&image->lock);
2070 }
2071
2072
2073 /**
2074  * mono_image_property_lookup:
2075  *
2076  * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
2077  *
2078  * LOCKING: Takes the image lock
2079  */
2080 gpointer 
2081 mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
2082 {
2083         gpointer res;
2084
2085         mono_image_lock (image);
2086         res = mono_property_hash_lookup (image->property_hash, subject, property);
2087         mono_image_unlock (image);
2088
2089         return res;
2090 }
2091
2092 /**
2093  * mono_image_property_insert:
2094  *
2095  * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2096  *
2097  * LOCKING: Takes the image lock
2098  */
2099 void
2100 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
2101 {
2102         mono_image_lock (image);
2103         mono_property_hash_insert (image->property_hash, subject, property, value);
2104         mono_image_unlock (image);
2105 }
2106
2107 /**
2108  * mono_image_property_remove:
2109  *
2110  * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2111  *
2112  * LOCKING: Takes the image lock
2113  */
2114 void
2115 mono_image_property_remove (MonoImage *image, gpointer subject)
2116 {
2117         mono_image_lock (image);
2118         mono_property_hash_remove_object (image->property_hash, subject);
2119         mono_image_unlock (image);
2120 }