e6312b4d71454089f839c970899671623bd4d091
[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 = g_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 void
857 mono_image_load_names (MonoImage *image)
858 {
859         /* modules don't have an assembly table row */
860         if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
861                 image->assembly_name = mono_metadata_string_heap (image, 
862                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
863                                         0, MONO_ASSEMBLY_NAME));
864         }
865
866         image->module_name = mono_metadata_string_heap (image, 
867                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
868                                         0, MONO_MODULE_NAME));
869 }
870
871 static MonoImage *
872 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
873                     gboolean care_about_cli, gboolean care_about_pecoff)
874 {
875         MonoCLIImageInfo *iinfo;
876         MonoDotNetHeader *header;
877
878         mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
879
880         mono_image_init (image);
881
882         iinfo = image->image_info;
883         header = &iinfo->cli_header;
884                 
885         if (status)
886                 *status = MONO_IMAGE_IMAGE_INVALID;
887
888         if (care_about_pecoff == FALSE)
889                 goto done;
890
891         if (!mono_verifier_verify_pe_data (image, NULL))
892                 goto invalid_image;
893
894         if (!mono_image_load_pe_data (image))
895                 goto invalid_image;
896         
897         if (care_about_cli == FALSE) {
898                 goto done;
899         }
900
901         if (!mono_verifier_verify_cli_data (image, NULL))
902                 goto invalid_image;
903
904         if (!mono_image_load_cli_data (image))
905                 goto invalid_image;
906
907         if (!mono_verifier_verify_table_data (image, NULL))
908                 goto invalid_image;
909
910         mono_image_load_names (image);
911
912         load_modules (image);
913
914 done:
915         mono_profiler_module_loaded (image, MONO_PROFILE_OK);
916         if (status)
917                 *status = MONO_IMAGE_OK;
918
919         return image;
920
921 invalid_image:
922         mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
923         mono_image_close (image);
924                 return NULL;
925 }
926
927 static MonoImage *
928 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
929                     gboolean care_about_cli, gboolean care_about_pecoff, gboolean refonly)
930 {
931         MonoCLIImageInfo *iinfo;
932         MonoImage *image;
933         MonoFileMap *filed;
934
935         if ((filed = mono_file_map_open (fname)) == NULL){
936                 if (IS_PORTABILITY_SET) {
937                         gchar *ffname = mono_portability_find_file (fname, TRUE);
938                         if (ffname) {
939                                 filed = mono_file_map_open (ffname);
940                                 g_free (ffname);
941                         }
942                 }
943
944                 if (filed == NULL) {
945                         if (status)
946                                 *status = MONO_IMAGE_ERROR_ERRNO;
947                         return NULL;
948                 }
949         }
950
951         image = g_new0 (MonoImage, 1);
952         image->raw_buffer_used = TRUE;
953         image->raw_data_len = mono_file_map_size (filed);
954         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);
955         if (!image->raw_data) {
956                 mono_file_map_close (filed);
957                 g_free (image);
958                 if (status)
959                         *status = MONO_IMAGE_IMAGE_INVALID;
960                 return NULL;
961         }
962         iinfo = g_new0 (MonoCLIImageInfo, 1);
963         image->image_info = iinfo;
964         image->name = mono_path_resolve_symlinks (fname);
965         image->ref_only = refonly;
966         image->ref_count = 1;
967         /* if MONO_SECURITY_MODE_CORE_CLR is set then determine if this image is platform code */
968         image->core_clr_platform_code = mono_security_core_clr_determine_platform_image (image);
969
970         mono_file_map_close (filed);
971         return do_mono_image_load (image, status, care_about_cli, care_about_pecoff);
972 }
973
974 MonoImage *
975 mono_image_loaded_full (const char *name, gboolean refonly)
976 {
977         MonoImage *res;
978         GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
979         
980         mono_images_lock ();
981         res = g_hash_table_lookup (loaded_images, name);
982         mono_images_unlock ();
983         return res;
984 }
985
986 /**
987  * mono_image_loaded:
988  * @name: name of the image to load
989  *
990  * This routine ensures that the given image is loaded.
991  *
992  * Returns: the loaded MonoImage, or NULL on failure.
993  */
994 MonoImage *
995 mono_image_loaded (const char *name)
996 {
997         return mono_image_loaded_full (name, FALSE);
998 }
999
1000 typedef struct {
1001         MonoImage *res;
1002         const char* guid;
1003 } GuidData;
1004
1005 static void
1006 find_by_guid (gpointer key, gpointer val, gpointer user_data)
1007 {
1008         GuidData *data = user_data;
1009         MonoImage *image;
1010
1011         if (data->res)
1012                 return;
1013         image = val;
1014         if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
1015                 data->res = image;
1016 }
1017
1018 MonoImage *
1019 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
1020 {
1021         GuidData data;
1022         GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1023         data.res = NULL;
1024         data.guid = guid;
1025
1026         mono_images_lock ();
1027         g_hash_table_foreach (loaded_images, find_by_guid, &data);
1028         mono_images_unlock ();
1029         return data.res;
1030 }
1031
1032 MonoImage *
1033 mono_image_loaded_by_guid (const char *guid)
1034 {
1035         return mono_image_loaded_by_guid_full (guid, FALSE);
1036 }
1037
1038 static MonoImage *
1039 register_image (MonoImage *image)
1040 {
1041         MonoImage *image2;
1042         GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1043
1044         mono_images_lock ();
1045         image2 = g_hash_table_lookup (loaded_images, image->name);
1046
1047         if (image2) {
1048                 /* Somebody else beat us to it */
1049                 mono_image_addref (image2);
1050                 mono_images_unlock ();
1051                 mono_image_close (image);
1052                 return image2;
1053         }
1054         g_hash_table_insert (loaded_images, image->name, image);
1055         if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
1056                 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);      
1057         mono_images_unlock ();
1058
1059         return image;
1060 }
1061
1062 MonoImage *
1063 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1064 {
1065         MonoCLIImageInfo *iinfo;
1066         MonoImage *image;
1067         char *datac;
1068
1069         if (!data || !data_len) {
1070                 if (status)
1071                         *status = MONO_IMAGE_IMAGE_INVALID;
1072                 return NULL;
1073         }
1074         datac = data;
1075         if (need_copy) {
1076                 datac = g_try_malloc (data_len);
1077                 if (!datac) {
1078                         if (status)
1079                                 *status = MONO_IMAGE_ERROR_ERRNO;
1080                         return NULL;
1081                 }
1082                 memcpy (datac, data, data_len);
1083         }
1084
1085         image = g_new0 (MonoImage, 1);
1086         image->raw_data = datac;
1087         image->raw_data_len = data_len;
1088         image->raw_data_allocated = need_copy;
1089         image->name = g_strdup_printf ("data-%p", datac);
1090         iinfo = g_new0 (MonoCLIImageInfo, 1);
1091         image->image_info = iinfo;
1092         image->ref_only = refonly;
1093
1094         image = do_mono_image_load (image, status, TRUE, TRUE);
1095         if (image == NULL)
1096                 return NULL;
1097
1098         return register_image (image);
1099 }
1100
1101 MonoImage *
1102 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1103 {
1104         return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1105 }
1106
1107 #ifdef PLATFORM_WIN32
1108 /* fname is not duplicated. */
1109 MonoImage*
1110 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1111 {
1112         MonoImage* image;
1113         MonoCLIImageInfo* iinfo;
1114
1115         image = g_new0 (MonoImage, 1);
1116         image->raw_data = (char*) module_handle;
1117         image->is_module_handle = TRUE;
1118         iinfo = g_new0 (MonoCLIImageInfo, 1);
1119         image->image_info = iinfo;
1120         image->name = fname;
1121         image->ref_count = has_entry_point ? 0 : 1;
1122         image->has_entry_point = has_entry_point;
1123
1124         image = do_mono_image_load (image, status, TRUE, TRUE);
1125         if (image == NULL)
1126                 return NULL;
1127
1128         return register_image (image);
1129 }
1130 #endif
1131
1132 MonoImage *
1133 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1134 {
1135         MonoImage *image;
1136         GHashTable *loaded_images;
1137         char *absfname;
1138         
1139         g_return_val_if_fail (fname != NULL, NULL);
1140         
1141 #ifdef PLATFORM_WIN32
1142         /* Load modules using LoadLibrary. */
1143         if (!refonly && coree_module_handle) {
1144                 HMODULE module_handle;
1145                 guint16 *fname_utf16;
1146                 DWORD last_error;
1147
1148                 absfname = mono_path_resolve_symlinks (fname);
1149                 fname_utf16 = NULL;
1150
1151                 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1152                 mono_images_lock ();
1153                 image = g_hash_table_lookup (loaded_images_hash, absfname);
1154                 if (image) {
1155                         g_assert (image->is_module_handle);
1156                         if (image->has_entry_point && image->ref_count == 0) {
1157                                 /* Increment reference count on images loaded outside of the runtime. */
1158                                 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1159                                 /* The image is already loaded because _CorDllMain removes images from the hash. */
1160                                 module_handle = LoadLibrary (fname_utf16);
1161                                 g_assert (module_handle == (HMODULE) image->raw_data);
1162                         }
1163                         mono_image_addref (image);
1164                         mono_images_unlock ();
1165                         if (fname_utf16)
1166                                 g_free (fname_utf16);
1167                         g_free (absfname);
1168                         return image;
1169                 }
1170
1171                 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1172                 module_handle = MonoLoadImage (fname_utf16);
1173                 if (status && module_handle == NULL)
1174                         last_error = GetLastError ();
1175
1176                 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1177                 image = g_hash_table_lookup (loaded_images_hash, absfname);
1178                 if (image)
1179                         mono_image_addref (image);
1180                 mono_images_unlock ();
1181
1182                 g_free (fname_utf16);
1183
1184                 if (module_handle == NULL) {
1185                         g_assert (!image);
1186                         g_free (absfname);
1187                         if (status) {
1188                                 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1189                                         *status = MONO_IMAGE_IMAGE_INVALID;
1190                                 else
1191                                         *status = MONO_IMAGE_ERROR_ERRNO;
1192                         }
1193                         return NULL;
1194                 }
1195
1196                 if (image) {
1197                         g_assert (image->is_module_handle);
1198                         g_assert (image->has_entry_point);
1199                         g_free (absfname);
1200                         return image;
1201                 }
1202
1203                 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1204         }
1205 #endif
1206
1207         absfname = mono_path_canonicalize (fname);
1208
1209         /*
1210          * The easiest solution would be to do all the loading inside the mutex,
1211          * but that would lead to scalability problems. So we let the loading
1212          * happen outside the mutex, and if multiple threads happen to load
1213          * the same image, we discard all but the first copy.
1214          */
1215         mono_images_lock ();
1216         loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1217         image = g_hash_table_lookup (loaded_images, absfname);
1218         g_free (absfname);
1219         
1220         if (image){
1221                 mono_image_addref (image);
1222                 mono_images_unlock ();
1223                 return image;
1224         }
1225         mono_images_unlock ();
1226
1227         image = do_mono_image_open (fname, status, TRUE, TRUE, refonly);
1228         if (image == NULL)
1229                 return NULL;
1230
1231         return register_image (image);
1232 }
1233
1234 /**
1235  * mono_image_open:
1236  * @fname: filename that points to the module we want to open
1237  * @status: An error condition is returned in this field
1238  *
1239  * Returns: An open image of type %MonoImage or NULL on error. 
1240  * The caller holds a temporary reference to the returned image which should be cleared 
1241  * when no longer needed by calling mono_image_close ().
1242  * if NULL, then check the value of @status for details on the error
1243  */
1244 MonoImage *
1245 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1246 {
1247         return mono_image_open_full (fname, status, FALSE);
1248 }
1249
1250 /**
1251  * mono_pe_file_open:
1252  * @fname: filename that points to the module we want to open
1253  * @status: An error condition is returned in this field
1254  *
1255  * Returns: An open image of type %MonoImage or NULL on error.  if
1256  * NULL, then check the value of @status for details on the error.
1257  * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1258  * It's just a PE file loader, used for FileVersionInfo.  It also does
1259  * not use the image cache.
1260  */
1261 MonoImage *
1262 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1263 {
1264         g_return_val_if_fail (fname != NULL, NULL);
1265         
1266         return(do_mono_image_open (fname, status, FALSE, TRUE, FALSE));
1267 }
1268
1269 /**
1270  * mono_image_open_raw
1271  * @fname: filename that points to the module we want to open
1272  * @status: An error condition is returned in this field
1273  * 
1274  * Returns an image without loading neither pe or cli data.
1275  * 
1276  * Use mono_image_load_pe_data and mono_image_load_cli_data to load them.  
1277  */
1278 MonoImage *
1279 mono_image_open_raw (const char *fname, MonoImageOpenStatus *status)
1280 {
1281         g_return_val_if_fail (fname != NULL, NULL);
1282         
1283         return(do_mono_image_open (fname, status, FALSE, FALSE, FALSE));
1284 }
1285
1286 void
1287 mono_image_fixup_vtable (MonoImage *image)
1288 {
1289 #ifdef PLATFORM_WIN32
1290         MonoCLIImageInfo *iinfo;
1291         MonoPEDirEntry *de;
1292         MonoVTableFixup *vtfixup;
1293         int count;
1294         gpointer slot;
1295         guint16 slot_type;
1296         int slot_count;
1297
1298         g_assert (image->is_module_handle);
1299
1300         iinfo = image->image_info;
1301         de = &iinfo->cli_cli_header.ch_vtable_fixups;
1302         if (!de->rva || !de->size)
1303                 return;
1304         vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1305         if (!vtfixup)
1306                 return;
1307         
1308         count = de->size / sizeof (MonoVTableFixup);
1309         while (count--) {
1310                 if (!vtfixup->rva || !vtfixup->count)
1311                         continue;
1312
1313                 slot = mono_image_rva_map (image, vtfixup->rva);
1314                 g_assert (slot);
1315                 slot_type = vtfixup->type;
1316                 slot_count = vtfixup->count;
1317                 if (slot_type & VTFIXUP_TYPE_32BIT)
1318                         while (slot_count--) {
1319                                 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1320                                 slot = ((guint32*) slot) + 1;
1321                         }
1322                 else if (slot_type & VTFIXUP_TYPE_64BIT)
1323                         while (slot_count--) {
1324                                 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1325                                 slot = ((guint32*) slot) + 1;
1326                         }
1327                 else
1328                         g_assert_not_reached();
1329
1330                 vtfixup++;
1331         }
1332 #else
1333         g_assert_not_reached();
1334 #endif
1335 }
1336
1337 static void
1338 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1339 {
1340         g_hash_table_destroy ((GHashTable*)val);
1341 }
1342
1343 /*
1344 static void
1345 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1346 {
1347         mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1348 }
1349 */
1350
1351 static void
1352 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
1353 {
1354         g_free (val);
1355 }
1356
1357 static void
1358 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1359 {
1360         g_slist_free ((GSList*)val);
1361 }
1362
1363 /**
1364  * mono_image_addref:
1365  * @image: The image file we wish to add a reference to
1366  *
1367  *  Increases the reference count of an image.
1368  */
1369 void
1370 mono_image_addref (MonoImage *image)
1371 {
1372         InterlockedIncrement (&image->ref_count);
1373 }       
1374
1375 void
1376 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1377 {
1378         stream->alloc_size = stream->index = stream->offset = 0;
1379         g_free (stream->data);
1380         stream->data = NULL;
1381         if (stream->hash) {
1382                 g_hash_table_destroy (stream->hash);
1383                 stream->hash = NULL;
1384         }
1385 }
1386
1387 static inline void
1388 free_hash (GHashTable *hash)
1389 {
1390         if (hash)
1391                 g_hash_table_destroy (hash);
1392 }
1393
1394 /**
1395  * mono_image_close:
1396  * @image: The image file we wish to close
1397  *
1398  * Closes an image file, deallocates all memory consumed and
1399  * unmaps all possible sections of the file
1400  */
1401 void
1402 mono_image_close (MonoImage *image)
1403 {
1404         MonoImage *image2;
1405         GHashTable *loaded_images;
1406         int i;
1407
1408         g_return_if_fail (image != NULL);
1409
1410         if (InterlockedDecrement (&image->ref_count) > 0)
1411                 return;
1412
1413 #ifdef PLATFORM_WIN32
1414         if (image->is_module_handle && image->has_entry_point) {
1415                 mono_images_lock ();
1416                 if (image->ref_count == 0) {
1417                         /* Image will be closed by _CorDllMain. */
1418                         FreeLibrary ((HMODULE) image->raw_data);
1419                         mono_images_unlock ();
1420                         return;
1421                 }
1422                 mono_images_unlock ();
1423         }
1424 #endif
1425
1426         mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1427
1428         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1429
1430         mono_metadata_clean_for_image (image);
1431
1432         /*
1433          * The caches inside a MonoImage might refer to metadata which is stored in referenced 
1434          * assemblies, so we can't release these references in mono_assembly_close () since the
1435          * MonoImage might outlive its associated MonoAssembly.
1436          */
1437         if (image->references && !image->dynamic) {
1438                 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1439                 int i;
1440
1441                 for (i = 0; i < t->rows; i++) {
1442                         if (image->references [i])
1443                                 mono_assembly_close (image->references [i]);
1444                 }
1445
1446                 g_free (image->references);
1447                 image->references = NULL;
1448         }
1449
1450         mono_images_lock ();
1451         loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1452         image2 = g_hash_table_lookup (loaded_images, image->name);
1453         if (image == image2) {
1454                 /* This is not true if we are called from mono_image_open () */
1455                 g_hash_table_remove (loaded_images, image->name);
1456         }
1457         if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1458                 g_hash_table_remove (loaded_images, (char *) image->assembly_name);     
1459
1460 #ifdef PLATFORM_WIN32
1461         if (image->is_module_handle && !image->has_entry_point)
1462                 FreeLibrary ((HMODULE) image->raw_data);
1463 #endif
1464
1465         mono_images_unlock ();
1466
1467         if (image->raw_buffer_used) {
1468                 if (image->raw_data != NULL)
1469                         mono_file_unmap (image->raw_data, image->raw_data_handle);
1470         }
1471         
1472         if (image->raw_data_allocated) {
1473                 /* FIXME: do we need this? (image is disposed anyway) */
1474                 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1475                 MonoCLIImageInfo *ii = image->image_info;
1476
1477                 if ((image->raw_metadata > image->raw_data) &&
1478                         (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1479                         image->raw_metadata = NULL;
1480
1481                 for (i = 0; i < ii->cli_section_count; i++)
1482                         if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1483                                 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1484                                 ii->cli_sections [i] = NULL;
1485
1486                 g_free (image->raw_data);
1487         }
1488
1489         if (debug_assembly_unload) {
1490                 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1491         } else {
1492                 g_free (image->name);
1493                 g_free (image->guid);
1494                 g_free (image->version);
1495                 g_free (image->files);
1496         }
1497
1498         if (image->method_cache)
1499                 mono_value_hash_table_destroy (image->method_cache);
1500         if (image->methodref_cache)
1501                 g_hash_table_destroy (image->methodref_cache);
1502         mono_internal_hash_table_destroy (&image->class_cache);
1503         g_hash_table_destroy (image->field_cache);
1504         if (image->array_cache) {
1505                 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1506                 g_hash_table_destroy (image->array_cache);
1507         }
1508         if (image->szarray_cache)
1509                 g_hash_table_destroy (image->szarray_cache);
1510         if (image->ptr_cache)
1511                 g_hash_table_destroy (image->ptr_cache);
1512         if (image->name_cache) {
1513                 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1514                 g_hash_table_destroy (image->name_cache);
1515         }
1516
1517         free_hash (image->native_wrapper_cache);
1518         free_hash (image->managed_wrapper_cache);
1519         free_hash (image->delegate_begin_invoke_cache);
1520         free_hash (image->delegate_end_invoke_cache);
1521         free_hash (image->delegate_invoke_cache);
1522         free_hash (image->delegate_abstract_invoke_cache);
1523         if (image->remoting_invoke_cache)
1524                 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1525         free_hash (image->remoting_invoke_cache);
1526         free_hash (image->runtime_invoke_cache);
1527         free_hash (image->runtime_invoke_direct_cache);
1528         free_hash (image->runtime_invoke_vcall_cache);
1529         free_hash (image->synchronized_cache);
1530         free_hash (image->unbox_wrapper_cache);
1531         free_hash (image->cominterop_invoke_cache);
1532         free_hash (image->cominterop_wrapper_cache);
1533         free_hash (image->typespec_cache);
1534         free_hash (image->ldfld_wrapper_cache);
1535         free_hash (image->ldflda_wrapper_cache);
1536         free_hash (image->stfld_wrapper_cache);
1537         free_hash (image->isinst_cache);
1538         free_hash (image->castclass_cache);
1539         free_hash (image->proxy_isinst_cache);
1540         free_hash (image->thunk_invoke_cache);
1541
1542         /* The ownership of signatures is not well defined */
1543         //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1544         g_hash_table_destroy (image->memberref_signatures);
1545         //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1546         g_hash_table_destroy (image->helper_signatures);
1547         g_hash_table_destroy (image->method_signatures);
1548
1549         if (image->generic_class_cache)
1550                 g_hash_table_destroy (image->generic_class_cache);
1551
1552         if (image->rgctx_template_hash)
1553                 g_hash_table_destroy (image->rgctx_template_hash);
1554
1555         if (image->property_hash)
1556                 mono_property_hash_destroy (image->property_hash);
1557
1558         g_slist_free (image->reflection_info_unregister_classes);
1559
1560         if (image->interface_bitset) {
1561                 mono_unload_interface_ids (image->interface_bitset);
1562                 mono_bitset_free (image->interface_bitset);
1563         }
1564         if (image->image_info){
1565                 MonoCLIImageInfo *ii = image->image_info;
1566
1567                 if (ii->cli_section_tables)
1568                         g_free (ii->cli_section_tables);
1569                 if (ii->cli_sections)
1570                         g_free (ii->cli_sections);
1571                 g_free (image->image_info);
1572         }
1573
1574         for (i = 0; i < image->module_count; ++i) {
1575                 if (image->modules [i])
1576                         mono_image_close (image->modules [i]);
1577         }
1578         if (image->modules)
1579                 g_free (image->modules);
1580         if (image->modules_loaded)
1581                 g_free (image->modules_loaded);
1582         if (image->references)
1583                 g_free (image->references);
1584         mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
1585
1586         DeleteCriticalSection (&image->szarray_cache_lock);
1587         DeleteCriticalSection (&image->lock);
1588
1589         /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1590         if (!image->dynamic) {
1591                 if (debug_assembly_unload)
1592                         mono_mempool_invalidate (image->mempool);
1593                 else {
1594                         mono_mempool_destroy (image->mempool);
1595                         g_free (image);
1596                 }
1597         } else {
1598                 /* Dynamic images are GC_MALLOCed */
1599                 g_free ((char*)image->module_name);
1600                 mono_dynamic_image_free ((MonoDynamicImage*)image);
1601                 if (debug_assembly_unload)
1602                         mono_mempool_invalidate (image->mempool);
1603                 else
1604                         mono_mempool_destroy (image->mempool);
1605         }
1606
1607         mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1608 }
1609
1610 /** 
1611  * mono_image_strerror:
1612  * @status: an code indicating the result from a recent operation
1613  *
1614  * Returns: a string describing the error
1615  */
1616 const char *
1617 mono_image_strerror (MonoImageOpenStatus status)
1618 {
1619         switch (status){
1620         case MONO_IMAGE_OK:
1621                 return "success";
1622         case MONO_IMAGE_ERROR_ERRNO:
1623                 return strerror (errno);
1624         case MONO_IMAGE_IMAGE_INVALID:
1625                 return "File does not contain a valid CIL image";
1626         case MONO_IMAGE_MISSING_ASSEMBLYREF:
1627                 return "An assembly was referenced, but could not be found";
1628         }
1629         return "Internal error";
1630 }
1631
1632 static gpointer
1633 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1634                                guint32 lang_id, gunichar2 *name,
1635                                MonoPEResourceDirEntry *entry,
1636                                MonoPEResourceDir *root, guint32 level)
1637 {
1638         gboolean is_string, is_dir;
1639         guint32 name_offset, dir_offset;
1640
1641         /* Level 0 holds a directory entry for each type of resource
1642          * (identified by ID or name).
1643          *
1644          * Level 1 holds a directory entry for each named resource
1645          * item, and each "anonymous" item of a particular type of
1646          * resource.
1647          *
1648          * Level 2 holds a directory entry for each language pointing to
1649          * the actual data.
1650          */
1651         is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1652         name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1653
1654         is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1655         dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1656
1657         if(level==0) {
1658                 if (is_string)
1659                         return NULL;
1660         } else if (level==1) {
1661                 if (res_id != name_offset)
1662                         return NULL;
1663 #if 0
1664                 if(name!=NULL &&
1665                    is_string==TRUE && name!=lookup (name_offset)) {
1666                         return(NULL);
1667                 }
1668 #endif
1669         } else if (level==2) {
1670                 if (is_string == TRUE || (is_string == FALSE && lang_id != 0 && name_offset != lang_id))
1671                         return NULL;
1672         } else {
1673                 g_assert_not_reached ();
1674         }
1675
1676         if(is_dir==TRUE) {
1677                 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1678                 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1679                 guint32 entries, i;
1680
1681                 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1682
1683                 for(i=0; i<entries; i++) {
1684                         MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1685                         gpointer ret;
1686                         
1687                         ret=mono_image_walk_resource_tree (info, res_id,
1688                                                            lang_id, name,
1689                                                            sub_entry, root,
1690                                                            level+1);
1691                         if(ret!=NULL) {
1692                                 return(ret);
1693                         }
1694                 }
1695
1696                 return(NULL);
1697         } else {
1698                 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
1699                 MonoPEResourceDataEntry *res;
1700
1701                 res = g_new0 (MonoPEResourceDataEntry, 1);
1702
1703                 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
1704                 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
1705                 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
1706                 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
1707
1708                 return (res);
1709         }
1710 }
1711
1712 /**
1713  * mono_image_lookup_resource:
1714  * @image: the image to look up the resource in
1715  * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1716  * @lang_id: The language id.
1717  * @name: the resource name to lookup.
1718  *
1719  * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1720  * of the given resource. The caller should free it using g_free () when no longer
1721  * needed.
1722  */
1723 gpointer
1724 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1725 {
1726         MonoCLIImageInfo *info;
1727         MonoDotNetHeader *header;
1728         MonoPEDatadir *datadir;
1729         MonoPEDirEntry *rsrc;
1730         MonoPEResourceDir *resource_dir;
1731         MonoPEResourceDirEntry *res_entries;
1732         guint32 entries, i;
1733
1734         if(image==NULL) {
1735                 return(NULL);
1736         }
1737
1738         mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
1739
1740         info=image->image_info;
1741         if(info==NULL) {
1742                 return(NULL);
1743         }
1744
1745         header=&info->cli_header;
1746         if(header==NULL) {
1747                 return(NULL);
1748         }
1749
1750         datadir=&header->datadir;
1751         if(datadir==NULL) {
1752                 return(NULL);
1753         }
1754
1755         rsrc=&datadir->pe_resource_table;
1756         if(rsrc==NULL) {
1757                 return(NULL);
1758         }
1759
1760         resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1761         if(resource_dir==NULL) {
1762                 return(NULL);
1763         }
1764
1765         entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1766         res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1767         
1768         for(i=0; i<entries; i++) {
1769                 MonoPEResourceDirEntry *entry=&res_entries[i];
1770                 gpointer ret;
1771                 
1772                 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1773                                                    name, entry, resource_dir,
1774                                                    0);
1775                 if(ret!=NULL) {
1776                         return(ret);
1777                 }
1778         }
1779
1780         return(NULL);
1781 }
1782
1783 /** 
1784  * mono_image_get_entry_point:
1785  * @image: the image where the entry point will be looked up.
1786  *
1787  * Use this routine to determine the metadata token for method that
1788  * has been flagged as the entry point.
1789  *
1790  * Returns: the token for the entry point method in the image
1791  */
1792 guint32
1793 mono_image_get_entry_point (MonoImage *image)
1794 {
1795         return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1796 }
1797
1798 /**
1799  * mono_image_get_resource:
1800  * @image: the image where the resource will be looked up.
1801  * @offset: The offset to add to the resource
1802  * @size: a pointer to an int where the size of the resource will be stored
1803  *
1804  * This is a low-level routine that fetches a resource from the
1805  * metadata that starts at a given @offset.  The @size parameter is
1806  * filled with the data field as encoded in the metadata.
1807  *
1808  * Returns: the pointer to the resource whose offset is @offset.
1809  */
1810 const char*
1811 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1812 {
1813         MonoCLIImageInfo *iinfo = image->image_info;
1814         MonoCLIHeader *ch = &iinfo->cli_cli_header;
1815         const char* data;
1816
1817         if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1818                 return NULL;
1819         
1820         data = mono_image_rva_map (image, ch->ch_resources.rva);
1821         if (!data)
1822                 return NULL;
1823         data += offset;
1824         if (size)
1825                 *size = read32 (data);
1826         data += 4;
1827         return data;
1828 }
1829
1830 MonoImage*
1831 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1832 {
1833         char *base_dir, *name;
1834         MonoImage *res;
1835         MonoTableInfo  *t = &image->tables [MONO_TABLE_FILE];
1836         const char *fname;
1837         guint32 fname_id;
1838
1839         if (fileidx < 1 || fileidx > t->rows)
1840                 return NULL;
1841
1842         mono_loader_lock ();
1843         if (image->files && image->files [fileidx - 1]) {
1844                 mono_loader_unlock ();
1845                 return image->files [fileidx - 1];
1846         }
1847
1848         if (!image->files)
1849                 image->files = g_new0 (MonoImage*, t->rows);
1850
1851         fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1852         fname = mono_metadata_string_heap (image, fname_id);
1853         base_dir = g_path_get_dirname (image->name);
1854         name = g_build_filename (base_dir, fname, NULL);
1855         res = mono_image_open (name, NULL);
1856         if (res) {
1857                 int i;
1858                 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1859                 res->assembly = image->assembly;
1860                 for (i = 0; i < res->module_count; ++i) {
1861                         if (res->modules [i] && !res->modules [i]->assembly)
1862                                 res->modules [i]->assembly = image->assembly;
1863                 }
1864
1865                 image->files [fileidx - 1] = res;
1866 #ifdef PLATFORM_WIN32
1867                 if (res->is_module_handle)
1868                         mono_image_fixup_vtable (res);
1869 #endif
1870         }
1871         mono_loader_unlock ();
1872         g_free (name);
1873         g_free (base_dir);
1874         return res;
1875 }
1876
1877 /**
1878  * mono_image_get_strong_name:
1879  * @image: a MonoImage
1880  * @size: a guint32 pointer, or NULL.
1881  *
1882  * If the image has a strong name, and @size is not NULL, the value
1883  * pointed to by size will have the size of the strong name.
1884  *
1885  * Returns: NULL if the image does not have a strong name, or a
1886  * pointer to the public key.
1887  */
1888 const char*
1889 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1890 {
1891         MonoCLIImageInfo *iinfo = image->image_info;
1892         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1893         const char* data;
1894
1895         if (!de->size || !de->rva)
1896                 return NULL;
1897         data = mono_image_rva_map (image, de->rva);
1898         if (!data)
1899                 return NULL;
1900         if (size)
1901                 *size = de->size;
1902         return data;
1903 }
1904
1905 /**
1906  * mono_image_strong_name_position:
1907  * @image: a MonoImage
1908  * @size: a guint32 pointer, or NULL.
1909  *
1910  * If the image has a strong name, and @size is not NULL, the value
1911  * pointed to by size will have the size of the strong name.
1912  *
1913  * Returns: the position within the image file where the strong name
1914  * is stored.
1915  */
1916 guint32
1917 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1918 {
1919         MonoCLIImageInfo *iinfo = image->image_info;
1920         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1921         guint32 pos;
1922
1923         if (size)
1924                 *size = de->size;
1925         if (!de->size || !de->rva)
1926                 return 0;
1927         pos = mono_cli_rva_image_map (image, de->rva);
1928         return pos == INVALID_ADDRESS ? 0 : pos;
1929 }
1930
1931 /**
1932  * mono_image_get_public_key:
1933  * @image: a MonoImage
1934  * @size: a guint32 pointer, or NULL.
1935  *
1936  * This is used to obtain the public key in the @image.
1937  * 
1938  * If the image has a public key, and @size is not NULL, the value
1939  * pointed to by size will have the size of the public key.
1940  * 
1941  * Returns: NULL if the image does not have a public key, or a pointer
1942  * to the public key.
1943  */
1944 const char*
1945 mono_image_get_public_key (MonoImage *image, guint32 *size)
1946 {
1947         const char *pubkey;
1948         guint32 len, tok;
1949
1950         if (image->dynamic) {
1951                 if (size)
1952                         *size = ((MonoDynamicImage*)image)->public_key_len;
1953                 return (char*)((MonoDynamicImage*)image)->public_key;
1954         }
1955         if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1956                 return NULL;
1957         tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1958         if (!tok)
1959                 return NULL;
1960         pubkey = mono_metadata_blob_heap (image, tok);
1961         len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1962         if (size)
1963                 *size = len;
1964         return pubkey;
1965 }
1966
1967 /**
1968  * mono_image_get_name:
1969  * @name: a MonoImage
1970  *
1971  * Returns: the name of the assembly.
1972  */
1973 const char*
1974 mono_image_get_name (MonoImage *image)
1975 {
1976         return image->assembly_name;
1977 }
1978
1979 /**
1980  * mono_image_get_filename:
1981  * @image: a MonoImage
1982  *
1983  * Used to get the filename that hold the actual MonoImage
1984  *
1985  * Returns: the filename.
1986  */
1987 const char*
1988 mono_image_get_filename (MonoImage *image)
1989 {
1990         return image->name;
1991 }
1992
1993 const char*
1994 mono_image_get_guid (MonoImage *image)
1995 {
1996         return image->guid;
1997 }
1998
1999 const MonoTableInfo*
2000 mono_image_get_table_info (MonoImage *image, int table_id)
2001 {
2002         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2003                 return NULL;
2004         return &image->tables [table_id];
2005 }
2006
2007 int
2008 mono_image_get_table_rows (MonoImage *image, int table_id)
2009 {
2010         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2011                 return 0;
2012         return image->tables [table_id].rows;
2013 }
2014
2015 int
2016 mono_table_info_get_rows (const MonoTableInfo *table)
2017 {
2018         return table->rows;
2019 }
2020
2021 /**
2022  * mono_image_get_assembly:
2023  * @image: the MonoImage.
2024  *
2025  * Use this routine to get the assembly that owns this image.
2026  *
2027  * Returns: the assembly that holds this image.
2028  */
2029 MonoAssembly* 
2030 mono_image_get_assembly (MonoImage *image)
2031 {
2032         return image->assembly;
2033 }
2034
2035 /**
2036  * mono_image_is_dynamic:
2037  * @image: the MonoImage
2038  *
2039  * Determines if the given image was created dynamically through the
2040  * System.Reflection.Emit API
2041  *
2042  * Returns: TRUE if the image was created dynamically, FALSE if not.
2043  */
2044 gboolean
2045 mono_image_is_dynamic (MonoImage *image)
2046 {
2047         return image->dynamic;
2048 }
2049
2050 /**
2051  * mono_image_has_authenticode_entry:
2052  * @image: the MonoImage
2053  *
2054  * Use this routine to determine if the image has a Authenticode
2055  * Certificate Table.
2056  *
2057  * Returns: TRUE if the image contains an authenticode entry in the PE
2058  * directory.
2059  */
2060 gboolean
2061 mono_image_has_authenticode_entry (MonoImage *image)
2062 {
2063         MonoCLIImageInfo *iinfo = image->image_info;
2064         MonoDotNetHeader *header = &iinfo->cli_header;
2065         MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
2066         // the Authenticode "pre" (non ASN.1) header is 8 bytes long
2067         return ((de->rva != 0) && (de->size > 8));
2068 }
2069
2070 gpointer
2071 mono_image_alloc (MonoImage *image, guint size)
2072 {
2073         gpointer res;
2074
2075         mono_perfcounters->loader_bytes += size;
2076         mono_image_lock (image);
2077         res = mono_mempool_alloc (image->mempool, size);
2078         mono_image_unlock (image);
2079
2080         return res;
2081 }
2082
2083 gpointer
2084 mono_image_alloc0 (MonoImage *image, guint size)
2085 {
2086         gpointer res;
2087
2088         mono_perfcounters->loader_bytes += size;
2089         mono_image_lock (image);
2090         res = mono_mempool_alloc0 (image->mempool, size);
2091         mono_image_unlock (image);
2092
2093         return res;
2094 }
2095
2096 char*
2097 mono_image_strdup (MonoImage *image, const char *s)
2098 {
2099         char *res;
2100
2101         mono_perfcounters->loader_bytes += strlen (s);
2102         mono_image_lock (image);
2103         res = mono_mempool_strdup (image->mempool, s);
2104         mono_image_unlock (image);
2105
2106         return res;
2107 }
2108
2109 GList*
2110 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
2111 {
2112         GList *new_list;
2113         
2114         new_list = mono_image_alloc (image, sizeof (GList));
2115         new_list->data = data;
2116         new_list->prev = list ? list->prev : NULL;
2117     new_list->next = list;
2118
2119     if (new_list->prev)
2120             new_list->prev->next = new_list;
2121     if (list)
2122             list->prev = new_list;
2123
2124         return new_list;
2125 }
2126
2127 GSList*
2128 g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
2129 {
2130         GSList *new_list;
2131
2132         new_list = mono_image_alloc (image, sizeof (GSList));
2133         new_list->data = data;
2134         new_list->next = NULL;
2135
2136         return g_slist_concat (list, new_list);
2137 }
2138
2139 void
2140 mono_image_lock (MonoImage *image)
2141 {
2142         mono_locks_acquire (&image->lock, ImageDataLock);
2143 }
2144
2145 void
2146 mono_image_unlock (MonoImage *image)
2147 {
2148         mono_locks_release (&image->lock, ImageDataLock);
2149 }
2150
2151
2152 /**
2153  * mono_image_property_lookup:
2154  *
2155  * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
2156  *
2157  * LOCKING: Takes the image lock
2158  */
2159 gpointer 
2160 mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
2161 {
2162         gpointer res;
2163
2164         mono_image_lock (image);
2165         res = mono_property_hash_lookup (image->property_hash, subject, property);
2166         mono_image_unlock (image);
2167
2168         return res;
2169 }
2170
2171 /**
2172  * mono_image_property_insert:
2173  *
2174  * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2175  *
2176  * LOCKING: Takes the image lock
2177  */
2178 void
2179 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
2180 {
2181         mono_image_lock (image);
2182         mono_property_hash_insert (image->property_hash, subject, property, value);
2183         mono_image_unlock (image);
2184 }
2185
2186 /**
2187  * mono_image_property_remove:
2188  *
2189  * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2190  *
2191  * LOCKING: Takes the image lock
2192  */
2193 void
2194 mono_image_property_remove (MonoImage *image, gpointer subject)
2195 {
2196         mono_image_lock (image);
2197         mono_property_hash_remove_object (image->property_hash, subject);
2198         mono_image_unlock (image);
2199 }