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