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