aboutsummaryrefslogtreecommitdiff
path: root/tools/llvm-pdbutil/llvm-pdbutil.cpp
blob: bee9f182e3fb58c44e8c759800fd8fe962f78bc1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
//===- llvm-pdbutil.cpp - Dump debug info from a PDB file -------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Dumps debug information present in PDB files.
//
//===----------------------------------------------------------------------===//

#include "llvm-pdbutil.h"

#include "Analyze.h"
#include "BytesOutputStyle.h"
#include "Diff.h"
#include "DumpOutputStyle.h"
#include "InputFile.h"
#include "LinePrinter.h"
#include "OutputStyle.h"
#include "PrettyCompilandDumper.h"
#include "PrettyExternalSymbolDumper.h"
#include "PrettyFunctionDumper.h"
#include "PrettyTypeDumper.h"
#include "PrettyVariableDumper.h"
#include "YAMLOutputStyle.h"

#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/BinaryFormat/Magic.h"
#include "llvm/Config/config.h"
#include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
#include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
#include "llvm/DebugInfo/CodeView/StringsAndChecksums.h"
#include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
#include "llvm/DebugInfo/CodeView/TypeTableBuilder.h"
#include "llvm/DebugInfo/MSF/MSFBuilder.h"
#include "llvm/DebugInfo/PDB/GenericError.h"
#include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
#include "llvm/DebugInfo/PDB/IPDBRawSymbol.h"
#include "llvm/DebugInfo/PDB/IPDBSession.h"
#include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
#include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
#include "llvm/DebugInfo/PDB/Native/InfoStream.h"
#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
#include "llvm/DebugInfo/PDB/Native/NativeSession.h"
#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
#include "llvm/DebugInfo/PDB/Native/RawConstants.h"
#include "llvm/DebugInfo/PDB/Native/RawError.h"
#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
#include "llvm/DebugInfo/PDB/PDB.h"
#include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
#include "llvm/DebugInfo/PDB/PDBSymbolData.h"
#include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
#include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"
#include "llvm/DebugInfo/PDB/PDBSymbolThunk.h"
#include "llvm/Support/BinaryByteStream.h"
#include "llvm/Support/COM.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/FileOutputBuffer.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/LineIterator.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/ScopedPrinter.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"

#include <set>

using namespace llvm;
using namespace llvm::codeview;
using namespace llvm::msf;
using namespace llvm::pdb;

