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