diff options
author | Dimitry Andric <dim@FreeBSD.org> | 2017-07-13 19:25:18 +0000 |
---|---|---|
committer | Dimitry Andric <dim@FreeBSD.org> | 2017-07-13 19:25:18 +0000 |
commit | ca089b24d48ef6fa8da2d0bb8c25bb802c4a95c0 (patch) | |
tree | 3a28a772df9b17aef34f49e3c727965ad28c0c93 /tools/llvm-pdbutil | |
parent | 9df3605dea17e84f8183581f6103bd0c79e2a606 (diff) |
Notes
Diffstat (limited to 'tools/llvm-pdbutil')
-rw-r--r-- | tools/llvm-pdbutil/CMakeLists.txt | 1 | ||||
-rw-r--r-- | tools/llvm-pdbutil/Diff.cpp | 692 | ||||
-rw-r--r-- | tools/llvm-pdbutil/DiffPrinter.cpp | 147 | ||||
-rw-r--r-- | tools/llvm-pdbutil/DiffPrinter.h | 172 | ||||
-rw-r--r-- | tools/llvm-pdbutil/DumpOutputStyle.cpp | 7 | ||||
-rw-r--r-- | tools/llvm-pdbutil/FormatUtil.cpp | 52 | ||||
-rw-r--r-- | tools/llvm-pdbutil/FormatUtil.h | 10 | ||||
-rw-r--r-- | tools/llvm-pdbutil/MinimalTypeDumper.cpp | 6 | ||||
-rw-r--r-- | tools/llvm-pdbutil/StreamUtil.cpp | 85 | ||||
-rw-r--r-- | tools/llvm-pdbutil/StreamUtil.h | 5 | ||||
-rw-r--r-- | tools/llvm-pdbutil/llvm-pdbutil.cpp | 44 | ||||
-rw-r--r-- | tools/llvm-pdbutil/llvm-pdbutil.h | 7 |
12 files changed, 913 insertions, 315 deletions
diff --git a/tools/llvm-pdbutil/CMakeLists.txt b/tools/llvm-pdbutil/CMakeLists.txt index 7a3245424efc6..bc28e6bdd7eaa 100644 --- a/tools/llvm-pdbutil/CMakeLists.txt +++ b/tools/llvm-pdbutil/CMakeLists.txt @@ -11,6 +11,7 @@ add_llvm_tool(llvm-pdbutil Analyze.cpp BytesOutputStyle.cpp Diff.cpp + DiffPrinter.cpp DumpOutputStyle.cpp llvm-pdbutil.cpp FormatUtil.cpp diff --git a/tools/llvm-pdbutil/Diff.cpp b/tools/llvm-pdbutil/Diff.cpp index 9b38ae1d603ef..aad4e1bf14279 100644 --- a/tools/llvm-pdbutil/Diff.cpp +++ b/tools/llvm-pdbutil/Diff.cpp @@ -9,22 +9,162 @@ #include "Diff.h" +#include "DiffPrinter.h" +#include "FormatUtil.h" #include "StreamUtil.h" #include "llvm-pdbutil.h" +#include "llvm/ADT/StringSet.h" + +#include "llvm/DebugInfo/PDB/Native/DbiStream.h" #include "llvm/DebugInfo/PDB/Native/Formatters.h" #include "llvm/DebugInfo/PDB/Native/InfoStream.h" #include "llvm/DebugInfo/PDB/Native/PDBFile.h" #include "llvm/DebugInfo/PDB/Native/PDBStringTable.h" #include "llvm/DebugInfo/PDB/Native/RawConstants.h" +#include "llvm/Support/FileSystem.h" #include "llvm/Support/FormatAdapters.h" #include "llvm/Support/FormatProviders.h" #include "llvm/Support/FormatVariadic.h" +#include "llvm/Support/Path.h" using namespace llvm; using namespace llvm::pdb; +namespace { +// Compare and format two stream numbers. Stream numbers are considered +// identical if they contain the same value, equivalent if they are both +// the invalid stream or neither is the invalid stream, and different if +// one is the invalid stream and another isn't. +struct StreamNumberProvider { + static DiffResult compare(uint16_t L, uint16_t R) { + if (L == R) + return DiffResult::IDENTICAL; + bool LP = L != kInvalidStreamIndex; + bool RP = R != kInvalidStreamIndex; + if (LP != RP) + return DiffResult::DIFFERENT; + return DiffResult::EQUIVALENT; + } + + static std::string format(uint16_t SN, bool Right) { + if (SN == kInvalidStreamIndex) + return "(not present)"; + return formatv("{0}", SN).str(); + } +}; + +// Compares and formats two module indices. Modis are considered identical +// if they are identical, equivalent if they either both contain a value or +// both don't contain a value, and different if one contains a value and the +// other doesn't. +struct ModiProvider { + DiffResult compare(Optional<uint32_t> L, Optional<uint32_t> R) { + if (L == R) + return DiffResult::IDENTICAL; + if (L.hasValue() != R.hasValue()) + return DiffResult::DIFFERENT; + return DiffResult::EQUIVALENT; + } + + std::string format(Optional<uint32_t> Modi, bool Right) { + if (!Modi.hasValue()) + return "(not present)"; + return formatv("{0}", *Modi).str(); + } +}; + +// Compares and formats two paths embedded in the PDB, ignoring the beginning +// of the path if the user specified it as a "root path" on the command line. +struct BinaryPathProvider { + explicit BinaryPathProvider(uint32_t MaxLen) : MaxLen(MaxLen) {} + + DiffResult compare(StringRef L, StringRef R) { + if (L == R) + return DiffResult::IDENTICAL; + + SmallString<64> LN = removeRoot(L, false); + SmallString<64> RN = removeRoot(R, true); + + return (LN.equals_lower(RN)) ? DiffResult::EQUIVALENT + : DiffResult::DIFFERENT; + } + + std::string format(StringRef S, bool Right) { + if (S.empty()) + return "(empty)"; + + SmallString<64> Native = removeRoot(S, Right); + return truncateStringFront(Native.str(), MaxLen); + } + + SmallString<64> removeRoot(StringRef Path, bool IsRight) const { + SmallString<64> Native(Path); + auto &RootOpt = IsRight ? opts::diff::RightRoot : opts::diff::LeftRoot; + SmallString<64> Root(static_cast<std::string>(RootOpt)); + // pdb paths always use windows syntax, convert slashes to backslashes. + sys::path::native(Root, sys::path::Style::windows); + if (sys::path::has_stem(Root, sys::path::Style::windows)) + sys::path::append(Root, sys::path::Style::windows, + sys::path::get_separator(sys::path::Style::windows)); + + sys::path::replace_path_prefix(Native, Root, "", sys::path::Style::windows); + return Native; + } + uint32_t MaxLen; +}; + +// Compare and format two stream purposes. For general streams, this just +// compares the description. For module streams it uses the path comparison +// algorithm taking into consideration the binary root, described above. +// Formatting stream purposes just prints the stream purpose, except for +// module streams and named streams, where it prefixes the name / module +// with an identifier. Example: +// +// Named Stream "\names" +// Module Stream "foo.obj" +// +// If a named stream is too long to fit in a column, it is truncated at the +// end, and if a module is too long to fit in a column, it is truncated at the +// beginning. Example: +// +// Named Stream "\Really Long Str..." +// Module Stream "...puts\foo.obj" +// +struct StreamPurposeProvider { + explicit StreamPurposeProvider(uint32_t MaxLen) : MaxLen(MaxLen) {} + + DiffResult compare(const std::pair<StreamPurpose, std::string> &L, + const std::pair<StreamPurpose, std::string> &R) { + if (L.first != R.first) + return DiffResult::DIFFERENT; + if (L.first == StreamPurpose::ModuleStream) { + BinaryPathProvider PathProvider(MaxLen); + return PathProvider.compare(L.second, R.second); + } + return (L.second == R.second) ? DiffResult::IDENTICAL + : DiffResult::DIFFERENT; + } + + std::string format(const std::pair<StreamPurpose, std::string> &P, + bool Right) { + if (P.first == StreamPurpose::Other) + return truncateStringBack(P.second, MaxLen); + if (P.first == StreamPurpose::NamedStream) + return truncateQuotedNameBack("Named Stream", P.second, MaxLen); + + assert(P.first == StreamPurpose::ModuleStream); + uint32_t ExtraChars = strlen("Module \"\""); + BinaryPathProvider PathProvider(MaxLen - ExtraChars); + std::string Result = PathProvider.format(P.second, Right); + return formatv("Module \"{0}\"", Result); + } + + uint32_t MaxLen; +}; +} // namespace + namespace llvm { template <> struct format_provider<PdbRaw_FeatureSig> { static void format(const PdbRaw_FeatureSig &Sig, raw_ostream &Stream, @@ -49,47 +189,6 @@ template <> struct format_provider<PdbRaw_FeatureSig> { template <typename R> using ValueOfRange = llvm::detail::ValueOfRange<R>; -template <typename Range, typename Comp> -static void set_differences(Range &&R1, Range &&R2, - SmallVectorImpl<ValueOfRange<Range>> *OnlyLeft, - SmallVectorImpl<ValueOfRange<Range>> *OnlyRight, - SmallVectorImpl<ValueOfRange<Range>> *Intersection, - Comp Comparator) { - - std::sort(R1.begin(), R1.end(), Comparator); - std::sort(R2.begin(), R2.end(), Comparator); - - if (OnlyLeft) { - OnlyLeft->reserve(R1.size()); - auto End = std::set_difference(R1.begin(), R1.end(), R2.begin(), R2.end(), - OnlyLeft->begin(), Comparator); - OnlyLeft->set_size(std::distance(OnlyLeft->begin(), End)); - } - if (OnlyRight) { - OnlyLeft->reserve(R2.size()); - auto End = std::set_difference(R2.begin(), R2.end(), R1.begin(), R1.end(), - OnlyRight->begin(), Comparator); - OnlyRight->set_size(std::distance(OnlyRight->begin(), End)); - } - if (Intersection) { - Intersection->reserve(std::min(R1.size(), R2.size())); - auto End = std::set_intersection(R1.begin(), R1.end(), R2.begin(), R2.end(), - Intersection->begin(), Comparator); - Intersection->set_size(std::distance(Intersection->begin(), End)); - } -} - -template <typename Range> -static void -set_differences(Range &&R1, Range &&R2, - SmallVectorImpl<ValueOfRange<Range>> *OnlyLeft, - SmallVectorImpl<ValueOfRange<Range>> *OnlyRight, - SmallVectorImpl<ValueOfRange<Range>> *Intersection = nullptr) { - std::less<ValueOfRange<Range>> Comp; - set_differences(std::forward<Range>(R1), std::forward<Range>(R2), OnlyLeft, - OnlyRight, Intersection, Comp); -} - DiffStyle::DiffStyle(PDBFile &File1, PDBFile &File2) : File1(File1), File2(File2) {} @@ -136,300 +235,363 @@ Error DiffStyle::dump() { return Error::success(); } -template <typename T> -static bool diffAndPrint(StringRef Label, PDBFile &File1, PDBFile &File2, T V1, - T V2) { - if (V1 == V2) { - outs() << formatv(" {0}: No differences detected!\n", Label); - return false; - } - - outs().indent(2) << Label << "\n"; - outs().indent(4) << formatv("{0}: {1}\n", File1.getFilePath(), V1); - outs().indent(4) << formatv("{0}: {1}\n", File2.getFilePath(), V2); - return true; -} - -template <typename T> -static bool diffAndPrint(StringRef Label, PDBFile &File1, PDBFile &File2, - ArrayRef<T> V1, ArrayRef<T> V2) { - if (V1 == V2) { - outs() << formatv(" {0}: No differences detected!\n", Label); - return false; - } - - outs().indent(2) << Label << "\n"; - outs().indent(4) << formatv("{0}: {1}\n", File1.getFilePath(), - make_range(V1.begin(), V1.end())); - outs().indent(4) << formatv("{0}: {1}\n", File2.getFilePath(), - make_range(V2.begin(), V2.end())); - return true; -} - -template <typename T> -static bool printSymmetricDifferences(PDBFile &File1, PDBFile &File2, - T &&OnlyRange1, T &&OnlyRange2, - StringRef Label) { - bool HasDiff = false; - if (!OnlyRange1.empty()) { - HasDiff = true; - outs() << formatv(" {0} {1}(s) only in ({2})\n", OnlyRange1.size(), Label, - File1.getFilePath()); - for (const auto &Item : OnlyRange1) - outs() << formatv(" {0}\n", Label, Item); - } - if (!OnlyRange2.empty()) { - HasDiff = true; - outs() << formatv(" {0} {1}(s) only in ({2})\n", OnlyRange2.size(), - File2.getFilePath()); - for (const auto &Item : OnlyRange2) - outs() << formatv(" {0}\n", Item); - } - return HasDiff; -} - Error DiffStyle::diffSuperBlock() { - outs() << "MSF Super Block: Searching for differences...\n"; - bool Diffs = false; - - Diffs |= diffAndPrint("Block Size", File1, File2, File1.getBlockSize(), - File2.getBlockSize()); - Diffs |= diffAndPrint("Block Count", File1, File2, File1.getBlockCount(), - File2.getBlockCount()); - Diffs |= diffAndPrint("Unknown 1", File1, File2, File1.getUnknown1(), - File2.getUnknown1()); - if (!Diffs) - outs() << "MSF Super Block: No differences detected...\n"; + DiffPrinter D(2, "MSF Super Block", 16, 20, opts::diff::PrintResultColumn, + opts::diff::PrintValueColumns, outs()); + D.printExplicit("File", DiffResult::UNSPECIFIED, + truncateStringFront(File1.getFilePath(), 18), + truncateStringFront(File2.getFilePath(), 18)); + D.print("Block Size", File1.getBlockSize(), File2.getBlockSize()); + D.print("Block Count", File1.getBlockCount(), File2.getBlockCount()); + D.print("Unknown 1", File1.getUnknown1(), File2.getUnknown1()); + D.print("Directory Size", File1.getNumDirectoryBytes(), + File2.getNumDirectoryBytes()); return Error::success(); } Error DiffStyle::diffStreamDirectory() { - SmallVector<std::string, 32> P; - SmallVector<std::string, 32> Q; + DiffPrinter D(2, "Stream Directory", 30, 20, opts::diff::PrintResultColumn, + opts::diff::PrintValueColumns, outs()); + D.printExplicit("File", DiffResult::UNSPECIFIED, + truncateStringFront(File1.getFilePath(), 18), + truncateStringFront(File2.getFilePath(), 18)); + + SmallVector<std::pair<StreamPurpose, std::string>, 32> P; + SmallVector<std::pair<StreamPurpose, std::string>, 32> Q; discoverStreamPurposes(File1, P); discoverStreamPurposes(File2, Q); - outs() << "Stream Directory: Searching for differences...\n"; - - bool HasDifferences = false; + D.print("Stream Count", File1.getNumStreams(), File2.getNumStreams()); auto PI = to_vector<32>(enumerate(P)); auto QI = to_vector<32>(enumerate(Q)); - typedef decltype(PI) ContainerType; - typedef typename ContainerType::value_type value_type; - - auto Comparator = [](const value_type &I1, const value_type &I2) { - return I1.value() < I2.value(); - }; - - decltype(PI) OnlyP; - decltype(QI) OnlyQ; - decltype(PI) Common; - - set_differences(PI, QI, &OnlyP, &OnlyQ, &Common, Comparator); - - if (!OnlyP.empty()) { - HasDifferences = true; - outs().indent(2) << formatv("{0} Stream(s) only in ({1})\n", OnlyP.size(), - File1.getFilePath()); - for (auto &Item : OnlyP) { - outs().indent(4) << formatv("Stream {0} - {1}\n", Item.index(), - Item.value()); + // Scan all streams in the left hand side, looking for ones that are also + // in the right. Each time we find one, remove it. When we're done, Q + // should contain all the streams that are in the right but not in the left. + StreamPurposeProvider StreamProvider(28); + for (const auto &P : PI) { + typedef decltype(PI) ContainerType; + typedef typename ContainerType::value_type value_type; + + auto Iter = llvm::find_if(QI, [P, &StreamProvider](const value_type &V) { + DiffResult Result = StreamProvider.compare(P.value(), V.value()); + return Result == DiffResult::EQUIVALENT || + Result == DiffResult::IDENTICAL; + }); + + if (Iter == QI.end()) { + D.printExplicit(StreamProvider.format(P.value(), false), + DiffResult::DIFFERENT, P.index(), "(not present)"); + continue; } - } - if (!OnlyQ.empty()) { - HasDifferences = true; - outs().indent(2) << formatv("{0} Streams(s) only in ({1})\n", OnlyQ.size(), - File2.getFilePath()); - for (auto &Item : OnlyQ) { - outs().indent(4) << formatv("Stream {0} - {1}\n", Item.index(), - Item.value()); - } + D.print<EquivalentDiffProvider>(StreamProvider.format(P.value(), false), + P.index(), Iter->index()); + QI.erase(Iter); } - if (!Common.empty()) { - outs().indent(2) << formatv("Found {0} common streams. Searching for " - "intra-stream differences.\n", - Common.size()); - bool HasCommonDifferences = false; - for (const auto &Left : Common) { - // Left was copied from the first range so its index refers to a stream - // index in the first file. Find the corresponding stream index in the - // second file. - auto Range = - std::equal_range(QI.begin(), QI.end(), Left, - [](const value_type &L, const value_type &R) { - return L.value() < R.value(); - }); - const auto &Right = *Range.first; - assert(Left.value() == Right.value()); - uint32_t LeftSize = File1.getStreamByteSize(Left.index()); - uint32_t RightSize = File2.getStreamByteSize(Right.index()); - if (LeftSize != RightSize) { - HasDifferences = true; - HasCommonDifferences = true; - outs().indent(4) << formatv("{0} ({1}: {2} bytes, {3}: {4} bytes)\n", - Left.value(), File1.getFilePath(), LeftSize, - File2.getFilePath(), RightSize); - } - } - if (!HasCommonDifferences) - outs().indent(2) << "Common Streams: No differences detected!\n"; + + for (const auto &Q : QI) { + D.printExplicit(StreamProvider.format(Q.value(), true), + DiffResult::DIFFERENT, "(not present)", Q.index()); } - if (!HasDifferences) - outs() << "Stream Directory: No differences detected!\n"; return Error::success(); } Error DiffStyle::diffStringTable() { + DiffPrinter D(2, "String Table", 30, 20, opts::diff::PrintResultColumn, + opts::diff::PrintValueColumns, outs()); + D.printExplicit("File", DiffResult::UNSPECIFIED, + truncateStringFront(File1.getFilePath(), 18), + truncateStringFront(File2.getFilePath(), 18)); + auto ExpectedST1 = File1.getStringTable(); auto ExpectedST2 = File2.getStringTable(); - outs() << "String Table: Searching for differences...\n"; bool Has1 = !!ExpectedST1; bool Has2 = !!ExpectedST2; - if (!(Has1 && Has2)) { - // If one has a string table and the other doesn't, we can print less - // output. - if (Has1 != Has2) { - if (Has1) { - outs() << formatv(" {0}: ({1} strings)\n", File1.getFilePath(), - ExpectedST1->getNameCount()); - outs() << formatv(" {0}: (string table not present)\n", - File2.getFilePath()); - } else { - outs() << formatv(" {0}: (string table not present)\n", - File1.getFilePath()); - outs() << formatv(" {0}: ({1})\n", File2.getFilePath(), - ExpectedST2->getNameCount()); - } - } + std::string Count1 = Has1 ? llvm::utostr(ExpectedST1->getNameCount()) + : "(string table not present)"; + std::string Count2 = Has2 ? llvm::utostr(ExpectedST2->getNameCount()) + : "(string table not present)"; + D.print("Number of Strings", Count1, Count2); + + if (!Has1 || !Has2) { consumeError(ExpectedST1.takeError()); consumeError(ExpectedST2.takeError()); return Error::success(); } - bool HasDiff = false; auto &ST1 = *ExpectedST1; auto &ST2 = *ExpectedST2; - if (ST1.getByteSize() != ST2.getByteSize()) { - outs() << " Stream Size\n"; - outs() << formatv(" {0} - {1} byte(s)\n", File1.getFilePath(), - ST1.getByteSize()); - outs() << formatv(" {0} - {1} byte(s)\n", File2.getFilePath(), - ST2.getByteSize()); - outs() << formatv(" Difference: {0} bytes\n", - AbsoluteDifference(ST1.getByteSize(), ST2.getByteSize())); - HasDiff = true; - } - HasDiff |= diffAndPrint("Hash Version", File1, File2, ST1.getHashVersion(), - ST1.getHashVersion()); - HasDiff |= diffAndPrint("Signature", File1, File2, ST1.getSignature(), - ST1.getSignature()); + D.print("Hash Version", ST1.getHashVersion(), ST2.getHashVersion()); + D.print("Byte Size", ST1.getByteSize(), ST2.getByteSize()); + D.print("Signature", ST1.getSignature(), ST2.getSignature()); // Both have a valid string table, dive in and compare individual strings. auto IdList1 = ST1.name_ids(); auto IdList2 = ST2.name_ids(); - std::vector<StringRef> Strings1, Strings2; - Strings1.reserve(IdList1.size()); - Strings2.reserve(IdList2.size()); + StringSet<> LS; + StringSet<> RS; + uint32_t Empty1 = 0; + uint32_t Empty2 = 0; for (auto ID : IdList1) { auto S = ST1.getStringForID(ID); if (!S) return S.takeError(); - Strings1.push_back(*S); + if (S->empty()) + ++Empty1; + else + LS.insert(*S); } for (auto ID : IdList2) { auto S = ST2.getStringForID(ID); if (!S) return S.takeError(); - Strings2.push_back(*S); + if (S->empty()) + ++Empty2; + else + RS.insert(*S); + } + D.print("Empty Strings", Empty1, Empty2); + + for (const auto &S : LS) { + auto R = RS.find(S.getKey()); + std::string Truncated = truncateStringMiddle(S.getKey(), 28); + uint32_t I = cantFail(ST1.getIDForString(S.getKey())); + if (R == RS.end()) { + D.printExplicit(Truncated, DiffResult::DIFFERENT, I, "(not present)"); + continue; + } + + uint32_t J = cantFail(ST2.getIDForString(R->getKey())); + D.print<EquivalentDiffProvider>(Truncated, I, J); + RS.erase(R); } - SmallVector<StringRef, 64> OnlyP; - SmallVector<StringRef, 64> OnlyQ; - auto End1 = std::remove(Strings1.begin(), Strings1.end(), ""); - auto End2 = std::remove(Strings2.begin(), Strings2.end(), ""); - uint32_t Empty1 = std::distance(End1, Strings1.end()); - uint32_t Empty2 = std::distance(End2, Strings2.end()); - Strings1.erase(End1, Strings1.end()); - Strings2.erase(End2, Strings2.end()); - set_differences(Strings1, Strings2, &OnlyP, &OnlyQ); - printSymmetricDifferences(File1, File2, OnlyP, OnlyQ, "String"); - - if (Empty1 != Empty2) { - PDBFile &MoreF = (Empty1 > Empty2) ? File1 : File2; - PDBFile &LessF = (Empty1 < Empty2) ? File1 : File2; - uint32_t Difference = AbsoluteDifference(Empty1, Empty2); - outs() << formatv(" {0} had {1} more empty strings than {2}\n", - MoreF.getFilePath(), Difference, LessF.getFilePath()); + for (const auto &S : RS) { + auto L = LS.find(S.getKey()); + std::string Truncated = truncateStringMiddle(S.getKey(), 28); + uint32_t J = cantFail(ST2.getIDForString(S.getKey())); + if (L == LS.end()) { + D.printExplicit(Truncated, DiffResult::DIFFERENT, "(not present)", J); + continue; + } + + uint32_t I = cantFail(ST1.getIDForString(L->getKey())); + D.print<EquivalentDiffProvider>(Truncated, I, J); } - if (!HasDiff) - outs() << "String Table: No differences detected!\n"; return Error::success(); } Error DiffStyle::diffFreePageMap() { return Error::success(); } Error DiffStyle::diffInfoStream() { + DiffPrinter D(2, "PDB Stream", 22, 40, opts::diff::PrintResultColumn, + opts::diff::PrintValueColumns, outs()); + D.printExplicit("File", DiffResult::UNSPECIFIED, + truncateStringFront(File1.getFilePath(), 38), + truncateStringFront(File2.getFilePath(), 38)); + auto ExpectedInfo1 = File1.getPDBInfoStream(); auto ExpectedInfo2 = File2.getPDBInfoStream(); - outs() << "PDB Stream: Searching for differences...\n"; bool Has1 = !!ExpectedInfo1; bool Has2 = !!ExpectedInfo2; if (!(Has1 && Has2)) { - if (Has1 != Has2) - outs() << formatv("{0} does not have a PDB Stream!\n", - Has1 ? File1.getFilePath() : File2.getFilePath()); - consumeError(ExpectedInfo2.takeError()); + std::string L = Has1 ? "(present)" : "(not present)"; + std::string R = Has2 ? "(present)" : "(not present)"; + D.print("Stream", L, R); + + consumeError(ExpectedInfo1.takeError()); consumeError(ExpectedInfo2.takeError()); return Error::success(); } - bool HasDiff = false; auto &IS1 = *ExpectedInfo1; auto &IS2 = *ExpectedInfo2; - if (IS1.getStreamSize() != IS2.getStreamSize()) { - outs() << " Stream Size\n"; - outs() << formatv(" {0} - {1} byte(s)\n", File1.getFilePath(), - IS1.getStreamSize()); - outs() << formatv(" {0} - {1} byte(s)\n", File2.getFilePath(), - IS2.getStreamSize()); - outs() << formatv( - " Difference: {0} bytes\n", - AbsoluteDifference(IS1.getStreamSize(), IS2.getStreamSize())); - HasDiff = true; + D.print("Stream Size", IS1.getStreamSize(), IS2.getStreamSize()); + D.print("Age", IS1.getAge(), IS2.getAge()); + D.print("Guid", IS1.getGuid(), IS2.getGuid()); + D.print("Signature", IS1.getSignature(), IS2.getSignature()); + D.print("Version", IS1.getVersion(), IS2.getVersion()); + D.diffUnorderedArray("Feature", IS1.getFeatureSignatures(), + IS2.getFeatureSignatures()); + D.print("Named Stream Size", IS1.getNamedStreamMapByteSize(), + IS2.getNamedStreamMapByteSize()); + StringMap<uint32_t> NSL = IS1.getNamedStreams().getStringMap(); + StringMap<uint32_t> NSR = IS2.getNamedStreams().getStringMap(); + D.diffUnorderedMap<EquivalentDiffProvider>("Named Stream", NSL, NSR); + return Error::success(); +} + +static std::vector<std::pair<uint32_t, DbiModuleDescriptor>> +getModuleDescriptors(const DbiModuleList &ML) { + std::vector<std::pair<uint32_t, DbiModuleDescriptor>> List; + List.reserve(ML.getModuleCount()); + for (uint32_t I = 0; I < ML.getModuleCount(); ++I) + List.emplace_back(I, ML.getModuleDescriptor(I)); + return List; +} + +static void +diffOneModule(DiffPrinter &D, + const std::pair<uint32_t, DbiModuleDescriptor> Item, + std::vector<std::pair<uint32_t, DbiModuleDescriptor>> &Other, + bool ItemIsRight) { + StreamPurposeProvider HeaderProvider(70); + std::pair<StreamPurpose, std::string> Header; + Header.first = StreamPurpose::ModuleStream; + Header.second = Item.second.getModuleName(); + D.printFullRow(HeaderProvider.format(Header, ItemIsRight)); + + const auto *L = &Item; + + BinaryPathProvider PathProvider(28); + auto Iter = llvm::find_if( + Other, [&PathProvider, ItemIsRight, + L](const std::pair<uint32_t, DbiModuleDescriptor> &Other) { + const auto *Left = L; + const auto *Right = &Other; + if (ItemIsRight) + std::swap(Left, Right); + DiffResult Result = PathProvider.compare(Left->second.getModuleName(), + Right->second.getModuleName()); + return Result == DiffResult::EQUIVALENT || + Result == DiffResult::IDENTICAL; + }); + if (Iter == Other.end()) { + // We didn't find this module at all on the other side. Just print one row + // and continue. + D.print<ModiProvider>("- Modi", Item.first, None); + return; } - HasDiff |= diffAndPrint("Age", File1, File2, IS1.getAge(), IS2.getAge()); - HasDiff |= diffAndPrint("Guid", File1, File2, IS1.getGuid(), IS2.getGuid()); - HasDiff |= diffAndPrint("Signature", File1, File2, IS1.getSignature(), - IS2.getSignature()); - HasDiff |= - diffAndPrint("Version", File1, File2, IS1.getVersion(), IS2.getVersion()); - HasDiff |= diffAndPrint("Features", File1, File2, IS1.getFeatureSignatures(), - IS2.getFeatureSignatures()); - HasDiff |= diffAndPrint("Named Stream Byte Size", File1, File2, - IS1.getNamedStreamMapByteSize(), - IS2.getNamedStreamMapByteSize()); - SmallVector<StringRef, 4> NS1; - SmallVector<StringRef, 4> NS2; - for (const auto &X : IS1.getNamedStreams().entries()) - NS1.push_back(X.getKey()); - for (const auto &X : IS2.getNamedStreams().entries()) - NS2.push_back(X.getKey()); - SmallVector<StringRef, 4> OnlyP; - SmallVector<StringRef, 4> OnlyQ; - set_differences(NS1, NS2, &OnlyP, &OnlyQ); - printSymmetricDifferences(File1, File2, OnlyP, OnlyQ, "Named Streams"); - if (!HasDiff) - outs() << "PDB Stream: No differences detected!\n"; - return Error::success(); + // We did find this module. Go through and compare each field. + const auto *R = &*Iter; + if (ItemIsRight) + std::swap(L, R); + + D.print<ModiProvider>("- Modi", L->first, R->first); + D.print<BinaryPathProvider>("- Obj File Name", L->second.getObjFileName(), + R->second.getObjFileName(), PathProvider); + D.print<StreamNumberProvider>("- Debug Stream", + L->second.getModuleStreamIndex(), + R->second.getModuleStreamIndex()); + D.print("- C11 Byte Size", L->second.getC11LineInfoByteSize(), + R->second.getC11LineInfoByteSize()); + D.print("- C13 Byte Size", L->second.getC13LineInfoByteSize(), + R->second.getC13LineInfoByteSize()); + D.print("- # of files", L->second.getNumberOfFiles(), + R->second.getNumberOfFiles()); + D.print("- Pdb File Path Index", L->second.getPdbFilePathNameIndex(), + R->second.getPdbFilePathNameIndex()); + D.print("- Source File Name Index", L->second.getSourceFileNameIndex(), + R->second.getSourceFileNameIndex()); + D.print("- Symbol Byte Size", L->second.getSymbolDebugInfoByteSize(), + R->second.getSymbolDebugInfoByteSize()); + Other.erase(Iter); } -Error DiffStyle::diffDbiStream() { return Error::success(); } +Error DiffStyle::diffDbiStream() { + DiffPrinter D(2, "DBI Stream", 40, 30, opts::diff::PrintResultColumn, + opts::diff::PrintValueColumns, outs()); + D.printExplicit("File", DiffResult::UNSPECIFIED, + truncateStringFront(File1.getFilePath(), 28), + truncateStringFront(File2.getFilePath(), 28)); + + auto ExpectedDbi1 = File1.getPDBDbiStream(); + auto ExpectedDbi2 = File2.getPDBDbiStream(); + + bool Has1 = !!ExpectedDbi1; + bool Has2 = !!ExpectedDbi2; + if (!(Has1 && Has2)) { + std::string L = Has1 ? "(present)" : "(not present)"; + std::string R = Has2 ? "(present)" : "(not present)"; + D.print("Stream", L, R); + + consumeError(ExpectedDbi1.takeError()); + consumeError(ExpectedDbi2.takeError()); + return Error::success(); + } + + auto &DL = *ExpectedDbi1; + auto &DR = *ExpectedDbi2; + + D.print("Dbi Version", (uint32_t)DL.getDbiVersion(), + (uint32_t)DR.getDbiVersion()); + D.print("Age", DL.getAge(), DR.getAge()); + D.print("Machine", (uint16_t)DL.getMachineType(), + (uint16_t)DR.getMachineType()); + D.print("Flags", DL.getFlags(), DR.getFlags()); + D.print("Build Major", DL.getBuildMajorVersion(), DR.getBuildMajorVersion()); + D.print("Build Minor", DL.getBuildMinorVersion(), DR.getBuildMinorVersion()); + D.print("Build Number", DL.getBuildNumber(), DR.getBuildNumber()); + D.print("PDB DLL Version", DL.getPdbDllVersion(), DR.getPdbDllVersion()); + D.print("PDB DLL RBLD", DL.getPdbDllRbld(), DR.getPdbDllRbld()); + D.print<StreamNumberProvider>("DBG (FPO)", + DL.getDebugStreamIndex(DbgHeaderType::FPO), + DR.getDebugStreamIndex(DbgHeaderType::FPO)); + D.print<StreamNumberProvider>( + "DBG (Exception)", DL.getDebugStreamIndex(DbgHeaderType::Exception), + DR.getDebugStreamIndex(DbgHeaderType::Exception)); + D.print<StreamNumberProvider>("DBG (Fixup)", + DL.getDebugStreamIndex(DbgHeaderType::Fixup), + DR.getDebugStreamIndex(DbgHeaderType::Fixup)); + D.print<StreamNumberProvider>( + "DBG (OmapToSrc)", DL.getDebugStreamIndex(DbgHeaderType::OmapToSrc), + DR.getDebugStreamIndex(DbgHeaderType::OmapToSrc)); + D.print<StreamNumberProvider>( + "DBG (OmapFromSrc)", DL.getDebugStreamIndex(DbgHeaderType::OmapFromSrc), + DR.getDebugStreamIndex(DbgHeaderType::OmapFromSrc)); + D.print<StreamNumberProvider>( + "DBG (SectionHdr)", DL.getDebugStreamIndex(DbgHeaderType::SectionHdr), + DR.getDebugStreamIndex(DbgHeaderType::SectionHdr)); + D.print<StreamNumberProvider>( + "DBG (TokenRidMap)", DL.getDebugStreamIndex(DbgHeaderType::TokenRidMap), + DR.getDebugStreamIndex(DbgHeaderType::TokenRidMap)); + D.print<StreamNumberProvider>("DBG (Xdata)", + DL.getDebugStreamIndex(DbgHeaderType::Xdata), + DR.getDebugStreamIndex(DbgHeaderType::Xdata)); + D.print<StreamNumberProvider>("DBG (Pdata)", + DL.getDebugStreamIndex(DbgHeaderType::Pdata), + DR.getDebugStreamIndex(DbgHeaderType::Pdata)); + D.print<StreamNumberProvider>("DBG (NewFPO)", + DL.getDebugStreamIndex(DbgHeaderType::NewFPO), + DR.getDebugStreamIndex(DbgHeaderType::NewFPO)); + D.print<StreamNumberProvider>( + "DBG (SectionHdrOrig)", + DL.getDebugStreamIndex(DbgHeaderType::SectionHdrOrig), + DR.getDebugStreamIndex(DbgHeaderType::SectionHdrOrig)); + D.print<StreamNumberProvider>("Globals Stream", + DL.getGlobalSymbolStreamIndex(), + DR.getGlobalSymbolStreamIndex()); + D.print<StreamNumberProvider>("Publics Stream", + DL.getPublicSymbolStreamIndex(), + DR.getPublicSymbolStreamIndex()); + D.print<StreamNumberProvider>("Symbol Records", DL.getSymRecordStreamIndex(), + DR.getSymRecordStreamIndex()); + D.print("Has CTypes", DL.hasCTypes(), DR.hasCTypes()); + D.print("Is Incrementally Linked", DL.isIncrementallyLinked(), + DR.isIncrementallyLinked()); + D.print("Is Stripped", DL.isStripped(), DR.isStripped()); + const DbiModuleList &ML = DL.modules(); + const DbiModuleList &MR = DR.modules(); + D.print("Module Count", ML.getModuleCount(), MR.getModuleCount()); + D.print("Source File Count", ML.getSourceFileCount(), + MR.getSourceFileCount()); + auto MDL = getModuleDescriptors(ML); + auto MDR = getModuleDescriptors(MR); + // Scan all module descriptors from the left, and look for corresponding + // module descriptors on the right. + for (const auto &L : MDL) + diffOneModule(D, L, MDR, false); + + for (const auto &R : MDR) + diffOneModule(D, R, MDL, true); + + return Error::success(); +} Error DiffStyle::diffSectionContribs() { return Error::success(); } diff --git a/tools/llvm-pdbutil/DiffPrinter.cpp b/tools/llvm-pdbutil/DiffPrinter.cpp new file mode 100644 index 0000000000000..dd61cc1825936 --- /dev/null +++ b/tools/llvm-pdbutil/DiffPrinter.cpp @@ -0,0 +1,147 @@ + +#include "DiffPrinter.h" + +#include "llvm/Support/FormatAdapters.h" + +using namespace llvm; +using namespace llvm::pdb; + +namespace { +struct Colorize { + Colorize(raw_ostream &OS, DiffResult Result) : OS(OS) { + if (!OS.has_colors()) + return; + switch (Result) { + case DiffResult::IDENTICAL: + OS.changeColor(raw_ostream::Colors::GREEN, false); + break; + case DiffResult::EQUIVALENT: + OS.changeColor(raw_ostream::Colors::YELLOW, true); + break; + default: + OS.changeColor(raw_ostream::Colors::RED, false); + break; + } + } + + ~Colorize() { + if (OS.has_colors()) + OS.resetColor(); + } + + raw_ostream &OS; +}; +} + +DiffPrinter::DiffPrinter(uint32_t Indent, StringRef Header, + uint32_t PropertyWidth, uint32_t FieldWidth, + bool Result, bool Fields, raw_ostream &Stream) + : PrintResult(Result), PrintValues(Fields), Indent(Indent), + PropertyWidth(PropertyWidth), FieldWidth(FieldWidth), OS(Stream) { + printHeaderRow(); + printFullRow(Header); +} + +DiffPrinter::~DiffPrinter() {} + +uint32_t DiffPrinter::tableWidth() const { + // `|` + uint32_t W = 1; + + // `<width>|` + W += PropertyWidth + 1; + + if (PrintResult) { + // ` I |` + W += 4; + } + + if (PrintValues) { + // `<width>|<width>|` + W += 2 * (FieldWidth + 1); + } + return W; +} + +void DiffPrinter::printFullRow(StringRef Text) { + newLine(); + printValue(Text, DiffResult::UNSPECIFIED, AlignStyle::Center, + tableWidth() - 2, true); + printSeparatorRow(); +} + +void DiffPrinter::printSeparatorRow() { + newLine(); + OS << formatv("{0}", fmt_repeat('-', PropertyWidth)); + if (PrintResult) { + OS << '+'; + OS << formatv("{0}", fmt_repeat('-', 3)); + } + if (PrintValues) { + OS << '+'; + OS << formatv("{0}", fmt_repeat('-', FieldWidth)); + OS << '+'; + OS << formatv("{0}", fmt_repeat('-', FieldWidth)); + } + OS << '|'; +} + +void DiffPrinter::printHeaderRow() { + newLine('-'); + OS << formatv("{0}", fmt_repeat('-', tableWidth() - 1)); +} + +void DiffPrinter::newLine(char InitialChar) { + OS << "\n"; + OS.indent(Indent) << InitialChar; +} + +void DiffPrinter::printExplicit(StringRef Property, DiffResult C, + StringRef Left, StringRef Right) { + newLine(); + printValue(Property, DiffResult::UNSPECIFIED, AlignStyle::Right, + PropertyWidth, true); + printResult(C); + printValue(Left, C, AlignStyle::Center, FieldWidth, false); + printValue(Right, C, AlignStyle::Center, FieldWidth, false); + printSeparatorRow(); +} + +void DiffPrinter::printResult(DiffResult Result) { + if (!PrintResult) + return; + switch (Result) { + case DiffResult::DIFFERENT: + printValue("D", Result, AlignStyle::Center, 3, true); + break; + case DiffResult::EQUIVALENT: + printValue("E", Result, AlignStyle::Center, 3, true); + break; + case DiffResult::IDENTICAL: + printValue("I", Result, AlignStyle::Center, 3, true); + break; + case DiffResult::UNSPECIFIED: + printValue(" ", Result, AlignStyle::Center, 3, true); + break; + } +} + +void DiffPrinter::printValue(StringRef Value, DiffResult C, AlignStyle Style, + uint32_t Width, bool Force) { + if (!Force && !PrintValues) + return; + + if (Style == AlignStyle::Right) + --Width; + + std::string FormattedItem = + formatv("{0}", fmt_align(Value, Style, Width)).str(); + if (C != DiffResult::UNSPECIFIED) { + Colorize Color(OS, C); + OS << FormattedItem; + } else + OS << FormattedItem; + if (Style == AlignStyle::Right) + OS << ' '; + OS << '|'; +} diff --git a/tools/llvm-pdbutil/DiffPrinter.h b/tools/llvm-pdbutil/DiffPrinter.h new file mode 100644 index 0000000000000..475747d8dc11d --- /dev/null +++ b/tools/llvm-pdbutil/DiffPrinter.h @@ -0,0 +1,172 @@ +//===- DiffPrinter.h ------------------------------------------ *- C++ --*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_TOOLS_LLVMPDBDUMP_DIFFPRINTER_H +#define LLVM_TOOLS_LLVMPDBDUMP_DIFFPRINTER_H + +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/StringMap.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/DebugInfo/PDB/Native/RawConstants.h" +#include "llvm/Support/FormatVariadic.h" +#include "llvm/Support/raw_ostream.h" + +#include <list> +#include <unordered_set> + +namespace std { +template <> struct hash<llvm::pdb::PdbRaw_FeatureSig> { + typedef llvm::pdb::PdbRaw_FeatureSig argument_type; + typedef std::size_t result_type; + result_type operator()(argument_type Item) const { + return std::hash<uint32_t>{}(uint32_t(Item)); + } +}; +} // namespace std + +namespace llvm { +namespace pdb { + +class PDBFile; + +enum class DiffResult { UNSPECIFIED, IDENTICAL, EQUIVALENT, DIFFERENT }; + +struct IdenticalDiffProvider { + template <typename T, typename U> + DiffResult compare(const T &Left, const U &Right) { + return (Left == Right) ? DiffResult::IDENTICAL : DiffResult::DIFFERENT; + } + + template <typename T> std::string format(const T &Item, bool Right) { + return formatv("{0}", Item).str(); + } +}; + +struct EquivalentDiffProvider { + template <typename T, typename U> + DiffResult compare(const T &Left, const U &Right) { + return (Left == Right) ? DiffResult::IDENTICAL : DiffResult::EQUIVALENT; + } + + template <typename T> std::string format(const T &Item, bool Right) { + return formatv("{0}", Item).str(); + } +}; + +class DiffPrinter { +public: + DiffPrinter(uint32_t Indent, StringRef Header, uint32_t PropertyWidth, + uint32_t FieldWidth, bool Result, bool Values, + raw_ostream &Stream); + ~DiffPrinter(); + + template <typename T, typename U> struct Identical {}; + + template <typename Provider = IdenticalDiffProvider, typename T, typename U> + void print(StringRef Property, const T &Left, const U &Right, + Provider P = Provider()) { + std::string L = P.format(Left, false); + std::string R = P.format(Right, true); + + DiffResult Result = P.compare(Left, Right); + printExplicit(Property, Result, L, R); + } + + void printExplicit(StringRef Property, DiffResult C, StringRef Left, + StringRef Right); + + template <typename T, typename U> + void printExplicit(StringRef Property, DiffResult C, const T &Left, + const U &Right) { + std::string L = formatv("{0}", Left).str(); + std::string R = formatv("{0}", Right).str(); + printExplicit(Property, C, StringRef(L), StringRef(R)); + } + + template <typename T, typename U> + void diffUnorderedArray(StringRef Property, ArrayRef<T> Left, + ArrayRef<U> Right) { + std::unordered_set<T> LS(Left.begin(), Left.end()); + std::unordered_set<U> RS(Right.begin(), Right.end()); + std::string Count1 = formatv("{0} element(s)", Left.size()); + std::string Count2 = formatv("{0} element(s)", Right.size()); + print(std::string(Property) + "s (set)", Count1, Count2); + for (const auto &L : LS) { + auto Iter = RS.find(L); + std::string Text = formatv("{0}", L).str(); + if (Iter == RS.end()) { + print(Property, Text, "(not present)"); + continue; + } + print(Property, Text, Text); + RS.erase(Iter); + } + for (const auto &R : RS) { + auto Iter = LS.find(R); + std::string Text = formatv("{0}", R).str(); + if (Iter == LS.end()) { + print(Property, "(not present)", Text); + continue; + } + print(Property, Text, Text); + } + } + + template <typename ValueProvider = IdenticalDiffProvider, typename T, + typename U> + void diffUnorderedMap(StringRef Property, const StringMap<T> &Left, + const StringMap<U> &Right, + ValueProvider P = ValueProvider()) { + StringMap<U> RightCopy(Right); + + std::string Count1 = formatv("{0} element(s)", Left.size()); + std::string Count2 = formatv("{0} element(s)", Right.size()); + print(std::string(Property) + "s (map)", Count1, Count2); + + for (const auto &L : Left) { + auto Iter = RightCopy.find(L.getKey()); + if (Iter == RightCopy.end()) { + printExplicit(L.getKey(), DiffResult::DIFFERENT, L.getValue(), + "(not present)"); + continue; + } + + print(L.getKey(), L.getValue(), Iter->getValue(), P); + RightCopy.erase(Iter); + } + + for (const auto &R : RightCopy) { + printExplicit(R.getKey(), DiffResult::DIFFERENT, "(not present)", + R.getValue()); + } + } + + void printFullRow(StringRef Text); + +private: + uint32_t tableWidth() const; + + void printHeaderRow(); + void printSeparatorRow(); + void newLine(char InitialChar = '|'); + void printValue(StringRef Value, DiffResult C, AlignStyle Style, + uint32_t Width, bool Force); + void printResult(DiffResult Result); + + bool PrintResult; + bool PrintValues; + uint32_t Indent; + uint32_t PropertyWidth; + uint32_t FieldWidth; + raw_ostream &OS; +}; +} // namespace pdb +} // namespace llvm + +#endif diff --git a/tools/llvm-pdbutil/DumpOutputStyle.cpp b/tools/llvm-pdbutil/DumpOutputStyle.cpp index a1f919b4dd065..0642d841fd9f2 100644 --- a/tools/llvm-pdbutil/DumpOutputStyle.cpp +++ b/tools/llvm-pdbutil/DumpOutputStyle.cpp @@ -418,6 +418,13 @@ Error DumpOutputStyle::dumpModules() { P.formatLine(" debug stream: {0}, # files: {1}, has ec info: {2}", Modi.getModuleStreamIndex(), Modi.getNumberOfFiles(), Modi.hasECInfo()); + StringRef PdbFilePath = + Err(Stream.getECName(Modi.getPdbFilePathNameIndex())); + StringRef SrcFilePath = + Err(Stream.getECName(Modi.getSourceFileNameIndex())); + P.formatLine(" pdb file ni: {0} `{1}`, src file ni: {2} `{3}`", + Modi.getPdbFilePathNameIndex(), PdbFilePath, + Modi.getSourceFileNameIndex(), SrcFilePath); } return Error::success(); } diff --git a/tools/llvm-pdbutil/FormatUtil.cpp b/tools/llvm-pdbutil/FormatUtil.cpp index 1bbe2724f0ab9..02030272dd4da 100644 --- a/tools/llvm-pdbutil/FormatUtil.cpp +++ b/tools/llvm-pdbutil/FormatUtil.cpp @@ -16,6 +16,58 @@ using namespace llvm; using namespace llvm::pdb; +std::string llvm::pdb::truncateStringBack(StringRef S, uint32_t MaxLen) { + if (MaxLen == 0 || S.size() <= MaxLen || S.size() <= 3) + return S; + + assert(MaxLen >= 3); + uint32_t FinalLen = std::min<size_t>(S.size(), MaxLen - 3); + S = S.take_front(FinalLen); + return std::string(S) + std::string("..."); +} + +std::string llvm::pdb::truncateStringMiddle(StringRef S, uint32_t MaxLen) { + if (MaxLen == 0 || S.size() <= MaxLen || S.size() <= 3) + return S; + + assert(MaxLen >= 3); + uint32_t FinalLen = std::min<size_t>(S.size(), MaxLen - 3); + StringRef Front = S.take_front(FinalLen / 2); + StringRef Back = S.take_back(Front.size()); + return std::string(Front) + std::string("...") + std::string(Back); +} + +std::string llvm::pdb::truncateStringFront(StringRef S, uint32_t MaxLen) { + if (MaxLen == 0 || S.size() <= MaxLen || S.size() <= 3) + return S; + + assert(MaxLen >= 3); + S = S.take_back(MaxLen - 3); + return std::string("...") + std::string(S); +} + +std::string llvm::pdb::truncateQuotedNameFront(StringRef Label, StringRef Name, + uint32_t MaxLen) { + uint32_t RequiredExtraChars = Label.size() + 1 + 2; + if (MaxLen == 0 || RequiredExtraChars + Name.size() <= MaxLen) + return formatv("{0} \"{1}\"", Label, Name).str(); + + assert(MaxLen >= RequiredExtraChars); + std::string TN = truncateStringFront(Name, MaxLen - RequiredExtraChars); + return formatv("{0} \"{1}\"", Label, TN).str(); +} + +std::string llvm::pdb::truncateQuotedNameBack(StringRef Label, StringRef Name, + uint32_t MaxLen) { + uint32_t RequiredExtraChars = Label.size() + 1 + 2; + if (MaxLen == 0 || RequiredExtraChars + Name.size() <= MaxLen) + return formatv("{0} \"{1}\"", Label, Name).str(); + + assert(MaxLen >= RequiredExtraChars); + std::string TN = truncateStringBack(Name, MaxLen - RequiredExtraChars); + return formatv("{0} \"{1}\"", Label, TN).str(); +} + std::string llvm::pdb::typesetItemList(ArrayRef<std::string> Opts, uint32_t IndentLevel, uint32_t GroupSize, StringRef Sep) { diff --git a/tools/llvm-pdbutil/FormatUtil.h b/tools/llvm-pdbutil/FormatUtil.h index 3db2dbacc57b6..df32ed9360fba 100644 --- a/tools/llvm-pdbutil/FormatUtil.h +++ b/tools/llvm-pdbutil/FormatUtil.h @@ -22,6 +22,14 @@ namespace llvm { namespace pdb { +std::string truncateStringBack(StringRef S, uint32_t MaxLen); +std::string truncateStringMiddle(StringRef S, uint32_t MaxLen); +std::string truncateStringFront(StringRef S, uint32_t MaxLen); +std::string truncateQuotedNameFront(StringRef Label, StringRef Name, + uint32_t MaxLen); +std::string truncateQuotedNameBack(StringRef Label, StringRef Name, + uint32_t MaxLen); + #define PUSH_MASKED_FLAG(Enum, Mask, TheOpt, Value, Text) \ if (Enum::TheOpt == (Value & Mask)) \ Opts.push_back(Text); @@ -33,7 +41,7 @@ namespace pdb { case Enum::X: \ return Ret; -template <typename T> static std::string formatUnknownEnum(T Value) { +template <typename T> std::string formatUnknownEnum(T Value) { return formatv("unknown ({0})", static_cast<typename std::underlying_type<T>::type>(Value)) .str(); diff --git a/tools/llvm-pdbutil/MinimalTypeDumper.cpp b/tools/llvm-pdbutil/MinimalTypeDumper.cpp index 1af53e35ed111..9621320ea99ad 100644 --- a/tools/llvm-pdbutil/MinimalTypeDumper.cpp +++ b/tools/llvm-pdbutil/MinimalTypeDumper.cpp @@ -299,7 +299,7 @@ Error MinimalTypeDumpVisitor::visitKnownRecord(CVType &CVR, Error MinimalTypeDumpVisitor::visitKnownRecord(CVType &CVR, ClassRecord &Class) { - P.formatLine("class name: `{0}`", Class.Name); + P.format(" `{0}`", Class.Name); if (Class.hasUniqueName()) P.formatLine("unique name: `{0}`", Class.UniqueName); P.formatLine("vtable: {0}, base list: {1}, field list: {2}", @@ -311,7 +311,7 @@ Error MinimalTypeDumpVisitor::visitKnownRecord(CVType &CVR, Error MinimalTypeDumpVisitor::visitKnownRecord(CVType &CVR, UnionRecord &Union) { - P.formatLine("class name: `{0}`", Union.Name); + P.format(" `{0}`", Union.Name); if (Union.hasUniqueName()) P.formatLine("unique name: `{0}`", Union.UniqueName); P.formatLine("field list: {0}", Union.FieldList); @@ -321,7 +321,7 @@ Error MinimalTypeDumpVisitor::visitKnownRecord(CVType &CVR, } Error MinimalTypeDumpVisitor::visitKnownRecord(CVType &CVR, EnumRecord &Enum) { - P.formatLine("name: `{0}`", Enum.Name); + P.format(" `{0}`", Enum.Name); if (Enum.hasUniqueName()) P.formatLine("unique name: `{0}`", Enum.UniqueName); P.formatLine("field list: {0}, underlying type: {1}", Enum.FieldList, diff --git a/tools/llvm-pdbutil/StreamUtil.cpp b/tools/llvm-pdbutil/StreamUtil.cpp index 81aa256b5002d..4d352004dec30 100644 --- a/tools/llvm-pdbutil/StreamUtil.cpp +++ b/tools/llvm-pdbutil/StreamUtil.cpp @@ -8,6 +8,7 @@ //===----------------------------------------------------------------------===// #include "StreamUtil.h" +#include "FormatUtil.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseMapInfo.h" @@ -18,11 +19,12 @@ #include "llvm/DebugInfo/PDB/Native/PDBFile.h" #include "llvm/DebugInfo/PDB/Native/TpiStream.h" -namespace llvm { -namespace pdb { -void discoverStreamPurposes(PDBFile &File, - SmallVectorImpl<std::string> &Purposes) { +using namespace llvm; +using namespace llvm::pdb; +void llvm::pdb::discoverStreamPurposes( + PDBFile &File, + SmallVectorImpl<std::pair<StreamPurpose, std::string>> &Purposes) { // It's OK if we fail to load some of these streams, we still attempt to print // what we can. auto Dbi = File.getPDBDbiStream(); @@ -52,74 +54,72 @@ void discoverStreamPurposes(PDBFile &File, Purposes.resize(StreamCount); for (uint16_t StreamIdx = 0; StreamIdx < StreamCount; ++StreamIdx) { - std::string Value; + std::pair<StreamPurpose, std::string> Value; if (StreamIdx == OldMSFDirectory) - Value = "Old MSF Directory"; + Value = std::make_pair(StreamPurpose::Other, "Old MSF Directory"); else if (StreamIdx == StreamPDB) - Value = "PDB Stream"; + Value = std::make_pair(StreamPurpose::Other, "PDB Stream"); else if (StreamIdx == StreamDBI) - Value = "DBI Stream"; + Value = std::make_pair(StreamPurpose::Other, "DBI Stream"); else if (StreamIdx == StreamTPI) - Value = "TPI Stream"; + Value = std::make_pair(StreamPurpose::Other, "TPI Stream"); else if (StreamIdx == StreamIPI) - Value = "IPI Stream"; + Value = std::make_pair(StreamPurpose::Other, "IPI Stream"); else if (Dbi && StreamIdx == Dbi->getGlobalSymbolStreamIndex()) - Value = "Global Symbol Hash"; + Value = std::make_pair(StreamPurpose::Other, "Global Symbol Hash"); else if (Dbi && StreamIdx == Dbi->getPublicSymbolStreamIndex()) - Value = "Public Symbol Hash"; + Value = std::make_pair(StreamPurpose::Other, "Public Symbol Hash"); else if (Dbi && StreamIdx == Dbi->getSymRecordStreamIndex()) - Value = "Public Symbol Records"; + Value = std::make_pair(StreamPurpose::Other, "Public Symbol Records"); else if (Tpi && StreamIdx == Tpi->getTypeHashStreamIndex()) - Value = "TPI Hash"; + Value = std::make_pair(StreamPurpose::Other, "TPI Hash"); else if (Tpi && StreamIdx == Tpi->getTypeHashStreamAuxIndex()) - Value = "TPI Aux Hash"; + Value = std::make_pair(StreamPurpose::Other, "TPI Aux Hash"); else if (Ipi && StreamIdx == Ipi->getTypeHashStreamIndex()) - Value = "IPI Hash"; + Value = std::make_pair(StreamPurpose::Other, "IPI Hash"); else if (Ipi && StreamIdx == Ipi->getTypeHashStreamAuxIndex()) - Value = "IPI Aux Hash"; + Value = std::make_pair(StreamPurpose::Other, "IPI Aux Hash"); else if (Dbi && StreamIdx == Dbi->getDebugStreamIndex(DbgHeaderType::Exception)) - Value = "Exception Data"; + Value = std::make_pair(StreamPurpose::Other, "Exception Data"); else if (Dbi && StreamIdx == Dbi->getDebugStreamIndex(DbgHeaderType::Fixup)) - Value = "Fixup Data"; + Value = std::make_pair(StreamPurpose::Other, "Fixup Data"); else if (Dbi && StreamIdx == Dbi->getDebugStreamIndex(DbgHeaderType::FPO)) - Value = "FPO Data"; + Value = std::make_pair(StreamPurpose::Other, "FPO Data"); else if (Dbi && StreamIdx == Dbi->getDebugStreamIndex(DbgHeaderType::NewFPO)) - Value = "New FPO Data"; + Value = std::make_pair(StreamPurpose::Other, "New FPO Data"); else if (Dbi && StreamIdx == Dbi->getDebugStreamIndex(DbgHeaderType::OmapFromSrc)) - Value = "Omap From Source Data"; + Value = std::make_pair(StreamPurpose::Other, "Omap From Source Data"); else if (Dbi && StreamIdx == Dbi->getDebugStreamIndex(DbgHeaderType::OmapToSrc)) - Value = "Omap To Source Data"; + Value = std::make_pair(StreamPurpose::Other, "Omap To Source Data"); else if (Dbi && StreamIdx == Dbi->getDebugStreamIndex(DbgHeaderType::Pdata)) - Value = "Pdata"; + Value = std::make_pair(StreamPurpose::Other, "Pdata"); else if (Dbi && StreamIdx == Dbi->getDebugStreamIndex(DbgHeaderType::SectionHdr)) - Value = "Section Header Data"; + Value = std::make_pair(StreamPurpose::Other, "Section Header Data"); else if (Dbi && StreamIdx == Dbi->getDebugStreamIndex(DbgHeaderType::SectionHdrOrig)) - Value = "Section Header Original Data"; + Value = + std::make_pair(StreamPurpose::Other, "Section Header Original Data"); else if (Dbi && StreamIdx == Dbi->getDebugStreamIndex(DbgHeaderType::TokenRidMap)) - Value = "Token Rid Data"; + Value = std::make_pair(StreamPurpose::Other, "Token Rid Data"); else if (Dbi && StreamIdx == Dbi->getDebugStreamIndex(DbgHeaderType::Xdata)) - Value = "Xdata"; + Value = std::make_pair(StreamPurpose::Other, "Xdata"); else { auto ModIter = ModStreams.find(StreamIdx); auto NSIter = NamedStreams.find(StreamIdx); if (ModIter != ModStreams.end()) { - Value = "Module \""; - Value += ModIter->second.getModuleName(); - Value += "\""; + Value = std::make_pair(StreamPurpose::ModuleStream, + ModIter->second.getModuleName()); } else if (NSIter != NamedStreams.end()) { - Value = "Named Stream \""; - Value += NSIter->second; - Value += "\""; + Value = std::make_pair(StreamPurpose::NamedStream, NSIter->second); } else { - Value = "???"; + Value = std::make_pair(StreamPurpose::Other, "???"); } } Purposes[StreamIdx] = Value; @@ -135,5 +135,18 @@ void discoverStreamPurposes(PDBFile &File, if (!Info) consumeError(Info.takeError()); } -} + +void llvm::pdb::discoverStreamPurposes(PDBFile &File, + SmallVectorImpl<std::string> &Purposes) { + SmallVector<std::pair<StreamPurpose, std::string>, 24> SP; + discoverStreamPurposes(File, SP); + Purposes.reserve(SP.size()); + for (const auto &P : SP) { + if (P.first == StreamPurpose::NamedStream) + Purposes.push_back(formatv("Named Stream \"{0}\"", P.second)); + else if (P.first == StreamPurpose::ModuleStream) + Purposes.push_back(formatv("Module \"{0}\"", P.second)); + else + Purposes.push_back(P.second); + } } diff --git a/tools/llvm-pdbutil/StreamUtil.h b/tools/llvm-pdbutil/StreamUtil.h index b5c0beba44fed..f49c0a0eceb66 100644 --- a/tools/llvm-pdbutil/StreamUtil.h +++ b/tools/llvm-pdbutil/StreamUtil.h @@ -17,8 +17,13 @@ namespace llvm { namespace pdb { class PDBFile; +enum class StreamPurpose { NamedStream, ModuleStream, Other }; + void discoverStreamPurposes(PDBFile &File, SmallVectorImpl<std::string> &Purposes); +void discoverStreamPurposes( + PDBFile &File, + SmallVectorImpl<std::pair<StreamPurpose, std::string>> &Purposes); } } diff --git a/tools/llvm-pdbutil/llvm-pdbutil.cpp b/tools/llvm-pdbutil/llvm-pdbutil.cpp index ad11ad4980008..6aa08ff3cd872 100644 --- a/tools/llvm-pdbutil/llvm-pdbutil.cpp +++ b/tools/llvm-pdbutil/llvm-pdbutil.cpp @@ -284,9 +284,32 @@ cl::opt<bool> NoEnumDefs("no-enum-definitions", } namespace diff { -cl::list<std::string> InputFilenames(cl::Positional, - cl::desc("<first> <second>"), - cl::OneOrMore, cl::sub(DiffSubcommand)); +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::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)); } cl::OptionCategory FileOptions("Module & File Options"); @@ -399,7 +422,7 @@ cl::opt<bool> DumpTypeExtras("type-extras", cl::cat(TypeOptions), cl::sub(DumpSubcommand)); cl::list<uint32_t> DumpTypeIndex( - "type-index", cl::ZeroOrMore, + "type-index", cl::ZeroOrMore, cl::CommaSeparated, cl::desc("only dump types with the specified hexadecimal type index"), cl::cat(TypeOptions), cl::sub(DumpSubcommand)); @@ -415,7 +438,7 @@ 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, + "id-index", cl::ZeroOrMore, cl::CommaSeparated, cl::desc("only dump ids with the specified hexadecimal type index"), cl::cat(TypeOptions), cl::sub(DumpSubcommand)); @@ -1079,6 +1102,11 @@ int main(int argc_, const char *argv_[]) { 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); @@ -1137,11 +1165,7 @@ int main(int argc_, const char *argv_[]) { std::for_each(opts::bytes::InputFilenames.begin(), opts::bytes::InputFilenames.end(), dumpBytes); } else if (opts::DiffSubcommand) { - if (opts::diff::InputFilenames.size() != 2) { - errs() << "diff subcommand expects exactly 2 arguments.\n"; - exit(1); - } - diff(opts::diff::InputFilenames[0], opts::diff::InputFilenames[1]); + 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"; diff --git a/tools/llvm-pdbutil/llvm-pdbutil.h b/tools/llvm-pdbutil/llvm-pdbutil.h index 9ee5866bbeffc..4e92e639a1278 100644 --- a/tools/llvm-pdbutil/llvm-pdbutil.h +++ b/tools/llvm-pdbutil/llvm-pdbutil.h @@ -168,6 +168,13 @@ extern llvm::cl::opt<bool> DumpModuleFiles; extern llvm::cl::list<ModuleSubsection> DumpModuleSubsections; extern llvm::cl::opt<bool> DumpModuleSyms; } // namespace pdb2yaml + +namespace diff { +extern llvm::cl::opt<bool> PrintValueColumns; +extern llvm::cl::opt<bool> PrintResultColumn; +extern llvm::cl::opt<std::string> LeftRoot; +extern llvm::cl::opt<std::string> RightRoot; +} // namespace diff } #endif |