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