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