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