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