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