Fix typo.
[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 "private.h"
23 #include "tabledefs.h"
24 #include "tokentype.h"
25 #include "metadata-internals.h"
26 #include <mono/io-layer/io-layer.h>
27
28 #define INVALID_ADDRESS 0xffffffff
29
30 /*
31  * Keeps track of the various assemblies loaded
32  */
33 static GHashTable *loaded_images_hash;
34 static GHashTable *loaded_images_guid_hash;
35
36 static CRITICAL_SECTION images_mutex;
37
38 guint32
39 mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
40 {
41         const int top = iinfo->cli_section_count;
42         MonoSectionTable *tables = iinfo->cli_section_tables;
43         int i;
44         
45         for (i = 0; i < top; i++){
46                 if ((addr >= tables->st_virtual_address) &&
47                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
48                         return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
49                 }
50                 tables++;
51         }
52         return INVALID_ADDRESS;
53 }
54
55 char *
56 mono_image_rva_map (MonoImage *image, guint32 addr)
57 {
58         MonoCLIImageInfo *iinfo = image->image_info;
59         const int top = iinfo->cli_section_count;
60         MonoSectionTable *tables = iinfo->cli_section_tables;
61         int i;
62         
63         for (i = 0; i < top; i++){
64                 if ((addr >= tables->st_virtual_address) &&
65                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
66                         if (!iinfo->cli_sections [i]) {
67                                 if (!mono_image_ensure_section_idx (image, i))
68                                         return NULL;
69                         }
70                         return (char*)iinfo->cli_sections [i] +
71                                 (addr - tables->st_virtual_address);
72                 }
73                 tables++;
74         }
75         return NULL;
76 }
77
78 static gchar *
79 canonicalize_path (const char *path)
80 {
81         gchar *abspath, *pos, *lastpos, *dest;
82         int backc;
83
84         if (g_path_is_absolute (path)) {
85                 abspath = g_strdup (path);
86         } else {
87                 gchar *tmpdir = g_get_current_dir ();
88                 abspath = g_build_filename (tmpdir, path, NULL);
89                 g_free (tmpdir);
90         }
91
92         abspath = g_strreverse (abspath);
93
94         backc = 0;
95         dest = lastpos = abspath;
96         pos = strchr (lastpos, G_DIR_SEPARATOR);
97
98         while (pos != NULL) {
99                 int len = pos - lastpos;
100                 if (len == 1 && lastpos [0] == '.') {
101                         // nop
102                 } else if (len == 2 && lastpos [0] == '.' && lastpos [1] == '.') {
103                         backc++;
104                 } else if (len > 0) {
105                         if (backc > 0) {
106                                 backc--;
107                         } else {
108                                 if (dest != lastpos) strncpy (dest, lastpos, len + 1);
109                                 dest += len + 1;
110                         }
111                 }
112                 lastpos = pos + 1;
113                 pos = strchr (lastpos, G_DIR_SEPARATOR);
114         }
115         
116         if (dest != lastpos) strcpy (dest, lastpos);
117         return g_strreverse (abspath);
118 }
119
120 /**
121  * mono_images_init:
122  *
123  *  Initialize the global variables used by this module.
124  */
125 void
126 mono_images_init (void)
127 {
128         InitializeCriticalSection (&images_mutex);
129
130         loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
131         loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
132 }
133
134 /**
135  * mono_image_ensure_section_idx:
136  * @image: The image we are operating on
137  * @section: section number that we will load/map into memory
138  *
139  * This routine makes sure that we have an in-memory copy of
140  * an image section (.text, .rsrc, .data).
141  *
142  * Returns: TRUE on success
143  */
144 int
145 mono_image_ensure_section_idx (MonoImage *image, int section)
146 {
147         MonoCLIImageInfo *iinfo = image->image_info;
148         MonoSectionTable *sect;
149         gboolean writable;
150         
151         g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
152
153         if (iinfo->cli_sections [section] != NULL)
154                 return TRUE;
155
156         sect = &iinfo->cli_section_tables [section];
157         
158         writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
159
160         if (!image->f) {
161                 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
162                         return FALSE;
163                 /* FIXME: we ignore the writable flag since we don't patch the binary */
164                 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
165                 return TRUE;
166         }
167         iinfo->cli_sections [section] = mono_raw_buffer_load (
168                 fileno (image->f), writable,
169                 sect->st_raw_data_ptr, sect->st_raw_data_size);
170
171         if (iinfo->cli_sections [section] == NULL)
172                 return FALSE;
173
174         return TRUE;
175 }
176
177 /**
178  * mono_image_ensure_section:
179  * @image: The image we are operating on
180  * @section: section name that we will load/map into memory
181  *
182  * This routine makes sure that we have an in-memory copy of
183  * an image section (.text, .rsrc, .data).
184  *
185  * Returns: TRUE on success
186  */
187 int
188 mono_image_ensure_section (MonoImage *image, const char *section)
189 {
190         MonoCLIImageInfo *ii = image->image_info;
191         int i;
192         
193         for (i = 0; i < ii->cli_section_count; i++){
194                 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
195                         continue;
196                 
197                 return mono_image_ensure_section_idx (image, i);
198         }
199         return FALSE;
200 }
201
202 static int
203 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
204 {
205         const int top = iinfo->cli_header.coff.coff_sections;
206         int i;
207
208         iinfo->cli_section_count = top;
209         iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
210         iinfo->cli_sections = g_new0 (void *, top);
211         
212         for (i = 0; i < top; i++){
213                 MonoSectionTable *t = &iinfo->cli_section_tables [i];
214
215                 if (!image->f) {
216                         if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
217                                 return FALSE;
218                         memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
219                         offset += sizeof (MonoSectionTable);
220                 } else {
221                         if (fread (t, sizeof (MonoSectionTable), 1, image->f) != 1)
222                                 return FALSE;
223                 }
224
225 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
226                 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
227                 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
228                 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
229                 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
230                 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
231                 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
232                 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
233                 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
234                 t->st_flags = GUINT32_FROM_LE (t->st_flags);
235 #endif
236                 /* consistency checks here */
237         }
238
239         return TRUE;
240 }
241
242 static gboolean
243 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
244 {
245         guint32 offset;
246         int n;
247         
248         offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
249         if (offset == INVALID_ADDRESS)
250                 return FALSE;
251
252         if (!image->f) {
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         } else {
257                 if (fseek (image->f, offset, SEEK_SET) != 0)
258                         return FALSE;
259         
260                 if ((n = fread (&iinfo->cli_cli_header, sizeof (MonoCLIHeader), 1, image->f)) != 1)
261                         return FALSE;
262         }
263
264 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
265 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
266 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
267 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
268         SWAP32 (iinfo->cli_cli_header.ch_size);
269         SWAP32 (iinfo->cli_cli_header.ch_flags);
270         SWAP32 (iinfo->cli_cli_header.ch_entry_point);
271         SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
272         SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
273         SWAPPDE (iinfo->cli_cli_header.ch_metadata);
274         SWAPPDE (iinfo->cli_cli_header.ch_resources);
275         SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
276         SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
277         SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
278         SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
279         SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
280         SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
281         SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
282         SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
283         SWAPPDE (iinfo->cli_cli_header.ch_module_image);
284         SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
285         SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
286         SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
287         SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
288 #undef SWAP32
289 #undef SWAP16
290 #undef SWAPPDE
291 #endif
292         /* Catch new uses of the fields that are supposed to be zero */
293
294         if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
295             (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
296             (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
297             (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
298             (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
299             (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
300             (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
301             (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
302             (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
303
304                 /*
305                  * No need to scare people who are testing this, I am just
306                  * labelling this as a LAMESPEC
307                  */
308                 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
309
310         }
311             
312         return TRUE;
313 }
314
315 static gboolean
316 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
317 {
318         guint32 offset, size;
319         guint16 streams;
320         int i;
321         guint32 pad;
322         char *ptr;
323         
324         offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
325         if (offset == INVALID_ADDRESS)
326                 return FALSE;
327
328         size = iinfo->cli_cli_header.ch_metadata.size;
329
330         if (!image->f) {
331                 if (offset + size > image->raw_data_len)
332                         return FALSE;
333                 image->raw_metadata = image->raw_data + offset;
334         } else {
335                 image->raw_metadata = mono_raw_buffer_load (fileno (image->f), FALSE, offset, size);
336                 if (image->raw_metadata == NULL)
337                         return FALSE;
338         }
339
340         ptr = image->raw_metadata;
341
342         if (strncmp (ptr, "BSJB", 4) == 0){
343                 guint32 version_string_len;
344
345                 ptr += 12;
346                 version_string_len = read32 (ptr);
347                 ptr += 4;
348                 image->version = g_strndup (ptr, version_string_len);
349                 ptr += version_string_len;
350                 pad = ptr - image->raw_metadata;
351                 if (pad % 4)
352                         ptr += 4 - (pad % 4);
353         } else
354                 return FALSE;
355
356         /* skip over flags */
357         ptr += 2;
358         
359         streams = read16 (ptr);
360         ptr += 2;
361
362         for (i = 0; i < streams; i++){
363                 if (strncmp (ptr + 8, "#~", 3) == 0){
364                         image->heap_tables.data = image->raw_metadata + read32 (ptr);
365                         image->heap_tables.size = read32 (ptr + 4);
366                         ptr += 8 + 3;
367                 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
368                         image->heap_strings.data = image->raw_metadata + read32 (ptr);
369                         image->heap_strings.size = read32 (ptr + 4);
370                         ptr += 8 + 9;
371                 } else if (strncmp (ptr + 8, "#US", 4) == 0){
372                         image->heap_us.data = image->raw_metadata + read32 (ptr);
373                         image->heap_us.size = read32 (ptr + 4);
374                         ptr += 8 + 4;
375                 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
376                         image->heap_blob.data = image->raw_metadata + read32 (ptr);
377                         image->heap_blob.size = read32 (ptr + 4);
378                         ptr += 8 + 6;
379                 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
380                         image->heap_guid.data = image->raw_metadata + read32 (ptr);
381                         image->heap_guid.size = read32 (ptr + 4);
382                         ptr += 8 + 6;
383                 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
384                         g_print ("Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name);
385                         return FALSE;
386                 } else {
387                         g_message ("Unknown heap type: %s\n", ptr + 8);
388                         ptr += 8 + strlen (ptr + 8) + 1;
389                 }
390                 pad = ptr - image->raw_metadata;
391                 if (pad % 4)
392                         ptr += 4 - (pad % 4);
393         }
394
395         g_assert (image->heap_guid.data);
396         g_assert (image->heap_guid.size >= 16);
397
398         image->guid = mono_guid_to_string (image->heap_guid.data);
399
400         return TRUE;
401 }
402
403 /*
404  * Load representation of logical metadata tables, from the "#~" stream
405  */
406 static gboolean
407 load_tables (MonoImage *image)
408 {
409         const char *heap_tables = image->heap_tables.data;
410         const guint32 *rows;
411         guint64 valid_mask, sorted_mask;
412         int valid = 0, table;
413         int heap_sizes;
414         
415         heap_sizes = heap_tables [6];
416         image->idx_string_wide = ((heap_sizes & 0x01) == 1);
417         image->idx_guid_wide   = ((heap_sizes & 0x02) == 2);
418         image->idx_blob_wide   = ((heap_sizes & 0x04) == 4);
419         
420         valid_mask = read64 (heap_tables + 8);
421         sorted_mask = read64 (heap_tables + 16);
422         rows = (const guint32 *) (heap_tables + 24);
423         
424         for (table = 0; table < 64; table++){
425                 if ((valid_mask & ((guint64) 1 << table)) == 0){
426                         image->tables [table].rows = 0;
427                         continue;
428                 }
429                 if (table > MONO_TABLE_LAST) {
430                         g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
431                 }
432                 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
433                         g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
434                 }*/
435                 image->tables [table].rows = read32 (rows);
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_add_to_name_cache (MonoImage *image, const char *nspace, 
460                                                           const char *name, guint32 index)
461 {
462         GHashTable *nspace_table;
463         GHashTable *name_cache = image->name_cache;
464
465         if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
466                 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
467                 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
468         }
469         g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
470 }
471
472 static void
473 load_modules (MonoImage *image, MonoImageOpenStatus *status)
474 {
475         MonoTableInfo *t;
476         int i;
477         char *base_dir;
478
479         if (image->modules)
480                 return;
481
482         t = &image->tables [MONO_TABLE_MODULEREF];
483         image->modules = g_new0 (MonoImage *, t->rows);
484         image->module_count = t->rows;
485         base_dir = g_path_get_dirname (image->name);
486         for (i = 0; i < t->rows; i++){
487                 char *module_ref;
488                 const char *name;
489                 guint32 cols [MONO_MODULEREF_SIZE];
490
491                 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
492                 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
493                 module_ref = g_build_filename (base_dir, name, NULL);
494                 image->modules [i] = mono_image_open (module_ref, status);
495                 if (image->modules [i]) {
496                         /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
497                 }
498                 /* 
499                  * FIXME: what do we do here? it could be a native dll...
500                  * We should probably do lazy-loading of modules.
501                  */
502                 if (status)
503                         *status = MONO_IMAGE_OK;
504                 g_free (module_ref);
505         }
506
507         g_free (base_dir);
508 }
509
510 static void
511 load_class_names (MonoImage *image)
512 {
513         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEDEF];
514         guint32 cols [MONO_TYPEDEF_SIZE];
515         const char *name;
516         const char *nspace;
517         guint32 i, visib, nspace_index;
518         GHashTable *name_cache2, *nspace_table;
519
520         /* Temporary hash table to avoid lookups in the nspace_table */
521         name_cache2 = g_hash_table_new (NULL, NULL);
522
523         for (i = 1; i <= t->rows; ++i) {
524                 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
525                 /* nested types are accessed from the nesting name */
526                 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
527                 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
528                         continue;
529                 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
530                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
531
532                 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
533                 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
534                 if (!nspace_table) {
535                         nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
536                         g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
537                         g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
538                                                                  nspace_table);
539                 }
540                 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
541         }
542
543         /* Load type names from EXPORTEDTYPES table */
544         {
545                 MonoTableInfo  *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
546                 guint32 cols [MONO_EXP_TYPE_SIZE];
547                 int i;
548
549                 for (i = 0; i < t->rows; ++i) {
550                         mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
551                         name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
552                         nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
553
554                         nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
555                         nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
556                         if (!nspace_table) {
557                                 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
558                                 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
559                                 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
560                                                                          nspace_table);
561                         }
562                         g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
563                 }
564         }
565
566         g_hash_table_destroy (name_cache2);
567 }
568
569 static void
570 register_guid (gpointer key, gpointer value, gpointer user_data)
571 {
572         MonoImage *image = (MonoImage*)value;
573
574         if (!g_hash_table_lookup (loaded_images_guid_hash, image))
575                 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
576 }
577
578 static void
579 build_guid_table (void)
580 {
581         g_hash_table_foreach (loaded_images_hash, register_guid, NULL);
582 }
583
584 void
585 mono_image_init (MonoImage *image)
586 {
587         image->method_cache = g_hash_table_new (NULL, NULL);
588         image->class_cache = g_hash_table_new (NULL, NULL);
589         image->field_cache = g_hash_table_new (NULL, NULL);
590         image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
591         image->array_cache = g_hash_table_new (NULL, NULL);
592
593         image->delegate_begin_invoke_cache = 
594                 g_hash_table_new ((GHashFunc)mono_signature_hash, 
595                                   (GCompareFunc)mono_metadata_signature_equal);
596         image->delegate_end_invoke_cache = 
597                 g_hash_table_new ((GHashFunc)mono_signature_hash, 
598                                   (GCompareFunc)mono_metadata_signature_equal);
599         image->delegate_invoke_cache = 
600                 g_hash_table_new ((GHashFunc)mono_signature_hash, 
601                                   (GCompareFunc)mono_metadata_signature_equal);
602         image->runtime_invoke_cache  = 
603                 g_hash_table_new ((GHashFunc)mono_signature_hash, 
604                                   (GCompareFunc)mono_metadata_signature_equal);
605         
606         image->managed_wrapper_cache = g_hash_table_new (NULL, NULL);
607         image->native_wrapper_cache = g_hash_table_new (NULL, NULL);
608         image->remoting_invoke_cache = g_hash_table_new (NULL, NULL);
609         image->synchronized_cache = g_hash_table_new (NULL, NULL);
610         image->unbox_wrapper_cache = g_hash_table_new (NULL, NULL);
611
612         image->typespec_cache = g_hash_table_new (NULL, NULL);
613         image->memberref_signatures = g_hash_table_new (NULL, NULL);
614         image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
615 }
616
617 static MonoImage *
618 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status)
619 {
620         MonoCLIImageInfo *iinfo;
621         MonoDotNetHeader *header;
622         MonoMSDOSHeader msdos;
623         int n;
624         guint32 offset = 0;
625
626         mono_image_init (image);
627
628         iinfo = image->image_info;
629         header = &iinfo->cli_header;
630                 
631         if (status)
632                 *status = MONO_IMAGE_IMAGE_INVALID;
633
634         if (!image->f) {
635                 if (offset + sizeof (msdos) > image->raw_data_len)
636                         goto invalid_image;
637                 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
638         } else {
639                 if (fread (&msdos, sizeof (msdos), 1, image->f) != 1)
640                         goto invalid_image;
641         }
642         
643         if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
644                 goto invalid_image;
645         
646         msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
647
648         if (msdos.pe_offset != sizeof (msdos)) {
649                 if (image->f)
650                         fseek (image->f, msdos.pe_offset, SEEK_SET);
651         }
652         offset = msdos.pe_offset;
653
654         if (!image->f) {
655                 if (offset + sizeof (MonoDotNetHeader) > image->raw_data_len)
656                         goto invalid_image;
657                 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
658                 offset += sizeof (MonoDotNetHeader);
659         } else {
660                 if ((n = fread (header, sizeof (MonoDotNetHeader), 1, image->f)) != 1)
661                         goto invalid_image;
662         }
663
664 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
665 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
666 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
667 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
668         SWAP32 (header->coff.coff_time);
669         SWAP32 (header->coff.coff_symptr);
670         SWAP32 (header->coff.coff_symcount);
671         SWAP16 (header->coff.coff_machine);
672         SWAP16 (header->coff.coff_sections);
673         SWAP16 (header->coff.coff_opt_header_size);
674         SWAP16 (header->coff.coff_attributes);
675         /* MonoPEHeader */
676         SWAP32 (header->pe.pe_code_size);
677         SWAP32 (header->pe.pe_data_size);
678         SWAP32 (header->pe.pe_uninit_data_size);
679         SWAP32 (header->pe.pe_rva_entry_point);
680         SWAP32 (header->pe.pe_rva_code_base);
681         SWAP32 (header->pe.pe_rva_data_base);
682         SWAP16 (header->pe.pe_magic);
683
684         /* MonoPEHeaderNT: not used yet */
685         SWAP32  (header->nt.pe_image_base);     /* must be 0x400000 */
686         SWAP32  (header->nt.pe_section_align);       /* must be 8192 */
687         SWAP32  (header->nt.pe_file_alignment);      /* must be 512 or 4096 */
688         SWAP16  (header->nt.pe_os_major);            /* must be 4 */
689         SWAP16  (header->nt.pe_os_minor);            /* must be 0 */
690         SWAP16  (header->nt.pe_user_major);
691         SWAP16  (header->nt.pe_user_minor);
692         SWAP16  (header->nt.pe_subsys_major);
693         SWAP16  (header->nt.pe_subsys_minor);
694         SWAP32  (header->nt.pe_reserved_1);
695         SWAP32  (header->nt.pe_image_size);
696         SWAP32  (header->nt.pe_header_size);
697         SWAP32  (header->nt.pe_checksum);
698         SWAP16  (header->nt.pe_subsys_required);
699         SWAP16  (header->nt.pe_dll_flags);
700         SWAP32  (header->nt.pe_stack_reserve);
701         SWAP32  (header->nt.pe_stack_commit);
702         SWAP32  (header->nt.pe_heap_reserve);
703         SWAP32  (header->nt.pe_heap_commit);
704         SWAP32  (header->nt.pe_loader_flags);
705         SWAP32  (header->nt.pe_data_dir_count);
706
707         /* MonoDotNetHeader: mostly unused */
708         SWAPPDE (header->datadir.pe_export_table);
709         SWAPPDE (header->datadir.pe_import_table);
710         SWAPPDE (header->datadir.pe_resource_table);
711         SWAPPDE (header->datadir.pe_exception_table);
712         SWAPPDE (header->datadir.pe_certificate_table);
713         SWAPPDE (header->datadir.pe_reloc_table);
714         SWAPPDE (header->datadir.pe_debug);
715         SWAPPDE (header->datadir.pe_copyright);
716         SWAPPDE (header->datadir.pe_global_ptr);
717         SWAPPDE (header->datadir.pe_tls_table);
718         SWAPPDE (header->datadir.pe_load_config_table);
719         SWAPPDE (header->datadir.pe_bound_import);
720         SWAPPDE (header->datadir.pe_iat);
721         SWAPPDE (header->datadir.pe_delay_import_desc);
722         SWAPPDE (header->datadir.pe_cli_header);
723         SWAPPDE (header->datadir.pe_reserved);
724
725 #undef SWAP32
726 #undef SWAP16
727 #undef SWAPPDE
728 #endif
729
730         if (header->coff.coff_machine != 0x14c)
731                 goto invalid_image;
732
733         if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
734                 goto invalid_image;
735
736         if (header->pesig[0] != 'P' || header->pesig[1] != 'E' || header->pe.pe_magic != 0x10B)
737                 goto invalid_image;
738
739 #if 0
740         /*
741          * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
742          * which produces binaries with 7.0.  From Sergey:
743          *
744          * The reason is that MSVC7 uses traditional compile/link
745          * sequence for CIL executables, and VS.NET (and Framework
746          * SDK) includes linker version 7, that puts 7.0 in this
747          * field.  That's why it's currently not possible to load VC
748          * binaries with Mono.  This field is pretty much meaningless
749          * anyway (what linker?).
750          */
751         if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
752                 goto invalid_image;
753 #endif
754
755         /*
756          * FIXME: byte swap all addresses here for header.
757          */
758         
759         if (!load_section_tables (image, iinfo, offset))
760                 goto invalid_image;
761         
762         /* Load the CLI header */
763         if (!load_cli_header (image, iinfo))
764                 goto invalid_image;
765
766         if (!load_metadata (image, iinfo))
767                 goto invalid_image;
768
769         load_class_names (image);
770
771         /* modules don't have an assembly table row */
772         if (image->tables [MONO_TABLE_ASSEMBLY].rows)
773                 image->assembly_name = mono_metadata_string_heap (image, 
774                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
775                                         0, MONO_ASSEMBLY_NAME));
776
777         image->module_name = mono_metadata_string_heap (image, 
778                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
779                                         0, MONO_MODULE_NAME));
780
781         load_modules (image, status);
782
783         if (status)
784                 *status = MONO_IMAGE_OK;
785
786         image->ref_count=1;
787
788         return image;
789
790 invalid_image:
791         mono_image_close (image);
792                 return NULL;
793 }
794
795 static MonoImage *
796 do_mono_image_open (const char *fname, MonoImageOpenStatus *status)
797 {
798         MonoCLIImageInfo *iinfo;
799         MonoImage *image;
800         FILE *filed;
801
802         if ((filed = fopen (fname, "rb")) == NULL){
803                 if (status)
804                         *status = MONO_IMAGE_ERROR_ERRNO;
805                 return NULL;
806         }
807
808         image = g_new0 (MonoImage, 1);
809         image->ref_count = 1;
810         image->f = filed;
811         iinfo = g_new0 (MonoCLIImageInfo, 1);
812         image->image_info = iinfo;
813         image->name = canonicalize_path (fname);
814
815         return do_mono_image_load (image, status);
816 }
817
818 MonoImage *
819 mono_image_loaded (const char *name)
820 {
821         MonoImage *res;
822         
823         EnterCriticalSection (&images_mutex);
824         res = g_hash_table_lookup (loaded_images_hash, name);
825         LeaveCriticalSection (&images_mutex);
826         return res;
827 }
828
829 MonoImage *
830 mono_image_loaded_by_guid (const char *guid)
831 {
832         MonoImage *res;
833
834         EnterCriticalSection (&images_mutex);
835         res = g_hash_table_lookup (loaded_images_guid_hash, guid);
836         LeaveCriticalSection (&images_mutex);
837         return res;
838 }
839
840 MonoImage *
841 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
842 {
843         MonoCLIImageInfo *iinfo;
844         MonoImage *image;
845         char *datac;
846
847         if (!data || !data_len) {
848                 if (status)
849                         *status = MONO_IMAGE_IMAGE_INVALID;
850                 return NULL;
851         }
852         datac = data;
853         if (need_copy) {
854                 datac = g_try_malloc (data_len);
855                 if (!datac) {
856                         if (status)
857                                 *status = MONO_IMAGE_ERROR_ERRNO;
858                         return NULL;
859                 }
860                 memcpy (datac, data, data_len);
861         }
862
863         image = g_new0 (MonoImage, 1);
864         image->ref_count = 1;
865         image->raw_data = datac;
866         image->raw_data_len = data_len;
867         image->raw_data_allocated = need_copy;
868         image->name = g_strdup_printf ("data-%p", datac);
869         iinfo = g_new0 (MonoCLIImageInfo, 1);
870         image->image_info = iinfo;
871
872         return do_mono_image_load (image, status);
873 }
874
875 /**
876  * mono_image_open:
877  * @fname: filename that points to the module we want to open
878  * @status: An error condition is returned in this field
879  *
880  * Retuns: An open image of type %MonoImage or NULL on error.
881  * if NULL, then check the value of @status for details on the error
882  */
883 MonoImage *
884 mono_image_open (const char *fname, MonoImageOpenStatus *status)
885 {
886         MonoImage *image, *image2;
887         char *absfname;
888         
889         g_return_val_if_fail (fname != NULL, NULL);
890         
891         absfname = canonicalize_path (fname);
892
893         /*
894          * The easiest solution would be to do all the loading inside the mutex,
895          * but that would lead to scalability problems. So we let the loading
896          * happen outside the mutex, and if multiple threads happen to load
897          * the same image, we discard all but the first copy.
898          */
899         EnterCriticalSection (&images_mutex);
900         image = g_hash_table_lookup (loaded_images_hash, absfname);
901         g_free (absfname);
902         
903         if (image){
904                 image->ref_count++;
905                 LeaveCriticalSection (&images_mutex);
906                 return image;
907         }
908         LeaveCriticalSection (&images_mutex);
909
910         image = do_mono_image_open (fname, status);
911         if (image == NULL)
912                 return NULL;
913
914         EnterCriticalSection (&images_mutex);
915         image2 = g_hash_table_lookup (loaded_images_hash, image->name);
916
917         if (image2) {
918                 /* Somebody else beat us to it */
919                 image2->ref_count ++;
920                 LeaveCriticalSection (&images_mutex);
921                 mono_image_close (image);
922                 return image2;
923         }
924         g_hash_table_insert (loaded_images_hash, image->name, image);
925         if (image->assembly_name && (g_hash_table_lookup (loaded_images_hash, image->assembly_name) == NULL))
926                 g_hash_table_insert (loaded_images_hash, (char *) image->assembly_name, image); 
927         g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
928         LeaveCriticalSection (&images_mutex);
929
930         return image;
931 }
932
933 static void
934 free_hash_table (gpointer key, gpointer val, gpointer user_data)
935 {
936         g_hash_table_destroy ((GHashTable*)val);
937 }
938
939 static void
940 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
941 {
942         mono_metadata_free_method_signature ((MonoMethodSignature*)val);
943 }
944
945 static void
946 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
947 {
948         g_free (val);
949 }
950
951 /**
952  * mono_image_addref:
953  * @image: The image file we wish to add a reference to
954  *
955  *  Increases the reference count of an image.
956  */
957 void
958 mono_image_addref (MonoImage *image)
959 {
960         InterlockedIncrement (&image->ref_count);
961 }       
962
963 /**
964  * mono_image_close:
965  * @image: The image file we wish to close
966  *
967  * Closes an image file, deallocates all memory consumed and
968  * unmaps all possible sections of the file
969  */
970 void
971 mono_image_close (MonoImage *image)
972 {
973         MonoImage *image2;
974
975         g_return_if_fail (image != NULL);
976
977         EnterCriticalSection (&images_mutex);
978         if (--image->ref_count) {
979                 LeaveCriticalSection (&images_mutex);
980                 return;
981         }
982         image2 = g_hash_table_lookup (loaded_images_hash, image->name);
983         if (image == image2) {
984                 /* This is not true if we are called from mono_image_open () */
985                 g_hash_table_remove (loaded_images_hash, image->name);
986                 g_hash_table_remove (loaded_images_guid_hash, image->guid);
987                 /* Multiple images might have the same guid */
988                 build_guid_table ();
989         }
990         if (image->assembly_name && (g_hash_table_lookup (loaded_images_hash, image->assembly_name) == image))
991                 g_hash_table_remove (loaded_images_hash, (char *) image->assembly_name);        
992         LeaveCriticalSection (&images_mutex);
993
994         if (image->f)
995                 fclose (image->f);
996         if (image->raw_data_allocated) {
997                 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
998                 MonoCLIImageInfo *ii = image->image_info;
999                 int i;
1000
1001                 if ((image->raw_metadata > image->raw_data) &&
1002                         (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1003                         image->raw_metadata = NULL;
1004
1005                 for (i = 0; i < ii->cli_section_count; i++)
1006                         if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1007                                 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1008                                 ii->cli_sections [i] = NULL;
1009
1010                 g_free (image->raw_data);
1011         }
1012         g_free (image->name);
1013         g_free (image->guid);
1014         g_free (image->files);
1015
1016         g_hash_table_destroy (image->method_cache);
1017         g_hash_table_destroy (image->class_cache);
1018         g_hash_table_destroy (image->field_cache);
1019         g_hash_table_destroy (image->array_cache);
1020         g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1021         g_hash_table_destroy (image->name_cache);
1022         g_hash_table_destroy (image->native_wrapper_cache);
1023         g_hash_table_destroy (image->managed_wrapper_cache);
1024         g_hash_table_destroy (image->delegate_begin_invoke_cache);
1025         g_hash_table_destroy (image->delegate_end_invoke_cache);
1026         g_hash_table_destroy (image->delegate_invoke_cache);
1027         g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1028         g_hash_table_destroy (image->remoting_invoke_cache);
1029         g_hash_table_destroy (image->runtime_invoke_cache);
1030         g_hash_table_destroy (image->synchronized_cache);
1031         g_hash_table_destroy (image->unbox_wrapper_cache);
1032         g_hash_table_destroy (image->typespec_cache);
1033         g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1034         g_hash_table_destroy (image->memberref_signatures);
1035         g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1036         g_hash_table_destroy (image->helper_signatures);
1037         
1038         if (image->raw_metadata != NULL)
1039                 mono_raw_buffer_free (image->raw_metadata);
1040         
1041         if (image->image_info){
1042                 MonoCLIImageInfo *ii = image->image_info;
1043                 int i;
1044
1045                 for (i = 0; i < ii->cli_section_count; i++){
1046                         if (!ii->cli_sections [i])
1047                                 continue;
1048                         mono_raw_buffer_free (ii->cli_sections [i]);
1049                 }
1050                 if (ii->cli_section_tables)
1051                         g_free (ii->cli_section_tables);
1052                 if (ii->cli_sections)
1053                         g_free (ii->cli_sections);
1054                 g_free (image->image_info);
1055         }
1056
1057         if (!image->dynamic)
1058                 /* Dynamic images are GC_MALLOCed */
1059                 g_free (image);
1060 }
1061
1062 /** 
1063  * mono_image_strerror:
1064  * @status: an code indicating the result from a recent operation
1065  *
1066  * Returns: a string describing the error
1067  */
1068 const char *
1069 mono_image_strerror (MonoImageOpenStatus status)
1070 {
1071         switch (status){
1072         case MONO_IMAGE_OK:
1073                 return "success";
1074         case MONO_IMAGE_ERROR_ERRNO:
1075                 return strerror (errno);
1076         case MONO_IMAGE_IMAGE_INVALID:
1077                 return "File does not contain a valid CIL image";
1078         case MONO_IMAGE_MISSING_ASSEMBLYREF:
1079                 return "An assembly was referenced, but could not be found";
1080         }
1081         return "Internal error";
1082 }
1083
1084 static gpointer
1085 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1086                                guint32 lang_id, gunichar2 *name,
1087                                MonoPEResourceDirEntry *entry,
1088                                MonoPEResourceDir *root, guint32 level)
1089 {
1090         gboolean is_string=entry->name_is_string;
1091
1092         /* Level 0 holds a directory entry for each type of resource
1093          * (identified by ID or name).
1094          *
1095          * Level 1 holds a directory entry for each named resource
1096          * item, and each "anonymous" item of a particular type of
1097          * resource.
1098          *
1099          * Level 2 holds a directory entry for each language pointing to
1100          * the actual data.
1101          */
1102
1103         if(level==0) {
1104                 if((is_string==FALSE && entry->name_offset!=res_id) ||
1105                    (is_string==TRUE)) {
1106                         return(NULL);
1107                 }
1108         } else if (level==1) {
1109 #if 0
1110                 if(name!=NULL &&
1111                    is_string==TRUE && name!=lookup (entry->name_offset)) {
1112                         return(NULL);
1113                 }
1114 #endif
1115         } else if (level==2) {
1116                 if((is_string==FALSE && entry->name_offset!=lang_id) ||
1117                    (is_string==TRUE)) {
1118                         return(NULL);
1119                 }
1120         } else {
1121                 g_assert_not_reached ();
1122         }
1123
1124         if(entry->is_dir==TRUE) {
1125                 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+entry->dir_offset);
1126                 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1127                 guint32 entries, i;
1128                 
1129                 entries=res_dir->res_named_entries + res_dir->res_id_entries;
1130
1131                 for(i=0; i<entries; i++) {
1132                         MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1133                         gpointer ret;
1134                         
1135                         ret=mono_image_walk_resource_tree (info, res_id,
1136                                                            lang_id, name,
1137                                                            sub_entry, root,
1138                                                            level+1);
1139                         if(ret!=NULL) {
1140                                 return(ret);
1141                         }
1142                 }
1143
1144                 return(NULL);
1145         } else {
1146                 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+entry->dir_offset);
1147                 
1148                 return(data_entry);
1149         }
1150 }
1151
1152 gpointer
1153 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1154 {
1155         MonoCLIImageInfo *info;
1156         MonoDotNetHeader *header;
1157         MonoPEDatadir *datadir;
1158         MonoPEDirEntry *rsrc;
1159         MonoPEResourceDir *resource_dir;
1160         MonoPEResourceDirEntry *res_entries;
1161         guint32 entries, i;
1162
1163         if(image==NULL) {
1164                 return(NULL);
1165         }
1166
1167         info=image->image_info;
1168         if(info==NULL) {
1169                 return(NULL);
1170         }
1171
1172         header=&info->cli_header;
1173         if(header==NULL) {
1174                 return(NULL);
1175         }
1176
1177         datadir=&header->datadir;
1178         if(datadir==NULL) {
1179                 return(NULL);
1180         }
1181
1182         rsrc=&datadir->pe_resource_table;
1183         if(rsrc==NULL) {
1184                 return(NULL);
1185         }
1186
1187         resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1188         if(resource_dir==NULL) {
1189                 return(NULL);
1190         }
1191         
1192         entries=resource_dir->res_named_entries + resource_dir->res_id_entries;
1193         res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1194         
1195         for(i=0; i<entries; i++) {
1196                 MonoPEResourceDirEntry *entry=&res_entries[i];
1197                 gpointer ret;
1198                 
1199                 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1200                                                    name, entry, resource_dir,
1201                                                    0);
1202                 if(ret!=NULL) {
1203                         return(ret);
1204                 }
1205         }
1206
1207         return(NULL);
1208 }
1209
1210 guint32
1211 mono_image_get_entry_point (MonoImage *image)
1212 {
1213         return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1214 }
1215
1216 const char*
1217 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1218 {
1219         MonoCLIImageInfo *iinfo = image->image_info;
1220         MonoCLIHeader *ch = &iinfo->cli_cli_header;
1221         const char* data;
1222
1223         if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1224                 return NULL;
1225         
1226         data = mono_image_rva_map (image, ch->ch_resources.rva);
1227         if (!data)
1228                 return NULL;
1229         data += offset;
1230         if (size)
1231                 *size = read32 (data);
1232         data += 4;
1233         return data;
1234 }
1235
1236 MonoImage*
1237 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1238 {
1239         char *base_dir, *name;
1240         MonoImage *res;
1241         MonoTableInfo  *t = &image->tables [MONO_TABLE_FILE];
1242         const char *fname;
1243         guint32 fname_id;
1244
1245         if (fileidx < 1 || fileidx > t->rows)
1246                 return NULL;
1247
1248         if (image->files && image->files [fileidx - 1])
1249                 return image->files [fileidx - 1];
1250
1251         if (!image->files)
1252                 image->files = g_new0 (MonoImage*, t->rows);
1253
1254         fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1255         fname = mono_metadata_string_heap (image, fname_id);
1256         base_dir = g_path_get_dirname (image->name);
1257         name = g_build_filename (base_dir, fname, NULL);
1258         res = mono_image_open (name, NULL);
1259         if (res) {
1260                 int i;
1261                 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1262                 res->assembly = image->assembly;
1263                 for (i = 0; i < res->module_count; ++i) {
1264                         if (res->modules [i] && !res->modules [i]->assembly)
1265                                 res->modules [i]->assembly = image->assembly;
1266                 }
1267
1268                 image->files [fileidx - 1] = res;
1269         }
1270         g_free (name);
1271         g_free (base_dir);
1272         return res;
1273 }
1274
1275 const char*
1276 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1277 {
1278         MonoCLIImageInfo *iinfo = image->image_info;
1279         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1280         const char* data;
1281
1282         if (!de->size || !de->rva)
1283                 return NULL;
1284         data = mono_image_rva_map (image, de->rva);
1285         if (!data)
1286                 return NULL;
1287         if (size)
1288                 *size = de->size;
1289         return data;
1290 }
1291
1292 guint32
1293 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1294 {
1295         MonoCLIImageInfo *iinfo = image->image_info;
1296         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1297         const int top = iinfo->cli_section_count;
1298         MonoSectionTable *tables = iinfo->cli_section_tables;
1299         int i;
1300         guint32 addr = de->rva;
1301         
1302         if (size)
1303                 *size = de->size;
1304         if (!de->size || !de->rva)
1305                 return 0;
1306         for (i = 0; i < top; i++){
1307                 if ((addr >= tables->st_virtual_address) &&
1308                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
1309                         return tables->st_raw_data_ptr +
1310                                 (addr - tables->st_virtual_address);
1311                 }
1312                 tables++;
1313         }
1314
1315         return 0;
1316 }
1317
1318 const char*
1319 mono_image_get_public_key (MonoImage *image, guint32 *size)
1320 {
1321         const char *pubkey;
1322         guint32 len, tok;
1323         if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1324                 return NULL;
1325         tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1326         if (!tok)
1327                 return NULL;
1328         pubkey = mono_metadata_blob_heap (image, tok);
1329         len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1330         if (size)
1331                 *size = len;
1332         return pubkey;
1333 }
1334
1335 const char*
1336 mono_image_get_name (MonoImage *image)
1337 {
1338         return image->assembly_name;
1339 }
1340
1341 const char*
1342 mono_image_get_filename (MonoImage *image)
1343 {
1344         return image->name;
1345 }
1346
1347 const MonoTableInfo*
1348 mono_image_get_table_info (MonoImage *image, int table_id)
1349 {
1350         if (table_id < 0 || table_id >= 64)
1351                 return NULL;
1352         return &image->tables [table_id];
1353 }
1354
1355 int
1356 mono_image_get_table_rows (MonoImage *image, int table_id)
1357 {
1358         if (table_id < 0 || table_id >= 64)
1359                 return 0;
1360         return image->tables [table_id].rows;
1361 }
1362
1363 int
1364 mono_table_info_get_rows (const MonoTableInfo *table)
1365 {
1366         return table->rows;
1367 }
1368
1369 MonoAssembly* 
1370 mono_image_get_assembly (MonoImage *image)
1371 {
1372         return image->assembly;
1373 }
1374
1375 gboolean
1376 mono_image_is_dynamic (MonoImage *image)
1377 {
1378         return image->dynamic;
1379 }
1380
1381 gboolean
1382 mono_image_has_authenticode_entry (MonoImage *image)
1383 {
1384         MonoCLIImageInfo *iinfo = image->image_info;
1385         MonoDotNetHeader *header = &iinfo->cli_header;
1386         MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
1387         // the Authenticode "pre" (non ASN.1) header is 8 bytes long
1388         return ((de->rva != 0) && (de->size > 8));
1389 }