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