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