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