namespace opts {

cl::SubCommand DumpSubcommand("dump", "Dump MSF and CodeView debug info");
cl::SubCommand BytesSubcommand("bytes", "Dump raw bytes from the PDB file");

cl::SubCommand
    PrettySubcommand("pretty",
                     "Dump semantic information about types and symbols");

cl::SubCommand DiffSubcommand("diff", "Diff the contents of 2 PDB files");

cl::SubCommand
    YamlToPdbSubcommand("yaml2pdb",
                        "Generate a PDB file from a YAML description");
cl::SubCommand
    PdbToYamlSubcommand("pdb2yaml",
                        "Generate a detailed YAML description of a PDB File");

cl::SubCommand
    AnalyzeSubcommand("analyze",
                      "Analyze various aspects of a PDB's structure");

cl::SubCommand MergeSubcommand("merge",
                               "Merge multiple PDBs into a single PDB");

cl::OptionCategory TypeCategory("Symbol Type Options");
cl::OptionCategory FilterCategory("Filtering and Sorting Options");
cl::OptionCategory OtherOptions("Other Options");

cl::ValuesClass ChunkValues = cl::values(
    clEnumValN(ModuleSubsection::CrossScopeExports, "cme",
               "Cross module exports (DEBUG_S_CROSSSCOPEEXPORTS subsection)"),
    clEnumValN(ModuleSubsection::CrossScopeImports, "cmi",
               "Cross module imports (DEBUG_S_CROSSSCOPEIMPORTS subsection)"),
    clEnumValN(ModuleSubsection::FileChecksums, "fc",
               "File checksums (DEBUG_S_CHECKSUMS subsection)"),
    clEnumValN(ModuleSubsection::InlineeLines, "ilines",
               "Inlinee lines (DEBUG_S_INLINEELINES subsection)"),
    clEnumValN(ModuleSubsection::Lines, "lines",
               "Lines (DEBUG_S_LINES subsection)"),
    clEnumValN(ModuleSubsection::StringTable, "strings",
               "String Table (DEBUG_S_STRINGTABLE subsection) (not "
               "typically present in PDB file)"),
    clEnumValN(ModuleSubsection::FrameData, "frames",
               "Frame Data (DEBUG_S_FRAMEDATA subsection)"),
    clEnumValN(ModuleSubsection::Symbols, "symbols",
               "Symbols (DEBUG_S_SYMBOLS subsection) (not typically "
               "present in PDB file)"),
    clEnumValN(ModuleSubsection::CoffSymbolRVAs, "rvas",
               "COFF Symbol RVAs (DEBUG_S_COFF_SYMBOL_RVA subsection)"),
    clEnumValN(ModuleSubsection::Unknown, "unknown",
               "Any subsection not covered by another option"),
    clEnumValN(ModuleSubsection::All, "all", "All known subsections"));

namespace pretty {
cl::list<std::string> InputFilenames(cl::Positional,
                                     cl::desc("<input PDB files>"),
                                     cl::OneOrMore, cl::sub(PrettySubcommand));

cl::opt<bool> Compilands("compilands", cl::desc("Display compilands"),
                         cl::cat(TypeCategory), cl::sub(PrettySubcommand));
cl::opt<bool> Symbols("module-syms",
                      cl::desc("Display symbols for each compiland"),
                      cl::cat(TypeCategory), cl::sub(PrettySubcommand));
cl::opt<bool> Globals("globals", cl::desc("Dump global symbols"),
                      cl::cat(TypeCategory), cl::sub(PrettySubcommand));
cl::opt<bool> Externals("externals", cl::desc("Dump external symbols"),
                        cl::cat(TypeCategory), cl::sub(PrettySubcommand));
cl::list<SymLevel> SymTypes(
    "sym-types", cl::desc("Type of symbols to dump (default all)"),
    cl::cat(TypeCategory), cl::sub(PrettySubcommand), cl::ZeroOrMore,
    cl::values(
        clEnumValN(SymLevel::Thunks, "thunks", "Display thunk symbols"),
        clEnumValN(SymLevel::Data, "data", "Display data symbols"),
        clEnumValN(SymLevel::Functions, "funcs", "Display function symbols"),
        clEnumValN(SymLevel::All, "all", "Display all symbols (default)")));

cl::opt<bool>
    Types("types",
          cl::desc("Display all types (implies -classes, -enums, -typedefs)"),
          cl::cat(TypeCategory), cl::sub(PrettySubcommand));
cl::opt<bool> Classes("classes", cl::desc("Display class types"),
                      cl::cat(TypeCategory), cl::sub(PrettySubcommand));
cl::opt<bool> Enums("enums", cl::desc("Display enum types"),
                    cl::cat(TypeCategory), cl::sub(PrettySubcommand));
cl::opt<bool> Typedefs("typedefs", cl::desc("Display typedef types"),
                       cl::cat(TypeCategory), cl::sub(PrettySubcommand));
cl::opt<SymbolSortMode> SymbolOrder(
    "symbol-order", cl::desc("symbol sort order"),
    cl::init(SymbolSortMode::None),
    cl::values(clEnumValN(SymbolSortMode::None, "none",
                          "Undefined / no particular sort order"),
               clEnumValN(SymbolSortMode::Name, "name", "Sort symbols by name"),
               clEnumValN(SymbolSortMode::Size, "size",
                          "Sort symbols by size")),
    cl::cat(TypeCategory), cl::sub(PrettySubcommand));

cl::opt<ClassSortMode> ClassOrder(
    "class-order", cl::desc("Class sort order"), cl::init(ClassSortMode::None),
    cl::values(
        clEnumValN(ClassSortMode::None, "none",
                   "Undefined / no particular sort order"),
        clEnumValN(ClassSortMode::Name, "name", "Sort classes by name"),
        clEnumValN(ClassSortMode::Size, "size", "Sort classes by size"),
        clEnumValN(ClassSortMode::Padding, "padding",
                   "Sort classes by amount of padding"),
        clEnumValN(ClassSortMode::PaddingPct, "padding-pct",
                   "Sort classes by percentage of space consumed by padding"),
        clEnumValN(ClassSortMode::PaddingImmediate, "padding-imm",
                   "Sort classes by amount of immediate padding"),
        clEnumValN(ClassSortMode::PaddingPctImmediate, "padding-pct-imm",
                   "Sort classes by percentage of space consumed by immediate "
                   "padding")),
    cl::cat(TypeCategory), cl::sub(PrettySubcommand));

cl::opt<ClassDefinitionFormat> ClassFormat(
    "class-definitions", cl::desc("Class definition format"),
    cl::init(ClassDefinitionFormat::All),
    cl::values(
        clEnumValN(ClassDefinitionFormat::All, "all",
                   "Display all class members including data, constants, "
                   "typedefs, functions, etc"),
        clEnumValN(ClassDefinitionFormat::Layout, "layout",
                   "Only display members that contribute to class size."),
        clEnumValN(ClassDefinitionFormat::None, "none",
                   "Don't display class definitions")),
    cl::cat(TypeCategory), cl::sub(PrettySubcommand));
cl::opt<uint32_t> ClassRecursionDepth(
    "class-recurse-depth", cl::desc("Class recursion depth (0=no limit)"),
    cl::init(0), cl::cat(TypeCategory), cl::sub(PrettySubcommand));

cl::opt<bool> Lines("lines", cl::desc("Line tables"), cl::cat(TypeCategory),
                    cl::sub(PrettySubcommand));
cl::opt<bool>
    All("all", cl::desc("Implies all other options in 'Symbol Types' category"),
        cl::cat(TypeCategory), cl::sub(PrettySubcommand));

cl::opt<uint64_t> LoadAddress(
    "load-address",
    cl::desc("Assume the module is loaded at the specified address"),
    cl::cat(OtherOptions), cl::sub(PrettySubcommand));
cl::opt<bool> Native("native", cl::desc("Use native PDB reader instead of DIA"),
                     cl::cat(OtherOptions), cl::sub(PrettySubcommand));
cl::opt<cl::boolOrDefault>
    ColorOutput("color-output",
                cl::desc("Override use of color (default = isatty)"),
                cl::cat(OtherOptions), cl::sub(PrettySubcommand));
cl::list<std::string> ExcludeTypes(
    "exclude-types", cl::desc("Exclude types by regular expression"),
    cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
cl::list<std::string> ExcludeSymbols(
    "exclude-symbols", cl::desc("Exclude symbols by regular expression"),
    cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
cl::list<std::string> ExcludeCompilands(
    "exclude-compilands", cl::desc("Exclude compilands by regular expression"),
    cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));

cl::list<std::string> IncludeTypes(
    "include-types",
    cl::desc("Include only types which match a regular expression"),
    cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
cl::list<std::string> IncludeSymbols(
    "include-symbols",
    cl::desc("Include only symbols which match a regular expression"),
    cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
cl::list<std::string> IncludeCompilands(
    "include-compilands",
    cl::desc("Include only compilands those which match a regular expression"),
    cl::ZeroOrMore, cl::cat(FilterCategory), cl::sub(PrettySubcommand));
cl::opt<uint32_t> SizeThreshold(
    "min-type-size", cl::desc("Displays only those types which are greater "
                              "than or equal to the specified size."),
    cl::init(0), cl::cat(FilterCategory), cl::sub(PrettySubcommand));
cl::opt<uint32_t> PaddingThreshold(
    "min-class-padding", cl::desc("Displays only those classes which have at "
                                  "least the specified amount of padding."),
    cl::init(0), cl::cat(FilterCategory), cl::sub(PrettySubcommand));
cl::opt<uint32_t> ImmediatePaddingThreshold(
    "min-class-padding-imm",
    cl::desc("Displays only those classes which have at least the specified "
             "amount of immediate padding, ignoring padding internal to bases "
             "and aggregates."),
    cl::init(0), cl::cat(FilterCategory), cl::sub(PrettySubcommand));

cl::opt<bool> ExcludeCompilerGenerated(
    "no-compiler-generated",
    cl::desc("Don't show compiler generated types and symbols"),
    cl::cat(FilterCategory), cl::sub(PrettySubcommand));
cl::opt<bool>
    ExcludeSystemLibraries("no-system-libs",
                           cl::desc("Don't show symbols from system libraries"),
                           cl::cat(FilterCategory), cl::sub(PrettySubcommand));

cl::opt<bool> NoEnumDefs("no-enum-definitions",
                         cl::desc("Don't display full enum definitions"),
                         cl::cat(FilterCategory), cl::sub(PrettySubcommand));
}

namespace diff {
cl::opt<bool> PrintValueColumns(
    "values", cl::init(true),
    cl::desc("Print one column for each PDB with the field value"),
    cl::Optional, cl::sub(DiffSubcommand));
cl::opt<bool>
    PrintResultColumn("result", cl::init(false),
                      cl::desc("Print a column with the result status"),
                      cl::Optional, cl::sub(DiffSubcommand));

cl::list<std::string>
    RawModiEquivalences("modi-equivalence", cl::ZeroOrMore,
                        cl::value_desc("left,right"),
                        cl::desc("Modules with the specified indices will be "
                                 "treated as referring to the same module"),
                        cl::sub(DiffSubcommand));

cl::opt<std::string> LeftRoot(
    "left-bin-root", cl::Optional,
    cl::desc("Treats the specified path as the root of the tree containing "
             "binaries referenced by the left PDB.  The root is stripped from "
             "embedded paths when doing equality comparisons."),
    cl::sub(DiffSubcommand));
cl::opt<std::string> RightRoot(
    "right-bin-root", cl::Optional,
    cl::desc("Treats the specified path as the root of the tree containing "
             "binaries referenced by the right PDB.  The root is stripped from "
             "embedded paths when doing equality comparisons"),
    cl::sub(DiffSubcommand));

cl::opt<std::string> Left(cl::Positional, cl::desc("<left>"),
                          cl::sub(DiffSubcommand));
cl::opt<std::string> Right(cl::Positional, cl::desc("<right>"),
                           cl::sub(DiffSubcommand));

llvm::DenseMap<uint32_t, uint32_t> Equivalences;
}

cl::OptionCategory FileOptions("Module & File Options");

namespace bytes {
cl::OptionCategory MsfBytes("MSF File Options");
cl::OptionCategory DbiBytes("Dbi Stream Options");
cl::OptionCategory PdbBytes("PDB Stream Options");
cl::OptionCategory Types("Type Options");
cl::OptionCategory ModuleCategory("Module Options");

llvm::Optional<NumberRange> DumpBlockRange;
llvm::Optional<NumberRange> DumpByteRange;

cl::opt<std::string> DumpBlockRangeOpt(
    "block-range", cl::value_desc("start[-end]"),
    cl::desc("Dump binary data from specified range of blocks."),
    cl::sub(BytesSubcommand), cl::cat(MsfBytes));

cl::opt<std::string>
    DumpByteRangeOpt("byte-range", cl::value_desc("start[-end]"),
                     cl::desc("Dump binary data from specified range of bytes"),
                     cl::sub(BytesSubcommand), cl::cat(MsfBytes));

cl::list<std::string>
    DumpStreamData("stream-data", cl::CommaSeparated, cl::ZeroOrMore,
                   cl::desc("Dump binary data from specified streams.  Format "
                            "is SN[:Start][@Size]"),
                   cl::sub(BytesSubcommand), cl::cat(MsfBytes));

cl::opt<bool> NameMap("name-map", cl::desc("Dump bytes of PDB Name Map"),
                      cl::sub(BytesSubcommand), cl::cat(PdbBytes));
cl::opt<bool> Fpm("fpm", cl::desc("Dump free page map"),
                  cl::sub(BytesSubcommand), cl::cat(MsfBytes));

cl::opt<bool> SectionContributions("sc", cl::desc("Dump section contributions"),
                                   cl::sub(BytesSubcommand), cl::cat(DbiBytes));
cl::opt<bool> SectionMap("sm", cl::desc("Dump section map"),
                         cl::sub(BytesSubcommand), cl::cat(DbiBytes));
cl::opt<bool> ModuleInfos("modi", cl::desc("Dump module info"),
                          cl::sub(BytesSubcommand), cl::cat(DbiBytes));
cl::opt<bool> FileInfo("files", cl::desc("Dump source file info"),
                       cl::sub(BytesSubcommand), cl::cat(DbiBytes));
cl::opt<bool> TypeServerMap("type-server", cl::desc("Dump type server map"),
                            cl::sub(BytesSubcommand), cl::cat(DbiBytes));
cl::opt<bool> ECData("ec", cl::desc("Dump edit and continue map"),
                     cl::sub(BytesSubcommand), cl::cat(DbiBytes));

cl::list<uint32_t>
    TypeIndex("type",
              cl::desc("Dump the type record with the given type index"),
              cl::ZeroOrMore, cl::CommaSeparated, cl::sub(BytesSubcommand),
              cl::cat(TypeCategory));
cl::list<uint32_t>
    IdIndex("id", cl::desc("Dump the id record with the given type index"),
            cl::ZeroOrMore, cl::CommaSeparated, cl::sub(BytesSubcommand),
            cl::cat(TypeCategory));

cl::opt<uint32_t> ModuleIndex(
    "mod",
    cl::desc(
        "Limit options in the Modules category to the specified module index"),
    cl::Optional, cl::sub(BytesSubcommand), cl::cat(ModuleCategory));
cl::opt<bool> ModuleSyms("syms", cl::desc("Dump symbol record substream"),
                         cl::sub(BytesSubcommand), cl::cat(ModuleCategory));
cl::opt<bool> ModuleC11("c11-chunks", cl::Hidden,
                        cl::desc("Dump C11 CodeView debug chunks"),
                        cl::sub(BytesSubcommand), cl::cat(ModuleCategory));
cl::opt<bool> ModuleC13("chunks",
                        cl::desc("Dump C13 CodeView debug chunk subsection"),
                        cl::sub(BytesSubcommand), cl::cat(ModuleCategory));
cl::opt<bool> SplitChunks(
    "split-chunks",
    cl::desc(
        "When dumping debug chunks, show a different section for each chunk"),
    cl::sub(BytesSubcommand), cl::cat(ModuleCategory));
cl::list<std::string> InputFilenames(cl::Positional,
                                     cl::desc("<input PDB files>"),
                                     cl::OneOrMore, cl::sub(BytesSubcommand));

} // namespace bytes

namespace dump {

cl::OptionCategory MsfOptions("MSF Container Options");
cl::OptionCategory TypeOptions("Type Record Options");
cl::OptionCategory SymbolOptions("Symbol Options");
cl::OptionCategory MiscOptions("Miscellaneous Options");

// MSF OPTIONS
cl::opt<bool> DumpSummary("summary", cl::desc("dump file summary"),
                          cl::cat(MsfOptions), cl::sub(DumpSubcommand));
cl::opt<bool> DumpStreams("streams",
                          cl::desc("dump summary of the PDB streams"),
                          cl::cat(MsfOptions), cl::sub(DumpSubcommand));
cl::opt<bool> DumpStreamBlocks(
    "stream-blocks",
    cl::desc("Add block information to the output of -streams"),
    cl::cat(MsfOptions), cl::sub(DumpSubcommand));
cl::opt<bool> DumpSymbolStats(
    "sym-stats",
    cl::desc("Dump a detailed breakdown of symbol usage/size for each module"),
    cl::cat(MsfOptions), cl::sub(DumpSubcommand));

cl::opt<bool> DumpUdtStats(
    "udt-stats",
    cl::desc("Dump a detailed breakdown of S_UDT record usage / stats"),
    cl::cat(MsfOptions), cl::sub(DumpSubcommand));

// TYPE OPTIONS
cl::opt<bool> DumpTypes("types",
                        cl::desc("dump CodeView type records from TPI stream"),
                        cl::cat(TypeOptions), cl::sub(DumpSubcommand));
cl::opt<bool> DumpTypeData(
    "type-data",
    cl::desc("dump CodeView type record raw bytes from TPI stream"),
    cl::cat(TypeOptions), cl::sub(DumpSubcommand));

cl::opt<bool> DumpTypeExtras("type-extras",
                             cl::desc("dump type hashes and index offsets"),
                             cl::cat(TypeOptions), cl::sub(DumpSubcommand));

cl::list<uint32_t> DumpTypeIndex(
    "type-index", cl::ZeroOrMore, cl::CommaSeparated,
    cl::desc("only dump types with the specified hexadecimal type index"),
    cl::cat(TypeOptions), cl::sub(DumpSubcommand));

cl::opt<bool> DumpIds("ids",
                      cl::desc("dump CodeView type records from IPI stream"),
                      cl::cat(TypeOptions), cl::sub(DumpSubcommand));
cl::opt<bool>
    DumpIdData("id-data",
               cl::desc("dump CodeView type record raw bytes from IPI stream"),
               cl::cat(TypeOptions), cl::sub(DumpSubcommand));

cl::opt<bool> DumpIdExtras("id-extras",
                           cl::desc("dump id hashes and index offsets"),
                           cl::cat(TypeOptions), cl::sub(DumpSubcommand));
cl::list<uint32_t> DumpIdIndex(
    "id-index", cl::ZeroOrMore, cl::CommaSeparated,
    cl::desc("only dump ids with the specified hexadecimal type index"),
    cl::cat(TypeOptions), cl::sub(DumpSubcommand));

cl::opt<bool> DumpTypeDependents(
    "dependents",
    cl::desc("In conjunection with -type-index and -id-index, dumps the entire "
             "dependency graph for the specified index instead of "
             "just the single record with the specified index"),
    cl::cat(TypeOptions), cl::sub(DumpSubcommand));

// SYMBOL OPTIONS
cl::opt<bool> DumpGlobals("globals", cl::desc("dump Globals symbol records"),
                          cl::cat(SymbolOptions), cl::sub(DumpSubcommand));
cl::opt<bool> DumpGlobalExtras("global-extras", cl::desc("dump Globals hashes"),
                               cl::cat(SymbolOptions), cl::sub(DumpSubcommand));
cl::opt<bool> DumpPublics("publics", cl::desc("dump Publics stream data"),
                          cl::cat(SymbolOptions), cl::sub(DumpSubcommand));
cl::opt<bool> DumpPublicExtras("public-extras",
                               cl::desc("dump Publics hashes and address maps"),
                               cl::cat(SymbolOptions), cl::sub(DumpSubcommand));
cl::opt<bool> DumpSymbols("symbols", cl::desc("dump module symbols"),
                          cl::cat(SymbolOptions), cl::sub(DumpSubcommand));

cl::opt<bool>
    DumpSymRecordBytes("sym-data",
                       cl::desc("dump CodeView symbol record raw bytes"),
                       cl::cat(SymbolOptions), cl::sub(DumpSubcommand));

// MODULE & FILE OPTIONS
cl::opt<bool> DumpModules("modules", cl::desc("dump compiland information"),
                          cl::cat(FileOptions), cl::sub(DumpSubcommand));
cl::opt<bool> DumpModuleFiles(
    "files",
    cl::desc("Dump the source files that contribute to each module's."),
    cl::cat(FileOptions), cl::sub(DumpSubcommand));
cl::opt<bool> DumpLines(
    "l",
    cl::desc("dump source file/line information (DEBUG_S_LINES subsection)"),
    cl::cat(FileOptions), cl::sub(DumpSubcommand));
cl::opt<bool> DumpInlineeLines(
    "il",
    cl::desc("dump inlinee line information (DEBUG_S_INLINEELINES subsection)"),
    cl::cat(FileOptions), cl::sub(DumpSubcommand));
cl::opt<bool> DumpXmi(
    "xmi",
    cl::desc(
        "dump cross module imports (DEBUG_S_CROSSSCOPEIMPORTS subsection)"),
    cl::cat(FileOptions), cl::sub(DumpSubcommand));
cl::opt<bool> DumpXme(
    "xme",
    cl::desc(
        "dump cross module exports (DEBUG_S_CROSSSCOPEEXPORTS subsection)"),
    cl::cat(FileOptions), cl::sub(DumpSubcommand));
cl::opt<uint32_t> DumpModi("modi", cl::Optional,
                           cl::desc("For all options that iterate over "
                                    "modules, limit to the specified module"),
                           cl::cat(FileOptions), cl::sub(DumpSubcommand));
cl::opt<bool> JustMyCode("jmc", cl::Optional,
                         cl::desc("For all options that iterate over modules, "
                                  "ignore modules from system libraries"),
                         cl::cat(FileOptions), cl::sub(DumpSubcommand));

// MISCELLANEOUS OPTIONS
cl::opt<bool> DumpStringTable("string-table", cl::desc("dump PDB String Table"),
                              cl::cat(MiscOptions), cl::sub(DumpSubcommand));

cl::opt<bool> DumpSectionContribs("section-contribs",
                                  cl::desc("dump section contributions"),
                                  cl::cat(MiscOptions),
                                  cl::sub(DumpSubcommand));
cl::opt<bool> DumpSectionMap("section-map", cl::desc("dump section map"),
                             cl::cat(MiscOptions), cl::sub(DumpSubcommand));
cl::opt<bool> DumpSectionHeaders("section-headers",
                                 cl::desc("Dump image section headers"),
                                 cl::cat(MiscOptions), cl::sub(DumpSubcommand));

cl::opt<bool> RawAll("all", cl::desc("Implies most other options."),
                     cl::cat(MiscOptions), cl::sub(DumpSubcommand));

cl::list<std::string> InputFilenames(cl::Positional,
                                     cl::desc("<input PDB files>"),
                                     cl::OneOrMore, cl::sub(DumpSubcommand));
}

namespace yaml2pdb {
cl::opt<std::string>
    YamlPdbOutputFile("pdb", cl::desc("the name of the PDB file to write"),
                      cl::sub(YamlToPdbSubcommand));

cl::opt<std::string> InputFilename(cl::Positional,
                                   cl::desc("<input YAML file>"), cl::Required,
                                   cl::sub(YamlToPdbSubcommand));
}

namespace pdb2yaml {
cl::opt<bool> All("all",
                  cl::desc("Dump everything we know how to dump."),
                  cl::sub(PdbToYamlSubcommand), cl::init(false));
cl::opt<bool> NoFileHeaders("no-file-headers",
                            cl::desc("Do not dump MSF file headers"),
                            cl::sub(PdbToYamlSubcommand), cl::init(false));
cl::opt<bool> Minimal("minimal",
                      cl::desc("Don't write fields with default values"),
                      cl::sub(PdbToYamlSubcommand), cl::init(false));

cl::opt<bool> StreamMetadata(
    "stream-metadata",
    cl::desc("Dump the number of streams and each stream's size"),
    cl::sub(PdbToYamlSubcommand), cl::init(false));
cl::opt<bool> StreamDirectory(
    "stream-directory",
    cl::desc("Dump each stream's block map (implies -stream-metadata)"),
    cl::sub(PdbToYamlSubcommand), cl::init(false));
cl::opt<bool> PdbStream("pdb-stream",
                        cl::desc("Dump the PDB Stream (Stream 1)"),
                        cl::sub(PdbToYamlSubcommand), cl::init(false));

cl::opt<bool> StringTable("string-table", cl::desc("Dump the PDB String Table"),
                          cl::sub(PdbToYamlSubcommand), cl::init(false));

cl::opt<bool> DbiStream("dbi-stream",
                        cl::desc("Dump the DBI Stream Headers (Stream 2)"),
                        cl::sub(PdbToYamlSubcommand), cl::init(false));

cl::opt<bool> TpiStream("tpi-stream",
                        cl::desc("Dump the TPI Stream (Stream 3)"),
                        cl::sub(PdbToYamlSubcommand), cl::init(false));

cl::opt<bool> IpiStream("ipi-stream",
                        cl::desc("Dump the IPI Stream (Stream 5)"),
                        cl::sub(PdbToYamlSubcommand), cl::init(false));

// MODULE & FILE OPTIONS
cl::opt<bool> DumpModules("modules", cl::desc("dump compiland information"),
                          cl::cat(FileOptions), cl::sub(PdbToYamlSubcommand));
cl::opt<bool> DumpModuleFiles("module-files", cl::desc("dump file information"),
                              cl::cat(FileOptions),
                              cl::sub(PdbToYamlSubcommand));
cl::list<ModuleSubsection> DumpModuleSubsections(
    "subsections", cl::ZeroOrMore, cl::CommaSeparated,
    cl::desc("dump subsections from each module's debug stream"), ChunkValues,
    cl::cat(FileOptions), cl::sub(PdbToYamlSubcommand));
cl::opt<bool> DumpModuleSyms("module-syms", cl::desc("dump module symbols"),
                             cl::cat(FileOptions),
                             cl::sub(PdbToYamlSubcommand));

cl::list<std::string> InputFilename(cl::Positional,
                                    cl::desc("<input PDB file>"), cl::Required,
                                    cl::sub(PdbToYamlSubcommand));
} // namespace pdb2yaml

namespace analyze {
cl::opt<bool> StringTable("hash-collisions", cl::desc("Find hash collisions"),
                          cl::sub(AnalyzeSubcommand), cl::init(false));
cl::list<std::string> InputFilename(cl::Positional,
                                    cl::desc("<input PDB file>"), cl::Required,
                                    cl::sub(AnalyzeSubcommand));
}

namespace merge {
cl::list<std::string> InputFilenames(cl::Positional,
                                     cl::desc("<input PDB files>"),
                                     cl::OneOrMore, cl::sub(MergeSubcommand));
cl::opt<std::string>
    PdbOutputFile("pdb", cl::desc("the name of the PDB file to write"),
                  cl::sub(MergeSubcommand));
}
}

static ExitOnError ExitOnErr;

static void yamlToPdb(StringRef Path) {
  BumpPtrAllocator Allocator;
  ErrorOr<std::unique_ptr<MemoryBuffer>> ErrorOrBuffer =
      MemoryBuffer::getFileOrSTDIN(Path, /*FileSize=*/-1,
                                   /*RequiresNullTerminator=*/false);

  if (ErrorOrBuffer.getError()) {
    ExitOnErr(make_error<GenericError>(generic_error_code::invalid_path, Path));
  }

  std::unique_ptr<MemoryBuffer> &Buffer = ErrorOrBuffer.get();

  llvm::yaml::Input In(Buffer->getBuffer());
  pdb::yaml::PdbObject YamlObj(Allocator);
  In >> YamlObj;

  PDBFileBuilder Builder(Allocator);

  uint32_t BlockSize = 4096;
  if (YamlObj.Headers.hasValue())
    BlockSize = YamlObj.Headers->SuperBlock.BlockSize;
  ExitOnErr(Builder.initialize(BlockSize));
  // Add each of the reserved streams.  We ignore stream metadata in the
  // yaml, because we will reconstruct our own view of the streams.  For
  // example, the YAML may say that there were 20 streams in the original
  // PDB, but maybe we only dump a subset of those 20 streams, so we will
  // have fewer, and the ones we do have may end up with different indices
  // than the ones in the original PDB.  So we just start with a clean slate.
  for (uint32_t I = 0; I < kSpecialStreamCount; ++I)
    ExitOnErr(Builder.getMsfBuilder().addStream(0));

  StringsAndChecksums Strings;
  Strings.setStrings(std::make_shared<DebugStringTableSubsection>());

  if (YamlObj.StringTable.hasValue()) {
    for (auto S : *YamlObj.StringTable)
      Strings.strings()->insert(S);
  }

  pdb::yaml::PdbInfoStream DefaultInfoStream;
  pdb::yaml::PdbDbiStream DefaultDbiStream;
  pdb::yaml::PdbTpiStream DefaultTpiStream;
  pdb::yaml::PdbTpiStream DefaultIpiStream;

  const auto &Info = YamlObj.PdbStream.getValueOr(DefaultInfoStream);

  auto &InfoBuilder = Builder.getInfoBuilder();
  InfoBuilder.setAge(Info.Age);
  InfoBuilder.setGuid(Info.Guid);
  InfoBuilder.setSignature(Info.Signature);
  InfoBuilder.setVersion(Info.Version);
  for (auto F : Info.Features)
    InfoBuilder.addFeature(F);

  const auto &Dbi = YamlObj.DbiStream.getValueOr(DefaultDbiStream);
  auto &DbiBuilder = Builder.getDbiBuilder();
  DbiBuilder.setAge(Dbi.Age);
  DbiBuilder.setBuildNumber(Dbi.BuildNumber);
  DbiBuilder.setFlags(Dbi.Flags);
  DbiBuilder.setMachineType(Dbi.MachineType);
  DbiBuilder.setPdbDllRbld(Dbi.PdbDllRbld);
  DbiBuilder.setPdbDllVersion(Dbi.PdbDllVersion);
  DbiBuilder.setVersionHeader(Dbi.VerHeader);
  for (const auto &MI : Dbi.ModInfos) {
    auto &ModiBuilder = ExitOnErr(DbiBuilder.addModuleInfo(MI.Mod));
    ModiBuilder.setObjFileName(MI.Obj);

    for (auto S : MI.SourceFiles)
      ExitOnErr(DbiBuilder.addModuleSourceFile(ModiBuilder, S));
    if (MI.Modi.hasValue()) {
      const auto &ModiStream = *MI.Modi;
      for (auto Symbol : ModiStream.Symbols) {
        ModiBuilder.addSymbol(
            Symbol.toCodeViewSymbol(Allocator, CodeViewContainer::Pdb));
      }
    }

    // Each module has its own checksum subsection, so scan for it every time.
    Strings.setChecksums(nullptr);
    CodeViewYAML::initializeStringsAndChecksums(MI.Subsections, Strings);

    auto CodeViewSubsections = ExitOnErr(CodeViewYAML::toCodeViewSubsectionList(
        Allocator, MI.Subsections, Strings));
    for (auto &SS : CodeViewSubsections) {
      ModiBuilder.addDebugSubsection(SS);
    }
  }

  auto &TpiBuilder = Builder.getTpiBuilder();
  const auto &Tpi = YamlObj.TpiStream.getValueOr(DefaultTpiStream);
  TpiBuilder.setVersionHeader(Tpi.Version);
  for (const auto &R : Tpi.Records) {
    CVType Type = R.toCodeViewRecord(Allocator);
    TpiBuilder.addTypeRecord(Type.RecordData, None);
  }

  const auto &Ipi = YamlObj.IpiStream.getValueOr(DefaultIpiStream);
  auto &IpiBuilder = Builder.getIpiBuilder();
  IpiBuilder.setVersionHeader(Ipi.Version);
  for (const auto &R : Ipi.Records) {
    CVType Type = R.toCodeViewRecord(Allocator);
    IpiBuilder.addTypeRecord(Type.RecordData, None);
  }

  Builder.getStringTableBuilder().setStrings(*Strings.strings());

  ExitOnErr(Builder.commit(opts::yaml2pdb::YamlPdbOutputFile));
}

static PDBFile &loadPDB(StringRef Path, std::unique_ptr<IPDBSession> &Session) {
  ExitOnErr(loadDataForPDB(PDB_ReaderType::Native, Path, Session));

  NativeSession *NS = static_cast<NativeSession *>(Session.get());
  return NS->getPDBFile();
}

static void pdb2Yaml(StringRef Path) {
  std::unique_ptr<IPDBSession> Session;
  auto &File = loadPDB(Path, Session);

  auto O = llvm::make_unique<YAMLOutputStyle>(File);
  O = llvm::make_unique<YAMLOutputStyle>(File);

  ExitOnErr(O->dump());
}

static void dumpRaw(StringRef Path) {

  InputFile IF = ExitOnErr(InputFile::open(Path));

  auto O = llvm::make_unique<DumpOutputStyle>(IF);
  ExitOnErr(O->dump());
}

static void dumpBytes(StringRef Path) {
  std::unique_ptr<IPDBSession> Session;
  auto &File = loadPDB(Path, Session);

  auto O = llvm::make_unique<BytesOutputStyle>(File);

  ExitOnErr(O->dump());
}

static void dumpAnalysis(StringRef Path) {
  std::unique_ptr<IPDBSession> Session;
  auto &File = loadPDB(Path, Session);
  auto O = llvm::make_unique<AnalysisStyle>(File);

  ExitOnErr(O->dump());
}

static void diff(StringRef Path1, StringRef Path2) {
  std::unique_ptr<IPDBSession> Session1;
  std::unique_ptr<IPDBSession> Session2;

  auto &File1 = loadPDB(Path1, Session1);
  auto &File2 = loadPDB(Path2, Session2);

  auto O = llvm::make_unique<DiffStyle>(File1, File2);

  ExitOnErr(O->dump());
}

bool opts::pretty::shouldDumpSymLevel(SymLevel Search) {
  if (SymTypes.empty())
    return true;
  if (llvm::find(SymTypes, Search) != SymTypes.end())
    return true;
  if (llvm::find(SymTypes, SymLevel::All) != SymTypes.end())
    return true;
  return false;
}

uint32_t llvm::pdb::getTypeLength(const PDBSymbolData &Symbol) {
  auto SymbolType = Symbol.getType();
  const IPDBRawSymbol &RawType = SymbolType->getRawSymbol();

  return RawType.getLength();
}

bool opts::pretty::compareFunctionSymbols(
    const std::unique_ptr<PDBSymbolFunc> &F1,
    const std::unique_ptr<PDBSymbolFunc> &F2) {
  assert(opts::pretty::SymbolOrder != opts::pretty::SymbolSortMode::None);

  if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::Name)
    return F1->getName() < F2->getName();

  // Note that we intentionally sort in descending order on length, since
  // long functions are more interesting than short functions.
  return F1->getLength() > F2->getLength();
}

bool opts::pretty::compareDataSymbols(
    const std::unique_ptr<PDBSymbolData> &F1,
    const std::unique_ptr<PDBSymbolData> &F2) {
  assert(opts::pretty::SymbolOrder != opts::pretty::SymbolSortMode::None);

  if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::Name)
    return F1->getName() < F2->getName();

