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