2010-01-03 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / metadata / image.c
1 /*
2  * image.c: Routines for manipulating an image stored in an
3  * extended PE/COFF file.
4  * 
5  * Authors:
6  *   Miguel de Icaza (miguel@ximian.com)
7  *   Paolo Molaro (lupus@ximian.com)
8  *
9  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
11  *
12  */
13 #include <config.h>
14 #include <stdio.h>
15 #include <glib.h>
16 #include <errno.h>
17 #include <time.h>
18 #include <string.h>
19 #include "image.h"
20 #include "cil-coff.h"
21 #include "mono-endian.h"
22 #include "tabledefs.h"
23 #include "tokentype.h"
24 #include "metadata-internals.h"
25 #include "profiler-private.h"
26 #include "loader.h"
27 #include "marshal.h"
28 #include "coree.h"
29 #include <mono/io-layer/io-layer.h>
30 #include <mono/utils/mono-logger.h>
31 #include <mono/utils/mono-path.h>
32 #include <mono/utils/mono-mmap.h>
33 #include <mono/utils/mono-io-portability.h>
34 #include <mono/metadata/class-internals.h>
35 #include <mono/metadata/assembly.h>
36 #include <mono/metadata/object-internals.h>
37 #include <mono/metadata/security-core-clr.h>
38 #include <mono/metadata/verify-internals.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #ifdef HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44
45 #define INVALID_ADDRESS 0xffffffff
46
47 /*
48  * Keeps track of the various assemblies loaded
49  */
50 static GHashTable *loaded_images_hash;
51 static GHashTable *loaded_images_refonly_hash;
52
53 static gboolean debug_assembly_unload = FALSE;
54
55 #define mono_images_lock() if (mutex_inited) EnterCriticalSection (&images_mutex)
56 #define mono_images_unlock() if (mutex_inited) LeaveCriticalSection (&images_mutex)
57 static gboolean mutex_inited;
58 static CRITICAL_SECTION images_mutex;
59
60 /* returns offset relative to image->raw_data */
61 guint32
62 mono_cli_rva_image_map (MonoImage *image, guint32 addr)
63 {
64         MonoCLIImageInfo *iinfo = image->image_info;
65         const int top = iinfo->cli_section_count;
66         MonoSectionTable *tables = iinfo->cli_section_tables;
67         int i;
68         
69         for (i = 0; i < top; i++){
70                 if ((addr >= tables->st_virtual_address) &&
71                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
72 #ifdef HOST_WIN32
73                         if (image->is_module_handle)
74                                 return addr;
75 #endif
76                         return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
77                 }
78                 tables++;
79         }
80         return INVALID_ADDRESS;
81 }
82
83 /**
84  * mono_images_rva_map:
85  * @image: a MonoImage
86  * @addr: relative virtual address (RVA)
87  *
88  * This is a low-level routine used by the runtime to map relative
89  * virtual address (RVA) into their location in memory. 
90  *
91  * Returns: the address in memory for the given RVA, or NULL if the
92  * RVA is not valid for this image. 
93  */
94 char *
95 mono_image_rva_map (MonoImage *image, guint32 addr)
96 {
97         MonoCLIImageInfo *iinfo = image->image_info;
98         const int top = iinfo->cli_section_count;
99         MonoSectionTable *tables = iinfo->cli_section_tables;
100         int i;
101         
102         for (i = 0; i < top; i++){
103                 if ((addr >= tables->st_virtual_address) &&
104                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
105                         if (!iinfo->cli_sections [i]) {
106                                 if (!mono_image_ensure_section_idx (image, i))
107                                         return NULL;
108                         }
109 #ifdef HOST_WIN32
110                         if (image->is_module_handle)
111                                 return image->raw_data + addr;
112 #endif
113                         return (char*)iinfo->cli_sections [i] +
114                                 (addr - tables->st_virtual_address);
115                 }
116                 tables++;
117         }
118         return NULL;
119 }
120
121 /**
122  * mono_images_init:
123  *
124  *  Initialize the global variables used by this module.
125  */
126 void
127 mono_images_init (void)
128 {
129         InitializeCriticalSection (&images_mutex);
130
131         loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
132         loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
133
134         debug_assembly_unload = g_getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
135
136         mutex_inited = TRUE;
137 }
138
139 /**
140  * mono_images_cleanup:
141  *
142  *  Free all resources used by this module.
143  */
144 void
145 mono_images_cleanup (void)
146 {
147         DeleteCriticalSection (&images_mutex);
148
149         g_hash_table_destroy (loaded_images_hash);
150         g_hash_table_destroy (loaded_images_refonly_hash);
151
152         mutex_inited = FALSE;
153 }
154
155 /**
156  * mono_image_ensure_section_idx:
157  * @image: The image we are operating on
158  * @section: section number that we will load/map into memory
159  *
160  * This routine makes sure that we have an in-memory copy of
161  * an image section (.text, .rsrc, .data).
162  *
163  * Returns: TRUE on success
164  */
165 int
166 mono_image_ensure_section_idx (MonoImage *image, int section)
167 {
168         MonoCLIImageInfo *iinfo = image->image_info;
169         MonoSectionTable *sect;
170         gboolean writable;
171         
172         g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
173
174         if (iinfo->cli_sections [section] != NULL)
175                 return TRUE;
176
177         sect = &iinfo->cli_section_tables [section];
178         
179         writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
180
181         if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
182                 return FALSE;
183 #ifdef HOST_WIN32
184         if (image->is_module_handle)
185                 iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address;
186         else
187 #endif
188         /* FIXME: we ignore the writable flag since we don't patch the binary */
189         iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
190         return TRUE;
191 }
192
193 /**
194  * mono_image_ensure_section:
195  * @image: The image we are operating on
196  * @section: section name that we will load/map into memory
197  *
198  * This routine makes sure that we have an in-memory copy of
199  * an image section (.text, .rsrc, .data).
200  *
201  * Returns: TRUE on success
202  */
203 int
204 mono_image_ensure_section (MonoImage *image, const char *section)
205 {
206         MonoCLIImageInfo *ii = image->image_info;
207         int i;
208         
209         for (i = 0; i < ii->cli_section_count; i++){
210                 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
211                         continue;
212                 
213                 return mono_image_ensure_section_idx (image, i);
214         }
215         return FALSE;
216 }
217
218 static int
219 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
220 {
221         const int top = iinfo->cli_header.coff.coff_sections;
222         int i;
223
224         iinfo->cli_section_count = top;
225         iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
226         iinfo->cli_sections = g_new0 (void *, top);
227         
228         for (i = 0; i < top; i++){
229                 MonoSectionTable *t = &iinfo->cli_section_tables [i];
230
231                 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
232                         return FALSE;
233                 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
234                 offset += sizeof (MonoSectionTable);
235
236 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
237                 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
238                 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
239                 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
240                 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
241                 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
242                 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
243                 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
244                 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
245                 t->st_flags = GUINT32_FROM_LE (t->st_flags);
246 #endif
247                 /* consistency checks here */
248         }
249
250         return TRUE;
251 }
252
253 static gboolean
254 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
255 {
256         guint32 offset;
257         
258         offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva);
259         if (offset == INVALID_ADDRESS)
260                 return FALSE;
261
262         if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
263                 return FALSE;
264         memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
265
266 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
267 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
268 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
269 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
270         SWAP32 (iinfo->cli_cli_header.ch_size);
271         SWAP32 (iinfo->cli_cli_header.ch_flags);
272         SWAP32 (iinfo->cli_cli_header.ch_entry_point);
273         SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
274         SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
275         SWAPPDE (iinfo->cli_cli_header.ch_metadata);
276         SWAPPDE (iinfo->cli_cli_header.ch_resources);
277         SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
278         SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
279         SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
280         SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
281         SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
282         SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
283         SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
284         SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
285         SWAPPDE (iinfo->cli_cli_header.ch_module_image);
286         SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
287         SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
288         SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
289         SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
290 #undef SWAP32
291 #undef SWAP16
292 #undef SWAPPDE
293 #endif
294         /* Catch new uses of the fields that are supposed to be zero */
295
296         if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
297             (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
298             (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
299             (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
300             (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
301             (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
302             (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
303             (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
304             (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
305
306                 /*
307                  * No need to scare people who are testing this, I am just
308                  * labelling this as a LAMESPEC
309                  */
310                 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
311
312         }
313             
314         return TRUE;
315 }
316
317 static gboolean
318 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
319 {
320         guint32 offset, size;
321         guint16 streams;
322         int i;
323         guint32 pad;
324         char *ptr;
325         
326         offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva);
327         if (offset == INVALID_ADDRESS)
328                 return FALSE;
329
330         size = iinfo->cli_cli_header.ch_metadata.size;
331
332         if (offset + size > image->raw_data_len)
333                 return FALSE;
334         image->raw_metadata = image->raw_data + offset;
335
336         /* 24.2.1: Metadata root starts here */
337         ptr = image->raw_metadata;
338
339         if (strncmp (ptr, "BSJB", 4) == 0){
340                 guint32 version_string_len;
341
342                 ptr += 4;
343                 image->md_version_major = read16 (ptr);
344                 ptr += 2;
345                 image->md_version_minor = read16 (ptr);
346                 ptr += 6;
347
348                 version_string_len = read32 (ptr);
349                 ptr += 4;
350                 image->version = g_strndup (ptr, version_string_len);
351                 ptr += version_string_len;
352                 pad = ptr - image->raw_metadata;
353                 if (pad % 4)
354                         ptr += 4 - (pad % 4);
355         } else
356                 return FALSE;
357
358         /* skip over flags */
359         ptr += 2;
360         
361         streams = read16 (ptr);
362         ptr += 2;
363
364         for (i = 0; i < streams; i++){
365                 if (strncmp (ptr + 8, "#~", 3) == 0){
366                         image->heap_tables.data = image->raw_metadata + read32 (ptr);
367                         image->heap_tables.size = read32 (ptr + 4);
368                         ptr += 8 + 3;
369                 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
370                         image->heap_strings.data = image->raw_metadata + read32 (ptr);
371                         image->heap_strings.size = read32 (ptr + 4);
372                         ptr += 8 + 9;
373                 } else if (strncmp (ptr + 8, "#US", 4) == 0){
374                         image->heap_us.data = image->raw_metadata + read32 (ptr);
375                         image->heap_us.size = read32 (ptr + 4);
376                         ptr += 8 + 4;
377                 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
378                         image->heap_blob.data = image->raw_metadata + read32 (ptr);
379                         image->heap_blob.size = read32 (ptr + 4);
380                         ptr += 8 + 6;
381                 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
382                         image->heap_guid.data = image->raw_metadata + read32 (ptr);
383                         image->heap_guid.size = read32 (ptr + 4);
384                         ptr += 8 + 6;
385                 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
386                         image->heap_tables.data = image->raw_metadata + read32 (ptr);
387                         image->heap_tables.size = read32 (ptr + 4);
388                         ptr += 8 + 3;
389                         image->uncompressed_metadata = TRUE;
390                         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);
391                 } else {
392                         g_message ("Unknown heap type: %s\n", ptr + 8);
393                         ptr += 8 + strlen (ptr + 8) + 1;
394                 }
395                 pad = ptr - image->raw_metadata;
396                 if (pad % 4)
397                         ptr += 4 - (pad % 4);
398         }
399
400         g_assert (image->heap_guid.data);
401         g_assert (image->heap_guid.size >= 16);
402
403         image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
404
405         return TRUE;
406 }
407
408 /*
409  * Load representation of logical metadata tables, from the "#~" stream
410  */
411 static gboolean
412 load_tables (MonoImage *image)
413 {
414         const char *heap_tables = image->heap_tables.data;
415         const guint32 *rows;
416         guint64 valid_mask, sorted_mask;
417         int valid = 0, table;
418         int heap_sizes;
419         
420         heap_sizes = heap_tables [6];
421         image->idx_string_wide = ((heap_sizes & 0x01) == 1);
422         image->idx_guid_wide   = ((heap_sizes & 0x02) == 2);
423         image->idx_blob_wide   = ((heap_sizes & 0x04) == 4);
424         
425         valid_mask = read64 (heap_tables + 8);
426         sorted_mask = read64 (heap_tables + 16);
427         rows = (const guint32 *) (heap_tables + 24);
428         
429         for (table = 0; table < 64; table++){
430                 if ((valid_mask & ((guint64) 1 << table)) == 0){
431                         if (table > MONO_TABLE_LAST)
432                                 continue;
433                         image->tables [table].rows = 0;
434                         continue;
435                 }
436                 if (table > MONO_TABLE_LAST) {
437                         g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
438                 } else {
439                         image->tables [table].rows = read32 (rows);
440                 }
441                 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
442                         g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
443                 }*/
444                 rows++;
445                 valid++;
446         }
447
448         image->tables_base = (heap_tables + 24) + (4 * valid);
449
450         /* They must be the same */
451         g_assert ((const void *) image->tables_base == (const void *) rows);
452
453         mono_metadata_compute_table_bases (image);
454         return TRUE;
455 }
456
457 static gboolean
458 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
459 {
460         if (!load_metadata_ptrs (image, iinfo))
461                 return FALSE;
462
463         return load_tables (image);
464 }
465
466 void
467 mono_image_check_for_module_cctor (MonoImage *image)
468 {
469         MonoTableInfo *t, *mt;
470         t = &image->tables [MONO_TABLE_TYPEDEF];
471         mt = &image->tables [MONO_TABLE_METHOD];
472         if (mono_framework_version () == 1) {
473                 image->checked_module_cctor = TRUE;
474                 return;
475         }
476         if (image->dynamic) {
477                 /* FIXME: */
478                 image->checked_module_cctor = TRUE;
479                 return;
480         }
481         if (t->rows >= 1) {
482                 guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
483                 const char *name = mono_metadata_string_heap (image, nameidx);
484                 if (strcmp (name, "<Module>") == 0) {
485                         guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
486                         guint32 last_method;
487                         if (t->rows > 1)
488                                 last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
489                         else 
490                                 last_method = mt->rows;
491                         for (; first_method < last_method; first_method++) {
492                                 nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
493                                 name = mono_metadata_string_heap (image, nameidx);
494                                 if (strcmp (name, ".cctor") == 0) {
495                                         image->has_module_cctor = TRUE;
496                                         image->checked_module_cctor = TRUE;
497                                         return;
498                                 }
499                         }
500                 }
501         }
502         image->has_module_cctor = FALSE;
503         image->checked_module_cctor = TRUE;
504 }
505
506 static void
507 load_modules (MonoImage *image)
508 {
509         MonoTableInfo *t;
510
511         if (image->modules)
512                 return;
513
514         t = &image->tables [MONO_TABLE_MODULEREF];
515         image->modules = g_new0 (MonoImage *, t->rows);
516         image->modules_loaded = g_new0 (gboolean, t->rows);
517         image->module_count = t->rows;
518 }
519
520 /**
521  * mono_image_load_module:
522  *
523  *   Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
524  * it cannot be loaded.
525  */
526 MonoImage*
527 mono_image_load_module (MonoImage *image, int idx)
528 {
529         MonoTableInfo *t;
530         MonoTableInfo *file_table;
531         int i;
532         char *base_dir;
533         gboolean refonly = image->ref_only;
534         GList *list_iter, *valid_modules = NULL;
535         MonoImageOpenStatus status;
536
537         if ((image->module_count == 0) || (idx > image->module_count))
538                 return NULL;
539         if (image->modules_loaded [idx - 1])
540                 return image->modules [idx - 1];
541
542         file_table = &image->tables [MONO_TABLE_FILE];
543         for (i = 0; i < file_table->rows; i++) {
544                 guint32 cols [MONO_FILE_SIZE];
545                 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
546                 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
547                         continue;
548                 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
549         }
550
551         t = &image->tables [MONO_TABLE_MODULEREF];
552         base_dir = g_path_get_dirname (image->name);
553
554         {
555                 char *module_ref;
556                 const char *name;
557                 guint32 cols [MONO_MODULEREF_SIZE];
558                 /* if there is no file table, we try to load the module... */
559                 int valid = file_table->rows == 0;
560
561                 mono_metadata_decode_row (t, idx - 1, cols, MONO_MODULEREF_SIZE);
562                 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
563                 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
564                         /* be safe with string dups, but we could just compare string indexes  */
565                         if (strcmp (list_iter->data, name) == 0) {
566                                 valid = TRUE;
567                                 break;
568                         }
569                 }
570                 if (valid) {
571                         module_ref = g_build_filename (base_dir, name, NULL);
572                         image->modules [idx - 1] = mono_image_open_full (module_ref, &status, refonly);
573                         if (image->modules [idx - 1]) {
574                                 mono_image_addref (image->modules [idx - 1]);
575                                 image->modules [idx - 1]->assembly = image->assembly;
576 #ifdef HOST_WIN32
577                                 if (image->modules [idx - 1]->is_module_handle)
578                                         mono_image_fixup_vtable (image->modules [idx - 1]);
579 #endif
580                                 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
581                         }
582                         g_free (module_ref);
583                 }
584         }
585
586         image->modules_loaded [idx - 1] = TRUE;
587
588         g_free (base_dir);
589         g_list_free (valid_modules);
590
591         return image->modules [idx - 1];
592 }
593
594 static gpointer
595 class_key_extract (gpointer value)
596 {
597         MonoClass *class = value;
598
599         return GUINT_TO_POINTER (class->type_token);
600 }
601
602 static gpointer*
603 class_next_value (gpointer value)
604 {
605         MonoClass *class = value;
606
607         return (gpointer*)&class->next_class_cache;
608 }
609
610 void
611 mono_image_init (MonoImage *image)
612 {
613         image->mempool = mono_mempool_new_size (512);
614         mono_internal_hash_table_init (&image->class_cache,
615                                        g_direct_hash,
616                                        class_key_extract,
617                                        class_next_value);
618         image->field_cache = g_hash_table_new (NULL, NULL);
619
620         image->typespec_cache = g_hash_table_new (NULL, NULL);
621         image->memberref_signatures = g_hash_table_new (NULL, NULL);
622         image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
623         image->method_signatures = g_hash_table_new (NULL, NULL);
624
625         image->property_hash = mono_property_hash_new ();
626         InitializeCriticalSection (&image->lock);
627         InitializeCriticalSection (&image->szarray_cache_lock);
628 }
629
630 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
631 #define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
632 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
633 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
634 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
635 #else
636 #define SWAP64(x)
637 #define SWAP32(x)
638 #define SWAP16(x)
639 #define SWAPPDE(x)
640 #endif
641
642 /*
643  * Returns < 0 to indicate an error.
644  */
645 static int
646 do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
647 {
648         MonoDotNetHeader64 header64;
649
650 #ifdef HOST_WIN32
651         if (!image->is_module_handle)
652 #endif
653         if (offset + sizeof (MonoDotNetHeader32) > image->raw_data_len)
654                 return -1;
655
656         memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
657
658         if (header->pesig [0] != 'P' || header->pesig [1] != 'E')
659                 return -1;
660
661         /* endian swap the fields common between PE and PE+ */
662         SWAP32 (header->coff.coff_time);
663         SWAP32 (header->coff.coff_symptr);
664         SWAP32 (header->coff.coff_symcount);
665         SWAP16 (header->coff.coff_machine);
666         SWAP16 (header->coff.coff_sections);
667         SWAP16 (header->coff.coff_opt_header_size);
668         SWAP16 (header->coff.coff_attributes);
669         /* MonoPEHeader */
670         SWAP32 (header->pe.pe_code_size);
671         SWAP32 (header->pe.pe_uninit_data_size);
672         SWAP32 (header->pe.pe_rva_entry_point);
673         SWAP32 (header->pe.pe_rva_code_base);
674         SWAP32 (header->pe.pe_rva_data_base);
675         SWAP16 (header->pe.pe_magic);
676
677         /* now we are ready for the basic tests */
678
679         if (header->pe.pe_magic == 0x10B) {
680                 offset += sizeof (MonoDotNetHeader);
681                 SWAP32 (header->pe.pe_data_size);
682                 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
683                         return -1;
684
685                 SWAP32  (header->nt.pe_image_base);     /* must be 0x400000 */
686                 SWAP32  (header->nt.pe_stack_reserve);
687                 SWAP32  (header->nt.pe_stack_commit);
688                 SWAP32  (header->nt.pe_heap_reserve);
689                 SWAP32  (header->nt.pe_heap_commit);
690         } else if (header->pe.pe_magic == 0x20B) {
691                 /* PE32+ file format */
692                 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
693                         return -1;
694                 memcpy (&header64, image->raw_data + offset, sizeof (MonoDotNetHeader64));
695                 offset += sizeof (MonoDotNetHeader64);
696                 /* copy the fields already swapped. the last field, pe_data_size, is missing */
697                 memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
698                 /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
699                  * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
700                  */
701                 SWAP64  (header64.nt.pe_image_base);
702                 header->nt.pe_image_base = header64.nt.pe_image_base;
703                 SWAP64  (header64.nt.pe_stack_reserve);
704                 header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
705                 SWAP64  (header64.nt.pe_stack_commit);
706                 header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
707                 SWAP64  (header64.nt.pe_heap_reserve);
708                 header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
709                 SWAP64  (header64.nt.pe_heap_commit);
710                 header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
711
712                 header->nt.pe_section_align = header64.nt.pe_section_align;
713                 header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
714                 header->nt.pe_os_major = header64.nt.pe_os_major;
715                 header->nt.pe_os_minor = header64.nt.pe_os_minor;
716                 header->nt.pe_user_major = header64.nt.pe_user_major;
717                 header->nt.pe_user_minor = header64.nt.pe_user_minor;
718                 header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
719                 header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
720                 header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
721                 header->nt.pe_image_size = header64.nt.pe_image_size;
722                 header->nt.pe_header_size = header64.nt.pe_header_size;
723                 header->nt.pe_checksum = header64.nt.pe_checksum;
724                 header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
725                 header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
726                 header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
727                 header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
728
729                 /* copy the datadir */
730                 memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
731         } else {
732                 return -1;
733         }
734
735         /* MonoPEHeaderNT: not used yet */
736         SWAP32  (header->nt.pe_section_align);       /* must be 8192 */
737         SWAP32  (header->nt.pe_file_alignment);      /* must be 512 or 4096 */
738         SWAP16  (header->nt.pe_os_major);            /* must be 4 */
739         SWAP16  (header->nt.pe_os_minor);            /* must be 0 */
740         SWAP16  (header->nt.pe_user_major);
741         SWAP16  (header->nt.pe_user_minor);
742         SWAP16  (header->nt.pe_subsys_major);
743         SWAP16  (header->nt.pe_subsys_minor);
744         SWAP32  (header->nt.pe_reserved_1);
745         SWAP32  (header->nt.pe_image_size);
746         SWAP32  (header->nt.pe_header_size);
747         SWAP32  (header->nt.pe_checksum);
748         SWAP16  (header->nt.pe_subsys_required);
749         SWAP16  (header->nt.pe_dll_flags);
750         SWAP32  (header->nt.pe_loader_flags);
751         SWAP32  (header->nt.pe_data_dir_count);
752
753         /* MonoDotNetHeader: mostly unused */
754         SWAPPDE (header->datadir.pe_export_table);
755         SWAPPDE (header->datadir.pe_import_table);
756         SWAPPDE (header->datadir.pe_resource_table);
757         SWAPPDE (header->datadir.pe_exception_table);
758         SWAPPDE (header->datadir.pe_certificate_table);
759         SWAPPDE (header->datadir.pe_reloc_table);
760         SWAPPDE (header->datadir.pe_debug);
761         SWAPPDE (header->datadir.pe_copyright);
762         SWAPPDE (header->datadir.pe_global_ptr);
763         SWAPPDE (header->datadir.pe_tls_table);
764         SWAPPDE (header->datadir.pe_load_config_table);
765         SWAPPDE (header->datadir.pe_bound_import);
766         SWAPPDE (header->datadir.pe_iat);
767         SWAPPDE (header->datadir.pe_delay_import_desc);
768         SWAPPDE (header->datadir.pe_cli_header);
769         SWAPPDE (header->datadir.pe_reserved);
770
771 #ifdef HOST_WIN32
772         if (image->is_module_handle)
773                 image->raw_data_len = header->nt.pe_image_size;
774 #endif
775
776         return offset;
777 }
778
779 gboolean
780 mono_image_load_pe_data (MonoImage *image)
781 {
782         MonoCLIImageInfo *iinfo;
783         MonoDotNetHeader *header;
784         MonoMSDOSHeader msdos;
785         gint32 offset = 0;
786
787         iinfo = image->image_info;
788         header = &iinfo->cli_header;
789
790 #ifdef HOST_WIN32
791         if (!image->is_module_handle)
792 #endif
793         if (offset + sizeof (msdos) > image->raw_data_len)
794                 goto invalid_image;
795         memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
796         
797         if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
798                 goto invalid_image;
799         
800         msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
801
802         offset = msdos.pe_offset;
803
804         offset = do_load_header (image, header, offset);
805         if (offset < 0)
806                 goto invalid_image;
807
808         /*
809          * this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
810          * we skip this test.
811         if (header->coff.coff_machine != 0x14c)
812                 goto invalid_image;
813         */
814
815 #if 0
816         /*
817          * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
818          * which produces binaries with 7.0.  From Sergey:
819          *
820          * The reason is that MSVC7 uses traditional compile/link
821          * sequence for CIL executables, and VS.NET (and Framework
822          * SDK) includes linker version 7, that puts 7.0 in this
823          * field.  That's why it's currently not possible to load VC
824          * binaries with Mono.  This field is pretty much meaningless
825          * anyway (what linker?).
826          */
827         if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
828                 goto invalid_image;
829 #endif
830
831         /*
832          * FIXME: byte swap all addresses here for header.
833          */
834         
835         if (!load_section_tables (image, iinfo, offset))
836                 goto invalid_image;
837
838         return TRUE;
839
840 invalid_image:
841         return FALSE;
842 }
843
844 gboolean
845 mono_image_load_cli_data (MonoImage *image)
846 {
847         MonoCLIImageInfo *iinfo;
848         MonoDotNetHeader *header;
849
850         iinfo = image->image_info;
851         header = &iinfo->cli_header;
852
853         /* Load the CLI header */
854         if (!load_cli_header (image, iinfo))
855                 return FALSE;
856
857         if (!load_metadata (image, iinfo))
858                 return FALSE;
859
860         return TRUE;
861 }
862
863 void
864 mono_image_load_names (MonoImage *image)
865 {
866         /* modules don't have an assembly table row */
867         if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
868                 image->assembly_name = mono_metadata_string_heap (image, 
869                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
870                                         0, MONO_ASSEMBLY_NAME));
871         }
872
873         image->module_name = mono_metadata_string_heap (image, 
874                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
875                                         0, MONO_MODULE_NAME));
876 }
877
878 static MonoImage *
879 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
880                     gboolean care_about_cli, gboolean care_about_pecoff)
881 {
882         MonoCLIImageInfo *iinfo;
883         MonoDotNetHeader *header;
884
885         mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
886
887         mono_image_init (image);
888
889         iinfo = image->image_info;
890         header = &iinfo->cli_header;
891                 
892         if (status)
893                 *status = MONO_IMAGE_IMAGE_INVALID;
894
895         if (care_about_pecoff == FALSE)
896                 goto done;
897
898         if (!mono_verifier_verify_pe_data (image, NULL))
899                 goto invalid_image;
900
901         if (!mono_image_load_pe_data (image))
902                 goto invalid_image;
903         
904         if (care_about_cli == FALSE) {
905                 goto done;
906         }
907
908         if (!mono_verifier_verify_cli_data (image, NULL))
909                 goto invalid_image;
910
911         if (!mono_image_load_cli_data (image))
912                 goto invalid_image;
913
914         if (!mono_verifier_verify_table_data (image, NULL))
915                 goto invalid_image;
916
917         mono_image_load_names (image);
918
919         load_modules (image);
920
921 done:
922         mono_profiler_module_loaded (image, MONO_PROFILE_OK);
923         if (status)
924                 *status = MONO_IMAGE_OK;
925
926         return image;
927
928 invalid_image:
929         mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
930         mono_image_close (image);
931                 return NULL;
932 }
933
934 static MonoImage *
935 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
936                     gboolean care_about_cli, gboolean care_about_pecoff, gboolean refonly)
937 {
938         MonoCLIImageInfo *iinfo;
939         MonoImage *image;
940         MonoFileMap *filed;
941
942         if ((filed = mono_file_map_open (fname)) == NULL){
943                 if (IS_PORTABILITY_SET) {
944                         gchar *ffname = mono_portability_find_file (fname, TRUE);
945                         if (ffname) {
946                                 filed = mono_file_map_open (ffname);
947                                 g_free (ffname);
948                         }
949                 }
950
951                 if (filed == NULL) {
952                         if (status)
953                                 *status = MONO_IMAGE_ERROR_ERRNO;
954                         return NULL;
955                 }
956         }
957
958         image = g_new0 (MonoImage, 1);
959         image->raw_buffer_used = TRUE;
960         image->raw_data_len = mono_file_map_size (filed);
961         image->raw_data = mono_file_map (image->raw_data_len, MONO_MMAP_READ|MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, &image->raw_data_handle);
962         if (!image->raw_data) {
963                 mono_file_map_close (filed);
964                 g_free (image);
965                 if (status)
966                         *status = MONO_IMAGE_IMAGE_INVALID;
967                 return NULL;
968         }
969         iinfo = g_new0 (MonoCLIImageInfo, 1);
970         image->image_info = iinfo;
971         image->name = mono_path_resolve_symlinks (fname);
972         image->ref_only = refonly;
973         image->ref_count = 1;
974         /* if MONO_SECURITY_MODE_CORE_CLR is set then determine if this image is platform code */
975         image->core_clr_platform_code = mono_security_core_clr_determine_platform_image (image);
976
977         mono_file_map_close (filed);
978         return do_mono_image_load (image, status, care_about_cli, care_about_pecoff);
979 }
980
981 MonoImage *
982 mono_image_loaded_full (const char *name, gboolean refonly)
983 {
984         MonoImage *res;
985         GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
986         
987         mono_images_lock ();
988         res = g_hash_table_lookup (loaded_images, name);
989         mono_images_unlock ();
990         return res;
991 }
992
993 /**
994  * mono_image_loaded:
995  * @name: name of the image to load
996  *
997  * This routine ensures that the given image is loaded.
998  *
999  * Returns: the loaded MonoImage, or NULL on failure.
1000  */
1001 MonoImage *
1002 mono_image_loaded (const char *name)
1003 {
1004         return mono_image_loaded_full (name, FALSE);
1005 }
1006
1007 typedef struct {
1008         MonoImage *res;
1009         const char* guid;
1010 } GuidData;
1011
1012 static void
1013 find_by_guid (gpointer key, gpointer val, gpointer user_data)
1014 {
1015         GuidData *data = user_data;
1016         MonoImage *image;
1017
1018         if (data->res)
1019                 return;
1020         image = val;
1021         if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
1022                 data->res = image;
1023 }
1024
1025 MonoImage *
1026 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
1027 {
1028         GuidData data;
1029         GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1030         data.res = NULL;
1031         data.guid = guid;
1032
1033         mono_images_lock ();
1034         g_hash_table_foreach (loaded_images, find_by_guid, &data);
1035         mono_images_unlock ();
1036         return data.res;
1037 }
1038
1039 MonoImage *
1040 mono_image_loaded_by_guid (const char *guid)
1041 {
1042         return mono_image_loaded_by_guid_full (guid, FALSE);
1043 }
1044
1045 static MonoImage *
1046 register_image (MonoImage *image)
1047 {
1048         MonoImage *image2;
1049         GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1050
1051         mono_images_lock ();
1052         image2 = g_hash_table_lookup (loaded_images, image->name);
1053
1054         if (image2) {
1055                 /* Somebody else beat us to it */
1056                 mono_image_addref (image2);
1057                 mono_images_unlock ();
1058                 mono_image_close (image);
1059                 return image2;
1060         }
1061         g_hash_table_insert (loaded_images, image->name, image);
1062         if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
1063                 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);      
1064         mono_images_unlock ();
1065
1066         return image;
1067 }
1068
1069 MonoImage *
1070 mono_image_open_from_data_with_name (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly, const char *name)
1071 {
1072         MonoCLIImageInfo *iinfo;
1073         MonoImage *image;
1074         char *datac;
1075
1076         if (!data || !data_len) {
1077                 if (status)
1078                         *status = MONO_IMAGE_IMAGE_INVALID;
1079                 return NULL;
1080         }
1081         datac = data;
1082         if (need_copy) {
1083                 datac = g_try_malloc (data_len);
1084                 if (!datac) {
1085                         if (status)
1086                                 *status = MONO_IMAGE_ERROR_ERRNO;
1087                         return NULL;
1088                 }
1089                 memcpy (datac, data, data_len);
1090         }
1091
1092         image = g_new0 (MonoImage, 1);
1093         image->raw_data = datac;
1094         image->raw_data_len = data_len;
1095         image->raw_data_allocated = need_copy;
1096         image->name = (name == NULL) ? g_strdup_printf ("data-%p", datac) : g_strdup(name);
1097         iinfo = g_new0 (MonoCLIImageInfo, 1);
1098         image->image_info = iinfo;
1099         image->ref_only = refonly;
1100
1101         image = do_mono_image_load (image, status, TRUE, TRUE);
1102         if (image == NULL)
1103                 return NULL;
1104
1105         return register_image (image);
1106 }
1107
1108 MonoImage *
1109 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1110 {
1111   return mono_image_open_from_data_with_name (data, data_len, need_copy, status, refonly, NULL);
1112 }
1113
1114 MonoImage *
1115 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1116 {
1117         return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1118 }
1119
1120 #ifdef HOST_WIN32
1121 /* fname is not duplicated. */
1122 MonoImage*
1123 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1124 {
1125         MonoImage* image;
1126         MonoCLIImageInfo* iinfo;
1127
1128         image = g_new0 (MonoImage, 1);
1129         image->raw_data = (char*) module_handle;
1130         image->is_module_handle = TRUE;
1131         iinfo = g_new0 (MonoCLIImageInfo, 1);
1132         image->image_info = iinfo;
1133         image->name = fname;
1134         image->ref_count = has_entry_point ? 0 : 1;
1135         image->has_entry_point = has_entry_point;
1136
1137         image = do_mono_image_load (image, status, TRUE, TRUE);
1138         if (image == NULL)
1139                 return NULL;
1140
1141         return register_image (image);
1142 }
1143 #endif
1144
1145 MonoImage *
1146 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1147 {
1148         MonoImage *image;
1149         GHashTable *loaded_images;
1150         char *absfname;
1151         
1152         g_return_val_if_fail (fname != NULL, NULL);
1153         
1154 #ifdef HOST_WIN32
1155         /* Load modules using LoadLibrary. */
1156         if (!refonly && coree_module_handle) {
1157                 HMODULE module_handle;
1158                 guint16 *fname_utf16;
1159                 DWORD last_error;
1160
1161                 absfname = mono_path_resolve_symlinks (fname);
1162                 fname_utf16 = NULL;
1163
1164                 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1165                 mono_images_lock ();
1166                 image = g_hash_table_lookup (loaded_images_hash, absfname);
1167                 if (image) {
1168                         g_assert (image->is_module_handle);
1169                         if (image->has_entry_point && image->ref_count == 0) {
1170                                 /* Increment reference count on images loaded outside of the runtime. */
1171                                 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1172                                 /* The image is already loaded because _CorDllMain removes images from the hash. */
1173                                 module_handle = LoadLibrary (fname_utf16);
1174                                 g_assert (module_handle == (HMODULE) image->raw_data);
1175                         }
1176                         mono_image_addref (image);
1177                         mono_images_unlock ();
1178                         if (fname_utf16)
1179                                 g_free (fname_utf16);
1180                         g_free (absfname);
1181                         return image;
1182                 }
1183
1184                 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1185                 module_handle = MonoLoadImage (fname_utf16);
1186                 if (status && module_handle == NULL)
1187                         last_error = GetLastError ();
1188
1189                 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1190                 image = g_hash_table_lookup (loaded_images_hash, absfname);
1191                 if (image)
1192                         mono_image_addref (image);
1193                 mono_images_unlock ();
1194
1195                 g_free (fname_utf16);
1196
1197                 if (module_handle == NULL) {
1198                         g_assert (!image);
1199                         g_free (absfname);
1200                         if (status) {
1201                                 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1202                                         *status = MONO_IMAGE_IMAGE_INVALID;
1203                                 else
1204                                         *status = MONO_IMAGE_ERROR_ERRNO;
1205                         }
1206                         return NULL;
1207                 }
1208
1209                 if (image) {
1210                         g_assert (image->is_module_handle);
1211                         g_assert (image->has_entry_point);
1212                         g_free (absfname);
1213                         return image;
1214                 }
1215
1216                 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1217         }
1218 #endif
1219
1220         absfname = mono_path_canonicalize (fname);
1221
1222         /*
1223          * The easiest solution would be to do all the loading inside the mutex,
1224          * but that would lead to scalability problems. So we let the loading
1225          * happen outside the mutex, and if multiple threads happen to load
1226          * the same image, we discard all but the first copy.
1227          */
1228         mono_images_lock ();
1229         loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1230         image = g_hash_table_lookup (loaded_images, absfname);
1231         g_free (absfname);
1232         
1233         if (image){
1234                 mono_image_addref (image);
1235                 mono_images_unlock ();
1236                 return image;
1237         }
1238         mono_images_unlock ();
1239
1240         image = do_mono_image_open (fname, status, TRUE, TRUE, refonly);
1241         if (image == NULL)
1242                 return NULL;
1243
1244         return register_image (image);
1245 }
1246
1247 /**
1248  * mono_image_open:
1249  * @fname: filename that points to the module we want to open
1250  * @status: An error condition is returned in this field
1251  *
1252  * Returns: An open image of type %MonoImage or NULL on error. 
1253  * The caller holds a temporary reference to the returned image which should be cleared 
1254  * when no longer needed by calling mono_image_close ().
1255  * if NULL, then check the value of @status for details on the error
1256  */
1257 MonoImage *
1258 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1259 {
1260         return mono_image_open_full (fname, status, FALSE);
1261 }
1262
1263 /**
1264  * mono_pe_file_open:
1265  * @fname: filename that points to the module we want to open
1266  * @status: An error condition is returned in this field
1267  *
1268  * Returns: An open image of type %MonoImage or NULL on error.  if
1269  * NULL, then check the value of @status for details on the error.
1270  * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1271  * It's just a PE file loader, used for FileVersionInfo.  It also does
1272  * not use the image cache.
1273  */
1274 MonoImage *
1275 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1276 {
1277         g_return_val_if_fail (fname != NULL, NULL);
1278         
1279         return(do_mono_image_open (fname, status, FALSE, TRUE, FALSE));
1280 }
1281
1282 /**
1283  * mono_image_open_raw
1284  * @fname: filename that points to the module we want to open
1285  * @status: An error condition is returned in this field
1286  * 
1287  * Returns an image without loading neither pe or cli data.
1288  * 
1289  * Use mono_image_load_pe_data and mono_image_load_cli_data to load them.  
1290  */
1291 MonoImage *
1292 mono_image_open_raw (const char *fname, MonoImageOpenStatus *status)
1293 {
1294         g_return_val_if_fail (fname != NULL, NULL);
1295         
1296         return(do_mono_image_open (fname, status, FALSE, FALSE, FALSE));
1297 }
1298
1299 void
1300 mono_image_fixup_vtable (MonoImage *image)
1301 {
1302 #ifdef HOST_WIN32
1303         MonoCLIImageInfo *iinfo;
1304         MonoPEDirEntry *de;
1305         MonoVTableFixup *vtfixup;
1306         int count;
1307         gpointer slot;
1308         guint16 slot_type;
1309         int slot_count;
1310
1311         g_assert (image->is_module_handle);
1312
1313         iinfo = image->image_info;
1314         de = &iinfo->cli_cli_header.ch_vtable_fixups;
1315         if (!de->rva || !de->size)
1316                 return;
1317         vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1318         if (!vtfixup)
1319                 return;
1320         
1321         count = de->size / sizeof (MonoVTableFixup);
1322         while (count--) {
1323                 if (!vtfixup->rva || !vtfixup->count)
1324                         continue;
1325
1326                 slot = mono_image_rva_map (image, vtfixup->rva);
1327                 g_assert (slot);
1328                 slot_type = vtfixup->type;
1329                 slot_count = vtfixup->count;
1330                 if (slot_type & VTFIXUP_TYPE_32BIT)
1331                         while (slot_count--) {
1332                                 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1333                                 slot = ((guint32*) slot) + 1;
1334                         }
1335                 else if (slot_type & VTFIXUP_TYPE_64BIT)
1336                         while (slot_count--) {
1337                                 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1338                                 slot = ((guint32*) slot) + 1;
1339                         }
1340                 else
1341                         g_assert_not_reached();
1342
1343                 vtfixup++;
1344         }
1345 #else
1346         g_assert_not_reached();
1347 #endif
1348 }
1349
1350 static void
1351 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1352 {
1353         g_hash_table_destroy ((GHashTable*)val);
1354 }
1355
1356 /*
1357 static void
1358 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1359 {
1360         mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1361 }
1362 */
1363
1364 static void
1365 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
1366 {
1367         g_free (val);
1368 }
1369
1370 static void
1371 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1372 {
1373         g_slist_free ((GSList*)val);
1374 }
1375
1376 /**
1377  * mono_image_addref:
1378  * @image: The image file we wish to add a reference to
1379  *
1380  *  Increases the reference count of an image.
1381  */
1382 void
1383 mono_image_addref (MonoImage *image)
1384 {
1385         InterlockedIncrement (&image->ref_count);
1386 }       
1387
1388 void
1389 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1390 {
1391         stream->alloc_size = stream->index = stream->offset = 0;
1392         g_free (stream->data);
1393         stream->data = NULL;
1394         if (stream->hash) {
1395                 g_hash_table_destroy (stream->hash);
1396                 stream->hash = NULL;
1397         }
1398 }
1399
1400 static inline void
1401 free_hash (GHashTable *hash)
1402 {
1403         if (hash)
1404                 g_hash_table_destroy (hash);
1405 }
1406
1407 /*
1408  * Returns whether mono_image_close_finish() must be called as well.
1409  * We must unload images in two steps because clearing the domain in
1410  * SGen requires the class metadata to be intact, but we need to free
1411  * the mono_g_hash_tables in case a collection occurs during domain
1412  * unloading and the roots would trip up the GC.
1413  */
1414 gboolean
1415 mono_image_close_except_pools (MonoImage *image)
1416 {
1417         MonoImage *image2;
1418         GHashTable *loaded_images;
1419         int i;
1420         GSList *free_list;
1421
1422         g_return_val_if_fail (image != NULL, FALSE);
1423
1424         /* 
1425          * Atomically decrement the refcount and remove ourselves from the hash tables, so
1426          * register_image () can't grab an image which is being closed.
1427          */
1428         mono_images_lock ();
1429
1430         if (InterlockedDecrement (&image->ref_count) > 0) {
1431                 mono_images_unlock ();
1432                 return FALSE;
1433         }
1434
1435         loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1436         image2 = g_hash_table_lookup (loaded_images, image->name);
1437         if (image == image2) {
1438                 /* This is not true if we are called from mono_image_open () */
1439                 g_hash_table_remove (loaded_images, image->name);
1440         }
1441         if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1442                 g_hash_table_remove (loaded_images, (char *) image->assembly_name);     
1443
1444         mono_images_unlock ();
1445
1446 #ifdef HOST_WIN32
1447         if (image->is_module_handle && image->has_entry_point) {
1448                 mono_images_lock ();
1449                 if (image->ref_count == 0) {
1450                         /* Image will be closed by _CorDllMain. */
1451                         FreeLibrary ((HMODULE) image->raw_data);
1452                         mono_images_unlock ();
1453                         return FALSE;
1454                 }
1455                 mono_images_unlock ();
1456         }
1457 #endif
1458
1459         mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1460
1461         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1462
1463         free_list = mono_metadata_clean_for_image (image);
1464
1465         /*
1466          * The caches inside a MonoImage might refer to metadata which is stored in referenced 
1467          * assemblies, so we can't release these references in mono_assembly_close () since the
1468          * MonoImage might outlive its associated MonoAssembly.
1469          */
1470         if (image->references && !image->dynamic) {
1471                 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1472                 int i;
1473
1474                 for (i = 0; i < t->rows; i++) {
1475                         if (image->references [i]) {
1476                                 if (!mono_assembly_close_except_image_pools (image->references [i]))
1477                                         image->references [i] = NULL;
1478                         }
1479                 }
1480         } else {
1481                 if (image->references) {
1482                         g_free (image->references);
1483                         image->references = NULL;
1484                 }
1485         }
1486
1487 #ifdef HOST_WIN32
1488         mono_images_lock ();
1489         if (image->is_module_handle && !image->has_entry_point)
1490                 FreeLibrary ((HMODULE) image->raw_data);
1491         mono_images_unlock ();
1492 #endif
1493
1494         if (image->raw_buffer_used) {
1495                 if (image->raw_data != NULL)
1496                         mono_file_unmap (image->raw_data, image->raw_data_handle);
1497         }
1498         
1499         if (image->raw_data_allocated) {
1500                 /* FIXME: do we need this? (image is disposed anyway) */
1501                 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1502                 MonoCLIImageInfo *ii = image->image_info;
1503
1504                 if ((image->raw_metadata > image->raw_data) &&
1505                         (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1506                         image->raw_metadata = NULL;
1507
1508                 for (i = 0; i < ii->cli_section_count; i++)
1509                         if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1510                                 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1511                                 ii->cli_sections [i] = NULL;
1512
1513                 g_free (image->raw_data);
1514         }
1515
1516         if (debug_assembly_unload) {
1517                 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1518         } else {
1519                 g_free (image->name);
1520                 g_free (image->guid);
1521                 g_free (image->version);
1522                 g_free (image->files);
1523         }
1524
1525         if (image->method_cache)
1526                 g_hash_table_destroy (image->method_cache);
1527         if (image->methodref_cache)
1528                 g_hash_table_destroy (image->methodref_cache);
1529         mono_internal_hash_table_destroy (&image->class_cache);
1530         g_hash_table_destroy (image->field_cache);
1531         if (image->array_cache) {
1532                 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1533                 g_hash_table_destroy (image->array_cache);
1534         }
1535         if (image->szarray_cache)
1536                 g_hash_table_destroy (image->szarray_cache);
1537         if (image->ptr_cache)
1538                 g_hash_table_destroy (image->ptr_cache);
1539         if (image->name_cache) {
1540                 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1541                 g_hash_table_destroy (image->name_cache);
1542         }
1543
1544         free_hash (image->native_wrapper_cache);
1545         free_hash (image->managed_wrapper_cache);
1546         free_hash (image->delegate_begin_invoke_cache);
1547         free_hash (image->delegate_end_invoke_cache);
1548         free_hash (image->delegate_invoke_cache);
1549         free_hash (image->delegate_abstract_invoke_cache);
1550         if (image->remoting_invoke_cache)
1551                 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1552         free_hash (image->remoting_invoke_cache);
1553         free_hash (image->runtime_invoke_cache);
1554         free_hash (image->runtime_invoke_direct_cache);
1555         free_hash (image->runtime_invoke_vcall_cache);
1556         free_hash (image->synchronized_cache);
1557         free_hash (image->unbox_wrapper_cache);
1558         free_hash (image->cominterop_invoke_cache);
1559         free_hash (image->cominterop_wrapper_cache);
1560         free_hash (image->typespec_cache);
1561         free_hash (image->ldfld_wrapper_cache);
1562         free_hash (image->ldflda_wrapper_cache);
1563         free_hash (image->stfld_wrapper_cache);
1564         free_hash (image->isinst_cache);
1565         free_hash (image->castclass_cache);
1566         free_hash (image->proxy_isinst_cache);
1567         free_hash (image->thunk_invoke_cache);
1568
1569         /* The ownership of signatures is not well defined */
1570         //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1571         g_hash_table_destroy (image->memberref_signatures);
1572         //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1573         g_hash_table_destroy (image->helper_signatures);
1574         g_hash_table_destroy (image->method_signatures);
1575
1576         if (image->generic_class_cache)
1577                 g_hash_table_destroy (image->generic_class_cache);
1578
1579         if (image->rgctx_template_hash)
1580                 g_hash_table_destroy (image->rgctx_template_hash);
1581
1582         if (image->property_hash)
1583                 mono_property_hash_destroy (image->property_hash);
1584
1585         g_slist_free (image->reflection_info_unregister_classes);
1586         image->reflection_info_unregister_classes = free_list;
1587
1588         if (image->interface_bitset) {
1589                 mono_unload_interface_ids (image->interface_bitset);
1590                 mono_bitset_free (image->interface_bitset);
1591         }
1592         if (image->image_info){
1593                 MonoCLIImageInfo *ii = image->image_info;
1594
1595                 if (ii->cli_section_tables)
1596                         g_free (ii->cli_section_tables);
1597                 if (ii->cli_sections)
1598                         g_free (ii->cli_sections);
1599                 g_free (image->image_info);
1600         }
1601
1602         for (i = 0; i < image->module_count; ++i) {
1603                 if (image->modules [i]) {
1604                         if (!mono_image_close_except_pools (image->modules [i]))
1605                                 image->modules [i] = NULL;
1606                 }
1607         }
1608         if (image->modules_loaded)
1609                 g_free (image->modules_loaded);
1610
1611         DeleteCriticalSection (&image->szarray_cache_lock);
1612         DeleteCriticalSection (&image->lock);
1613
1614         /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1615         if (image->dynamic) {
1616                 /* Dynamic images are GC_MALLOCed */
1617                 g_free ((char*)image->module_name);
1618                 mono_dynamic_image_free ((MonoDynamicImage*)image);
1619         }
1620
1621         mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1622
1623         return TRUE;
1624 }
1625
1626 void
1627 mono_image_close_finish (MonoImage *image)
1628 {
1629         int i;
1630         GSList *l;
1631
1632         for (l = image->reflection_info_unregister_classes; l; l = l->next)
1633                 g_free (l->data);
1634         g_slist_free (image->reflection_info_unregister_classes);
1635         image->reflection_info_unregister_classes = NULL;
1636
1637         if (image->references && !image->dynamic) {
1638                 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1639                 int i;
1640
1641                 for (i = 0; i < t->rows; i++) {
1642                         if (image->references [i])
1643                                 mono_assembly_close_finish (image->references [i]);
1644                 }
1645
1646                 g_free (image->references);
1647                 image->references = NULL;
1648         }
1649
1650         for (i = 0; i < image->module_count; ++i) {
1651                 if (image->modules [i])
1652                         mono_image_close_finish (image->modules [i]);
1653         }
1654         if (image->modules)
1655                 g_free (image->modules);
1656
1657         mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
1658
1659         if (!image->dynamic) {
1660                 if (debug_assembly_unload)
1661                         mono_mempool_invalidate (image->mempool);
1662                 else {
1663                         mono_mempool_destroy (image->mempool);
1664                         g_free (image);
1665                 }
1666         } else {
1667                 if (debug_assembly_unload)
1668                         mono_mempool_invalidate (image->mempool);
1669                 else
1670                         mono_mempool_destroy (image->mempool);
1671         }
1672 }
1673
1674 /**
1675  * mono_image_close:
1676  * @image: The image file we wish to close
1677  *
1678  * Closes an image file, deallocates all memory consumed and
1679  * unmaps all possible sections of the file
1680  */
1681 void
1682 mono_image_close (MonoImage *image)
1683 {
1684         if (mono_image_close_except_pools (image))
1685                 mono_image_close_finish (image);
1686 }
1687
1688 /** 
1689  * mono_image_strerror:
1690  * @status: an code indicating the result from a recent operation
1691  *
1692  * Returns: a string describing the error
1693  */
1694 const char *
1695 mono_image_strerror (MonoImageOpenStatus status)
1696 {
1697         switch (status){
1698         case MONO_IMAGE_OK:
1699                 return "success";
1700         case MONO_IMAGE_ERROR_ERRNO:
1701                 return strerror (errno);
1702         case MONO_IMAGE_IMAGE_INVALID:
1703                 return "File does not contain a valid CIL image";
1704         case MONO_IMAGE_MISSING_ASSEMBLYREF:
1705                 return "An assembly was referenced, but could not be found";
1706         }
1707         return "Internal error";
1708 }
1709
1710 static gpointer
1711 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1712                                guint32 lang_id, gunichar2 *name,
1713                                MonoPEResourceDirEntry *entry,
1714                                MonoPEResourceDir *root, guint32 level)
1715 {
1716         gboolean is_string, is_dir;
1717         guint32 name_offset, dir_offset;
1718
1719         /* Level 0 holds a directory entry for each type of resource
1720          * (identified by ID or name).
1721          *
1722          * Level 1 holds a directory entry for each named resource
1723          * item, and each "anonymous" item of a particular type of
1724          * resource.
1725          *
1726          * Level 2 holds a directory entry for each language pointing to
1727          * the actual data.
1728          */
1729         is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1730         name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1731
1732         is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1733         dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1734
1735         if(level==0) {
1736                 if (is_string)
1737                         return NULL;
1738         } else if (level==1) {
1739                 if (res_id != name_offset)
1740                         return NULL;
1741 #if 0
1742                 if(name!=NULL &&
1743                    is_string==TRUE && name!=lookup (name_offset)) {
1744                         return(NULL);
1745                 }
1746 #endif
1747         } else if (level==2) {
1748                 if (is_string == TRUE || (is_string == FALSE && lang_id != 0 && name_offset != lang_id))
1749                         return NULL;
1750         } else {
1751                 g_assert_not_reached ();
1752         }
1753
1754         if(is_dir==TRUE) {
1755                 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1756                 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1757                 guint32 entries, i;
1758
1759                 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1760
1761                 for(i=0; i<entries; i++) {
1762                         MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1763                         gpointer ret;
1764                         
1765                         ret=mono_image_walk_resource_tree (info, res_id,
1766                                                            lang_id, name,
1767                                                            sub_entry, root,
1768                                                            level+1);
1769                         if(ret!=NULL) {
1770                                 return(ret);
1771                         }
1772                 }
1773
1774                 return(NULL);
1775         } else {
1776                 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
1777                 MonoPEResourceDataEntry *res;
1778
1779                 res = g_new0 (MonoPEResourceDataEntry, 1);
1780
1781                 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
1782                 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
1783                 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
1784                 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
1785
1786                 return (res);
1787         }
1788 }
1789
1790 /**
1791  * mono_image_lookup_resource:
1792  * @image: the image to look up the resource in
1793  * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1794  * @lang_id: The language id.
1795  * @name: the resource name to lookup.
1796  *
1797  * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1798  * of the given resource. The caller should free it using g_free () when no longer
1799  * needed.
1800  */
1801 gpointer
1802 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1803 {
1804         MonoCLIImageInfo *info;
1805         MonoDotNetHeader *header;
1806         MonoPEDatadir *datadir;
1807         MonoPEDirEntry *rsrc;
1808         MonoPEResourceDir *resource_dir;
1809         MonoPEResourceDirEntry *res_entries;
1810         guint32 entries, i;
1811
1812         if(image==NULL) {
1813                 return(NULL);
1814         }
1815
1816         mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
1817
1818         info=image->image_info;
1819         if(info==NULL) {
1820                 return(NULL);
1821         }
1822
1823         header=&info->cli_header;
1824         if(header==NULL) {
1825                 return(NULL);
1826         }
1827
1828         datadir=&header->datadir;
1829         if(datadir==NULL) {
1830                 return(NULL);
1831         }
1832
1833         rsrc=&datadir->pe_resource_table;
1834         if(rsrc==NULL) {
1835                 return(NULL);
1836         }
1837
1838         resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1839         if(resource_dir==NULL) {
1840                 return(NULL);
1841         }
1842
1843         entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1844         res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1845         
1846         for(i=0; i<entries; i++) {
1847                 MonoPEResourceDirEntry *entry=&res_entries[i];
1848                 gpointer ret;
1849                 
1850                 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1851                                                    name, entry, resource_dir,
1852                                                    0);
1853                 if(ret!=NULL) {
1854                         return(ret);
1855                 }
1856         }
1857
1858         return(NULL);
1859 }
1860
1861 /** 
1862  * mono_image_get_entry_point:
1863  * @image: the image where the entry point will be looked up.
1864  *
1865  * Use this routine to determine the metadata token for method that
1866  * has been flagged as the entry point.
1867  *
1868  * Returns: the token for the entry point method in the image
1869  */
1870 guint32
1871 mono_image_get_entry_point (MonoImage *image)
1872 {
1873         return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1874 }
1875
1876 /**
1877  * mono_image_get_resource:
1878  * @image: the image where the resource will be looked up.
1879  * @offset: The offset to add to the resource
1880  * @size: a pointer to an int where the size of the resource will be stored
1881  *
1882  * This is a low-level routine that fetches a resource from the
1883  * metadata that starts at a given @offset.  The @size parameter is
1884  * filled with the data field as encoded in the metadata.
1885  *
1886  * Returns: the pointer to the resource whose offset is @offset.
1887  */
1888 const char*
1889 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1890 {
1891         MonoCLIImageInfo *iinfo = image->image_info;
1892         MonoCLIHeader *ch = &iinfo->cli_cli_header;
1893         const char* data;
1894
1895         if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1896                 return NULL;
1897         
1898         data = mono_image_rva_map (image, ch->ch_resources.rva);
1899         if (!data)
1900                 return NULL;
1901         data += offset;
1902         if (size)
1903                 *size = read32 (data);
1904         data += 4;
1905         return data;
1906 }
1907
1908 MonoImage*
1909 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1910 {
1911         char *base_dir, *name;
1912         MonoImage *res;
1913         MonoTableInfo  *t = &image->tables [MONO_TABLE_FILE];
1914         const char *fname;
1915         guint32 fname_id;
1916
1917         if (fileidx < 1 || fileidx > t->rows)
1918                 return NULL;
1919
1920         mono_loader_lock ();
1921         if (image->files && image->files [fileidx - 1]) {
1922                 mono_loader_unlock ();
1923                 return image->files [fileidx - 1];
1924         }
1925
1926         if (!image->files)
1927                 image->files = g_new0 (MonoImage*, t->rows);
1928
1929         fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1930         fname = mono_metadata_string_heap (image, fname_id);
1931         base_dir = g_path_get_dirname (image->name);
1932         name = g_build_filename (base_dir, fname, NULL);
1933         res = mono_image_open (name, NULL);
1934         if (res) {
1935                 int i;
1936                 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1937                 res->assembly = image->assembly;
1938                 for (i = 0; i < res->module_count; ++i) {
1939                         if (res->modules [i] && !res->modules [i]->assembly)
1940                                 res->modules [i]->assembly = image->assembly;
1941                 }
1942
1943                 image->files [fileidx - 1] = res;
1944 #ifdef HOST_WIN32
1945                 if (res->is_module_handle)
1946                         mono_image_fixup_vtable (res);
1947 #endif
1948         }
1949         mono_loader_unlock ();
1950         g_free (name);
1951         g_free (base_dir);
1952         return res;
1953 }
1954
1955 /**
1956  * mono_image_get_strong_name:
1957  * @image: a MonoImage
1958  * @size: a guint32 pointer, or NULL.
1959  *
1960  * If the image has a strong name, and @size is not NULL, the value
1961  * pointed to by size will have the size of the strong name.
1962  *
1963  * Returns: NULL if the image does not have a strong name, or a
1964  * pointer to the public key.
1965  */
1966 const char*
1967 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1968 {
1969         MonoCLIImageInfo *iinfo = image->image_info;
1970         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1971         const char* data;
1972
1973         if (!de->size || !de->rva)
1974                 return NULL;
1975         data = mono_image_rva_map (image, de->rva);
1976         if (!data)
1977                 return NULL;
1978         if (size)
1979                 *size = de->size;
1980         return data;
1981 }
1982
1983 /**
1984  * mono_image_strong_name_position:
1985  * @image: a MonoImage
1986  * @size: a guint32 pointer, or NULL.
1987  *
1988  * If the image has a strong name, and @size is not NULL, the value
1989  * pointed to by size will have the size of the strong name.
1990  *
1991  * Returns: the position within the image file where the strong name
1992  * is stored.
1993  */
1994 guint32
1995 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1996 {
1997         MonoCLIImageInfo *iinfo = image->image_info;
1998         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1999         guint32 pos;
2000
2001         if (size)
2002                 *size = de->size;
2003         if (!de->size || !de->rva)
2004                 return 0;
2005         pos = mono_cli_rva_image_map (image, de->rva);
2006         return pos == INVALID_ADDRESS ? 0 : pos;
2007 }
2008
2009 /**
2010  * mono_image_get_public_key:
2011  * @image: a MonoImage
2012  * @size: a guint32 pointer, or NULL.
2013  *
2014  * This is used to obtain the public key in the @image.
2015  * 
2016  * If the image has a public key, and @size is not NULL, the value
2017  * pointed to by size will have the size of the public key.
2018  * 
2019  * Returns: NULL if the image does not have a public key, or a pointer
2020  * to the public key.
2021  */
2022 const char*
2023 mono_image_get_public_key (MonoImage *image, guint32 *size)
2024 {
2025         const char *pubkey;
2026         guint32 len, tok;
2027
2028         if (image->dynamic) {
2029                 if (size)
2030                         *size = ((MonoDynamicImage*)image)->public_key_len;
2031                 return (char*)((MonoDynamicImage*)image)->public_key;
2032         }
2033         if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
2034                 return NULL;
2035         tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
2036         if (!tok)
2037                 return NULL;
2038         pubkey = mono_metadata_blob_heap (image, tok);
2039         len = mono_metadata_decode_blob_size (pubkey, &pubkey);
2040         if (size)
2041                 *size = len;
2042         return pubkey;
2043 }
2044
2045 /**
2046  * mono_image_get_name:
2047  * @name: a MonoImage
2048  *
2049  * Returns: the name of the assembly.
2050  */
2051 const char*
2052 mono_image_get_name (MonoImage *image)
2053 {
2054         return image->assembly_name;
2055 }
2056
2057 /**
2058  * mono_image_get_filename:
2059  * @image: a MonoImage
2060  *
2061  * Used to get the filename that hold the actual MonoImage
2062  *
2063  * Returns: the filename.
2064  */
2065 const char*
2066 mono_image_get_filename (MonoImage *image)
2067 {
2068         return image->name;
2069 }
2070
2071 const char*
2072 mono_image_get_guid (MonoImage *image)
2073 {
2074         return image->guid;
2075 }
2076
2077 const MonoTableInfo*
2078 mono_image_get_table_info (MonoImage *image, int table_id)
2079 {
2080         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2081                 return NULL;
2082         return &image->tables [table_id];
2083 }
2084
2085 int
2086 mono_image_get_table_rows (MonoImage *image, int table_id)
2087 {
2088         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2089                 return 0;
2090         return image->tables [table_id].rows;
2091 }
2092
2093 int
2094 mono_table_info_get_rows (const MonoTableInfo *table)
2095 {
2096         return table->rows;
2097 }
2098
2099 /**
2100  * mono_image_get_assembly:
2101  * @image: the MonoImage.
2102  *
2103  * Use this routine to get the assembly that owns this image.
2104  *
2105  * Returns: the assembly that holds this image.
2106  */
2107 MonoAssembly* 
2108 mono_image_get_assembly (MonoImage *image)
2109 {
2110         return image->assembly;
2111 }
2112
2113 /**
2114  * mono_image_is_dynamic:
2115  * @image: the MonoImage
2116  *
2117  * Determines if the given image was created dynamically through the
2118  * System.Reflection.Emit API
2119  *
2120  * Returns: TRUE if the image was created dynamically, FALSE if not.
2121  */
2122 gboolean
2123 mono_image_is_dynamic (MonoImage *image)
2124 {
2125         return image->dynamic;
2126 }
2127
2128 /**
2129  * mono_image_has_authenticode_entry:
2130  * @image: the MonoImage
2131  *
2132  * Use this routine to determine if the image has a Authenticode
2133  * Certificate Table.
2134  *
2135  * Returns: TRUE if the image contains an authenticode entry in the PE
2136  * directory.
2137  */
2138 gboolean
2139 mono_image_has_authenticode_entry (MonoImage *image)
2140 {
2141         MonoCLIImageInfo *iinfo = image->image_info;
2142         MonoDotNetHeader *header = &iinfo->cli_header;
2143         MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
2144         // the Authenticode "pre" (non ASN.1) header is 8 bytes long
2145         return ((de->rva != 0) && (de->size > 8));
2146 }
2147
2148 gpointer
2149 mono_image_alloc (MonoImage *image, guint size)
2150 {
2151         gpointer res;
2152
2153         mono_perfcounters->loader_bytes += size;
2154         mono_image_lock (image);
2155         res = mono_mempool_alloc (image->mempool, size);
2156         mono_image_unlock (image);
2157
2158         return res;
2159 }
2160
2161 gpointer
2162 mono_image_alloc0 (MonoImage *image, guint size)
2163 {
2164         gpointer res;
2165
2166         mono_perfcounters->loader_bytes += size;
2167         mono_image_lock (image);
2168         res = mono_mempool_alloc0 (image->mempool, size);
2169         mono_image_unlock (image);
2170
2171         return res;
2172 }
2173
2174 char*
2175 mono_image_strdup (MonoImage *image, const char *s)
2176 {
2177         char *res;
2178
2179         mono_perfcounters->loader_bytes += strlen (s);
2180         mono_image_lock (image);
2181         res = mono_mempool_strdup (image->mempool, s);
2182         mono_image_unlock (image);
2183
2184         return res;
2185 }
2186
2187 GList*
2188 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
2189 {
2190         GList *new_list;
2191         
2192         new_list = mono_image_alloc (image, sizeof (GList));
2193         new_list->data = data;
2194         new_list->prev = list ? list->prev : NULL;
2195     new_list->next = list;
2196
2197     if (new_list->prev)
2198             new_list->prev->next = new_list;
2199     if (list)
2200             list->prev = new_list;
2201
2202         return new_list;
2203 }
2204
2205 GSList*
2206 g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
2207 {
2208         GSList *new_list;
2209
2210         new_list = mono_image_alloc (image, sizeof (GSList));
2211         new_list->data = data;
2212         new_list->next = NULL;
2213
2214         return g_slist_concat (list, new_list);
2215 }
2216
2217 void
2218 mono_image_lock (MonoImage *image)
2219 {
2220         mono_locks_acquire (&image->lock, ImageDataLock);
2221 }
2222
2223 void
2224 mono_image_unlock (MonoImage *image)
2225 {
2226         mono_locks_release (&image->lock, ImageDataLock);
2227 }
2228
2229
2230 /**
2231  * mono_image_property_lookup:
2232  *
2233  * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
2234  *
2235  * LOCKING: Takes the image lock
2236  */
2237 gpointer 
2238 mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
2239 {
2240         gpointer res;
2241
2242         mono_image_lock (image);
2243         res = mono_property_hash_lookup (image->property_hash, subject, property);
2244         mono_image_unlock (image);
2245
2246         return res;
2247 }
2248
2249 /**
2250  * mono_image_property_insert:
2251  *
2252  * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2253  *
2254  * LOCKING: Takes the image lock
2255  */
2256 void
2257 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
2258 {
2259         mono_image_lock (image);
2260         mono_property_hash_insert (image->property_hash, subject, property, value);
2261         mono_image_unlock (image);
2262 }
2263
2264 /**
2265  * mono_image_property_remove:
2266  *
2267  * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2268  *
2269  * LOCKING: Takes the image lock
2270  */
2271 void
2272 mono_image_property_remove (MonoImage *image, gpointer subject)
2273 {
2274         mono_image_lock (image);
2275         mono_property_hash_remove_object (image->property_hash, subject);
2276         mono_image_unlock (image);
2277 }