2008-04-08 Rodrigo Kumpera <rkumpera@novell.com>
[mono.git] / mono / metadata / pedump.c
1 /*
2  * pedump.c: Dumps the contents of an extended PE/COFF file
3  *
4  * Author:
5  *   Miguel de Icaza (miguel@ximian.com)
6  *
7  * (C) 2001 Ximian, Inc.
8  */
9 #include <config.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include "image.h"
14 #include <glib.h>
15 #include "cil-coff.h"
16 #include "mono-endian.h"
17 #include "verify.h"
18 #include <mono/metadata/class.h>
19 #include <mono/metadata/debug-helpers.h>
20 #include <mono/metadata/tokentype.h>
21 #include <mono/metadata/appdomain.h>
22 #include <mono/metadata/assembly.h>
23 #include <mono/metadata/metadata-internals.h>
24 #include <mono/metadata/rawbuffer.h>
25 #include <mono/metadata/class-internals.h>
26 #include <mono/metadata/verify-internals.h>
27 #include "mono/utils/mono-digest.h"
28
29 gboolean dump_data = TRUE;
30 gboolean verify_pe = FALSE;
31
32 /* unused
33 static void
34 hex_dump (const char *buffer, int base, int count)
35 {
36         int i;
37         
38         for (i = 0; i < count; i++){
39                 if ((i % 16) == 0)
40                         printf ("\n0x%08x: ", (unsigned char) base + i);
41
42                 printf ("%02x ", (unsigned char) (buffer [i]));
43         }
44 }
45 */
46
47 static void
48 hex8 (const char *label, unsigned char x)
49 {
50         printf ("\t%s: 0x%02x\n", label, (unsigned char) x);
51 }
52
53 static void
54 hex16 (const char *label, guint16 x)
55 {
56         printf ("\t%s: 0x%04x\n", label, x);
57 }
58
59 static void
60 hex32 (const char *label, guint32 x)
61 {
62         printf ("\t%s: 0x%08x\n", label, x);
63 }
64
65 static void
66 dump_coff_header (MonoCOFFHeader *coff)
67 {
68         printf ("\nCOFF Header:\n");
69         hex16 ("                Machine", coff->coff_machine);
70         hex16 ("               Sections", coff->coff_sections);
71         hex32 ("             Time stamp", coff->coff_time);
72         hex32 ("Pointer to Symbol Table", coff->coff_symptr);
73         hex32 ("           Symbol Count", coff->coff_symcount);
74         hex16 ("   Optional Header Size", coff->coff_opt_header_size);
75         hex16 ("        Characteristics", coff->coff_attributes);
76
77 }
78
79 static void
80 dump_pe_header (MonoPEHeader *pe)
81 {
82         printf ("\nPE Header:\n");
83         hex16 ("         Magic (0x010b)", pe->pe_magic);
84         hex8  ("             LMajor (6)", pe->pe_major);
85         hex8  ("             LMinor (0)", pe->pe_minor);
86         hex32 ("              Code Size", pe->pe_code_size);
87         hex32 ("  Initialized Data Size", pe->pe_data_size);
88         hex32 ("Uninitialized Data Size", pe->pe_uninit_data_size);
89         hex32 ("        Entry Point RVA", pe->pe_rva_entry_point);
90         hex32 ("          Code Base RVA", pe->pe_rva_code_base);
91         hex32 ("          Data Base RVA", pe->pe_rva_data_base);
92         printf ("\n");
93 }
94
95 static void
96 dump_nt_header (MonoPEHeaderNT *nt)
97 {
98         printf ("\nNT Header:\n");
99
100         hex32 ("   Image Base (0x400000)", nt->pe_image_base);
101         hex32 ("Section Alignment (8192)", nt->pe_section_align);
102         hex32 ("   File Align (512/4096)", nt->pe_file_alignment);
103         hex16 ("            OS Major (4)", nt->pe_os_major);
104         hex16 ("            OS Minor (0)", nt->pe_os_minor);
105         hex16 ("          User Major (0)", nt->pe_user_major);
106         hex16 ("          User Minor (0)", nt->pe_user_minor);
107         hex16 ("        Subsys major (4)", nt->pe_subsys_major);
108         hex16 ("        Subsys minor (0)", nt->pe_subsys_minor);
109         hex32 ("               Reserverd", nt->pe_reserved_1);
110         hex32 ("              Image Size", nt->pe_image_size);
111         hex32 ("             Header Size", nt->pe_header_size);
112         hex32 ("            Checksum (0)", nt->pe_checksum);
113         hex16 ("               Subsystem", nt->pe_subsys_required);
114         hex16 ("           DLL Flags (0)", nt->pe_dll_flags);
115         hex32 (" Stack Reserve Size (1M)", nt->pe_stack_reserve);
116         hex32 ("Stack commit Size (4096)", nt->pe_stack_commit);
117         hex32 ("  Heap Reserve Size (1M)", nt->pe_heap_reserve);
118         hex32 (" Heap Commit Size (4096)", nt->pe_heap_commit);
119         hex32 ("      Loader flags (0x1)", nt->pe_loader_flags);
120         hex32 ("   Data Directories (16)", nt->pe_data_dir_count);
121 }
122
123 static void
124 dent (const char *label, MonoPEDirEntry de)
125 {
126         printf ("\t%s: 0x%08x [0x%08x]\n", label, de.rva, de.size);
127 }
128
129 static void
130 dump_blob (const char *desc, const char* p, guint32 size)
131 {
132         int i;
133
134         printf ("%s", desc);
135         if (!p) {
136                 printf (" none\n");
137                 return;
138         }
139
140         for (i = 0; i < size; ++i) {
141                 if (!(i % 16))
142                         printf ("\n\t");
143                 printf (" %02X", p [i] & 0xFF);
144         }
145         printf ("\n");
146 }
147
148 static void
149 dump_public_key (MonoImage *m)
150 {
151         guint32 size;
152         const char *p;
153
154         p = mono_image_get_public_key (m, &size);
155         dump_blob ("\nPublic key:", p, size);
156 }
157
158 static void
159 dump_strong_name (MonoImage *m)
160 {
161         guint32 size;
162         const char *p;
163
164         p = mono_image_get_strong_name (m, &size);
165         dump_blob ("\nStrong name:", p, size);
166 }
167
168 static void
169 dump_datadir (MonoPEDatadir *dd)
170 {
171         printf ("\nData directories:\n");
172         dent ("     Export Table", dd->pe_export_table);
173         dent ("     Import Table", dd->pe_import_table);
174         dent ("   Resource Table", dd->pe_resource_table);
175         dent ("  Exception Table", dd->pe_exception_table);
176         dent ("Certificate Table", dd->pe_certificate_table);
177         dent ("      Reloc Table", dd->pe_reloc_table);
178         dent ("            Debug", dd->pe_debug);
179         dent ("        Copyright", dd->pe_copyright);
180         dent ("       Global Ptr", dd->pe_global_ptr);
181         dent ("        TLS Table", dd->pe_tls_table);
182         dent ("Load Config Table", dd->pe_load_config_table);
183         dent ("     Bound Import", dd->pe_bound_import);
184         dent ("              IAT", dd->pe_iat);
185         dent ("Delay Import Desc", dd->pe_delay_import_desc);
186         dent ("       CLI Header", dd->pe_cli_header);
187 }
188
189 static void
190 dump_dotnet_header (MonoDotNetHeader *header)
191 {
192         dump_coff_header (&header->coff);
193         dump_pe_header (&header->pe);
194         dump_nt_header (&header->nt);
195         dump_datadir (&header->datadir);
196 }
197
198 static void
199 dump_section_table (MonoSectionTable *st)
200 {
201         guint32 flags = st->st_flags;
202                 
203         printf ("\n\tName: %s\n", st->st_name);
204         hex32 ("   Virtual Size", st->st_virtual_size);
205         hex32 ("Virtual Address", st->st_virtual_address);
206         hex32 ("  Raw Data Size", st->st_raw_data_size);
207         hex32 ("   Raw Data Ptr", st->st_raw_data_ptr);
208         hex32 ("      Reloc Ptr", st->st_reloc_ptr);
209         hex32 ("     LineNo Ptr", st->st_lineno_ptr);
210         hex16 ("    Reloc Count", st->st_reloc_count);
211         hex16 ("     Line Count", st->st_line_count);
212
213         printf ("\tFlags: %s%s%s%s%s%s%s%s%s%s\n",
214                 (flags & SECT_FLAGS_HAS_CODE) ? "code, " : "",
215                 (flags & SECT_FLAGS_HAS_INITIALIZED_DATA) ? "data, " : "",
216                 (flags & SECT_FLAGS_HAS_UNINITIALIZED_DATA) ? "bss, " : "",
217                 (flags & SECT_FLAGS_MEM_DISCARDABLE) ? "discard, " : "",
218                 (flags & SECT_FLAGS_MEM_NOT_CACHED) ? "nocache, " : "",
219                 (flags & SECT_FLAGS_MEM_NOT_PAGED) ? "nopage, " : "",
220                 (flags & SECT_FLAGS_MEM_SHARED) ? "shared, " : "",
221                 (flags & SECT_FLAGS_MEM_EXECUTE) ? "exec, " : "",
222                 (flags & SECT_FLAGS_MEM_READ) ? "read, " : "",
223                 (flags & SECT_FLAGS_MEM_WRITE) ? "write" : "");
224 }
225
226 static void
227 dump_sections (MonoCLIImageInfo *iinfo)
228 {
229         const int top = iinfo->cli_header.coff.coff_sections;
230         int i;
231         
232         for (i = 0; i < top; i++)
233                 dump_section_table (&iinfo->cli_section_tables [i]);
234 }
235
236 static void
237 dump_cli_header (MonoCLIHeader *ch)
238 {
239         printf ("\n");
240         printf ("          CLI header size: %d\n", ch->ch_size);
241         printf ("         Runtime required: %d.%d\n", ch->ch_runtime_major, ch->ch_runtime_minor);
242         printf ("                    Flags: %s, %s, %s, %s\n",
243                 (ch->ch_flags & CLI_FLAGS_ILONLY ? "ilonly" : "contains native"),
244                 (ch->ch_flags & CLI_FLAGS_32BITREQUIRED ? "32bits" : "32/64"),
245                 (ch->ch_flags & CLI_FLAGS_ILONLY ? "trackdebug" : "no-trackdebug"),
246                 (ch->ch_flags & CLI_FLAGS_STRONGNAMESIGNED ? "strongnamesigned" : "notsigned"));
247         dent   ("         Metadata", ch->ch_metadata);
248         hex32  ("Entry Point Token", ch->ch_entry_point);
249         dent   ("     Resources at", ch->ch_resources);
250         dent   ("   Strong Name at", ch->ch_strong_name);
251         dent   ("  Code Manager at", ch->ch_code_manager_table);
252         dent   ("  VTableFixups at", ch->ch_vtable_fixups);
253         dent   ("     EAT jumps at", ch->ch_export_address_table_jumps);
254 }       
255
256 static void
257 dsh (const char *label, MonoImage *meta, MonoStreamHeader *sh)
258 {
259         printf ("%s: 0x%08x - 0x%08x [%d == 0x%08x]\n",
260                 label,
261                 (int)(sh->data - meta->raw_metadata), (int)(sh->data + sh->size - meta->raw_metadata),
262                 sh->size, sh->size);
263 }
264
265 static void
266 dump_metadata_header (MonoImage *meta)
267 {
268         printf ("\nMetadata header:\n");
269         printf ("           Version: %d.%d\n", meta->md_version_major, meta->md_version_minor);
270         printf ("    Version string: %s\n", meta->version);
271 }
272
273 static void
274 dump_metadata_ptrs (MonoImage *meta)
275 {
276         printf ("\nMetadata pointers:\n");
277         dsh ("\tTables (#~)", meta, &meta->heap_tables);
278         dsh ("\t    Strings", meta, &meta->heap_strings);
279         dsh ("\t       Blob", meta, &meta->heap_blob);
280         dsh ("\tUser string", meta, &meta->heap_us);
281         dsh ("\t       GUID", meta, &meta->heap_guid);
282 }
283
284 static void
285 dump_metadata (MonoImage *meta)
286 {
287         int table;
288
289         dump_metadata_header (meta);
290
291         dump_metadata_ptrs (meta);
292
293         printf ("Rows:\n");
294         for (table = 0; table < MONO_TABLE_NUM; table++){
295                 if (meta->tables [table].rows == 0)
296                         continue;
297                 printf ("Table %s: %d records (%d bytes, at %p)\n",
298                         mono_meta_table_name (table),
299                         meta->tables [table].rows,
300                         meta->tables [table].row_size,
301                         meta->tables [table].base
302                         );
303         }
304 }
305
306 static void
307 dump_methoddef (MonoImage *metadata, guint32 token)
308 {
309         const char *loc;
310
311         if (!token)
312                 return;
313         loc = mono_metadata_locate_token (metadata, token);
314
315         printf ("RVA for Entry Point: 0x%08x\n", read32 (loc));
316 }
317
318 static void
319 dump_dotnet_iinfo (MonoImage *image)
320 {
321         MonoCLIImageInfo *iinfo = image->image_info;
322
323         dump_dotnet_header (&iinfo->cli_header);
324         dump_sections (iinfo);
325         dump_cli_header (&iinfo->cli_cli_header);
326         dump_strong_name (image);
327         dump_public_key (image);
328         dump_metadata (image);
329
330         dump_methoddef (image, iinfo->cli_cli_header.ch_entry_point);
331 }
332
333 static int
334 dump_verify_info (MonoImage *image, int flags)
335 {
336         GSList *errors, *tmp;
337         int count = 0, verifiable = 0;
338         const char* desc [] = {
339                 "Ok", "Error", "Warning", NULL, "CLS", NULL, NULL, NULL, "Not Verifiable"
340         };
341
342         errors = mono_image_verify_tables (image, flags);
343
344         for (tmp = errors; tmp; tmp = tmp->next) {
345                 MonoVerifyInfo *info = tmp->data;
346                 g_print ("%s: %s\n", desc [info->status], info->message);
347                 if (info->status == MONO_VERIFY_ERROR)
348                         count++;
349         }
350         mono_free_verify_list (errors);
351
352         if (flags & (MONO_VERIFY_ALL + 1)) { /* verify code */
353                 int i;
354                 MonoTableInfo *m = &image->tables [MONO_TABLE_METHOD];
355                 
356                 mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
357
358                 for (i = 0; i < m->rows; ++i) {
359                         MonoMethod *method;
360                         method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i+1), NULL);
361                         errors = mono_method_verify (method, flags);
362                         if (errors) {
363                                 char *sig;
364                                 MonoClass *klass = mono_method_get_class (method);
365                                 sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
366                                 //FIXME report the class name taking nesting into account
367                                 g_print ("In method: %s.%s::%s(%s)\n", mono_class_get_namespace (klass), mono_class_get_name (klass), mono_method_get_name (method), sig);
368                                 g_free (sig);
369                         }
370
371                         for (tmp = errors; tmp; tmp = tmp->next) {
372                                 MonoVerifyInfo *info = tmp->data;
373                                 g_print ("%s: %s\n", desc [info->status], info->message);
374                                 if (info->status == MONO_VERIFY_ERROR) {
375                                         count++;
376                                         verifiable = 3;
377                                 }
378                                 if(info->status == MONO_VERIFY_NOT_VERIFIABLE) {
379                                         if (verifiable < 2)
380                                                 verifiable = 2; 
381                                 }
382                         }
383                         mono_free_verify_list (errors);
384                 }
385         }
386
387         if (count)
388                 g_print ("Error count: %d\n", count);
389         return verifiable;
390 }
391
392 static void
393 usage (void)
394 {
395         printf ("Usage is: pedump [--verify error,warn,cls,all,code,fail-on-verifiable,non-strict] file.exe\n");
396         exit (1);
397 }
398
399 int
400 main (int argc, char *argv [])
401 {
402         MonoImage *image;
403         char *file = NULL;
404         char *flags = NULL;
405         const char *flag_desc [] = {"error", "warn", "cls", "all", "code", "fail-on-verifiable", "non-strict", NULL};
406         guint flag_vals [] = {MONO_VERIFY_ERROR, MONO_VERIFY_WARNING, MONO_VERIFY_CLS, MONO_VERIFY_ALL, MONO_VERIFY_ALL + 1, MONO_VERIFY_FAIL_FAST, MONO_VERIFY_NON_STRICT};
407         int i;
408         
409         for (i = 1; i < argc; i++){
410                 if (argv [i][0] != '-'){
411                         file = argv [i];
412                         continue;
413                 }
414
415                 if (strcmp (argv [i], "--help") == 0)
416                         usage ();
417                 else if (strcmp (argv [i], "--verify") == 0) {
418                         verify_pe = 1;
419                         dump_data = 0;
420                         ++i;
421                         flags = argv [i];
422                 } else {
423                         usage ();
424                 }
425         }
426         
427         if (!file)
428                 usage ();
429
430         mono_metadata_init ();
431         mono_raw_buffer_init ();
432         mono_images_init ();
433         mono_assemblies_init ();
434         mono_loader_init ();
435  
436         image = mono_image_open (file, NULL);
437         if (!image){
438                 fprintf (stderr, "Can not open image %s\n", file);
439                 exit (1);
440         }
441
442         if (dump_data)
443                 dump_dotnet_iinfo (image);
444         if (verify_pe) {
445                 int f = 0;
446                 char *tok = strtok (flags, ",");
447                 MonoAssembly *assembly;
448                 while (tok) {
449                         for (i = 0; flag_desc [i]; ++i) {
450                                 if (strcmp (tok, flag_desc [i]) == 0) {
451                                         f |= flag_vals [i];
452                                         break;
453                                 }
454                         }
455                         if (!flag_desc [i])
456                                 g_print ("Unknown verify flag %s\n", tok);
457                         tok = strtok (NULL, ",");
458                 }
459                 mono_init_from_assembly (file, file);
460                 assembly = mono_assembly_open (file, NULL);
461
462                 if (!assembly) {
463                         g_print ("Could not open assembly %s\n", file);
464                         return 4;
465                 }
466
467                 return dump_verify_info (assembly->image, f);
468         } else
469                 mono_image_close (image);
470         
471         return 0;
472 }
473