  // Note that we intentionally sort in descending order on length, since
  // large types are more interesting than short ones.
  return getTypeLength(*F1) > getTypeLength(*F2);
}

static void dumpPretty(StringRef Path) {
  std::unique_ptr<IPDBSession> Session;

  const auto ReaderType =
      opts::pretty::Native ? PDB_ReaderType::Native : PDB_ReaderType::DIA;
  ExitOnErr(loadDataForPDB(ReaderType, Path, Session));

  if (opts::pretty::LoadAddress)
    Session->setLoadAddress(opts::pretty::LoadAddress);

  auto &Stream = outs();
  const bool UseColor = opts::pretty::ColorOutput == cl::BOU_UNSET
                            ? Stream.has_colors()
                            : opts::pretty::ColorOutput == cl::BOU_TRUE;
  LinePrinter Printer(2, UseColor, Stream);

  auto GlobalScope(Session->getGlobalScope());
  std::string FileName(GlobalScope->getSymbolsFileName());

  WithColor(Printer, PDB_ColorItem::None).get() << "Summary for ";
  WithColor(Printer, PDB_ColorItem::Path).get() << FileName;
  Printer.Indent();
  uint64_t FileSize = 0;

  Printer.NewLine();
  WithColor(Printer, PDB_ColorItem::Identifier).get() << "Size";
  if (!sys::fs::file_size(FileName, FileSize)) {
    Printer << ": " << FileSize << " bytes";
  } else {
    Printer << ": (Unable to obtain file size)";
  }

  Printer.NewLine();
  WithColor(Printer, PDB_ColorItem::Identifier).get() << "Guid";
  Printer << ": " << GlobalScope->getGuid();

  Printer.NewLine();
  WithColor(Printer, PDB_ColorItem::Identifier).get() << "Age";
  Printer << ": " << GlobalScope->getAge();

  Printer.NewLine();
  WithColor(Printer, PDB_ColorItem::Identifier).get() << "Attributes";
  Printer << ": ";
  if (GlobalScope->hasCTypes())
    outs() << "HasCTypes ";
  if (GlobalScope->hasPrivateSymbols())
    outs() << "HasPrivateSymbols ";
  Printer.Unindent();

  if (opts::pretty::Compilands) {
    Printer.NewLine();
    WithColor(Printer, PDB_ColorItem::SectionHeader).get()
        << "---COMPILANDS---";
    Printer.Indent();
    auto Compilands = GlobalScope->findAllChildren<PDBSymbolCompiland>();
    CompilandDumper Dumper(Printer);
    CompilandDumpFlags options = CompilandDumper::Flags::None;
    if (opts::pretty::Lines)
      options = options | CompilandDumper::Flags::Lines;
    while (auto Compiland = Compilands->getNext())
      Dumper.start(*Compiland, options);
    Printer.Unindent();
  }

  if (opts::pretty::Classes || opts::pretty::Enums || opts::pretty::Typedefs) {
    Printer.NewLine();
    WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---TYPES---";
    Printer.Indent();
    TypeDumper Dumper(Printer);
    Dumper.start(*GlobalScope);
    Printer.Unindent();
  }

  if (opts::pretty::Symbols) {
    Printer.NewLine();
    WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---SYMBOLS---";
    Printer.Indent();
    auto Compilands = GlobalScope->findAllChildren<PDBSymbolCompiland>();
    CompilandDumper Dumper(Printer);
    while (auto Compiland = Compilands->getNext())
      Dumper.start(*Compiland, true);
    Printer.Unindent();
  }

  if (opts::pretty::Globals) {
    Printer.NewLine();
    WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---GLOBALS---";
    Printer.Indent();
    if (shouldDumpSymLevel(opts::pretty::SymLevel::Functions)) {
      FunctionDumper Dumper(Printer);
      auto Functions = GlobalScope->findAllChildren<PDBSymbolFunc>();
      if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::None) {
        while (auto Function = Functions->getNext()) {
          Printer.NewLine();
          Dumper.start(*Function, FunctionDumper::PointerType::None);
        }
      } else {
        std::vector<std::unique_ptr<PDBSymbolFunc>> Funcs;
        while (auto Func = Functions->getNext())
          Funcs.push_back(std::move(Func));
        std::sort(Funcs.begin(), Funcs.end(),
                  opts::pretty::compareFunctionSymbols);
        for (const auto &Func : Funcs) {
          Printer.NewLine();
          Dumper.start(*Func, FunctionDumper::PointerType::None);
        }
      }
    }
    if (shouldDumpSymLevel(opts::pretty::SymLevel::Data)) {
      auto Vars = GlobalScope->findAllChildren<PDBSymbolData>();
      VariableDumper Dumper(Printer);
      if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::None) {
        while (auto Var = Vars->getNext())
          Dumper.start(*Var);
      } else {
        std::vector<std::unique_ptr<PDBSymbolData>> Datas;
        while (auto Var = Vars->getNext())
          Datas.push_back(std::move(Var));
        std::sort(Datas.begin(), Datas.end(), opts::pretty::compareDataSymbols);
        for (const auto &Var : Datas)
          Dumper.start(*Var);
      }
    }
    if (shouldDumpSymLevel(opts::pretty::SymLevel::Thunks)) {
      auto Thunks = GlobalScope->findAllChildren<PDBSymbolThunk>();
      CompilandDumper Dumper(Printer);
      while (auto Thunk = Thunks->getNext())
        Dumper.dump(*Thunk);
    }
    Printer.Unindent();
  }
  if (opts::pretty::Externals) {
    Printer.NewLine();
    WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---EXTERNALS---";
    Printer.Indent();
    ExternalSymbolDumper Dumper(Printer);
    Dumper.start(*GlobalScope);
  }
  if (opts::pretty::Lines) {
    Printer.NewLine();
  }
  outs().flush();
}

