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