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