static void mergePdbs() {
  BumpPtrAllocator Allocator;
  TypeTableBuilder MergedTpi(Allocator);
  TypeTableBuilder MergedIpi(Allocator);

  // Create a Tpi and Ipi type table with all types from all input files.
  for (const auto &Path : opts::merge::InputFilenames) {
    std::unique_ptr<IPDBSession> Session;
    auto &File = loadPDB(Path, Session);
    SmallVector<TypeIndex, 128> TypeMap;
    SmallVector<TypeIndex, 128> IdMap;
    if (File.hasPDBTpiStream()) {
      auto &Tpi = ExitOnErr(File.getPDBTpiStream());
      ExitOnErr(
          codeview::mergeTypeRecords(MergedTpi, TypeMap, Tpi.typeArray()));
    }
    if (File.hasPDBIpiStream()) {
      auto &Ipi = ExitOnErr(File.getPDBIpiStream());
      ExitOnErr(codeview::mergeIdRecords(MergedIpi, TypeMap, IdMap,
                                         Ipi.typeArray()));
    }
  }

  // Then write the PDB.
  PDBFileBuilder Builder(Allocator);
  ExitOnErr(Builder.initialize(4096));
  // Add each of the reserved streams.  We might not put any data in them,
  // but at least they have to be present.
  for (uint32_t I = 0; I < kSpecialStreamCount; ++I)
    ExitOnErr(Builder.getMsfBuilder().addStream(0));

  auto &DestTpi = Builder.getTpiBuilder();
  auto &DestIpi = Builder.getIpiBuilder();
  MergedTpi.ForEachRecord([&DestTpi](TypeIndex TI, ArrayRef<uint8_t> Data) {
    DestTpi.addTypeRecord(Data, None);
  });
  MergedIpi.ForEachRecord([&DestIpi](TypeIndex TI, ArrayRef<uint8_t> Data) {
    DestIpi.addTypeRecord(Data, None);
  });
  Builder.getInfoBuilder().addFeature(PdbRaw_FeatureSig::VC140);

  SmallString<64> OutFile(opts::merge::PdbOutputFile);
  if (OutFile.empty()) {
    OutFile = opts::merge::InputFilenames[0];
    llvm::sys::path::replace_extension(OutFile, "merged.pdb");
  }
  ExitOnErr(Builder.commit(OutFile));
}

