Merge pull request #5714 from alexischr/update_bockbuild
[mono.git] / tools / pedump / 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  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
8  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
9  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
10  */
11 #include <config.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <mono/metadata/image.h>
16 #include <glib.h>
17 #include <mono/metadata/cil-coff.h>
18 #include <mono/metadata/mono-endian.h>
19 #include <mono/metadata/verify.h>
20 #include <mono/metadata/class.h>
21 #include <mono/metadata/debug-helpers.h>
22 #include <mono/metadata/tokentype.h>
23 #include <mono/metadata/appdomain.h>
24 #include <mono/metadata/assembly-internals.h>
25 #include <mono/metadata/metadata-internals.h>
26 #include <mono/metadata/class-internals.h>
27 #include <mono/metadata/verify-internals.h>
28 #include <mono/metadata/marshal.h>
29 #include <mono/metadata/w32handle.h>
30 #include "mono/utils/mono-digest.h"
31 #include <mono/utils/mono-mmap.h>
32 #include <mono/utils/mono-counters.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #ifdef HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38
39 gboolean dump_data = TRUE;
40 gboolean verify_pe = FALSE;
41 gboolean verify_metadata = FALSE;
42 gboolean verify_code = FALSE;
43 gboolean verify_partial_md = FALSE;
44
45 static char *assembly_directory[2];
46
47 static MonoAssembly *pedump_preload (MonoAssemblyName *aname, gchar **assemblies_path, gpointer user_data);
48 static void pedump_assembly_load_hook (MonoAssembly *assembly, gpointer user_data);
49 static MonoAssembly *pedump_assembly_search_hook (MonoAssemblyName *aname, gpointer user_data);
50
51 /* unused
52 static void
53 hex_dump (const char *buffer, int base, int count)
54 {
55         int i;
56         
57         for (i = 0; i < count; i++){
58                 if ((i % 16) == 0)
59                         printf ("\n0x%08x: ", (unsigned char) base + i);
60
61                 printf ("%02x ", (unsigned char) (buffer [i]));
62         }
63 }
64 */
65
66 static void
67 hex8 (const char *label, unsigned char x)
68 {
69         printf ("\t%s: 0x%02x\n", label, (unsigned char) x);
70 }
71
72 static void
73 hex16 (const char *label, guint16 x)
74 {
75         printf ("\t%s: 0x%04x\n", label, x);
76 }
77
78 static void
79 hex32 (const char *label, guint32 x)
80 {
81         printf ("\t%s: 0x%08x\n", label, x);
82 }
83
84 static void
85 dump_coff_header (MonoCOFFHeader *coff)
86 {
87         printf ("\nCOFF Header:\n");
88         hex16 ("                Machine", coff->coff_machine);
89         hex16 ("               Sections", coff->coff_sections);
90         hex32 ("             Time stamp", coff->coff_time);
91         hex32 ("Pointer to Symbol Table", coff->coff_symptr);
92         hex32 ("           Symbol Count", coff->coff_symcount);
93         hex16 ("   Optional Header Size", coff->coff_opt_header_size);
94         hex16 ("        Characteristics", coff->coff_attributes);
95
96 }
97
98 static void
99 dump_pe_header (MonoPEHeader *pe)
100 {
101         printf ("\nPE Header:\n");
102         hex16 ("         Magic (0x010b)", pe->pe_magic);
103         hex8  ("             LMajor (6)", pe->pe_major);
104         hex8  ("             LMinor (0)", pe->pe_minor);
105         hex32 ("              Code Size", pe->pe_code_size);
106         hex32 ("  Initialized Data Size", pe->pe_data_size);
107         hex32 ("Uninitialized Data Size", pe->pe_uninit_data_size);
108         hex32 ("        Entry Point RVA", pe->pe_rva_entry_point);
109         hex32 ("          Code Base RVA", pe->pe_rva_code_base);
110         hex32 ("          Data Base RVA", pe->pe_rva_data_base);
111         printf ("\n");
112 }
113
114 static void
115 dump_nt_header (MonoPEHeaderNT *nt)
116 {
117         printf ("\nNT Header:\n");
118
119         hex32 ("   Image Base (0x400000)", nt->pe_image_base);
120         hex32 ("Section Alignment (8192)", nt->pe_section_align);
121         hex32 ("   File Align (512/4096)", nt->pe_file_alignment);
122         hex16 ("            OS Major (4)", nt->pe_os_major);
123         hex16 ("            OS Minor (0)", nt->pe_os_minor);
124         hex16 ("          User Major (0)", nt->pe_user_major);
125         hex16 ("          User Minor (0)", nt->pe_user_minor);
126         hex16 ("        Subsys major (4)", nt->pe_subsys_major);
127         hex16 ("        Subsys minor (0)", nt->pe_subsys_minor);
128         hex32 ("               Reserverd", nt->pe_reserved_1);
129         hex32 ("              Image Size", nt->pe_image_size);
130         hex32 ("             Header Size", nt->pe_header_size);
131         hex32 ("            Checksum (0)", nt->pe_checksum);
132         hex16 ("               Subsystem", nt->pe_subsys_required);
133         hex16 ("           DLL Flags (0)", nt->pe_dll_flags);
134         hex32 (" Stack Reserve Size (1M)", nt->pe_stack_reserve);
135         hex32 ("Stack commit Size (4096)", nt->pe_stack_commit);
136         hex32 ("  Heap Reserve Size (1M)", nt->pe_heap_reserve);
137         hex32 (" Heap Commit Size (4096)", nt->pe_heap_commit);
138         hex32 ("      Loader flags (0x1)", nt->pe_loader_flags);
139         hex32 ("   Data Directories (16)", nt->pe_data_dir_count);
140 }
141
142 static void
143 dent (const char *label, MonoPEDirEntry de)
144 {
145         printf ("\t%s: 0x%08x [0x%08x]\n", label, de.rva, de.size);
146 }
147
148 static void
149 dump_blob (const char *desc, const char* p, guint32 size)
150 {
151         int i;
152
153         printf ("%s", desc);
154         if (!p) {
155                 printf (" none\n");
156                 return;
157         }
158
159         for (i = 0; i < size; ++i) {
160                 if (!(i % 16))
161                         printf ("\n\t");
162                 printf (" %02X", p [i] & 0xFF);
163         }
164         printf ("\n");
165 }
166
167 static void
168 dump_public_key (MonoImage *m)
169 {
170         guint32 size;
171         const char *p;
172
173         p = mono_image_get_public_key (m, &size);
174         dump_blob ("\nPublic key:", p, size);
175 }
176
177 static void
178 dump_strong_name (MonoImage *m)
179 {
180         guint32 size;
181         const char *p;
182
183         p = mono_image_get_strong_name (m, &size);
184         dump_blob ("\nStrong name:", p, size);
185 }
186
187 static void
188 dump_datadir (MonoPEDatadir *dd)
189 {
190         printf ("\nData directories:\n");
191         dent ("     Export Table", dd->pe_export_table);
192         dent ("     Import Table", dd->pe_import_table);
193         dent ("   Resource Table", dd->pe_resource_table);
194         dent ("  Exception Table", dd->pe_exception_table);
195         dent ("Certificate Table", dd->pe_certificate_table);
196         dent ("      Reloc Table", dd->pe_reloc_table);
197         dent ("            Debug", dd->pe_debug);
198         dent ("        Copyright", dd->pe_copyright);
199         dent ("       Global Ptr", dd->pe_global_ptr);
200         dent ("        TLS Table", dd->pe_tls_table);
201         dent ("Load Config Table", dd->pe_load_config_table);
202         dent ("     Bound Import", dd->pe_bound_import);
203         dent ("              IAT", dd->pe_iat);
204         dent ("Delay Import Desc", dd->pe_delay_import_desc);
205         dent ("       CLI Header", dd->pe_cli_header);
206 }
207
208 static void
209 dump_dotnet_header (MonoDotNetHeader *header)
210 {
211         dump_coff_header (&header->coff);
212         dump_pe_header (&header->pe);
213         dump_nt_header (&header->nt);
214         dump_datadir (&header->datadir);
215 }
216
217 static void
218 dump_section_table (MonoSectionTable *st)
219 {
220         guint32 flags = st->st_flags;
221                 
222         printf ("\n\tName: %s\n", st->st_name);
223         hex32 ("   Virtual Size", st->st_virtual_size);
224         hex32 ("Virtual Address", st->st_virtual_address);
225         hex32 ("  Raw Data Size", st->st_raw_data_size);
226         hex32 ("   Raw Data Ptr", st->st_raw_data_ptr);
227         hex32 ("      Reloc Ptr", st->st_reloc_ptr);
228         hex32 ("     LineNo Ptr", st->st_lineno_ptr);
229         hex16 ("    Reloc Count", st->st_reloc_count);
230         hex16 ("     Line Count", st->st_line_count);
231
232         printf ("\tFlags: %s%s%s%s%s%s%s%s%s%s\n",
233                 (flags & SECT_FLAGS_HAS_CODE) ? "code, " : "",
234                 (flags & SECT_FLAGS_HAS_INITIALIZED_DATA) ? "data, " : "",
235                 (flags & SECT_FLAGS_HAS_UNINITIALIZED_DATA) ? "bss, " : "",
236                 (flags & SECT_FLAGS_MEM_DISCARDABLE) ? "discard, " : "",
237                 (flags & SECT_FLAGS_MEM_NOT_CACHED) ? "nocache, " : "",
238                 (flags & SECT_FLAGS_MEM_NOT_PAGED) ? "nopage, " : "",
239                 (flags & SECT_FLAGS_MEM_SHARED) ? "shared, " : "",
240                 (flags & SECT_FLAGS_MEM_EXECUTE) ? "exec, " : "",
241                 (flags & SECT_FLAGS_MEM_READ) ? "read, " : "",
242                 (flags & SECT_FLAGS_MEM_WRITE) ? "write" : "");
243 }
244
245 static void
246 dump_sections (MonoCLIImageInfo *iinfo)
247 {
248         const int top = iinfo->cli_header.coff.coff_sections;
249         int i;
250         
251         for (i = 0; i < top; i++)
252                 dump_section_table (&iinfo->cli_section_tables [i]);
253 }
254
255 static void
256 dump_cli_header (MonoCLIHeader *ch)
257 {
258         printf ("\n");
259         printf ("          CLI header size: %d\n", ch->ch_size);
260         printf ("         Runtime required: %d.%d\n", ch->ch_runtime_major, ch->ch_runtime_minor);
261         printf ("                    Flags: %s, %s, %s, %s\n",
262                 (ch->ch_flags & CLI_FLAGS_ILONLY ? "ilonly" : "contains native"),
263                 (ch->ch_flags & CLI_FLAGS_32BITREQUIRED ? "32bits" : "32/64"),
264                 (ch->ch_flags & CLI_FLAGS_TRACKDEBUGDATA ? "trackdebug" : "no-trackdebug"),
265                 (ch->ch_flags & CLI_FLAGS_STRONGNAMESIGNED ? "strongnamesigned" : "notsigned"));
266         dent   ("         Metadata", ch->ch_metadata);
267         hex32  ("Entry Point Token", ch->ch_entry_point);
268         dent   ("     Resources at", ch->ch_resources);
269         dent   ("   Strong Name at", ch->ch_strong_name);
270         dent   ("  Code Manager at", ch->ch_code_manager_table);
271         dent   ("  VTableFixups at", ch->ch_vtable_fixups);
272         dent   ("     EAT jumps at", ch->ch_export_address_table_jumps);
273 }       
274
275 static void
276 dsh (const char *label, MonoImage *meta, MonoStreamHeader *sh)
277 {
278         printf ("%s: 0x%08x - 0x%08x [%d == 0x%08x]\n",
279                 label,
280                 (int)(sh->data - meta->raw_metadata), (int)(sh->data + sh->size - meta->raw_metadata),
281                 sh->size, sh->size);
282 }
283
284 static void
285 dump_metadata_header (MonoImage *meta)
286 {
287         printf ("\nMetadata header:\n");
288         printf ("           Version: %d.%d\n", meta->md_version_major, meta->md_version_minor);
289         printf ("    Version string: %s\n", meta->version);
290 }
291
292 static void
293 dump_metadata_ptrs (MonoImage *meta)
294 {
295         printf ("\nMetadata pointers:\n");
296         dsh ("\tTables (#~)", meta, &meta->heap_tables);
297         dsh ("\t    Strings", meta, &meta->heap_strings);
298         dsh ("\t       Blob", meta, &meta->heap_blob);
299         dsh ("\tUser string", meta, &meta->heap_us);
300         dsh ("\t       GUID", meta, &meta->heap_guid);
301 }
302
303 static void
304 dump_metadata (MonoImage *meta)
305 {
306         int table;
307
308         dump_metadata_header (meta);
309
310         dump_metadata_ptrs (meta);
311
312         printf ("Rows:\n");
313         for (table = 0; table < MONO_TABLE_NUM; table++){
314                 if (meta->tables [table].rows == 0)
315                         continue;
316                 printf ("Table %s: %d records (%d bytes, at %x)\n",
317                         mono_meta_table_name (table),
318                         meta->tables [table].rows,
319                         meta->tables [table].row_size,
320                         (unsigned int)(meta->tables [table].base - meta->raw_data)
321                         );
322         }
323 }
324
325 static void
326 dump_methoddef (MonoImage *metadata, guint32 token)
327 {
328         const char *loc;
329
330         if (!token)
331                 return;
332         loc = mono_metadata_locate_token (metadata, token);
333
334         printf ("RVA for Entry Point: 0x%08x\n", read32 (loc));
335 }
336
337 static void
338 dump_dotnet_iinfo (MonoImage *image)
339 {
340         MonoCLIImageInfo *iinfo = (MonoCLIImageInfo *)image->image_info;
341
342         dump_dotnet_header (&iinfo->cli_header);
343         dump_sections (iinfo);
344         dump_cli_header (&iinfo->cli_cli_header);
345         dump_strong_name (image);
346         dump_public_key (image);
347         dump_metadata (image);
348
349         dump_methoddef (image, iinfo->cli_cli_header.ch_entry_point);
350 }
351
352 static int
353 dump_verify_info (MonoImage *image, int flags, gboolean valid_only)
354 {
355         GSList *errors, *tmp;
356         int count = 0, verifiable = 0;
357         const char* desc [] = {
358                 "Ok", "Error", "Warning", NULL, "CLS", NULL, NULL, NULL, "Not Verifiable"
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                         MonoError error;
368
369                         method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i+1), NULL, NULL, &error);
370                         if (!method) {
371                                 g_print ("Warning: Cannot lookup method with token 0x%08x due to %s\n", i + 1, mono_error_get_message (&error));
372                                 mono_error_cleanup (&error);
373                                 continue;
374                         }
375                         errors = mono_method_verify (method, flags);
376                         if (errors) {
377                                 MonoClass *klass = mono_method_get_class (method);
378                                 char *name = mono_type_full_name (&klass->byval_arg);
379                                 if (mono_method_signature (method) == NULL) {
380                                         g_print ("In method: %s::%s(ERROR)\n", name, mono_method_get_name (method));
381                                 } else {
382                                         char *sig;
383                                         sig = mono_signature_get_desc (mono_method_signature (method), FALSE);  
384                                         g_print ("In method: %s::%s(%s)\n", name, mono_method_get_name (method), sig);
385                                         g_free (sig);
386                                 }
387                                 g_free (name);
388                         }
389
390                         for (tmp = errors; tmp; tmp = tmp->next) {
391                                 MonoVerifyInfo *info = (MonoVerifyInfo *)tmp->data;
392                                 if (info->status == MONO_VERIFY_NOT_VERIFIABLE && valid_only)
393                                         continue;
394
395                                 g_print ("%s: %s\n", desc [info->status], info->message);
396                                 if (info->status == MONO_VERIFY_ERROR) {
397                                         count++;
398                                         verifiable = 3;
399                                 }
400                                 if(info->status == MONO_VERIFY_NOT_VERIFIABLE) {
401                                         if (verifiable < 2)
402                                                 verifiable = 2; 
403                                 }
404                         }
405                         mono_free_verify_list (errors);
406                 }
407         }
408
409         if (count)
410                 g_print ("Error count: %d\n", count);
411         return verifiable;
412 }
413
414 static void
415 usage (void)
416 {
417         printf ("Usage is: pedump [--verify error,warn,cls,all,code,fail-on-verifiable,non-strict,valid-only,metadata] file.exe\n");
418         exit (1);
419 }
420
421 static int
422 verify_image_file (const char *fname)
423 {
424         GSList *errors = NULL, *tmp;
425         MonoImage *image;
426         MonoTableInfo *table;
427         MonoAssembly *assembly;
428         MonoImageOpenStatus status;
429         int i, count = 0;
430         const char* desc [] = {
431                 "Ok", "Error", "Warning", NULL, "CLS", NULL, NULL, NULL, "Not Verifiable"
432         };
433
434         if (!strstr (fname, "mscorlib.dll")) {
435                 image = mono_image_open_raw (fname, &status);
436                 if (!image) {
437                         printf ("Could not open %s\n", fname);
438                         return 1;
439                 }
440
441                 if (!mono_verifier_verify_pe_data (image, &errors))
442                         goto invalid_image;
443
444                 if (!mono_image_load_pe_data (image)) {
445                         printf ("Could not load pe data for assembly %s\n", fname);
446                         return 1;
447                 }
448
449                 if (!mono_verifier_verify_cli_data (image, &errors))
450                         goto invalid_image;
451
452                 if (!mono_image_load_cli_data (image)) {
453                         printf ("Could not load cli data for assembly %s\n", fname);
454                         return 1;
455                 }
456
457                 if (!mono_verifier_verify_table_data (image, &errors))
458                         goto invalid_image;
459
460                 mono_image_load_names (image);
461
462                 /*fake an assembly for class loading to work*/
463                 assembly = g_new0 (MonoAssembly, 1);
464                 assembly->in_gac = FALSE;
465                 assembly->image = image;
466                 image->assembly = assembly;
467                 mono_assembly_fill_assembly_name (image, &assembly->aname);
468
469                 /*Finish initializing the runtime*/
470                 mono_install_assembly_load_hook (pedump_assembly_load_hook, NULL);
471                 mono_install_assembly_search_hook (pedump_assembly_search_hook, NULL);
472
473                 mono_init_version ("pedump", image->version);
474
475                 mono_install_assembly_preload_hook (pedump_preload, GUINT_TO_POINTER (FALSE));
476
477                 mono_icall_init ();
478                 mono_marshal_init ();
479         } else {
480                 /*Finish initializing the runtime*/
481                 mono_install_assembly_load_hook (pedump_assembly_load_hook, NULL);
482                 mono_install_assembly_search_hook (pedump_assembly_search_hook, NULL);
483
484                 mono_init_version ("pedump", NULL);
485
486                 mono_install_assembly_preload_hook (pedump_preload, GUINT_TO_POINTER (FALSE));
487
488                 mono_icall_init ();
489                 mono_marshal_init ();
490                 image = mono_get_corlib ();
491
492                 if (!mono_verifier_verify_pe_data (image, &errors))
493                         goto invalid_image;
494
495                 if (!mono_image_load_pe_data (image)) {
496                         printf ("Could not load pe data for assembly %s\n", fname);
497                         return 1;
498                 }
499
500                 if (!mono_verifier_verify_cli_data (image, &errors))
501                         goto invalid_image;
502
503                 if (!mono_image_load_cli_data (image)) {
504                         printf ("Could not load cli data for assembly %s\n", fname);
505                         return 1;
506                 }
507
508                 if (!mono_verifier_verify_table_data (image, &errors))
509                         goto invalid_image;
510         }
511
512         if (!verify_partial_md && !mono_verifier_verify_full_table_data (image, &errors))
513                 goto invalid_image;
514
515
516         table = &image->tables [MONO_TABLE_TYPEDEF];
517         for (i = 1; i <= table->rows; ++i) {
518                 MonoError error;
519                 guint32 token = i | MONO_TOKEN_TYPE_DEF;
520                 MonoClass *klass = mono_class_get_checked (image, token, &error);
521                 if (!klass) {
522                         printf ("Could not load class with token %x due to %s\n", token, mono_error_get_message (&error));
523                         mono_error_cleanup (&error);
524                         continue;
525                 }
526                 mono_class_init (klass);
527                 if (mono_class_has_failure (klass)) {
528                         MonoError type_load_error;
529                         error_init (&type_load_error);
530                         mono_error_set_for_class_failure (&type_load_error, klass);
531                         printf ("Could not initialize class(0x%08x) %s.%s due to %s\n", token, klass->name_space, klass->name, mono_error_get_message (&type_load_error));
532                         mono_error_cleanup (&type_load_error);
533                         ++count;
534                 }
535
536                 mono_class_setup_vtable (klass);
537                 if (mono_class_has_failure (klass)) {
538                         MonoError type_load_error;
539                         error_init (&type_load_error);
540                         mono_error_set_for_class_failure (&type_load_error, klass);
541                         printf ("Could not initialize vtable of class(0x%08x) %s.%s due to %s\n", token, klass->name_space, klass->name, mono_error_get_message (&type_load_error));
542                         mono_error_cleanup (&type_load_error);
543                         ++count;
544                 }
545         }
546         if (count)
547                 return 5;
548         return 0;
549
550 invalid_image:
551         for (tmp = errors; tmp; tmp = tmp->next) {
552                 MonoVerifyInfo *info = (MonoVerifyInfo *)tmp->data;
553                 g_print ("%s: %s\n", desc [info->status], info->message);
554                 if (info->status == MONO_VERIFY_ERROR)
555                         count++;
556         }
557         mono_free_verify_list (errors);
558         if (count)
559                 g_print ("Error count: %d\n", count);
560         return 1;
561 }
562
563 static gboolean
564 try_load_from (MonoAssembly **assembly, const gchar *path1, const gchar *path2,
565                                         const gchar *path3, const gchar *path4, gboolean refonly)
566 {
567         gchar *fullpath;
568
569         *assembly = NULL;
570         fullpath = g_build_filename (path1, path2, path3, path4, NULL);
571         if (g_file_test (fullpath, G_FILE_TEST_IS_REGULAR))
572                 *assembly = mono_assembly_open_predicate (fullpath, refonly, FALSE, NULL, NULL, NULL);
573
574         g_free (fullpath);
575         return (*assembly != NULL);
576 }
577
578 static MonoAssembly *
579 real_load (gchar **search_path, const gchar *culture, const gchar *name, gboolean refonly)
580 {
581         MonoAssembly *result = NULL;
582         gchar **path;
583         gchar *filename;
584         const gchar *local_culture;
585         gint len;
586
587         if (!culture || *culture == '\0') {
588                 local_culture = "";
589         } else {
590                 local_culture = culture;
591         }
592
593         filename =  g_strconcat (name, ".dll", NULL);
594         len = strlen (filename);
595
596         for (path = search_path; *path; path++) {
597                 if (**path == '\0')
598                         continue; /* Ignore empty ApplicationBase */
599
600                 /* See test cases in bug #58992 and bug #57710 */
601                 /* 1st try: [culture]/[name].dll (culture may be empty) */
602                 strcpy (filename + len - 4, ".dll");
603                 if (try_load_from (&result, *path, local_culture, "", filename, refonly))
604                         break;
605
606                 /* 2nd try: [culture]/[name].exe (culture may be empty) */
607                 strcpy (filename + len - 4, ".exe");
608                 if (try_load_from (&result, *path, local_culture, "", filename, refonly))
609                         break;
610
611                 /* 3rd try: [culture]/[name]/[name].dll (culture may be empty) */
612                 strcpy (filename + len - 4, ".dll");
613                 if (try_load_from (&result, *path, local_culture, name, filename, refonly))
614                         break;
615
616                 /* 4th try: [culture]/[name]/[name].exe (culture may be empty) */
617                 strcpy (filename + len - 4, ".exe");
618                 if (try_load_from (&result, *path, local_culture, name, filename, refonly))
619                         break;
620         }
621
622         g_free (filename);
623         return result;
624 }
625
626 /*
627  * Try to load referenced assemblies from assemblies_path.
628  */
629 static MonoAssembly *
630 pedump_preload (MonoAssemblyName *aname,
631                                  gchar **assemblies_path,
632                                  gpointer user_data)
633 {
634         MonoAssembly *result = NULL;
635         gboolean refonly = GPOINTER_TO_UINT (user_data);
636
637         if (assemblies_path && assemblies_path [0] != NULL) {
638                 result = real_load (assemblies_path, aname->culture, aname->name, refonly);
639         }
640         if (!result)
641                 result = real_load (assembly_directory, aname->culture, aname->name, refonly);
642
643         return result;
644 }
645
646 static GList *loaded_assemblies = NULL;
647
648 static void
649 pedump_assembly_load_hook (MonoAssembly *assembly, gpointer user_data)
650 {
651         loaded_assemblies = g_list_prepend (loaded_assemblies, assembly);
652 }
653
654 static MonoAssembly *
655 pedump_assembly_search_hook (MonoAssemblyName *aname, gpointer user_data)
656 {
657         GList *tmp;
658
659        for (tmp = loaded_assemblies; tmp; tmp = tmp->next) {
660                MonoAssembly *ass = (MonoAssembly *)tmp->data;
661                if (mono_assembly_names_equal (aname, &ass->aname))
662                        return ass;
663        }
664        return NULL;
665 }
666
667 static void
668 thread_state_init (MonoThreadUnwindState *ctx)
669 {
670 }
671
672 #define VALID_ONLY_FLAG 0x08000000
673 #define VERIFY_CODE_ONLY MONO_VERIFY_ALL + 1 
674 #define VERIFY_METADATA_ONLY VERIFY_CODE_ONLY + 1
675 #define VERIFY_PARTIAL_METADATA VERIFY_CODE_ONLY + 2
676
677 int
678 main (int argc, char *argv [])
679 {
680         int image_result = 0;
681         MonoImage *image;
682         char *file = NULL;
683         char *flags = NULL;
684         MiniVerifierMode verifier_mode = MONO_VERIFIER_MODE_VERIFIABLE;
685         const char *flag_desc [] = {"error", "warn", "cls", "all", "code", "fail-on-verifiable", "non-strict", "valid-only", "metadata", "partial-md", NULL};
686         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, VERIFY_PARTIAL_METADATA, 0};
687         int i, verify_flags = MONO_VERIFY_REPORT_ALL_ERRORS, run_new_metadata_verifier = 0;
688         MonoThreadInfoRuntimeCallbacks ticallbacks;
689         
690         for (i = 1; i < argc; i++){
691                 if (argv [i][0] != '-'){
692                         file = argv [i];
693                         continue;
694                 }
695
696                 if (strcmp (argv [i], "--help") == 0)
697                         usage ();
698                 else if (strcmp (argv [i], "--verify") == 0) {
699                         verify_pe = 1;
700                         dump_data = 0;
701                         ++i;
702                         flags = argv [i];
703                 } else {
704                         usage ();
705                 }
706         }
707         
708         if (!file)
709                 usage ();
710
711         //We have to force the runtime to load the corlib under verification as its own corlib so core types are properly populated in mono_defaults.
712         if (strstr (file, "mscorlib.dll"))
713                 g_setenv ("MONO_PATH", g_path_get_dirname (file), 1);
714         assembly_directory [0] = g_path_get_dirname (file);
715         assembly_directory [1] = NULL;
716
717 #ifndef DISABLE_PERFCOUNTERS
718         mono_perfcounters_init ();
719 #endif
720         mono_counters_init ();
721         mono_tls_init_runtime_keys ();
722         memset (&ticallbacks, 0, sizeof (ticallbacks));
723         ticallbacks.thread_state_init = thread_state_init;
724 #ifndef HOST_WIN32
725         mono_w32handle_init ();
726 #endif
727         mono_thread_info_runtime_init (&ticallbacks);
728
729         mono_metadata_init ();
730         mono_images_init ();
731         mono_assemblies_init ();
732         mono_loader_init ();
733  
734
735         if (verify_pe) {
736                 char *tok = strtok (flags, ",");
737
738                 verify_metadata = 1;
739                 verify_code = 0;
740                 while (tok) {
741                         for (i = 0; flag_desc [i]; ++i) {
742                                 if (strcmp (tok, flag_desc [i]) == 0) {
743                                         if (flag_vals [i] == VERIFY_CODE_ONLY) {
744                                                 verify_metadata = 0;
745                                                 verify_code = 1;
746                                         } else if(flag_vals [i] == MONO_VERIFY_ALL) {
747                                                 verify_code = 1;
748                                         } else if(flag_vals [i] == VERIFY_METADATA_ONLY) {
749                                                 verify_metadata = 0;
750                                                 run_new_metadata_verifier = 1;
751                                         } else if(flag_vals [i] == VERIFY_PARTIAL_METADATA) {
752                                                 verify_partial_md = 1;
753                                         }
754                                         if (flag_vals [i] == VALID_ONLY_FLAG)
755                                                 verifier_mode = MONO_VERIFIER_MODE_VALID;
756                                         else
757                                                 verify_flags |= flag_vals [i];
758                                         break;
759                                 }
760                         }
761                         if (!flag_desc [i])
762                                 g_print ("Unknown verify flag %s\n", tok);
763                         tok = strtok (NULL, ",");
764                 }
765
766                 mono_verifier_set_mode (verifier_mode);
767                 /**/
768         }
769
770         if (verify_pe || run_new_metadata_verifier) {
771                 run_new_metadata_verifier = 1;
772         }
773
774         if (run_new_metadata_verifier) {
775                 mono_verifier_set_mode (verifier_mode);
776
777                 image_result = verify_image_file (file);
778                 if (image_result == 1 || !verify_code)
779                         return image_result;
780         }
781
782         image = mono_image_open (file, NULL);
783         if (!image){
784                 fprintf (stderr, "Cannot open image %s\n", file);
785                 exit (1);
786         }
787
788         if (dump_data)
789                 dump_dotnet_iinfo (image);
790         if (verify_pe) {
791                 MonoAssembly *assembly;
792                 MonoImage *image;
793                 MonoImageOpenStatus status;
794                 int code_result;
795
796                 mono_verifier_set_mode (verifier_mode);
797
798                 assembly = mono_assembly_open_predicate (file, FALSE, FALSE, NULL, NULL, NULL);
799                 /*fake an assembly for netmodules so the verifier works*/
800                 if (!assembly && (image = mono_image_open (file, &status)) && image->tables [MONO_TABLE_ASSEMBLY].rows == 0) {
801                         assembly = g_new0 (MonoAssembly, 1);
802                         assembly->in_gac = FALSE;
803                         assembly->image = image;
804                         image->assembly = assembly;
805                 }
806
807                 if (!assembly) {
808                         g_print ("Could not open assembly %s\n", file);
809                         return 4;
810                 }
811
812                 code_result = dump_verify_info (assembly->image, verify_flags, verifier_mode == MONO_VERIFIER_MODE_VALID);
813                 return code_result ? code_result : image_result;
814         } else
815                 mono_image_close (image);
816         
817         return 0;
818 }
819