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