static bool parseRange(StringRef Str,
                       Optional<opts::bytes::NumberRange> &Parsed) {
  if (Str.empty())
    return true;

  llvm::Regex R("^([^-]+)(-([^-]+))?$");
  llvm::SmallVector<llvm::StringRef, 2> Matches;
  if (!R.match(Str, &Matches))
    return false;

  Parsed.emplace();
  if (!to_integer(Matches[1], Parsed->Min))
    return false;

  if (!Matches[3].empty()) {
    Parsed->Max.emplace();
    if (!to_integer(Matches[3], *Parsed->Max))
      return false;
  }
  return true;
}

static void simplifyChunkList(llvm::cl::list<opts::ModuleSubsection> &Chunks) {
  // If this list contains "All" plus some other stuff, remove the other stuff
  // and just keep "All" in the list.
  if (!llvm::is_contained(Chunks, opts::ModuleSubsection::All))
    return;
  Chunks.reset();
  Chunks.push_back(opts::ModuleSubsection::All);
}

int main(int argc_, const char *argv_[]) {
  // Print a stack trace if we signal out.
  sys::PrintStackTraceOnErrorSignal(argv_[0]);
  PrettyStackTraceProgram X(argc_, argv_);

  ExitOnErr.setBanner("llvm-pdbutil: ");

  SmallVector<const char *, 256> argv;
  SpecificBumpPtrAllocator<char> ArgAllocator;
  ExitOnErr(errorCodeToError(sys::Process::GetArgumentVector(
      argv, makeArrayRef(argv_, argc_), ArgAllocator)));

  llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.

  cl::ParseCommandLineOptions(argv.size(), argv.data(), "LLVM PDB Dumper\n");

  if (opts::BytesSubcommand) {
    if (!parseRange(opts::bytes::DumpBlockRangeOpt,
                    opts::bytes::DumpBlockRange)) {
      errs() << "Argument '" << opts::bytes::DumpBlockRangeOpt
             << "' invalid format.\n";
      errs().flush();
      exit(1);
    }
    if (!parseRange(opts::bytes::DumpByteRangeOpt,
                    opts::bytes::DumpByteRange)) {
      errs() << "Argument '" << opts::bytes::DumpByteRangeOpt
             << "' invalid format.\n";
      errs().flush();
      exit(1);
    }
  }

  if (opts::DumpSubcommand) {
    if (opts::dump::RawAll) {
      opts::dump::DumpGlobals = true;
      opts::dump::DumpInlineeLines = true;
      opts::dump::DumpIds = true;
      opts::dump::DumpIdExtras = true;
      opts::dump::DumpLines = true;
      opts::dump::DumpModules = true;
      opts::dump::DumpModuleFiles = true;
      opts::dump::DumpPublics = true;
      opts::dump::DumpSectionContribs = true;
      opts::dump::DumpSectionHeaders = true;
      opts::dump::DumpSectionMap = true;
      opts::dump::DumpStreams = true;
      opts::dump::DumpStreamBlocks = true;
      opts::dump::DumpStringTable = true;
      opts::dump::DumpSummary = true;
      opts::dump::DumpSymbols = true;
      opts::dump::DumpSymbolStats = true;
      opts::dump::DumpTypes = true;
      opts::dump::DumpTypeExtras = true;
      opts::dump::DumpUdtStats = true;
      opts::dump::DumpXme = true;
      opts::dump::DumpXmi = true;
    }
  }
  if (opts::PdbToYamlSubcommand) {
    if (opts::pdb2yaml::All) {
      opts::pdb2yaml::StreamMetadata = true;
      opts::pdb2yaml::StreamDirectory = true;
      opts::pdb2yaml::PdbStream = true;
      opts::pdb2yaml::StringTable = true;
      opts::pdb2yaml::DbiStream = true;
      opts::pdb2yaml::TpiStream = true;
      opts::pdb2yaml::IpiStream = true;
      opts::pdb2yaml::DumpModules = true;
      opts::pdb2yaml::DumpModuleFiles = true;
      opts::pdb2yaml::DumpModuleSyms = true;
      opts::pdb2yaml::DumpModuleSubsections.push_back(
          opts::ModuleSubsection::All);
    }
    simplifyChunkList(opts::pdb2yaml::DumpModuleSubsections);

    if (opts::pdb2yaml::DumpModuleSyms || opts::pdb2yaml::DumpModuleFiles)
      opts::pdb2yaml::DumpModules = true;

    if (opts::pdb2yaml::DumpModules)
      opts::pdb2yaml::DbiStream = true;
  }
  if (opts::DiffSubcommand) {
    if (!opts::diff::PrintResultColumn && !opts::diff::PrintValueColumns) {
      llvm::errs() << "WARNING: No diff columns specified\n";
    }
  }

  llvm::sys::InitializeCOMRAII COM(llvm::sys::COMThreadingMode::MultiThreaded);

  if (opts::PdbToYamlSubcommand) {
    pdb2Yaml(opts::pdb2yaml::InputFilename.front());
  } else if (opts::YamlToPdbSubcommand) {
    if (opts::yaml2pdb::YamlPdbOutputFile.empty()) {
      SmallString<16> OutputFilename(opts::yaml2pdb::InputFilename.getValue());
      sys::path::replace_extension(OutputFilename, ".pdb");
      opts::yaml2pdb::YamlPdbOutputFile = OutputFilename.str();
    }
    yamlToPdb(opts::yaml2pdb::InputFilename);
  } else if (opts::AnalyzeSubcommand) {
    dumpAnalysis(opts::analyze::InputFilename.front());
  } else if (opts::PrettySubcommand) {
    if (opts::pretty::Lines)
      opts::pretty::Compilands = true;

    if (opts::pretty::All) {
      opts::pretty::Compilands = true;
      opts::pretty::Symbols = true;
      opts::pretty::Globals = true;
      opts::pretty::Types = true;
      opts::pretty::Externals = true;
      opts::pretty::Lines = true;
    }

    if (opts::pretty::Types) {
      opts::pretty::Classes = true;
      opts::pretty::Typedefs = true;
      opts::pretty::Enums = true;
    }

    // When adding filters for excluded compilands and types, we need to
    // remember that these are regexes.  So special characters such as * and \
    // need to be escaped in the regex.  In the case of a literal \, this means
    // it needs to be escaped again in the C++.  So matching a single \ in the
    // input requires 4 \es in the C++.
    if (opts::pretty::ExcludeCompilerGenerated) {
      opts::pretty::ExcludeTypes.push_back("__vc_attributes");
      opts::pretty::ExcludeCompilands.push_back("\\* Linker \\*");
    }
    if (opts::pretty::ExcludeSystemLibraries) {
      opts::pretty::ExcludeCompilands.push_back(
          "f:\\\\binaries\\\\Intermediate\\\\vctools\\\\crt_bld");
      opts::pretty::ExcludeCompilands.push_back("f:\\\\dd\\\\vctools\\\\crt");
      opts::pretty::ExcludeCompilands.push_back(
          "d:\\\\th.obj.x86fre\\\\minkernel");
    }
    llvm::for_each(opts::pretty::InputFilenames, dumpPretty);
  } else if (opts::DumpSubcommand) {
    llvm::for_each(opts::dump::InputFilenames, dumpRaw);
  } else if (opts::BytesSubcommand) {
    llvm::for_each(opts::bytes::InputFilenames, dumpBytes);
  } else if (opts::DiffSubcommand) {
    for (StringRef S : opts::diff::RawModiEquivalences) {
      StringRef Left;
      StringRef Right;
      std::tie(Left, Right) = S.split(',');
      uint32_t X, Y;
      if (!to_integer(Left, X) || !to_integer(Right, Y)) {
        errs() << formatv("invalid value {0} specified for modi equivalence\n",
                          S);
        exit(1);
      }
      opts::diff::Equivalences[X] = Y;
    }

    diff(opts::diff::Left, opts::diff::Right);
  } else if (opts::MergeSubcommand) {
    if (opts::merge::InputFilenames.size() < 2) {
      errs() << "merge subcommand requires at least 2 input files.\n";
      exit(1);
    }
    mergePdbs();
  }

  outs().flush();
  return 0;
}