New test.
[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_ptrs (MonoImage *meta)
266 {
267         printf ("\nMetadata pointers:\n");
268         dsh ("\tTables (#~)", meta, &meta->heap_tables);
269         dsh ("\t    Strings", meta, &meta->heap_strings);
270         dsh ("\t       Blob", meta, &meta->heap_blob);
271         dsh ("\tUser string", meta, &meta->heap_us);
272         dsh ("\t       GUID", meta, &meta->heap_guid);
273 }
274
275 static void
276 dump_metadata (MonoImage *meta)
277 {
278         int table;
279         
280         dump_metadata_ptrs (meta);
281
282         printf ("Rows:\n");
283         for (table = 0; table < MONO_TABLE_NUM; table++){
284                 if (meta->tables [table].rows == 0)
285                         continue;
286                 printf ("Table %s: %d records (%d bytes, at %p)\n",
287                         mono_meta_table_name (table),
288                         meta->tables [table].rows,
289                         meta->tables [table].row_size,
290                         meta->tables [table].base
291                         );
292         }
293 }
294
295 static void
296 dump_methoddef (MonoImage *metadata, guint32 token)
297 {
298         const char *loc;
299
300         if (!token)
301                 return;
302         loc = mono_metadata_locate_token (metadata, token);
303
304         printf ("RVA for Entry Point: 0x%08x\n", read32 (loc));
305 }
306
307 static void
308 dump_dotnet_iinfo (MonoImage *image)
309 {
310         MonoCLIImageInfo *iinfo = image->image_info;
311
312         dump_dotnet_header (&iinfo->cli_header);
313         dump_sections (iinfo);
314         dump_cli_header (&iinfo->cli_cli_header);
315         dump_strong_name (image);
316         dump_public_key (image);
317         dump_metadata (image);
318
319         dump_methoddef (image, iinfo->cli_cli_header.ch_entry_point);
320 }
321
322 static void
323 dump_verify_info (MonoImage *image, int flags)
324 {
325         GSList *errors, *tmp;
326         int count = 0;
327         const char* desc [] = {
328                 "Ok", "Error", "Warning", NULL, "CLS"
329         };
330
331         errors = mono_image_verify_tables (image, flags);
332
333         for (tmp = errors; tmp; tmp = tmp->next) {
334                 MonoVerifyInfo *info = tmp->data;
335                 g_print ("%s: %s\n", desc [info->status], info->message);
336                 if (info->status == MONO_VERIFY_ERROR)
337                         count++;
338         }
339         mono_free_verify_list (errors);
340
341         if (flags & (MONO_VERIFY_ALL + 1)) { /* verify code */
342                 int i;
343                 MonoTableInfo *m = &image->tables [MONO_TABLE_METHOD];
344
345                 for (i = 0; i < m->rows; ++i) {
346                         MonoMethod *method;
347
348                         method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i+1), NULL);
349                         errors = mono_method_verify (method, flags);
350                         if (errors) {
351                                 char *sig;
352                                 MonoClass *klass = mono_method_get_class (method);
353                                 sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
354                                 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);
355                                 g_free (sig);
356                         }
357
358                         for (tmp = errors; tmp; tmp = tmp->next) {
359                                 MonoVerifyInfo *info = tmp->data;
360                                 g_print ("%s: %s\n", desc [info->status], info->message);
361                                 if (info->status == MONO_VERIFY_ERROR)
362                                         count++;
363                         }
364                         mono_free_verify_list (errors);
365                 }
366         }
367
368         if (count)
369                 g_print ("Error count: %d\n", count);
370 }
371
372 static void
373 usage (void)
374 {
375         printf ("Usage is: pedump [--verify error,warn,cls,all,code] file.exe\n");
376         exit (1);
377 }
378
379 int
380 main (int argc, char *argv [])
381 {
382         MonoImage *image;
383         char *file = NULL;
384         char *flags = NULL;
385         const char *flag_desc [] = {"error", "warn", "cls", "all", "code", NULL};
386         guint flag_vals [] = {MONO_VERIFY_ERROR, MONO_VERIFY_WARNING, MONO_VERIFY_CLS, MONO_VERIFY_ALL, MONO_VERIFY_ALL + 1};
387         int i;
388         
389         for (i = 1; i < argc; i++){
390                 if (argv [i][0] != '-'){
391                         file = argv [i];
392                         continue;
393                 }
394
395                 if (strcmp (argv [i], "--help") == 0)
396                         usage ();
397                 else if (strcmp (argv [i], "--verify") == 0) {
398                         verify_pe = 1;
399                         dump_data = 0;
400                         ++i;
401                         flags = argv [i];
402                 } else {
403                         usage ();
404                 }
405         }
406         
407         if (!file)
408                 usage ();
409
410         mono_metadata_init ();
411         mono_raw_buffer_init ();
412         mono_images_init ();
413         mono_assemblies_init ();
414         mono_loader_init ();
415  
416         image = mono_image_open (file, NULL);
417         if (!image){
418                 fprintf (stderr, "Can not open image %s\n", file);
419                 exit (1);
420         }
421
422         if (dump_data)
423                 dump_dotnet_iinfo (image);
424         if (verify_pe) {
425                 int f = 0;
426                 char *tok = strtok (flags, ",");
427                 MonoAssembly *assembly;
428                 while (tok) {
429                         for (i = 0; flag_desc [i]; ++i) {
430                                 if (strcmp (tok, flag_desc [i]) == 0) {
431                                         f |= flag_vals [i];
432                                         break;
433                                 }
434                         }
435                         if (!flag_desc [i])
436                                 g_print ("Unknown verify flag %s\n", tok);
437                         tok = strtok (NULL, ",");
438                 }
439                 mono_init (file);
440                 assembly = mono_assembly_open (file, NULL);
441                 dump_verify_info (assembly->image, f);
442         } else
443                 mono_image_close (image);
444         
445         return 0;
446 }
447