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