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