Tue Aug 28 15:47:15 CEST 2001 Paolo Molaro <lupus@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  * Author:
6  *   Miguel de Icaza (miguel@ximian.com)
7  *
8  * (C) 2001 Ximian, Inc.  http://www.ximian.com
9  *
10  * TODO:
11  *   Implement big-endian versions of the reading routines.
12  */
13 #include <config.h>
14 #include <stdio.h>
15 #include <glib.h>
16 #include <errno.h>
17 #include <string.h>
18 #include "image.h"
19 #include "cil-coff.h"
20 #include "rawbuffer.h"
21 #include "endian.h"
22 #include "private.h"
23
24 #define INVALID_ADDRESS 0xffffffff
25
26 /*
27  * Keeps track of the various assemblies loaded
28  */
29 static GHashTable *loaded_images_hash;
30
31 guint32
32 mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
33 {
34         const int top = iinfo->cli_section_count;
35         MonoSectionTable *tables = iinfo->cli_section_tables;
36         int i;
37         
38         for (i = 0; i < top; i++){
39                 if ((addr >= tables->st_virtual_address) &&
40                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
41                         return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
42                 }
43                 tables++;
44         }
45         return INVALID_ADDRESS;
46 }
47
48 char *
49 mono_cli_rva_map (MonoCLIImageInfo *iinfo, guint32 addr)
50 {
51         const int top = iinfo->cli_section_count;
52         MonoSectionTable *tables = iinfo->cli_section_tables;
53         int i;
54         
55         for (i = 0; i < top; i++){
56                 if ((addr >= tables->st_virtual_address) &&
57                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
58                         return iinfo->cli_sections [i] +
59                                 (addr - tables->st_virtual_address);
60                 }
61                 tables++;
62         }
63         return NULL;
64 }
65
66 /**
67  * mono_image_ensure_section_idx:
68  * @image: The image we are operating on
69  * @section: section number that we will load/map into memory
70  *
71  * This routine makes sure that we have an in-memory copy of
72  * an image section (.text, .rsrc, .data).
73  *
74  * Returns: TRUE on success
75  */
76 int
77 mono_image_ensure_section_idx (MonoImage *image, int section)
78 {
79         MonoCLIImageInfo *iinfo = image->image_info;
80         MonoSectionTable *sect;
81         gboolean writable;
82         
83         g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
84
85         if (iinfo->cli_sections [section] != NULL)
86                 return TRUE;
87
88         sect = &iinfo->cli_section_tables [section];
89         
90         writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
91
92         iinfo->cli_sections [section] = mono_raw_buffer_load (
93                 fileno (image->f), writable,
94                 sect->st_raw_data_ptr, sect->st_raw_data_size);
95
96         if (iinfo->cli_sections [section] == NULL)
97                 return FALSE;
98
99         return TRUE;
100 }
101
102 /**
103  * mono_image_ensure_section:
104  * @image: The image we are operating on
105  * @section: section name that we will load/map into memory
106  *
107  * This routine makes sure that we have an in-memory copy of
108  * an image section (.text, .rsrc, .data).
109  *
110  * Returns: TRUE on success
111  */
112 int
113 mono_image_ensure_section (MonoImage *image, const char *section)
114 {
115         MonoCLIImageInfo *ii = image->image_info;
116         int i;
117         
118         for (i = 0; i < ii->cli_section_count; i++){
119                 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
120                         continue;
121                 
122                 return mono_image_ensure_section_idx (image, i);
123         }
124         return FALSE;
125 }
126
127 static int
128 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo)
129 {
130         const int top = iinfo->cli_header.coff.coff_sections;
131         int i;
132
133         iinfo->cli_section_count = top;
134         iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
135         iinfo->cli_sections = g_new0 (void *, top);
136         
137         for (i = 0; i < top; i++){
138                 MonoSectionTable *t = &iinfo->cli_section_tables [i];
139                 
140                 if (fread (t, sizeof (MonoSectionTable), 1, image->f) != 1)
141                         return FALSE;
142
143                 t->st_virtual_size = le32_to_cpu (t->st_virtual_size);
144                 t->st_virtual_address = le32_to_cpu (t->st_virtual_address);
145                 t->st_raw_data_size = le32_to_cpu (t->st_raw_data_size);
146                 t->st_raw_data_ptr = le32_to_cpu (t->st_raw_data_ptr);
147                 t->st_reloc_ptr = le32_to_cpu (t->st_reloc_ptr);
148                 t->st_lineno_ptr = le32_to_cpu (t->st_lineno_ptr);
149                 t->st_reloc_count = le16_to_cpu (t->st_reloc_count);
150                 t->st_line_count = le16_to_cpu (t->st_line_count);
151
152                 /* consistency checks here */
153         }
154
155         for (i = 0; i < top; i++)
156                 if (!mono_image_ensure_section_idx (image, i))
157                         return FALSE;
158         
159         return TRUE;
160 }
161
162 static gboolean
163 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
164 {
165         guint32 offset;
166         int n;
167         
168         offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
169         if (offset == INVALID_ADDRESS)
170                 return FALSE;
171
172         if (fseek (image->f, offset, 0) != 0)
173                 return FALSE;
174         
175         if ((n = fread (&iinfo->cli_cli_header, sizeof (MonoCLIHeader), 1, image->f)) != 1)
176                 return FALSE;
177
178         /* Catch new uses of the fields that are supposed to be zero */
179
180         if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
181             (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
182             (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
183             (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
184             (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
185             (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
186             (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
187             (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
188             (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
189
190                 /*
191                  * No need to scare people who are testing this, I am just
192                  * labelling this as a LAMESPEC
193                  */
194                 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
195
196         }
197             
198         return TRUE;
199 }
200
201 static gboolean
202 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
203 {
204         guint32 offset, size;
205         guint16 streams;
206         int i;
207         char *ptr;
208         
209         offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
210         size = iinfo->cli_cli_header.ch_metadata.size;
211         
212         image->raw_metadata = mono_raw_buffer_load (fileno (image->f), FALSE, offset, size);
213         if (image->raw_metadata == NULL)
214                 return FALSE;
215
216         ptr = image->raw_metadata;
217
218         if (strncmp (ptr, "BSJB", 4) == 0){
219                 guint32 version_string_len;
220
221                 ptr += 12;
222                 version_string_len = read32 (ptr);
223                 ptr += 4;
224                 ptr += version_string_len;
225                 if (((guint32) ptr) % 4)
226                         ptr += 4 - (((guint32) ptr) %4);
227         } else
228                 return FALSE;
229
230         /* skip over flags */
231         ptr += 2;
232         
233         streams = read16 (ptr);
234         ptr += 2;
235
236         for (i = 0; i < streams; i++){
237                 if (strncmp (ptr + 8, "#~", 3) == 0){
238                         image->heap_tables.offset = read32 (ptr);
239                         image->heap_tables.size = read32 (ptr + 4);
240                         ptr += 8 + 3;
241                 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
242                         image->heap_strings.offset = read32 (ptr);
243                         image->heap_strings.size = read32 (ptr + 4);
244                         ptr += 8 + 9;
245                 } else if (strncmp (ptr + 8, "#US", 4) == 0){
246                         image->heap_us.offset = read32 (ptr);
247                         image->heap_us.size = read32 (ptr + 4);
248                         ptr += 8 + 4;
249                 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
250                         image->heap_blob.offset = read32 (ptr);
251                         image->heap_blob.size = read32 (ptr + 4);
252                         ptr += 8 + 6;
253                 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
254                         image->heap_guid.offset = read32 (ptr);
255                         image->heap_guid.size = read32 (ptr + 4);
256                         ptr += 8 + 6;
257                 } else
258                         g_message ("Unknown heap type: %s\n", ptr + 8);
259                 if (((guint32)ptr) % 4){
260                         ptr += 4 - (((guint32)ptr) % 4);
261                 }
262         }
263         return TRUE;
264 }
265
266 /*
267  * Load representation of logical metadata tables, from the "#~" stream
268  */
269 static gboolean
270 load_tables (MonoImage *image)
271 {
272         char *heap_tables = image->raw_metadata + image->heap_tables.offset;
273         guint32 *rows;
274         guint64 valid_mask;
275         int valid = 0, table;
276         int heap_sizes;
277         
278         heap_sizes = heap_tables [6];
279         image->idx_string_wide = ((heap_sizes & 0x01) == 1);
280         image->idx_guid_wide   = ((heap_sizes & 0x02) == 2);
281         image->idx_blob_wide   = ((heap_sizes & 0x04) == 4);
282         
283         valid_mask = read64 (heap_tables + 8);
284         rows = (guint32 *) (heap_tables + 24);
285         
286         for (table = 0; table < 64; table++){
287                 if ((valid_mask & ((guint64) 1 << table)) == 0){
288                         image->tables [table].rows = 0;
289                         continue;
290                 }
291                 if (table > 0x2b) {
292                         g_warning("bits in valid must be zero above 0x2b (II - 23.1.6)");
293                 }
294                 image->tables [table].rows = read32 (rows);
295                 rows++;
296                 valid++;
297         }
298
299         image->tables_base = (heap_tables + 24) + (4 * valid);
300
301         /* They must be the same */
302         g_assert ((void *) image->tables_base == (void *) rows);
303
304         mono_metadata_compute_table_bases (image);
305         return TRUE;
306 }
307
308 static gboolean
309 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
310 {
311         if (!load_metadata_ptrs (image, iinfo))
312                 return FALSE;
313
314         return load_tables (image);
315 }
316
317 static void
318 load_class_names (MonoImage *image) {
319         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEDEF];
320         guint32 cols [MONO_TYPEDEF_SIZE];
321         const char* name;
322         const char *nspace;
323         GHashTable *nspace_table;
324         GHashTable *name_cache = image->name_cache;
325         guint32 i;
326
327         for (i = 1; i <= t->rows; ++i) {
328                 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
329                 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
330                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
331                 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
332                         nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
333                         g_hash_table_insert (name_cache, nspace, nspace_table);
334                 }
335                 g_hash_table_insert (nspace_table, name, GUINT_TO_POINTER (i));
336         }
337 }
338
339 static MonoImage *
340 do_mono_image_open (const char *fname, enum MonoImageOpenStatus *status)
341 {
342         MonoCLIImageInfo *iinfo;
343         MonoDotNetHeader *header;
344         MonoMSDOSHeader msdos;
345         MonoImage *image;
346         int n;
347
348         image = g_new0 (MonoImage, 1);
349         image->f = fopen (fname, "r");
350         image->name = g_strdup (fname);
351         iinfo = g_new0 (MonoCLIImageInfo, 1);
352         image->image_info = iinfo;
353
354         image->method_cache = g_hash_table_new (g_direct_hash, g_direct_equal);
355         image->class_cache = g_hash_table_new (g_direct_hash, g_direct_equal);
356         image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
357         image->array_cache = g_hash_table_new (g_direct_hash, g_direct_equal);
358
359         header = &iinfo->cli_header;
360                 
361         if (image->f == NULL){
362                 if (status)
363                         *status = MONO_IMAGE_ERROR_ERRNO;
364                 mono_image_close (image);
365                 return NULL;
366         }
367
368         if (status)
369                 *status = MONO_IMAGE_IMAGE_INVALID;
370         
371         if (fread (&msdos, sizeof (msdos), 1, image->f) != 1)
372                 goto invalid_image;
373         
374         if (!(msdos.msdos_header [0] == 'M' && msdos.msdos_header [1] == 'Z'))
375                 goto invalid_image;
376         
377         if (msdos.pe_offset != sizeof (msdos))
378                 fseek (image->f, msdos.pe_offset, SEEK_SET);
379         
380         if ((n = fread (header, sizeof (MonoDotNetHeader), 1, image->f)) != 1)
381                 goto invalid_image;
382
383         if (header->coff.coff_machine != 0x14c) /* FIXME: ENOENDIAN */
384                 goto invalid_image;
385
386         if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
387                 goto invalid_image;
388
389         if (header->pe.pe_magic != 0x10B) /* FIXME: ENOENDIAN */
390                 goto invalid_image;
391
392         if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
393                 goto invalid_image;
394
395         /*
396          * FIXME: byte swap all addresses here for header.
397          */
398         
399         if (!load_section_tables (image, iinfo))
400                 goto invalid_image;
401         
402         /* Load the CLI header */
403         if (!load_cli_header (image, iinfo))
404                 goto invalid_image;
405
406         if (!load_metadata (image, iinfo))
407                 goto invalid_image;
408
409         load_class_names (image);
410
411         image->assembly_name = mono_metadata_string_heap (image, 
412                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
413                                         0, MONO_ASSEMBLY_NAME));
414
415         if (status)
416                 *status = MONO_IMAGE_OK;
417
418         return image;
419
420 invalid_image:
421         mono_image_close (image);
422                 return NULL;
423 }
424
425 /**
426  * mono_image_open:
427  * @fname: filename that points to the module we want to open
428  * @status: An error condition is returned in this field
429  *
430  * Retuns: An open image of type %MonoImage or NULL on error.
431  * if NULL, then check the value of @status for details on the error
432  */
433 MonoImage *
434 mono_image_open (const char *fname, enum MonoImageOpenStatus *status)
435 {
436         MonoImage *image;
437         
438         g_return_val_if_fail (fname != NULL, NULL);
439
440         if (loaded_images_hash){
441                 image = g_hash_table_lookup (loaded_images_hash, fname);
442                 if (image){
443                         image->ref_count++;
444                         return image;
445                 }
446         }
447
448         image = do_mono_image_open (fname, status);
449         if (image == NULL)
450                 return NULL;
451
452         if (!loaded_images_hash)
453                 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
454         g_hash_table_insert (loaded_images_hash, image->name, image);
455
456         return image;
457 }
458
459 static void
460 free_hash_table(gpointer key, gpointer val, gpointer user_data)
461 {
462         g_hash_table_destroy ((GHashTable*)val);
463 }
464
465 /**
466  * mono_image_close:
467  * @image: The image file we wish to close
468  *
469  * Closes an image file, deallocates all memory consumed and
470  * unmaps all possible sections of the file
471  */
472 void
473 mono_image_close (MonoImage *image)
474 {
475         g_return_if_fail (image != NULL);
476
477         if (--image->ref_count)
478                 return;
479
480         g_hash_table_remove (loaded_images_hash, image->name);
481         
482         if (image->f)
483                 fclose (image->f);
484
485         g_free (image->name);
486
487         g_hash_table_destroy (image->method_cache);
488         g_hash_table_destroy (image->class_cache);
489         g_hash_table_destroy (image->array_cache);
490         g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
491         g_hash_table_destroy (image->name_cache);
492         
493         if (image->raw_metadata != NULL)
494                 mono_raw_buffer_free (image->raw_metadata);
495         
496         if (image->image_info){
497                 MonoCLIImageInfo *ii = image->image_info;
498                 int i;
499
500                 for (i = 0; i < ii->cli_section_count; i++){
501                         if (!ii->cli_sections [i])
502                                 continue;
503                         mono_raw_buffer_free (ii->cli_sections [i]);
504                 }
505                 if (ii->cli_section_tables)
506                         g_free (ii->cli_section_tables);
507                 if (ii->cli_sections)
508                         g_free (ii->cli_sections);
509                 g_free (image->image_info);
510         }
511         
512         g_free (image);
513 }
514
515 /** 
516  * mono_image_strerror:
517  * @status: an code indicating the result from a recent operation
518  *
519  * Returns: a string describing the error
520  */
521 const char *
522 mono_image_strerror (enum MonoImageOpenStatus status)
523 {
524         switch (status){
525         case MONO_IMAGE_OK:
526                 return "success";
527         case MONO_IMAGE_ERROR_ERRNO:
528                 return strerror (errno);
529         case MONO_IMAGE_IMAGE_INVALID:
530                 return "File does not contain a valid CIL image";
531         case MONO_IMAGE_MISSING_ASSEMBLYREF:
532                 return "An assembly was referenced, but could not be found";
533         }
534         return "Internal error";
535 }
536