2003-12-20 Zoltan Varga <vargaz@freemail.hu>
[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  * (C) 2001-2003 Ximian, Inc.  http://www.ximian.com
10  *
11  */
12 #include <config.h>
13 #include <stdio.h>
14 #include <glib.h>
15 #include <errno.h>
16 #include <time.h>
17 #include <string.h>
18 #include "image.h"
19 #include "cil-coff.h"
20 #include "rawbuffer.h"
21 #include "mono-endian.h"
22 #include "private.h"
23 #include "tabledefs.h"
24 #include "tokentype.h"
25 #include <mono/io-layer/io-layer.h>
26
27 #define INVALID_ADDRESS 0xffffffff
28
29 /*
30  * Keeps track of the various assemblies loaded
31  */
32 static GHashTable *loaded_images_hash;
33 static GHashTable *loaded_images_guid_hash;
34
35 static CRITICAL_SECTION images_mutex;
36
37 guint32
38 mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
39 {
40         const int top = iinfo->cli_section_count;
41         MonoSectionTable *tables = iinfo->cli_section_tables;
42         int i;
43         
44         for (i = 0; i < top; i++){
45                 if ((addr >= tables->st_virtual_address) &&
46                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
47                         return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
48                 }
49                 tables++;
50         }
51         return INVALID_ADDRESS;
52 }
53
54 char *
55 mono_cli_rva_map (MonoCLIImageInfo *iinfo, guint32 addr)
56 {
57         const int top = iinfo->cli_section_count;
58         MonoSectionTable *tables = iinfo->cli_section_tables;
59         int i;
60         
61         for (i = 0; i < top; i++){
62                 if ((addr >= tables->st_virtual_address) &&
63                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
64                         return (char*)iinfo->cli_sections [i] +
65                                 (addr - tables->st_virtual_address);
66                 }
67                 tables++;
68         }
69         return NULL;
70 }
71
72 /**
73  * mono_images_init:
74  *
75  *  Initialize the global variables used by this module.
76  */
77 void
78 mono_images_init (void)
79 {
80         InitializeCriticalSection (&images_mutex);
81
82         loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
83         loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
84 }
85
86 /**
87  * mono_image_ensure_section_idx:
88  * @image: The image we are operating on
89  * @section: section number that we will load/map into memory
90  *
91  * This routine makes sure that we have an in-memory copy of
92  * an image section (.text, .rsrc, .data).
93  *
94  * Returns: TRUE on success
95  */
96 int
97 mono_image_ensure_section_idx (MonoImage *image, int section)
98 {
99         MonoCLIImageInfo *iinfo = image->image_info;
100         MonoSectionTable *sect;
101         gboolean writable;
102         
103         g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
104
105         if (iinfo->cli_sections [section] != NULL)
106                 return TRUE;
107
108         sect = &iinfo->cli_section_tables [section];
109         
110         writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
111
112         if (!image->f) {
113                 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
114                         return FALSE;
115                 /* FIXME: we ignore the writable flag since we don't patch the binary */
116                 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
117                 return TRUE;
118         }
119         iinfo->cli_sections [section] = mono_raw_buffer_load (
120                 fileno (image->f), writable,
121                 sect->st_raw_data_ptr, sect->st_raw_data_size);
122
123         if (iinfo->cli_sections [section] == NULL)
124                 return FALSE;
125
126         return TRUE;
127 }
128
129 /**
130  * mono_image_ensure_section:
131  * @image: The image we are operating on
132  * @section: section name that we will load/map into memory
133  *
134  * This routine makes sure that we have an in-memory copy of
135  * an image section (.text, .rsrc, .data).
136  *
137  * Returns: TRUE on success
138  */
139 int
140 mono_image_ensure_section (MonoImage *image, const char *section)
141 {
142         MonoCLIImageInfo *ii = image->image_info;
143         int i;
144         
145         for (i = 0; i < ii->cli_section_count; i++){
146                 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
147                         continue;
148                 
149                 return mono_image_ensure_section_idx (image, i);
150         }
151         return FALSE;
152 }
153
154 static int
155 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
156 {
157         const int top = iinfo->cli_header.coff.coff_sections;
158         int i;
159
160         iinfo->cli_section_count = top;
161         iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
162         iinfo->cli_sections = g_new0 (void *, top);
163         
164         for (i = 0; i < top; i++){
165                 MonoSectionTable *t = &iinfo->cli_section_tables [i];
166
167                 if (!image->f) {
168                         if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
169                                 return FALSE;
170                         memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
171                         offset += sizeof (MonoSectionTable);
172                 } else {
173                         if (fread (t, sizeof (MonoSectionTable), 1, image->f) != 1)
174                                 return FALSE;
175                 }
176
177 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
178                 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
179                 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
180                 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
181                 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
182                 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
183                 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
184                 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
185                 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
186                 t->st_flags = GUINT32_FROM_LE (t->st_flags);
187 #endif
188                 /* consistency checks here */
189         }
190
191         for (i = 0; i < top; i++)
192                 if (!mono_image_ensure_section_idx (image, i))
193                         return FALSE;
194         
195         return TRUE;
196 }
197
198 static gboolean
199 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
200 {
201         guint32 offset;
202         int n;
203         
204         offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
205         if (offset == INVALID_ADDRESS)
206                 return FALSE;
207
208         if (!image->f) {
209                 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
210                         return FALSE;
211                 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
212         } else {
213                 if (fseek (image->f, offset, SEEK_SET) != 0)
214                         return FALSE;
215         
216                 if ((n = fread (&iinfo->cli_cli_header, sizeof (MonoCLIHeader), 1, image->f)) != 1)
217                         return FALSE;
218         }
219
220 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
221 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
222 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
223 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
224         SWAP32 (iinfo->cli_cli_header.ch_size);
225         SWAP32 (iinfo->cli_cli_header.ch_flags);
226         SWAP32 (iinfo->cli_cli_header.ch_entry_point);
227         SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
228         SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
229         SWAPPDE (iinfo->cli_cli_header.ch_metadata);
230         SWAPPDE (iinfo->cli_cli_header.ch_resources);
231         SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
232         SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
233         SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
234         SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
235         SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
236         SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
237         SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
238         SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
239         SWAPPDE (iinfo->cli_cli_header.ch_module_image);
240         SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
241         SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
242         SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
243         SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
244 #undef SWAP32
245 #undef SWAP16
246 #undef SWAPPDE
247 #endif
248         /* Catch new uses of the fields that are supposed to be zero */
249
250         if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
251             (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
252             (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
253             (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
254             (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
255             (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
256             (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
257             (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
258             (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
259
260                 /*
261                  * No need to scare people who are testing this, I am just
262                  * labelling this as a LAMESPEC
263                  */
264                 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
265
266         }
267             
268         return TRUE;
269 }
270
271 static gboolean
272 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
273 {
274         guint32 offset, size;
275         guint16 streams;
276         int i;
277         guint32 pad;
278         char *ptr;
279         
280         offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
281         size = iinfo->cli_cli_header.ch_metadata.size;
282
283         if (!image->f) {
284                 if (offset + size > image->raw_data_len)
285                         return FALSE;
286                 image->raw_metadata = image->raw_data + offset;
287         } else {
288                 image->raw_metadata = mono_raw_buffer_load (fileno (image->f), FALSE, offset, size);
289                 if (image->raw_metadata == NULL)
290                         return FALSE;
291         }
292
293         ptr = image->raw_metadata;
294
295         if (strncmp (ptr, "BSJB", 4) == 0){
296                 guint32 version_string_len;
297
298                 ptr += 12;
299                 version_string_len = read32 (ptr);
300                 ptr += 4;
301                 image->version = g_strndup (ptr, version_string_len);
302                 ptr += version_string_len;
303                 pad = ptr - image->raw_metadata;
304                 if (pad % 4)
305                         ptr += 4 - (pad % 4);
306         } else
307                 return FALSE;
308
309         /* skip over flags */
310         ptr += 2;
311         
312         streams = read16 (ptr);
313         ptr += 2;
314
315         for (i = 0; i < streams; i++){
316                 if (strncmp (ptr + 8, "#~", 3) == 0){
317                         image->heap_tables.data = image->raw_metadata + read32 (ptr);
318                         image->heap_tables.size = read32 (ptr + 4);
319                         ptr += 8 + 3;
320                 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
321                         image->heap_strings.data = image->raw_metadata + read32 (ptr);
322                         image->heap_strings.size = read32 (ptr + 4);
323                         ptr += 8 + 9;
324                 } else if (strncmp (ptr + 8, "#US", 4) == 0){
325                         image->heap_us.data = image->raw_metadata + read32 (ptr);
326                         image->heap_us.size = read32 (ptr + 4);
327                         ptr += 8 + 4;
328                 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
329                         image->heap_blob.data = image->raw_metadata + read32 (ptr);
330                         image->heap_blob.size = read32 (ptr + 4);
331                         ptr += 8 + 6;
332                 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
333                         image->heap_guid.data = image->raw_metadata + read32 (ptr);
334                         image->heap_guid.size = read32 (ptr + 4);
335                         ptr += 8 + 6;
336                 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
337                         g_print ("Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name);
338                         return FALSE;
339                 } else {
340                         g_message ("Unknown heap type: %s\n", ptr + 8);
341                         ptr += 8 + strlen (ptr) + 1;
342                 }
343                 pad = ptr - image->raw_metadata;
344                 if (pad % 4)
345                         ptr += 4 - (pad % 4);
346         }
347
348         g_assert (image->heap_guid.data);
349         g_assert (image->heap_guid.size >= 16);
350
351         image->guid = mono_guid_to_string (image->heap_guid.data);
352
353         return TRUE;
354 }
355
356 /*
357  * Load representation of logical metadata tables, from the "#~" stream
358  */
359 static gboolean
360 load_tables (MonoImage *image)
361 {
362         const char *heap_tables = image->heap_tables.data;
363         const guint32 *rows;
364         guint64 valid_mask, sorted_mask;
365         int valid = 0, table;
366         int heap_sizes;
367         
368         heap_sizes = heap_tables [6];
369         image->idx_string_wide = ((heap_sizes & 0x01) == 1);
370         image->idx_guid_wide   = ((heap_sizes & 0x02) == 2);
371         image->idx_blob_wide   = ((heap_sizes & 0x04) == 4);
372         
373         valid_mask = read64 (heap_tables + 8);
374         sorted_mask = read64 (heap_tables + 16);
375         rows = (const guint32 *) (heap_tables + 24);
376         
377         for (table = 0; table < 64; table++){
378                 if ((valid_mask & ((guint64) 1 << table)) == 0){
379                         image->tables [table].rows = 0;
380                         continue;
381                 }
382                 if (table > MONO_TABLE_LAST) {
383                         g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
384                 }
385                 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
386                         g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
387                 }*/
388                 image->tables [table].rows = read32 (rows);
389                 rows++;
390                 valid++;
391         }
392
393         image->tables_base = (heap_tables + 24) + (4 * valid);
394
395         /* They must be the same */
396         g_assert ((const void *) image->tables_base == (const void *) rows);
397
398         mono_metadata_compute_table_bases (image);
399         return TRUE;
400 }
401
402 static gboolean
403 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
404 {
405         if (!load_metadata_ptrs (image, iinfo))
406                 return FALSE;
407
408         return load_tables (image);
409 }
410
411 void
412 mono_image_add_to_name_cache (MonoImage *image, const char *nspace, 
413                                                           const char *name, guint32 index)
414 {
415         GHashTable *nspace_table;
416         GHashTable *name_cache = image->name_cache;
417
418         if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
419                 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
420                 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
421         }
422         g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
423 }
424
425 static void
426 load_modules (MonoImage *image, MonoImageOpenStatus *status)
427 {
428         MonoTableInfo *t;
429         int i;
430         char *base_dir;
431
432         if (image->modules)
433                 return;
434
435         t = &image->tables [MONO_TABLE_MODULEREF];
436         image->modules = g_new0 (MonoImage *, t->rows);
437         base_dir = g_path_get_dirname (image->name);
438         for (i = 0; i < t->rows; i++){
439                 char *module_ref;
440                 const char *name;
441                 guint32 cols [MONO_MODULEREF_SIZE];
442
443                 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
444                 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
445                 module_ref = g_build_filename (base_dir, name, NULL);
446                 image->modules [i] = mono_image_open (module_ref, status);
447                 if (image->modules [i]) {
448                         //g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly);
449                 }
450                 /* 
451                  * FIXME: what do we do here? it could be a native dll...
452                  * We should probably do lazy-loading of modules.
453                  */
454                 if (status)
455                         *status = MONO_IMAGE_OK;
456                 g_free (module_ref);
457         }
458
459         g_free (base_dir);
460 }
461
462 static void
463 load_class_names (MonoImage *image)
464 {
465         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEDEF];
466         guint32 cols [MONO_TYPEDEF_SIZE];
467         const char *name;
468         const char *nspace;
469         guint32 i, visib, nspace_index;
470         GHashTable *name_cache2, *nspace_table;
471
472         /* Temporary hash table to avoid lookups in the nspace_table */
473         name_cache2 = g_hash_table_new (NULL, NULL);
474
475         for (i = 1; i <= t->rows; ++i) {
476                 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
477                 /* nested types are accessed from the nesting name */
478                 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
479                 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
480                         continue;
481                 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
482                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
483
484                 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
485                 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
486                 if (!nspace_table) {
487                         nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
488                         g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
489                         g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
490                                                                  nspace_table);
491                 }
492                 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
493         }
494
495         /* Load type names from EXPORTEDTYPES table */
496         {
497                 MonoTableInfo  *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
498                 guint32 cols [MONO_EXP_TYPE_SIZE];
499                 int i;
500
501                 for (i = 0; i < t->rows; ++i) {
502                         mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
503                         name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
504                         nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
505
506                         nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
507                         nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
508                         if (!nspace_table) {
509                                 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
510                                 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
511                                 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
512                                                                          nspace_table);
513                         }
514                         g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
515                 }
516         }
517
518         g_hash_table_destroy (name_cache2);
519 }
520
521 static void
522 register_guid (gpointer key, gpointer value, gpointer user_data)
523 {
524         MonoImage *image = (MonoImage*)value;
525
526         if (!g_hash_table_lookup (loaded_images_guid_hash, image))
527                 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
528 }
529
530 static void
531 build_guid_table (void)
532 {
533         g_hash_table_foreach (loaded_images_hash, register_guid, NULL);
534 }
535
536 void
537 mono_image_init (MonoImage *image)
538 {
539         image->method_cache = g_hash_table_new (NULL, NULL);
540         image->class_cache = g_hash_table_new (NULL, NULL);
541         image->field_cache = g_hash_table_new (NULL, NULL);
542         image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
543         image->array_cache = g_hash_table_new (NULL, NULL);
544
545         image->delegate_begin_invoke_cache = 
546                 g_hash_table_new ((GHashFunc)mono_signature_hash, 
547                                   (GCompareFunc)mono_metadata_signature_equal);
548         image->delegate_end_invoke_cache = 
549                 g_hash_table_new ((GHashFunc)mono_signature_hash, 
550                                   (GCompareFunc)mono_metadata_signature_equal);
551         image->delegate_invoke_cache = 
552                 g_hash_table_new ((GHashFunc)mono_signature_hash, 
553                                   (GCompareFunc)mono_metadata_signature_equal);
554
555         image->runtime_invoke_cache = g_hash_table_new (NULL, NULL);
556         image->managed_wrapper_cache = g_hash_table_new (NULL, NULL);
557         image->native_wrapper_cache = g_hash_table_new (NULL, NULL);
558         image->remoting_invoke_cache = g_hash_table_new (NULL, NULL);
559         image->synchronized_cache = g_hash_table_new (NULL, NULL);
560
561         image->generics_cache = g_hash_table_new ((GHashFunc)mono_metadata_type_hash, (GEqualFunc)mono_metadata_type_equal);
562         image->typespec_cache = g_hash_table_new (NULL, NULL);
563 }
564
565 static MonoImage *
566 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status)
567 {
568         MonoCLIImageInfo *iinfo;
569         MonoDotNetHeader *header;
570         MonoMSDOSHeader msdos;
571         int n;
572         guint32 offset = 0;
573
574         mono_image_init (image);
575
576         iinfo = image->image_info;
577         header = &iinfo->cli_header;
578                 
579         if (status)
580                 *status = MONO_IMAGE_IMAGE_INVALID;
581
582         if (!image->f) {
583                 if (offset + sizeof (msdos) > image->raw_data_len)
584                         goto invalid_image;
585                 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
586         } else {
587                 if (fread (&msdos, sizeof (msdos), 1, image->f) != 1)
588                         goto invalid_image;
589         }
590         
591         if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
592                 goto invalid_image;
593         
594         msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
595
596         if (msdos.pe_offset != sizeof (msdos)) {
597                 if (image->f)
598                         fseek (image->f, msdos.pe_offset, SEEK_SET);
599         }
600         offset = msdos.pe_offset;
601
602         if (!image->f) {
603                 if (offset + sizeof (MonoDotNetHeader) > image->raw_data_len)
604                         goto invalid_image;
605                 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
606                 offset += sizeof (MonoDotNetHeader);
607         } else {
608                 if ((n = fread (header, sizeof (MonoDotNetHeader), 1, image->f)) != 1)
609                         goto invalid_image;
610         }
611
612 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
613 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
614 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
615 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
616         SWAP32 (header->coff.coff_time);
617         SWAP32 (header->coff.coff_symptr);
618         SWAP32 (header->coff.coff_symcount);
619         SWAP16 (header->coff.coff_machine);
620         SWAP16 (header->coff.coff_sections);
621         SWAP16 (header->coff.coff_opt_header_size);
622         SWAP16 (header->coff.coff_attributes);
623         /* MonoPEHeader */
624         SWAP32 (header->pe.pe_code_size);
625         SWAP32 (header->pe.pe_data_size);
626         SWAP32 (header->pe.pe_uninit_data_size);
627         SWAP32 (header->pe.pe_rva_entry_point);
628         SWAP32 (header->pe.pe_rva_code_base);
629         SWAP32 (header->pe.pe_rva_data_base);
630         SWAP16 (header->pe.pe_magic);
631
632         /* MonoPEHeaderNT: not used yet */
633         SWAP32  (header->nt.pe_image_base);     /* must be 0x400000 */
634         SWAP32  (header->nt.pe_section_align);       /* must be 8192 */
635         SWAP32  (header->nt.pe_file_alignment);      /* must be 512 or 4096 */
636         SWAP16  (header->nt.pe_os_major);            /* must be 4 */
637         SWAP16  (header->nt.pe_os_minor);            /* must be 0 */
638         SWAP16  (header->nt.pe_user_major);
639         SWAP16  (header->nt.pe_user_minor);
640         SWAP16  (header->nt.pe_subsys_major);
641         SWAP16  (header->nt.pe_subsys_minor);
642         SWAP32  (header->nt.pe_reserved_1);
643         SWAP32  (header->nt.pe_image_size);
644         SWAP32  (header->nt.pe_header_size);
645         SWAP32  (header->nt.pe_checksum);
646         SWAP16  (header->nt.pe_subsys_required);
647         SWAP16  (header->nt.pe_dll_flags);
648         SWAP32  (header->nt.pe_stack_reserve);
649         SWAP32  (header->nt.pe_stack_commit);
650         SWAP32  (header->nt.pe_heap_reserve);
651         SWAP32  (header->nt.pe_heap_commit);
652         SWAP32  (header->nt.pe_loader_flags);
653         SWAP32  (header->nt.pe_data_dir_count);
654
655         /* MonoDotNetHeader: mostly unused */
656         SWAPPDE (header->datadir.pe_export_table);
657         SWAPPDE (header->datadir.pe_import_table);
658         SWAPPDE (header->datadir.pe_resource_table);
659         SWAPPDE (header->datadir.pe_exception_table);
660         SWAPPDE (header->datadir.pe_certificate_table);
661         SWAPPDE (header->datadir.pe_reloc_table);
662         SWAPPDE (header->datadir.pe_debug);
663         SWAPPDE (header->datadir.pe_copyright);
664         SWAPPDE (header->datadir.pe_global_ptr);
665         SWAPPDE (header->datadir.pe_tls_table);
666         SWAPPDE (header->datadir.pe_load_config_table);
667         SWAPPDE (header->datadir.pe_bound_import);
668         SWAPPDE (header->datadir.pe_iat);
669         SWAPPDE (header->datadir.pe_delay_import_desc);
670         SWAPPDE (header->datadir.pe_cli_header);
671         SWAPPDE (header->datadir.pe_reserved);
672
673 #undef SWAP32
674 #undef SWAP16
675 #undef SWAPPDE
676 #endif
677
678         if (header->coff.coff_machine != 0x14c)
679                 goto invalid_image;
680
681         if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
682                 goto invalid_image;
683
684         if (header->pesig[0] != 'P' || header->pesig[1] != 'E' || header->pe.pe_magic != 0x10B)
685                 goto invalid_image;
686
687 #if 0
688         /*
689          * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
690          * which produces binaries with 7.0.  From Sergey:
691          *
692          * The reason is that MSVC7 uses traditional compile/link
693          * sequence for CIL executables, and VS.NET (and Framework
694          * SDK) includes linker version 7, that puts 7.0 in this
695          * field.  That's why it's currently not possible to load VC
696          * binaries with Mono.  This field is pretty much meaningless
697          * anyway (what linker?).
698          */
699         if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
700                 goto invalid_image;
701 #endif
702
703         /*
704          * FIXME: byte swap all addresses here for header.
705          */
706         
707         if (!load_section_tables (image, iinfo, offset))
708                 goto invalid_image;
709         
710         /* Load the CLI header */
711         if (!load_cli_header (image, iinfo))
712                 goto invalid_image;
713
714         if (!load_metadata (image, iinfo))
715                 goto invalid_image;
716
717         load_class_names (image);
718
719         /* modules don't have an assembly table row */
720         if (image->tables [MONO_TABLE_ASSEMBLY].rows)
721                 image->assembly_name = mono_metadata_string_heap (image, 
722                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
723                                         0, MONO_ASSEMBLY_NAME));
724
725         image->module_name = mono_metadata_string_heap (image, 
726                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
727                                         0, MONO_MODULE_NAME));
728
729         load_modules (image, status);
730
731         if (status)
732                 *status = MONO_IMAGE_OK;
733
734         image->ref_count=1;
735
736         return image;
737
738 invalid_image:
739         mono_image_close (image);
740                 return NULL;
741 }
742
743 static MonoImage *
744 do_mono_image_open (const char *fname, MonoImageOpenStatus *status)
745 {
746         MonoCLIImageInfo *iinfo;
747         MonoImage *image;
748         FILE *filed;
749
750         if ((filed = fopen (fname, "rb")) == NULL){
751                 if (status)
752                         *status = MONO_IMAGE_ERROR_ERRNO;
753                 return NULL;
754         }
755
756         image = g_new0 (MonoImage, 1);
757         image->ref_count = 1;
758         image->f = filed;
759         image->name = g_strdup (fname);
760         iinfo = g_new0 (MonoCLIImageInfo, 1);
761         image->image_info = iinfo;
762
763         return do_mono_image_load (image, status);
764 }
765
766 MonoImage *
767 mono_image_loaded (const char *name)
768 {
769         MonoImage *res;
770         
771         if (strcmp (name, "corlib") == 0)
772                 name = "mscorlib";
773
774         EnterCriticalSection (&images_mutex);
775         res = g_hash_table_lookup (loaded_images_hash, name);
776         LeaveCriticalSection (&images_mutex);
777         return res;
778 }
779
780 MonoImage *
781 mono_image_loaded_by_guid (const char *guid)
782 {
783         MonoImage *res;
784
785         EnterCriticalSection (&images_mutex);
786         res = g_hash_table_lookup (loaded_images_guid_hash, guid);
787         LeaveCriticalSection (&images_mutex);
788         return res;
789 }
790
791 MonoImage *
792 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
793 {
794         MonoCLIImageInfo *iinfo;
795         MonoImage *image;
796         char *datac;
797
798         if (!data || !data_len) {
799                 if (status)
800                         *status = MONO_IMAGE_IMAGE_INVALID;
801                 return NULL;
802         }
803         datac = data;
804         if (need_copy) {
805                 datac = g_try_malloc (data_len);
806                 if (!datac) {
807                         if (status)
808                                 *status = MONO_IMAGE_ERROR_ERRNO;
809                         return NULL;
810                 }
811                 memcpy (datac, data, data_len);
812         }
813
814         image = g_new0 (MonoImage, 1);
815         image->ref_count = 1;
816         image->raw_data = datac;
817         image->raw_data_len = data_len;
818         image->raw_data_allocated = need_copy;
819         image->name = g_strdup_printf ("data-%p", datac);
820         iinfo = g_new0 (MonoCLIImageInfo, 1);
821         image->image_info = iinfo;
822
823         return do_mono_image_load (image, status);
824 }
825
826 /**
827  * mono_image_open:
828  * @fname: filename that points to the module we want to open
829  * @status: An error condition is returned in this field
830  *
831  * Retuns: An open image of type %MonoImage or NULL on error.
832  * if NULL, then check the value of @status for details on the error
833  */
834 MonoImage *
835 mono_image_open (const char *fname, MonoImageOpenStatus *status)
836 {
837         MonoImage *image, *image2;
838         
839         g_return_val_if_fail (fname != NULL, NULL);
840
841         /*
842          * The easiest solution would be to do all the loading inside the mutex,
843          * but that would lead to scalability problems. So we let the loading
844          * happen outside the mutex, and if multiple threads happen to load
845          * the same image, we discard all but the first copy.
846          */
847         EnterCriticalSection (&images_mutex);
848         image = g_hash_table_lookup (loaded_images_hash, fname);
849         if (image){
850                 image->ref_count++;
851                 LeaveCriticalSection (&images_mutex);
852                 return image;
853         }
854         LeaveCriticalSection (&images_mutex);
855
856         image = do_mono_image_open (fname, status);
857         if (image == NULL)
858                 return NULL;
859
860         EnterCriticalSection (&images_mutex);
861         image2 = g_hash_table_lookup (loaded_images_hash, fname);
862         if (image2) {
863                 /* Somebody else beat us to it */
864                 image2->ref_count ++;
865                 LeaveCriticalSection (&images_mutex);
866                 mono_image_close (image);
867
868                 return image2;
869         }
870         g_hash_table_insert (loaded_images_hash, image->name, image);
871         if (image->assembly_name)
872                 g_hash_table_insert (loaded_images_hash, (char *) image->assembly_name, image); 
873         g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
874         LeaveCriticalSection (&images_mutex);
875
876         return image;
877 }
878
879 static void
880 free_hash_table (gpointer key, gpointer val, gpointer user_data)
881 {
882         g_hash_table_destroy ((GHashTable*)val);
883 }
884
885 /**
886  * mono_image_close:
887  * @image: The image file we wish to close
888  *
889  * Closes an image file, deallocates all memory consumed and
890  * unmaps all possible sections of the file
891  */
892 void
893 mono_image_close (MonoImage *image)
894 {
895         MonoImage *image2;
896
897         g_return_if_fail (image != NULL);
898
899         EnterCriticalSection (&images_mutex);
900         if (--image->ref_count) {
901                 LeaveCriticalSection (&images_mutex);
902                 return;
903         }
904         image2 = g_hash_table_lookup (loaded_images_hash, image->name);
905         if (image == image2) {
906                 /* This is not true if we are called from mono_image_open () */
907                 g_hash_table_remove (loaded_images_hash, image->name);
908                 if (image->assembly_name)
909                         g_hash_table_remove (loaded_images_hash, (char *) image->assembly_name);        
910                 g_hash_table_remove (loaded_images_guid_hash, image->guid);
911                 /* Multiple images might have the same guid */
912                 build_guid_table ();
913         }       
914         LeaveCriticalSection (&images_mutex);
915
916         if (image->f)
917                 fclose (image->f);
918         if (image->raw_data_allocated)
919                 g_free (image->raw_data);
920
921         g_free (image->name);
922         g_free (image->files);
923
924         g_hash_table_destroy (image->method_cache);
925         g_hash_table_destroy (image->class_cache);
926         g_hash_table_destroy (image->field_cache);
927         g_hash_table_destroy (image->array_cache);
928         g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
929         g_hash_table_destroy (image->name_cache);
930         g_hash_table_destroy (image->native_wrapper_cache);
931         g_hash_table_destroy (image->managed_wrapper_cache);
932         g_hash_table_destroy (image->delegate_begin_invoke_cache);
933         g_hash_table_destroy (image->delegate_end_invoke_cache);
934         g_hash_table_destroy (image->delegate_invoke_cache);
935         g_hash_table_destroy (image->remoting_invoke_cache);
936         g_hash_table_destroy (image->runtime_invoke_cache);
937         
938         if (image->raw_metadata != NULL)
939                 mono_raw_buffer_free (image->raw_metadata);
940         
941         if (image->image_info){
942                 MonoCLIImageInfo *ii = image->image_info;
943                 int i;
944
945                 for (i = 0; i < ii->cli_section_count; i++){
946                         if (!ii->cli_sections [i])
947                                 continue;
948                         mono_raw_buffer_free (ii->cli_sections [i]);
949                 }
950                 if (ii->cli_section_tables)
951                         g_free (ii->cli_section_tables);
952                 if (ii->cli_sections)
953                         g_free (ii->cli_sections);
954                 g_free (image->image_info);
955         }
956
957         g_free (image);
958 }
959
960 /** 
961  * mono_image_strerror:
962  * @status: an code indicating the result from a recent operation
963  *
964  * Returns: a string describing the error
965  */
966 const char *
967 mono_image_strerror (MonoImageOpenStatus status)
968 {
969         switch (status){
970         case MONO_IMAGE_OK:
971                 return "success";
972         case MONO_IMAGE_ERROR_ERRNO:
973                 return strerror (errno);
974         case MONO_IMAGE_IMAGE_INVALID:
975                 return "File does not contain a valid CIL image";
976         case MONO_IMAGE_MISSING_ASSEMBLYREF:
977                 return "An assembly was referenced, but could not be found";
978         }
979         return "Internal error";
980 }
981
982 static gpointer
983 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
984                                guint32 lang_id, gunichar2 *name,
985                                MonoPEResourceDirEntry *entry,
986                                MonoPEResourceDir *root, guint32 level)
987 {
988         gboolean is_string=entry->name_is_string;
989
990         /* Level 0 holds a directory entry for each type of resource
991          * (identified by ID or name).
992          *
993          * Level 1 holds a directory entry for each named resource
994          * item, and each "anonymous" item of a particular type of
995          * resource.
996          *
997          * Level 2 holds a directory entry for each language pointing to
998          * the actual data.
999          */
1000
1001         if(level==0) {
1002                 if((is_string==FALSE && entry->name_offset!=res_id) ||
1003                    (is_string==TRUE)) {
1004                         return(NULL);
1005                 }
1006         } else if (level==1) {
1007 #if 0
1008                 if(name!=NULL &&
1009                    is_string==TRUE && name!=lookup (entry->name_offset)) {
1010                         return(NULL);
1011                 }
1012 #endif
1013         } else if (level==2) {
1014                 if((is_string==FALSE && entry->name_offset!=lang_id) ||
1015                    (is_string==TRUE)) {
1016                         return(NULL);
1017                 }
1018         } else {
1019                 g_assert_not_reached ();
1020         }
1021
1022         if(entry->is_dir==TRUE) {
1023                 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+entry->dir_offset);
1024                 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1025                 guint32 entries, i;
1026                 
1027                 entries=res_dir->res_named_entries + res_dir->res_id_entries;
1028
1029                 for(i=0; i<entries; i++) {
1030                         MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1031                         gpointer ret;
1032                         
1033                         ret=mono_image_walk_resource_tree (info, res_id,
1034                                                            lang_id, name,
1035                                                            sub_entry, root,
1036                                                            level+1);
1037                         if(ret!=NULL) {
1038                                 return(ret);
1039                         }
1040                 }
1041
1042                 return(NULL);
1043         } else {
1044                 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+entry->dir_offset);
1045                 
1046                 return(data_entry);
1047         }
1048 }
1049
1050 gpointer
1051 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1052 {
1053         MonoCLIImageInfo *info;
1054         MonoDotNetHeader *header;
1055         MonoPEDatadir *datadir;
1056         MonoPEDirEntry *rsrc;
1057         MonoPEResourceDir *resource_dir;
1058         MonoPEResourceDirEntry *res_entries;
1059         guint32 entries, i;
1060
1061         if(image==NULL) {
1062                 return(NULL);
1063         }
1064
1065         info=image->image_info;
1066         if(info==NULL) {
1067                 return(NULL);
1068         }
1069
1070         header=&info->cli_header;
1071         if(header==NULL) {
1072                 return(NULL);
1073         }
1074
1075         datadir=&header->datadir;
1076         if(datadir==NULL) {
1077                 return(NULL);
1078         }
1079
1080         rsrc=&datadir->pe_resource_table;
1081         if(rsrc==NULL) {
1082                 return(NULL);
1083         }
1084
1085         resource_dir=(MonoPEResourceDir *)mono_cli_rva_map (info, rsrc->rva);
1086         if(resource_dir==NULL) {
1087                 return(NULL);
1088         }
1089         
1090         entries=resource_dir->res_named_entries + resource_dir->res_id_entries;
1091         res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1092         
1093         for(i=0; i<entries; i++) {
1094                 MonoPEResourceDirEntry *entry=&res_entries[i];
1095                 gpointer ret;
1096                 
1097                 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1098                                                    name, entry, resource_dir,
1099                                                    0);
1100                 if(ret!=NULL) {
1101                         return(ret);
1102                 }
1103         }
1104
1105         return(NULL);
1106 }
1107
1108 guint32
1109 mono_image_get_entry_point (MonoImage *image)
1110 {
1111         return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1112 }
1113
1114 const char*
1115 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1116 {
1117         MonoCLIImageInfo *iinfo = image->image_info;
1118         MonoCLIHeader *ch = &iinfo->cli_cli_header;
1119         const char* data;
1120
1121         if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1122                 return NULL;
1123         
1124         data = mono_cli_rva_map (iinfo, ch->ch_resources.rva);
1125         if (!data)
1126                 return NULL;
1127         data += offset;
1128         if (size)
1129                 *size = read32 (data);
1130         data += 4;
1131         return data;
1132 }
1133
1134 MonoImage*
1135 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1136 {
1137         char *base_dir, *name;
1138         MonoImage *res;
1139         MonoTableInfo  *t = &image->tables [MONO_TABLE_FILE];
1140         const char *fname;
1141         guint32 fname_id;
1142
1143         if (fileidx < 1 || fileidx > t->rows)
1144                 return NULL;
1145
1146         if (image->files && image->files [fileidx - 1])
1147                 return image->files [fileidx - 1];
1148
1149         if (!image->files)
1150                 image->files = g_new0 (MonoImage*, t->rows);
1151
1152         fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1153         fname = mono_metadata_string_heap (image, fname_id);
1154         base_dir = g_path_get_dirname (image->name);
1155         name = g_build_filename (base_dir, fname, NULL);
1156         res = mono_image_open (name, NULL);
1157         if (res) {
1158                 int i;
1159                 t = &res->tables [MONO_TABLE_MODULEREF];
1160                 //g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly);
1161                 res->assembly = image->assembly;
1162                 for (i = 0; i < t->rows; ++i) {
1163                         if (res->modules [i] && !res->modules [i]->assembly)
1164                                 res->modules [i]->assembly = image->assembly;
1165                 }
1166
1167                 image->files [fileidx - 1] = res;
1168         }
1169         g_free (name);
1170         g_free (base_dir);
1171         return res;
1172 }
1173
1174 const char*
1175 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1176 {
1177         MonoCLIImageInfo *iinfo = image->image_info;
1178         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1179         const char* data;
1180
1181         if (!de->size || !de->rva)
1182                 return NULL;
1183         data = mono_cli_rva_map (iinfo, de->rva);
1184         if (!data)
1185                 return NULL;
1186         if (size)
1187                 *size = de->size;
1188         return data;
1189 }
1190
1191 guint32
1192 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1193 {
1194         MonoCLIImageInfo *iinfo = image->image_info;
1195         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1196         const int top = iinfo->cli_section_count;
1197         MonoSectionTable *tables = iinfo->cli_section_tables;
1198         int i;
1199         guint32 addr = de->rva;
1200         
1201         if (size)
1202                 *size = de->size;
1203         if (!de->size || !de->rva)
1204                 return 0;
1205         for (i = 0; i < top; i++){
1206                 if ((addr >= tables->st_virtual_address) &&
1207                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
1208                         return tables->st_raw_data_ptr +
1209                                 (addr - tables->st_virtual_address);
1210                 }
1211                 tables++;
1212         }
1213
1214         return 0;
1215 }
1216
1217 const char*
1218 mono_image_get_public_key (MonoImage *image, guint32 *size)
1219 {
1220         const char *pubkey;
1221         guint32 len, tok;
1222         if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1223                 return NULL;
1224         tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1225         if (!tok)
1226                 return NULL;
1227         pubkey = mono_metadata_blob_heap (image, tok);
1228         len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1229         if (size)
1230                 *size = len;
1231         return pubkey;
1232 }
1233