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