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