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