Sat Aug 18 12:40:32 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
153         for (i = 0; i < top; i++)
154                 if (!mono_image_ensure_section_idx (image, i))
155                         return FALSE;
156         
157         return TRUE;
158 }
159
160 static gboolean
161 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
162 {
163         guint32 offset;
164         int n;
165         
166         offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
167         if (offset == INVALID_ADDRESS)
168                 return FALSE;
169
170         if (fseek (image->f, offset, 0) != 0)
171                 return FALSE;
172         
173         if ((n = fread (&iinfo->cli_cli_header, sizeof (MonoCLIHeader), 1, image->f)) != 1)
174                 return FALSE;
175
176         /* Catch new uses of the fields that are supposed to be zero */
177
178         if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
179             (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
180             (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
181             (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
182             (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
183             (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
184             (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
185             (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
186             (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
187                 g_warning ("Some fields in the CLI header which should have been zero are not zero");
188         }
189             
190         return TRUE;
191 }
192
193 static gboolean
194 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
195 {
196         MonoMetadata *metadata = &image->metadata;
197         guint32 offset, size;
198         guint16 streams;
199         int i;
200         char *ptr;
201         
202         offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
203         size = iinfo->cli_cli_header.ch_metadata.size;
204         
205         metadata->raw_metadata = mono_raw_buffer_load (fileno (image->f), FALSE, offset, size);
206         if (metadata->raw_metadata == NULL)
207                 return FALSE;
208
209         ptr = metadata->raw_metadata;
210
211         if (strncmp (ptr, "BSJB", 4) == 0){
212                 guint32 version_string_len;
213
214                 ptr += 12;
215                 version_string_len = read32 (ptr);
216                 ptr += 4;
217                 ptr += version_string_len;
218                 if (((guint32) ptr) % 4)
219                         ptr += 4 - (((guint32) ptr) %4);
220         } else
221                 return FALSE;
222
223         /* skip over flags */
224         ptr += 2;
225         
226         streams = read16 (ptr);
227         ptr += 2;
228
229         for (i = 0; i < streams; i++){
230                 if (strncmp (ptr + 8, "#~", 3) == 0){
231                         metadata->heap_tables.offset = read32 (ptr);
232                         metadata->heap_tables.size = read32 (ptr + 4);
233                         ptr += 8 + 3;
234                 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
235                         metadata->heap_strings.offset = read32 (ptr);
236                         metadata->heap_strings.size = read32 (ptr + 4);
237                         ptr += 8 + 9;
238                 } else if (strncmp (ptr + 8, "#US", 4) == 0){
239                         metadata->heap_us.offset = read32 (ptr);
240                         metadata->heap_us.size = read32 (ptr + 4);
241                         ptr += 8 + 4;
242                 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
243                         metadata->heap_blob.offset = read32 (ptr);
244                         metadata->heap_blob.size = read32 (ptr + 4);
245                         ptr += 8 + 6;
246                 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
247                         metadata->heap_guid.offset = read32 (ptr);
248                         metadata->heap_guid.size = read32 (ptr + 4);
249                         ptr += 8 + 6;
250                 } else
251                         g_message ("Unknown heap type: %s\n", ptr + 8);
252                 if (((guint32)ptr) % 4){
253                         ptr += 4 - (((guint32)ptr) % 4);
254                 }
255         }
256         return TRUE;
257 }
258
259 /*
260  * Load representation of logical metadata tables, from the "#~" stream
261  */
262 static gboolean
263 load_tables (MonoImage *image, MonoMetadata *meta)
264 {
265         char *heap_tables = meta->raw_metadata + meta->heap_tables.offset;
266         guint32 *rows;
267         guint64 valid_mask;
268         int valid = 0, table;
269         int heap_sizes;
270         
271         heap_sizes = heap_tables [6];
272         meta->idx_string_wide = ((heap_sizes & 0x01) == 1);
273         meta->idx_guid_wide   = ((heap_sizes & 0x02) == 2);
274         meta->idx_blob_wide   = ((heap_sizes & 0x04) == 4);
275         
276         valid_mask = read64 (heap_tables + 8);
277         rows = (guint32 *) (heap_tables + 24);
278         
279         for (table = 0; table < 64; table++){
280                 if ((valid_mask & ((guint64) 1 << table)) == 0){
281                         meta->tables [table].rows = 0;
282                         continue;
283                 }
284                 if (table > 0x2b) {
285                         g_warning("bits in valid must be zero above 0x2b (II - 23.1.6)");
286                 }
287                 meta->tables [table].rows = read32 (rows);
288                 rows++;
289                 valid++;
290         }
291
292         meta->tables_base = (heap_tables + 24) + (4 * valid);
293
294         /* They must be the same */
295         g_assert ((void *) meta->tables_base == (void *) rows);
296
297         mono_metadata_compute_table_bases (meta);
298         return TRUE;
299 }
300
301 static gboolean
302 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
303 {
304         if (!load_metadata_ptrs (image, iinfo))
305                 return FALSE;
306
307         return load_tables (image, &image->metadata);
308 }
309
310 static MonoImage *
311 do_mono_image_open (const char *fname, enum MonoImageOpenStatus *status)
312 {
313         MonoCLIImageInfo *iinfo;
314         MonoDotNetHeader *header;
315         MonoMSDOSHeader msdos;
316         MonoImage *image;
317         int n;
318
319         image = g_new0 (MonoImage, 1);
320         image->f = fopen (fname, "r");
321         image->name = g_strdup (fname);
322         iinfo = g_new0 (MonoCLIImageInfo, 1);
323         image->image_info = iinfo;
324
325         image->method_cache = g_hash_table_new (g_direct_hash, g_direct_equal);
326         image->class_cache = g_hash_table_new (g_direct_hash, g_direct_equal);
327         image->array_cache = g_hash_table_new (g_direct_hash, g_direct_equal);
328
329         header = &iinfo->cli_header;
330                 
331         if (image->f == NULL){
332                 if (status)
333                         *status = MONO_IMAGE_ERROR_ERRNO;
334                 mono_image_close (image);
335                 return NULL;
336         }
337
338         if (status)
339                 *status = MONO_IMAGE_IMAGE_INVALID;
340         
341         if (fread (&msdos, sizeof (msdos), 1, image->f) != 1)
342                 goto invalid_image;
343         
344         if (!(msdos.msdos_header [0] == 0x4d && msdos.msdos_header [1] == 0x5a))
345                 goto invalid_image;
346         
347         if ((n = fread (header, sizeof (MonoDotNetHeader), 1, image->f)) != 1)
348                 goto invalid_image;
349
350         /*
351          * FIXME: byte swap all addresses here for header.
352          */
353         
354         if (!load_section_tables (image, iinfo))
355                 goto invalid_image;
356         
357         /* Load the CLI header */
358         if (!load_cli_header (image, iinfo))
359                 goto invalid_image;
360
361         if (!load_metadata (image, iinfo))
362                 goto invalid_image;
363         
364         if (status)
365                 *status = MONO_IMAGE_OK;
366
367         return image;
368
369 invalid_image:
370         mono_image_close (image);
371                 return NULL;
372 }
373
374 /**
375  * mono_image_open:
376  * @fname: filename that points to the module we want to open
377  * @status: An error condition is returned in this field
378  *
379  * Retuns: An open image of type %MonoImage or NULL on error.
380  * if NULL, then check the value of @status for details on the error
381  */
382 MonoImage *
383 mono_image_open (const char *fname, enum MonoImageOpenStatus *status)
384 {
385         MonoImage *image;
386         
387         g_return_val_if_fail (fname != NULL, NULL);
388
389         if (loaded_images_hash){
390                 image = g_hash_table_lookup (loaded_images_hash, fname);
391                 if (image){
392                         image->ref_count++;
393                         return image;
394                 }
395         }
396
397         image = do_mono_image_open (fname, status);
398         if (image == NULL)
399                 return NULL;
400
401         if (!loaded_images_hash)
402                 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
403         g_hash_table_insert (loaded_images_hash, image->name, image);
404
405         return image;
406 }
407
408 /**
409  * mono_image_close:
410  * @image: The image file we wish to close
411  *
412  * Closes an image file, deallocates all memory consumed and
413  * unmaps all possible sections of the file
414  */
415 void
416 mono_image_close (MonoImage *image)
417 {
418         g_return_if_fail (image != NULL);
419
420         if (--image->ref_count)
421                 return;
422
423         g_hash_table_remove (loaded_images_hash, image->name);
424         
425         if (image->f)
426                 fclose (image->f);
427
428         g_free (image->name);
429         
430         if (image->metadata.raw_metadata != NULL)
431                 mono_raw_buffer_free (image->metadata.raw_metadata);
432         
433         if (image->image_info){
434                 MonoCLIImageInfo *ii = image->image_info;
435                 int i;
436
437                 for (i = 0; i < ii->cli_section_count; i++){
438                         if (!ii->cli_sections [i])
439                                 continue;
440                         mono_raw_buffer_free (ii->cli_sections [i]);
441                 }
442                 if (ii->cli_section_tables)
443                         g_free (ii->cli_section_tables);
444                 if (ii->cli_sections)
445                         g_free (ii->cli_sections);
446                 g_free (image->image_info);
447         }
448         
449         g_free (image);
450 }
451
452 /** 
453  * mono_image_strerror:
454  * @status: an code indicating the result from a recent operation
455  *
456  * Returns: a string describing the error
457  */
458 const char *
459 mono_image_strerror (enum MonoImageOpenStatus status)
460 {
461         switch (status){
462         case MONO_IMAGE_OK:
463                 return "success";
464         case MONO_IMAGE_ERROR_ERRNO:
465                 return strerror (errno);
466         case MONO_IMAGE_IMAGE_INVALID:
467                 return "File does not contain a valid CIL image";
468         case MONO_IMAGE_MISSING_ASSEMBLYREF:
469                 return "An assembly was referenced, but could not be found";
470         }
471         return "Internal error";
472 }
473