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