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