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