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