Thu Aug 30 18:34:38 CEST 2007 Paolo Molaro <lupus@ximian.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 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
646 #define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
647 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
648 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
649 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
650 #else
651 #define SWAP64(x)
652 #define SWAP32(x)
653 #define SWAP16(x)
654 #define SWAPPDE(x)
655 #endif
656
657 /*
658  * Returns < 0 to indicate an error.
659  */
660 static int
661 do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
662 {
663         MonoDotNetHeader64 header64;
664
665         if (offset + sizeof (MonoDotNetHeader32) > image->raw_data_len)
666                 return -1;
667
668         memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
669
670         if (header->pesig [0] != 'P' || header->pesig [1] != 'E')
671                 return -1;
672
673         /* endian swap the fields common between PE and PE+ */
674         SWAP32 (header->coff.coff_time);
675         SWAP32 (header->coff.coff_symptr);
676         SWAP32 (header->coff.coff_symcount);
677         SWAP16 (header->coff.coff_machine);
678         SWAP16 (header->coff.coff_sections);
679         SWAP16 (header->coff.coff_opt_header_size);
680         SWAP16 (header->coff.coff_attributes);
681         /* MonoPEHeader */
682         SWAP32 (header->pe.pe_code_size);
683         SWAP32 (header->pe.pe_uninit_data_size);
684         SWAP32 (header->pe.pe_rva_entry_point);
685         SWAP32 (header->pe.pe_rva_code_base);
686         SWAP32 (header->pe.pe_rva_data_base);
687         SWAP16 (header->pe.pe_magic);
688
689         /* now we are ready for the basic tests */
690
691         if (header->pe.pe_magic == 0x10B) {
692                 offset += sizeof (MonoDotNetHeader);
693                 SWAP32 (header->pe.pe_data_size);
694                 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
695                         return -1;
696
697                 SWAP32  (header->nt.pe_image_base);     /* must be 0x400000 */
698                 SWAP32  (header->nt.pe_stack_reserve);
699                 SWAP32  (header->nt.pe_stack_commit);
700                 SWAP32  (header->nt.pe_heap_reserve);
701                 SWAP32  (header->nt.pe_heap_commit);
702         } else if (header->pe.pe_magic == 0x20B) {
703                 /* PE32+ file format */
704                 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
705                         return -1;
706                 memcpy (&header64, image->raw_data + offset, sizeof (MonoDotNetHeader64));
707                 offset += sizeof (MonoDotNetHeader64);
708                 /* copy the fields already swapped. the last field, pe_data_size, is missing */
709                 memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
710                 /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
711                  * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
712                  */
713                 SWAP64  (header64.nt.pe_image_base);
714                 header->nt.pe_image_base = header64.nt.pe_image_base;
715                 SWAP64  (header64.nt.pe_stack_reserve);
716                 header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
717                 SWAP64  (header64.nt.pe_stack_commit);
718                 header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
719                 SWAP64  (header64.nt.pe_heap_reserve);
720                 header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
721                 SWAP64  (header64.nt.pe_heap_commit);
722                 header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
723
724                 header->nt.pe_section_align = header64.nt.pe_section_align;
725                 header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
726                 header->nt.pe_os_major = header64.nt.pe_os_major;
727                 header->nt.pe_os_minor = header64.nt.pe_os_minor;
728                 header->nt.pe_user_major = header64.nt.pe_user_major;
729                 header->nt.pe_user_minor = header64.nt.pe_user_minor;
730                 header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
731                 header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
732                 header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
733                 header->nt.pe_image_size = header64.nt.pe_image_size;
734                 header->nt.pe_header_size = header64.nt.pe_header_size;
735                 header->nt.pe_checksum = header64.nt.pe_checksum;
736                 header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
737                 header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
738                 header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
739                 header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
740
741                 /* copy the datadir */
742                 memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
743         } else {
744                 return -1;
745         }
746
747         /* MonoPEHeaderNT: not used yet */
748         SWAP32  (header->nt.pe_section_align);       /* must be 8192 */
749         SWAP32  (header->nt.pe_file_alignment);      /* must be 512 or 4096 */
750         SWAP16  (header->nt.pe_os_major);            /* must be 4 */
751         SWAP16  (header->nt.pe_os_minor);            /* must be 0 */
752         SWAP16  (header->nt.pe_user_major);
753         SWAP16  (header->nt.pe_user_minor);
754         SWAP16  (header->nt.pe_subsys_major);
755         SWAP16  (header->nt.pe_subsys_minor);
756         SWAP32  (header->nt.pe_reserved_1);
757         SWAP32  (header->nt.pe_image_size);
758         SWAP32  (header->nt.pe_header_size);
759         SWAP32  (header->nt.pe_checksum);
760         SWAP16  (header->nt.pe_subsys_required);
761         SWAP16  (header->nt.pe_dll_flags);
762         SWAP32  (header->nt.pe_loader_flags);
763         SWAP32  (header->nt.pe_data_dir_count);
764
765         /* MonoDotNetHeader: mostly unused */
766         SWAPPDE (header->datadir.pe_export_table);
767         SWAPPDE (header->datadir.pe_import_table);
768         SWAPPDE (header->datadir.pe_resource_table);
769         SWAPPDE (header->datadir.pe_exception_table);
770         SWAPPDE (header->datadir.pe_certificate_table);
771         SWAPPDE (header->datadir.pe_reloc_table);
772         SWAPPDE (header->datadir.pe_debug);
773         SWAPPDE (header->datadir.pe_copyright);
774         SWAPPDE (header->datadir.pe_global_ptr);
775         SWAPPDE (header->datadir.pe_tls_table);
776         SWAPPDE (header->datadir.pe_load_config_table);
777         SWAPPDE (header->datadir.pe_bound_import);
778         SWAPPDE (header->datadir.pe_iat);
779         SWAPPDE (header->datadir.pe_delay_import_desc);
780         SWAPPDE (header->datadir.pe_cli_header);
781         SWAPPDE (header->datadir.pe_reserved);
782
783         return offset;
784 }
785
786 static MonoImage *
787 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
788                     gboolean care_about_cli)
789 {
790         MonoCLIImageInfo *iinfo;
791         MonoDotNetHeader *header;
792         MonoMSDOSHeader msdos;
793         gint32 offset = 0;
794
795         mono_image_init (image);
796
797         iinfo = image->image_info;
798         header = &iinfo->cli_header;
799                 
800         if (status)
801                 *status = MONO_IMAGE_IMAGE_INVALID;
802
803         if (offset + sizeof (msdos) > image->raw_data_len)
804                 goto invalid_image;
805         memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
806         
807         if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
808                 goto invalid_image;
809         
810         msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
811
812         offset = msdos.pe_offset;
813
814         offset = do_load_header (image, header, offset);
815         if (offset < 0)
816                 goto invalid_image;
817
818         /*
819          * this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
820          * we skip this test.
821         if (header->coff.coff_machine != 0x14c)
822                 goto invalid_image;
823         */
824
825 #if 0
826         /*
827          * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
828          * which produces binaries with 7.0.  From Sergey:
829          *
830          * The reason is that MSVC7 uses traditional compile/link
831          * sequence for CIL executables, and VS.NET (and Framework
832          * SDK) includes linker version 7, that puts 7.0 in this
833          * field.  That's why it's currently not possible to load VC
834          * binaries with Mono.  This field is pretty much meaningless
835          * anyway (what linker?).
836          */
837         if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
838                 goto invalid_image;
839 #endif
840
841         /*
842          * FIXME: byte swap all addresses here for header.
843          */
844         
845         if (!load_section_tables (image, iinfo, offset))
846                 goto invalid_image;
847         
848         if (care_about_cli == FALSE) {
849                 goto done;
850         }
851         
852         /* Load the CLI header */
853         if (!load_cli_header (image, iinfo))
854                 goto invalid_image;
855
856         if (!load_metadata (image, iinfo))
857                 goto invalid_image;
858
859         /* modules don't have an assembly table row */
860         if (image->tables [MONO_TABLE_ASSEMBLY].rows)
861                 image->assembly_name = mono_metadata_string_heap (image, 
862                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
863                                         0, MONO_ASSEMBLY_NAME));
864
865         image->module_name = mono_metadata_string_heap (image, 
866                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
867                                         0, MONO_MODULE_NAME));
868
869         load_modules (image);
870
871 done:
872         if (status)
873                 *status = MONO_IMAGE_OK;
874
875         return image;
876
877 invalid_image:
878         mono_image_close (image);
879                 return NULL;
880 }
881
882 static MonoImage *
883 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
884                     gboolean care_about_cli, gboolean refonly)
885 {
886         MonoCLIImageInfo *iinfo;
887         MonoImage *image;
888         FILE *filed;
889         struct stat stat_buf;
890
891         if ((filed = fopen (fname, "rb")) == NULL){
892                 if (status)
893                         *status = MONO_IMAGE_ERROR_ERRNO;
894                 return NULL;
895         }
896
897         if (fstat (fileno (filed), &stat_buf)) {
898                 fclose (filed);
899                 if (status)
900                         *status = MONO_IMAGE_ERROR_ERRNO;
901                 return NULL;
902         }
903         image = g_new0 (MonoImage, 1);
904         image->file_descr = filed;
905         image->raw_data_len = stat_buf.st_size;
906         image->raw_data = mono_raw_buffer_load (fileno (filed), FALSE, 0, stat_buf.st_size);
907         iinfo = g_new0 (MonoCLIImageInfo, 1);
908         image->image_info = iinfo;
909         image->name = mono_path_resolve_symlinks (fname);
910         image->ref_only = refonly;
911         image->ref_count = 1;
912
913         return do_mono_image_load (image, status, care_about_cli);
914 }
915
916 MonoImage *
917 mono_image_loaded_full (const char *name, gboolean refonly)
918 {
919         MonoImage *res;
920         GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
921         
922         mono_images_lock ();
923         res = g_hash_table_lookup (loaded_images, name);
924         mono_images_unlock ();
925         return res;
926 }
927
928 /**
929  * mono_image_loaded:
930  * @name: name of the image to load
931  *
932  * This routine ensures that the given image is loaded.
933  *
934  * Returns: the loaded MonoImage, or NULL on failure.
935  */
936 MonoImage *
937 mono_image_loaded (const char *name)
938 {
939         return mono_image_loaded_full (name, FALSE);
940 }
941
942 MonoImage *
943 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
944 {
945         MonoImage *res;
946         GHashTable *loaded_images = refonly ? loaded_images_refonly_guid_hash : loaded_images_guid_hash;
947
948         mono_images_lock ();
949         res = g_hash_table_lookup (loaded_images, guid);
950         mono_images_unlock ();
951         return res;
952 }
953
954 MonoImage *
955 mono_image_loaded_by_guid (const char *guid)
956 {
957         return mono_image_loaded_by_guid_full (guid, FALSE);
958 }
959
960 static MonoImage *
961 register_image (MonoImage *image)
962 {
963         MonoImage *image2;
964         GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
965
966         mono_images_lock ();
967         image2 = g_hash_table_lookup (loaded_images, image->name);
968
969         if (image2) {
970                 /* Somebody else beat us to it */
971                 mono_image_addref (image2);
972                 mono_images_unlock ();
973                 mono_image_close (image);
974                 return image2;
975         }
976         g_hash_table_insert (loaded_images, image->name, image);
977         if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
978                 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);      
979         g_hash_table_insert (image->ref_only ? loaded_images_refonly_guid_hash : loaded_images_guid_hash, image->guid, image);
980         mono_images_unlock ();
981
982         return image;
983 }
984
985 MonoImage *
986 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
987 {
988         MonoCLIImageInfo *iinfo;
989         MonoImage *image;
990         char *datac;
991
992         if (!data || !data_len) {
993                 if (status)
994                         *status = MONO_IMAGE_IMAGE_INVALID;
995                 return NULL;
996         }
997         datac = data;
998         if (need_copy) {
999                 datac = g_try_malloc (data_len);
1000                 if (!datac) {
1001                         if (status)
1002                                 *status = MONO_IMAGE_ERROR_ERRNO;
1003                         return NULL;
1004                 }
1005                 memcpy (datac, data, data_len);
1006         }
1007
1008         image = g_new0 (MonoImage, 1);
1009         image->raw_data = datac;
1010         image->raw_data_len = data_len;
1011         image->raw_data_allocated = need_copy;
1012         image->name = g_strdup_printf ("data-%p", datac);
1013         iinfo = g_new0 (MonoCLIImageInfo, 1);
1014         image->image_info = iinfo;
1015         image->ref_only = refonly;
1016
1017         image = do_mono_image_load (image, status, TRUE);
1018         if (image == NULL)
1019                 return NULL;
1020
1021         return register_image (image);
1022 }
1023
1024 MonoImage *
1025 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1026 {
1027         return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1028 }
1029
1030 MonoImage *
1031 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1032 {
1033         MonoImage *image;
1034         GHashTable *loaded_images;
1035         char *absfname;
1036         
1037         g_return_val_if_fail (fname != NULL, NULL);
1038         
1039         absfname = mono_path_canonicalize (fname);
1040
1041         /*
1042          * The easiest solution would be to do all the loading inside the mutex,
1043          * but that would lead to scalability problems. So we let the loading
1044          * happen outside the mutex, and if multiple threads happen to load
1045          * the same image, we discard all but the first copy.
1046          */
1047         mono_images_lock ();
1048         loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1049         image = g_hash_table_lookup (loaded_images, absfname);
1050         g_free (absfname);
1051         
1052         if (image){
1053                 mono_image_addref (image);
1054                 mono_images_unlock ();
1055                 return image;
1056         }
1057         mono_images_unlock ();
1058
1059         image = do_mono_image_open (fname, status, TRUE, refonly);
1060         if (image == NULL)
1061                 return NULL;
1062
1063         return register_image (image);
1064 }
1065
1066 /**
1067  * mono_image_open:
1068  * @fname: filename that points to the module we want to open
1069  * @status: An error condition is returned in this field
1070  *
1071  * Returns: An open image of type %MonoImage or NULL on error. 
1072  * The caller holds a temporary reference to the returned image which should be cleared 
1073  * when no longer needed by calling mono_image_close ().
1074  * if NULL, then check the value of @status for details on the error
1075  */
1076 MonoImage *
1077 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1078 {
1079         return mono_image_open_full (fname, status, FALSE);
1080 }
1081
1082 /**
1083  * mono_pe_file_open:
1084  * @fname: filename that points to the module we want to open
1085  * @status: An error condition is returned in this field
1086  *
1087  * Returns: An open image of type %MonoImage or NULL on error.  if
1088  * NULL, then check the value of @status for details on the error.
1089  * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1090  * It's just a PE file loader, used for FileVersionInfo.  It also does
1091  * not use the image cache.
1092  */
1093 MonoImage *
1094 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1095 {
1096         g_return_val_if_fail (fname != NULL, NULL);
1097         
1098         return(do_mono_image_open (fname, status, FALSE, FALSE));
1099 }
1100
1101 static void
1102 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1103 {
1104         g_hash_table_destroy ((GHashTable*)val);
1105 }
1106
1107 /*
1108 static void
1109 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1110 {
1111         mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1112 }
1113 */
1114
1115 static void
1116 free_blob_cache_entry (gpointer key, gpointer val, gpointer user_data)
1117 {
1118         g_free (key);
1119 }
1120
1121 static void
1122 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
1123 {
1124         g_free (val);
1125 }
1126
1127 static void
1128 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1129 {
1130         g_slist_free ((GSList*)val);
1131 }
1132
1133 /**
1134  * mono_image_addref:
1135  * @image: The image file we wish to add a reference to
1136  *
1137  *  Increases the reference count of an image.
1138  */
1139 void
1140 mono_image_addref (MonoImage *image)
1141 {
1142         InterlockedIncrement (&image->ref_count);
1143 }       
1144
1145 void
1146 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1147 {
1148         stream->alloc_size = stream->index = stream->offset = 0;
1149         g_free (stream->data);
1150         stream->data = NULL;
1151         if (stream->hash) {
1152                 g_hash_table_destroy (stream->hash);
1153                 stream->hash = NULL;
1154         }
1155 }
1156
1157 /**
1158  * mono_image_close:
1159  * @image: The image file we wish to close
1160  *
1161  * Closes an image file, deallocates all memory consumed and
1162  * unmaps all possible sections of the file
1163  */
1164 void
1165 mono_image_close (MonoImage *image)
1166 {
1167         MonoImage *image2;
1168         GHashTable *loaded_images, *loaded_images_guid;
1169         int i;
1170
1171         g_return_if_fail (image != NULL);
1172
1173         if (InterlockedDecrement (&image->ref_count) > 0)
1174                 return;
1175
1176         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1177
1178         mono_metadata_clean_for_image (image);
1179
1180         /*
1181          * The caches inside a MonoImage might refer to metadata which is stored in referenced 
1182          * assemblies, so we can't release these references in mono_assembly_close () since the
1183          * MonoImage might outlive its associated MonoAssembly.
1184          */
1185         if (image->references) {
1186                 int i;
1187
1188                 for (i = 0; image->references [i]; i++) {
1189                         if (image->references [i])
1190                                 mono_assembly_close (image->references [i]);
1191                 }
1192
1193                 g_free (image->references);
1194                 image->references = NULL;
1195         }
1196
1197         mono_images_lock ();
1198         loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1199         loaded_images_guid = image->ref_only ? loaded_images_refonly_guid_hash : loaded_images_guid_hash;
1200         image2 = g_hash_table_lookup (loaded_images, image->name);
1201         if (image == image2) {
1202                 /* This is not true if we are called from mono_image_open () */
1203                 g_hash_table_remove (loaded_images, image->name);
1204                 g_hash_table_remove (loaded_images_guid, image->guid);
1205         }
1206         if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1207                 g_hash_table_remove (loaded_images, (char *) image->assembly_name);     
1208
1209         /* Multiple images might have the same guid */
1210         build_guid_table (image->ref_only);
1211
1212         mono_images_unlock ();
1213
1214         if (image->file_descr) {
1215                 fclose (image->file_descr);
1216                 image->file_descr = NULL;
1217                 if (image->raw_data != NULL)
1218                         mono_raw_buffer_free (image->raw_data);
1219         }
1220         
1221         if (image->raw_data_allocated) {
1222                 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1223                 MonoCLIImageInfo *ii = image->image_info;
1224
1225                 if ((image->raw_metadata > image->raw_data) &&
1226                         (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1227                         image->raw_metadata = NULL;
1228
1229                 for (i = 0; i < ii->cli_section_count; i++)
1230                         if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1231                                 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1232                                 ii->cli_sections [i] = NULL;
1233
1234                 g_free (image->raw_data);
1235         }
1236
1237         if (debug_assembly_unload) {
1238                 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1239         } else {
1240                 g_free (image->name);
1241                 g_free (image->guid);
1242                 g_free (image->version);
1243                 g_free (image->files);
1244         }
1245
1246         g_hash_table_destroy (image->method_cache);
1247         mono_internal_hash_table_destroy (&image->class_cache);
1248         g_hash_table_destroy (image->field_cache);
1249         if (image->array_cache) {
1250                 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1251                 g_hash_table_destroy (image->array_cache);
1252         }
1253         if (image->ptr_cache)
1254                 g_hash_table_destroy (image->ptr_cache);
1255         if (image->name_cache) {
1256                 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1257                 g_hash_table_destroy (image->name_cache);
1258         }
1259         g_hash_table_destroy (image->native_wrapper_cache);
1260         g_hash_table_destroy (image->managed_wrapper_cache);
1261         g_hash_table_destroy (image->delegate_begin_invoke_cache);
1262         g_hash_table_destroy (image->delegate_end_invoke_cache);
1263         g_hash_table_destroy (image->delegate_invoke_cache);
1264         g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1265         g_hash_table_destroy (image->remoting_invoke_cache);
1266         g_hash_table_destroy (image->runtime_invoke_cache);
1267         g_hash_table_destroy (image->synchronized_cache);
1268         g_hash_table_destroy (image->unbox_wrapper_cache);
1269         g_hash_table_destroy (image->cominterop_invoke_cache);
1270         g_hash_table_destroy (image->cominterop_wrapper_cache);
1271         g_hash_table_destroy (image->typespec_cache);
1272         g_hash_table_destroy (image->ldfld_wrapper_cache);
1273         g_hash_table_destroy (image->ldflda_wrapper_cache);
1274         g_hash_table_destroy (image->ldfld_remote_wrapper_cache);
1275         g_hash_table_destroy (image->stfld_wrapper_cache);
1276         g_hash_table_destroy (image->stfld_remote_wrapper_cache);
1277         g_hash_table_destroy (image->isinst_cache);
1278         g_hash_table_destroy (image->castclass_cache);
1279         g_hash_table_destroy (image->proxy_isinst_cache);
1280
1281         /* The ownership of signatures is not well defined */
1282         //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1283         g_hash_table_destroy (image->memberref_signatures);
1284         //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1285         g_hash_table_destroy (image->helper_signatures);
1286         g_hash_table_destroy (image->method_signatures);
1287
1288         if (image->interface_bitset) {
1289                 mono_unload_interface_ids (image->interface_bitset);
1290                 mono_bitset_free (image->interface_bitset);
1291         }
1292         if (image->image_info){
1293                 MonoCLIImageInfo *ii = image->image_info;
1294
1295                 if (ii->cli_section_tables)
1296                         g_free (ii->cli_section_tables);
1297                 if (ii->cli_sections)
1298                         g_free (ii->cli_sections);
1299                 g_free (image->image_info);
1300         }
1301
1302         for (i = 0; i < image->module_count; ++i) {
1303                 if (image->modules [i])
1304                         mono_image_close (image->modules [i]);
1305         }
1306         if (image->modules)
1307                 g_free (image->modules);
1308         if (image->modules_loaded)
1309                 g_free (image->modules_loaded);
1310         if (image->references)
1311                 g_free (image->references);
1312         /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1313         if (!image->dynamic) {
1314                 if (debug_assembly_unload)
1315                         mono_mempool_invalidate (image->mempool);
1316                 else {
1317                         mono_mempool_destroy (image->mempool);
1318                         g_free (image);
1319                 }
1320         } else {
1321                 /* Dynamic images are GC_MALLOCed */
1322                 struct _MonoDynamicImage *di = (struct _MonoDynamicImage*)image;
1323                 int i;
1324                 g_free ((char*)image->module_name);
1325                 if (di->typespec)
1326                         g_hash_table_destroy (di->typespec);
1327                 if (di->typeref)
1328                         g_hash_table_destroy (di->typeref);
1329                 if (di->handleref)
1330                         g_hash_table_destroy (di->handleref);
1331                 if (di->tokens)
1332                         mono_g_hash_table_destroy (di->tokens);
1333                 if (di->blob_cache) {
1334                         g_hash_table_foreach (di->blob_cache, free_blob_cache_entry, NULL);
1335                         g_hash_table_destroy (di->blob_cache);
1336                 }
1337                 g_list_free (di->array_methods);
1338                 if (di->gen_params)
1339                         g_ptr_array_free (di->gen_params, TRUE);
1340                 if (di->token_fixups)
1341                         mono_g_hash_table_destroy (di->token_fixups);
1342                 if (di->method_to_table_idx)
1343                         g_hash_table_destroy (di->method_to_table_idx);
1344                 if (di->field_to_table_idx)
1345                         g_hash_table_destroy (di->field_to_table_idx);
1346                 if (di->method_aux_hash)
1347                         g_hash_table_destroy (di->method_aux_hash);
1348                 g_free (di->strong_name);
1349                 g_free (di->win32_res);
1350                 /*g_print ("string heap destroy for image %p\n", di);*/
1351                 mono_dynamic_stream_reset (&di->sheap);
1352                 mono_dynamic_stream_reset (&di->code);
1353                 mono_dynamic_stream_reset (&di->resources);
1354                 mono_dynamic_stream_reset (&di->us);
1355                 mono_dynamic_stream_reset (&di->blob);
1356                 mono_dynamic_stream_reset (&di->tstream);
1357                 mono_dynamic_stream_reset (&di->guid);
1358                 for (i = 0; i < MONO_TABLE_NUM; ++i) {
1359                         g_free (di->tables [i].values);
1360                 }
1361                 mono_mempool_destroy (image->mempool);
1362         }
1363 }
1364
1365 /** 
1366  * mono_image_strerror:
1367  * @status: an code indicating the result from a recent operation
1368  *
1369  * Returns: a string describing the error
1370  */
1371 const char *
1372 mono_image_strerror (MonoImageOpenStatus status)
1373 {
1374         switch (status){
1375         case MONO_IMAGE_OK:
1376                 return "success";
1377         case MONO_IMAGE_ERROR_ERRNO:
1378                 return strerror (errno);
1379         case MONO_IMAGE_IMAGE_INVALID:
1380                 return "File does not contain a valid CIL image";
1381         case MONO_IMAGE_MISSING_ASSEMBLYREF:
1382                 return "An assembly was referenced, but could not be found";
1383         }
1384         return "Internal error";
1385 }
1386
1387 static gpointer
1388 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1389                                guint32 lang_id, gunichar2 *name,
1390                                MonoPEResourceDirEntry *entry,
1391                                MonoPEResourceDir *root, guint32 level)
1392 {
1393         gboolean is_string, is_dir;
1394         guint32 name_offset, dir_offset;
1395
1396         /* Level 0 holds a directory entry for each type of resource
1397          * (identified by ID or name).
1398          *
1399          * Level 1 holds a directory entry for each named resource
1400          * item, and each "anonymous" item of a particular type of
1401          * resource.
1402          *
1403          * Level 2 holds a directory entry for each language pointing to
1404          * the actual data.
1405          */
1406         name_offset = GUINT32_FROM_LE (entry->name_offset) & 0x7fffffff;
1407         dir_offset = GUINT32_FROM_LE (entry->dir_offset) & 0x7fffffff;
1408
1409 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
1410         is_string = (GUINT32_FROM_LE (entry->name_offset) & 0x80000000) != 0;
1411         is_dir = (GUINT32_FROM_LE (entry->dir_offset) & 0x80000000) != 0;
1412 #else
1413         is_string = entry->name_is_string;
1414         is_dir = entry->is_dir;
1415 #endif
1416
1417         if(level==0) {
1418                 if((is_string==FALSE && name_offset!=res_id) ||
1419                    (is_string==TRUE)) {
1420                         return(NULL);
1421                 }
1422         } else if (level==1) {
1423 #if 0
1424                 if(name!=NULL &&
1425                    is_string==TRUE && name!=lookup (name_offset)) {
1426                         return(NULL);
1427                 }
1428 #endif
1429         } else if (level==2) {
1430                 if ((is_string == FALSE &&
1431                     name_offset != lang_id &&
1432                     lang_id != 0) ||
1433                    (is_string == TRUE)) {
1434                         return(NULL);
1435                 }
1436         } else {
1437                 g_assert_not_reached ();
1438         }
1439
1440         if(is_dir==TRUE) {
1441                 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1442                 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1443                 guint32 entries, i;
1444
1445                 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1446
1447                 for(i=0; i<entries; i++) {
1448                         MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1449                         gpointer ret;
1450                         
1451                         ret=mono_image_walk_resource_tree (info, res_id,
1452                                                            lang_id, name,
1453                                                            sub_entry, root,
1454                                                            level+1);
1455                         if(ret!=NULL) {
1456                                 return(ret);
1457                         }
1458                 }
1459
1460                 return(NULL);
1461         } else {
1462                 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
1463                 MonoPEResourceDataEntry *res;
1464
1465                 res = g_new0 (MonoPEResourceDataEntry, 1);
1466
1467                 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
1468                 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
1469                 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
1470                 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
1471
1472                 return (res);
1473         }
1474 }
1475
1476 /**
1477  * mono_image_lookup_resource:
1478  * @image: the image to look up the resource in
1479  * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1480  * @lang_id: The language id.
1481  * @name: the resource name to lookup.
1482  *
1483  * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1484  * of the given resource. The caller should free it using g_free () when no longer
1485  * needed.
1486  */
1487 gpointer
1488 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1489 {
1490         MonoCLIImageInfo *info;
1491         MonoDotNetHeader *header;
1492         MonoPEDatadir *datadir;
1493         MonoPEDirEntry *rsrc;
1494         MonoPEResourceDir *resource_dir;
1495         MonoPEResourceDirEntry *res_entries;
1496         guint32 entries, i;
1497
1498         if(image==NULL) {
1499                 return(NULL);
1500         }
1501
1502         info=image->image_info;
1503         if(info==NULL) {
1504                 return(NULL);
1505         }
1506
1507         header=&info->cli_header;
1508         if(header==NULL) {
1509                 return(NULL);
1510         }
1511
1512         datadir=&header->datadir;
1513         if(datadir==NULL) {
1514                 return(NULL);
1515         }
1516
1517         rsrc=&datadir->pe_resource_table;
1518         if(rsrc==NULL) {
1519                 return(NULL);
1520         }
1521
1522         resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1523         if(resource_dir==NULL) {
1524                 return(NULL);
1525         }
1526
1527         entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1528         res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1529         
1530         for(i=0; i<entries; i++) {
1531                 MonoPEResourceDirEntry *entry=&res_entries[i];
1532                 gpointer ret;
1533                 
1534                 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1535                                                    name, entry, resource_dir,
1536                                                    0);
1537                 if(ret!=NULL) {
1538                         return(ret);
1539                 }
1540         }
1541
1542         return(NULL);
1543 }
1544
1545 /** 
1546  * mono_image_get_entry_point:
1547  * @image: the image where the entry point will be looked up.
1548  *
1549  * Use this routine to determine the metadata token for method that
1550  * has been flagged as the entry point.
1551  *
1552  * Returns: the token for the entry point method in the image
1553  */
1554 guint32
1555 mono_image_get_entry_point (MonoImage *image)
1556 {
1557         return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1558 }
1559
1560 /**
1561  * mono_image_get_resource:
1562  * @image: the image where the resource will be looked up.
1563  * @offset: The offset to add to the resource
1564  * @size: a pointer to an int where the size of the resource will be stored
1565  *
1566  * This is a low-level routine that fetches a resource from the
1567  * metadata that starts at a given @offset.  The @size parameter is
1568  * filled with the data field as encoded in the metadata.
1569  *
1570  * Returns: the pointer to the resource whose offset is @offset.
1571  */
1572 const char*
1573 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1574 {
1575         MonoCLIImageInfo *iinfo = image->image_info;
1576         MonoCLIHeader *ch = &iinfo->cli_cli_header;
1577         const char* data;
1578
1579         if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1580                 return NULL;
1581         
1582         data = mono_image_rva_map (image, ch->ch_resources.rva);
1583         if (!data)
1584                 return NULL;
1585         data += offset;
1586         if (size)
1587                 *size = read32 (data);
1588         data += 4;
1589         return data;
1590 }
1591
1592 MonoImage*
1593 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1594 {
1595         char *base_dir, *name;
1596         MonoImage *res;
1597         MonoTableInfo  *t = &image->tables [MONO_TABLE_FILE];
1598         const char *fname;
1599         guint32 fname_id;
1600
1601         if (fileidx < 1 || fileidx > t->rows)
1602                 return NULL;
1603
1604         if (image->files && image->files [fileidx - 1])
1605                 return image->files [fileidx - 1];
1606
1607         if (!image->files)
1608                 image->files = g_new0 (MonoImage*, t->rows);
1609
1610         fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1611         fname = mono_metadata_string_heap (image, fname_id);
1612         base_dir = g_path_get_dirname (image->name);
1613         name = g_build_filename (base_dir, fname, NULL);
1614         res = mono_image_open (name, NULL);
1615         if (res) {
1616                 int i;
1617                 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1618                 res->assembly = image->assembly;
1619                 for (i = 0; i < res->module_count; ++i) {
1620                         if (res->modules [i] && !res->modules [i]->assembly)
1621                                 res->modules [i]->assembly = image->assembly;
1622                 }
1623
1624                 image->files [fileidx - 1] = res;
1625         }
1626         g_free (name);
1627         g_free (base_dir);
1628         return res;
1629 }
1630
1631 /**
1632  * mono_image_get_strong_name:
1633  * @image: a MonoImage
1634  * @size: a guint32 pointer, or NULL.
1635  *
1636  * If the image has a strong name, and @size is not NULL, the value
1637  * pointed to by size will have the size of the strong name.
1638  *
1639  * Returns: NULL if the image does not have a strong name, or a
1640  * pointer to the public key.
1641  */
1642 const char*
1643 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1644 {
1645         MonoCLIImageInfo *iinfo = image->image_info;
1646         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1647         const char* data;
1648
1649         if (!de->size || !de->rva)
1650                 return NULL;
1651         data = mono_image_rva_map (image, de->rva);
1652         if (!data)
1653                 return NULL;
1654         if (size)
1655                 *size = de->size;
1656         return data;
1657 }
1658
1659 /**
1660  * mono_image_strong_name_position:
1661  * @image: a MonoImage
1662  * @size: a guint32 pointer, or NULL.
1663  *
1664  * If the image has a strong name, and @size is not NULL, the value
1665  * pointed to by size will have the size of the strong name.
1666  *
1667  * Returns: the position within the image file where the strong name
1668  * is stored.
1669  */
1670 guint32
1671 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1672 {
1673         MonoCLIImageInfo *iinfo = image->image_info;
1674         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1675         const int top = iinfo->cli_section_count;
1676         MonoSectionTable *tables = iinfo->cli_section_tables;
1677         int i;
1678         guint32 addr = de->rva;
1679         
1680         if (size)
1681                 *size = de->size;
1682         if (!de->size || !de->rva)
1683                 return 0;
1684         for (i = 0; i < top; i++){
1685                 if ((addr >= tables->st_virtual_address) &&
1686                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
1687                         return tables->st_raw_data_ptr +
1688                                 (addr - tables->st_virtual_address);
1689                 }
1690                 tables++;
1691         }
1692
1693         return 0;
1694 }
1695
1696 /**
1697  * mono_image_get_public_key:
1698  * @image: a MonoImage
1699  * @size: a guint32 pointer, or NULL.
1700  *
1701  * This is used to obtain the public key in the @image.
1702  * 
1703  * If the image has a public key, and @size is not NULL, the value
1704  * pointed to by size will have the size of the public key.
1705  * 
1706  * Returns: NULL if the image does not have a public key, or a pointer
1707  * to the public key.
1708  */
1709 const char*
1710 mono_image_get_public_key (MonoImage *image, guint32 *size)
1711 {
1712         const char *pubkey;
1713         guint32 len, tok;
1714         if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1715                 return NULL;
1716         tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1717         if (!tok)
1718                 return NULL;
1719         pubkey = mono_metadata_blob_heap (image, tok);
1720         len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1721         if (size)
1722                 *size = len;
1723         return pubkey;
1724 }
1725
1726 /**
1727  * mono_image_get_name:
1728  * @name: a MonoImage
1729  *
1730  * Returns: the name of the assembly.
1731  */
1732 const char*
1733 mono_image_get_name (MonoImage *image)
1734 {
1735         return image->assembly_name;
1736 }
1737
1738 /**
1739  * mono_image_get_filename:
1740  * @image: a MonoImage
1741  *
1742  * Used to get the filename that hold the actual MonoImage
1743  *
1744  * Returns: the filename.
1745  */
1746 const char*
1747 mono_image_get_filename (MonoImage *image)
1748 {
1749         return image->name;
1750 }
1751
1752 const char*
1753 mono_image_get_guid (MonoImage *image)
1754 {
1755         return image->guid;
1756 }
1757
1758 const MonoTableInfo*
1759 mono_image_get_table_info (MonoImage *image, int table_id)
1760 {
1761         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1762                 return NULL;
1763         return &image->tables [table_id];
1764 }
1765
1766 int
1767 mono_image_get_table_rows (MonoImage *image, int table_id)
1768 {
1769         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1770                 return 0;
1771         return image->tables [table_id].rows;
1772 }
1773
1774 int
1775 mono_table_info_get_rows (const MonoTableInfo *table)
1776 {
1777         return table->rows;
1778 }
1779
1780 /**
1781  * mono_image_get_assembly:
1782  * @image: the MonoImage.
1783  *
1784  * Use this routine to get the assembly that owns this image.
1785  *
1786  * Returns: the assembly that holds this image.
1787  */
1788 MonoAssembly* 
1789 mono_image_get_assembly (MonoImage *image)
1790 {
1791         return image->assembly;
1792 }
1793
1794 /**
1795  * mono_image_is_dynamic:
1796  * @image: the MonoImage
1797  *
1798  * Determines if the given image was created dynamically through the
1799  * System.Reflection.Emit API
1800  *
1801  * Returns: TRUE if the image was created dynamically, FALSE if not.
1802  */
1803 gboolean
1804 mono_image_is_dynamic (MonoImage *image)
1805 {
1806         return image->dynamic;
1807 }
1808
1809 /**
1810  * mono_image_has_authenticode_entry:
1811  * @image: the MonoImage
1812  *
1813  * Use this routine to determine if the image has a Authenticode
1814  * Certificate Table.
1815  *
1816  * Returns: TRUE if the image contains an authenticode entry in the PE
1817  * directory.
1818  */
1819 gboolean
1820 mono_image_has_authenticode_entry (MonoImage *image)
1821 {
1822         MonoCLIImageInfo *iinfo = image->image_info;
1823         MonoDotNetHeader *header = &iinfo->cli_header;
1824         MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
1825         // the Authenticode "pre" (non ASN.1) header is 8 bytes long
1826         return ((de->rva != 0) && (de->size > 8));
1827 }