GSIStreamBuilder.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. //===- DbiStreamBuilder.cpp - PDB Dbi Stream Creation -----------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // The data structures defined in this file are based on the reference
  10. // implementation which is available at
  11. // https://github.com/Microsoft/microsoft-pdb/blob/master/PDB/dbi/gsi.cpp
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h"
  15. #include "llvm/DebugInfo/CodeView/RecordName.h"
  16. #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
  17. #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
  18. #include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
  19. #include "llvm/DebugInfo/MSF/MSFBuilder.h"
  20. #include "llvm/DebugInfo/MSF/MSFCommon.h"
  21. #include "llvm/DebugInfo/MSF/MappedBlockStream.h"
  22. #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h"
  23. #include "llvm/DebugInfo/PDB/Native/Hash.h"
  24. #include "llvm/Support/BinaryItemStream.h"
  25. #include "llvm/Support/BinaryStreamWriter.h"
  26. #include "llvm/Support/Parallel.h"
  27. #include "llvm/Support/xxhash.h"
  28. #include <algorithm>
  29. #include <vector>
  30. using namespace llvm;
  31. using namespace llvm::msf;
  32. using namespace llvm::pdb;
  33. using namespace llvm::codeview;
  34. // Helper class for building the public and global PDB hash table buckets.
  35. struct llvm::pdb::GSIHashStreamBuilder {
  36. // Sum of the size of all public or global records.
  37. uint32_t RecordByteSize = 0;
  38. std::vector<PSHashRecord> HashRecords;
  39. // The hash bitmap has `ceil((IPHR_HASH + 1) / 32)` words in it. The
  40. // reference implementation builds a hash table with IPHR_HASH buckets in it.
  41. // The last bucket is used to link together free hash table cells in a linked
  42. // list, but it is always empty in the compressed, on-disk format. However,
  43. // the bitmap must have a bit for it.
  44. std::array<support::ulittle32_t, (IPHR_HASH + 32) / 32> HashBitmap;
  45. std::vector<support::ulittle32_t> HashBuckets;
  46. uint32_t calculateSerializedLength() const;
  47. Error commit(BinaryStreamWriter &Writer);
  48. void finalizePublicBuckets();
  49. void finalizeGlobalBuckets(uint32_t RecordZeroOffset);
  50. // Assign public and global symbol records into hash table buckets.
  51. // Modifies the list of records to store the bucket index, but does not
  52. // change the order.
  53. void finalizeBuckets(uint32_t RecordZeroOffset,
  54. MutableArrayRef<BulkPublic> Globals);
  55. };
  56. // DenseMapInfo implementation for deduplicating symbol records.
  57. struct llvm::pdb::SymbolDenseMapInfo {
  58. static inline CVSymbol getEmptyKey() {
  59. static CVSymbol Empty;
  60. return Empty;
  61. }
  62. static inline CVSymbol getTombstoneKey() {
  63. static CVSymbol Tombstone(
  64. DenseMapInfo<ArrayRef<uint8_t>>::getTombstoneKey());
  65. return Tombstone;
  66. }
  67. static unsigned getHashValue(const CVSymbol &Val) {
  68. return xxHash64(Val.RecordData);
  69. }
  70. static bool isEqual(const CVSymbol &LHS, const CVSymbol &RHS) {
  71. return LHS.RecordData == RHS.RecordData;
  72. }
  73. };
  74. namespace {
  75. LLVM_PACKED_START
  76. struct PublicSym32Layout {
  77. RecordPrefix Prefix;
  78. PublicSym32Header Pub;
  79. // char Name[];
  80. };
  81. LLVM_PACKED_END
  82. } // namespace
  83. // Calculate how much memory this public needs when serialized.
  84. static uint32_t sizeOfPublic(const BulkPublic &Pub) {
  85. uint32_t NameLen = Pub.NameLen;
  86. NameLen = std::min(NameLen,
  87. uint32_t(MaxRecordLength - sizeof(PublicSym32Layout) - 1));
  88. return alignTo(sizeof(PublicSym32Layout) + NameLen + 1, 4);
  89. }
  90. static CVSymbol serializePublic(uint8_t *Mem, const BulkPublic &Pub) {
  91. // Assume the caller has allocated sizeOfPublic bytes.
  92. uint32_t NameLen = std::min(
  93. Pub.NameLen, uint32_t(MaxRecordLength - sizeof(PublicSym32Layout) - 1));
  94. size_t Size = alignTo(sizeof(PublicSym32Layout) + NameLen + 1, 4);
  95. assert(Size == sizeOfPublic(Pub));
  96. auto *FixedMem = reinterpret_cast<PublicSym32Layout *>(Mem);
  97. FixedMem->Prefix.RecordKind = static_cast<uint16_t>(codeview::S_PUB32);
  98. FixedMem->Prefix.RecordLen = static_cast<uint16_t>(Size - 2);
  99. FixedMem->Pub.Flags = Pub.Flags;
  100. FixedMem->Pub.Offset = Pub.Offset;
  101. FixedMem->Pub.Segment = Pub.Segment;
  102. char *NameMem = reinterpret_cast<char *>(FixedMem + 1);
  103. memcpy(NameMem, Pub.Name, NameLen);
  104. // Zero the null terminator and remaining bytes.
  105. memset(&NameMem[NameLen], 0, Size - sizeof(PublicSym32Layout) - NameLen);
  106. return CVSymbol(makeArrayRef(reinterpret_cast<uint8_t *>(Mem), Size));
  107. }
  108. uint32_t GSIHashStreamBuilder::calculateSerializedLength() const {
  109. uint32_t Size = sizeof(GSIHashHeader);
  110. Size += HashRecords.size() * sizeof(PSHashRecord);
  111. Size += HashBitmap.size() * sizeof(uint32_t);
  112. Size += HashBuckets.size() * sizeof(uint32_t);
  113. return Size;
  114. }
  115. Error GSIHashStreamBuilder::commit(BinaryStreamWriter &Writer) {
  116. GSIHashHeader Header;
  117. Header.VerSignature = GSIHashHeader::HdrSignature;
  118. Header.VerHdr = GSIHashHeader::HdrVersion;
  119. Header.HrSize = HashRecords.size() * sizeof(PSHashRecord);
  120. Header.NumBuckets = HashBitmap.size() * 4 + HashBuckets.size() * 4;
  121. if (auto EC = Writer.writeObject(Header))
  122. return EC;
  123. if (auto EC = Writer.writeArray(makeArrayRef(HashRecords)))
  124. return EC;
  125. if (auto EC = Writer.writeArray(makeArrayRef(HashBitmap)))
  126. return EC;
  127. if (auto EC = Writer.writeArray(makeArrayRef(HashBuckets)))
  128. return EC;
  129. return Error::success();
  130. }
  131. static bool isAsciiString(StringRef S) {
  132. return llvm::all_of(S, [](char C) { return unsigned(C) < 0x80; });
  133. }
  134. // See `caseInsensitiveComparePchPchCchCch` in gsi.cpp
  135. static int gsiRecordCmp(StringRef S1, StringRef S2) {
  136. size_t LS = S1.size();
  137. size_t RS = S2.size();
  138. // Shorter strings always compare less than longer strings.
  139. if (LS != RS)
  140. return (LS > RS) - (LS < RS);
  141. // If either string contains non ascii characters, memcmp them.
  142. if (LLVM_UNLIKELY(!isAsciiString(S1) || !isAsciiString(S2)))
  143. return memcmp(S1.data(), S2.data(), LS);
  144. // Both strings are ascii, perform a case-insensitive comparison.
  145. return S1.compare_insensitive(S2.data());
  146. }
  147. void GSIStreamBuilder::finalizePublicBuckets() {
  148. PSH->finalizeBuckets(0, Publics);
  149. }
  150. void GSIStreamBuilder::finalizeGlobalBuckets(uint32_t RecordZeroOffset) {
  151. // Build up a list of globals to be bucketed. Use the BulkPublic data
  152. // structure for this purpose, even though these are global records, not
  153. // public records. Most of the same fields are required:
  154. // - Name
  155. // - NameLen
  156. // - SymOffset
  157. // - BucketIdx
  158. // The dead fields are Offset, Segment, and Flags.
  159. std::vector<BulkPublic> Records;
  160. Records.resize(Globals.size());
  161. uint32_t SymOffset = RecordZeroOffset;
  162. for (size_t I = 0, E = Globals.size(); I < E; ++I) {
  163. StringRef Name = getSymbolName(Globals[I]);
  164. Records[I].Name = Name.data();
  165. Records[I].NameLen = Name.size();
  166. Records[I].SymOffset = SymOffset;
  167. SymOffset += Globals[I].length();
  168. }
  169. GSH->finalizeBuckets(RecordZeroOffset, Records);
  170. }
  171. void GSIHashStreamBuilder::finalizeBuckets(
  172. uint32_t RecordZeroOffset, MutableArrayRef<BulkPublic> Records) {
  173. // Hash every name in parallel.
  174. parallelForEachN(0, Records.size(), [&](size_t I) {
  175. Records[I].setBucketIdx(hashStringV1(Records[I].Name) % IPHR_HASH);
  176. });
  177. // Count up the size of each bucket. Then, use an exclusive prefix sum to
  178. // calculate the bucket start offsets. This is C++17 std::exclusive_scan, but
  179. // we can't use it yet.
  180. uint32_t BucketStarts[IPHR_HASH] = {0};
  181. for (const BulkPublic &P : Records)
  182. ++BucketStarts[P.BucketIdx];
  183. uint32_t Sum = 0;
  184. for (uint32_t &B : BucketStarts) {
  185. uint32_t Size = B;
  186. B = Sum;
  187. Sum += Size;
  188. }
  189. // Place globals into the hash table in bucket order. When placing a global,
  190. // update the bucket start. Every hash table slot should be filled. Always use
  191. // a refcount of one for now.
  192. HashRecords.resize(Records.size());
  193. uint32_t BucketCursors[IPHR_HASH];
  194. memcpy(BucketCursors, BucketStarts, sizeof(BucketCursors));
  195. for (int I = 0, E = Records.size(); I < E; ++I) {
  196. uint32_t HashIdx = BucketCursors[Records[I].BucketIdx]++;
  197. HashRecords[HashIdx].Off = I;
  198. HashRecords[HashIdx].CRef = 1;
  199. }
  200. // Within the buckets, sort each bucket by memcmp of the symbol's name. It's
  201. // important that we use the same sorting algorithm as is used by the
  202. // reference implementation to ensure that the search for a record within a
  203. // bucket can properly early-out when it detects the record won't be found.
  204. // The algorithm used here corresponds to the function
  205. // caseInsensitiveComparePchPchCchCch in the reference implementation.
  206. parallelForEachN(0, IPHR_HASH, [&](size_t I) {
  207. auto B = HashRecords.begin() + BucketStarts[I];
  208. auto E = HashRecords.begin() + BucketCursors[I];
  209. if (B == E)
  210. return;
  211. auto BucketCmp = [Records](const PSHashRecord &LHash,
  212. const PSHashRecord &RHash) {
  213. const BulkPublic &L = Records[uint32_t(LHash.Off)];
  214. const BulkPublic &R = Records[uint32_t(RHash.Off)];
  215. assert(L.BucketIdx == R.BucketIdx);
  216. int Cmp = gsiRecordCmp(L.getName(), R.getName());
  217. if (Cmp != 0)
  218. return Cmp < 0;
  219. // This comparison is necessary to make the sorting stable in the presence
  220. // of two static globals with the same name. The easiest way to observe
  221. // this is with S_LDATA32 records.
  222. return L.SymOffset < R.SymOffset;
  223. };
  224. llvm::sort(B, E, BucketCmp);
  225. // After we are done sorting, replace the global indices with the stream
  226. // offsets of each global. Add one when writing symbol offsets to disk.
  227. // See GSI1::fixSymRecs.
  228. for (PSHashRecord &HRec : make_range(B, E))
  229. HRec.Off = Records[uint32_t(HRec.Off)].SymOffset + 1;
  230. });
  231. // For each non-empty bucket, push the bucket start offset into HashBuckets
  232. // and set a bit in the hash bitmap.
  233. for (uint32_t I = 0; I < HashBitmap.size(); ++I) {
  234. uint32_t Word = 0;
  235. for (uint32_t J = 0; J < 32; ++J) {
  236. // Skip empty buckets.
  237. uint32_t BucketIdx = I * 32 + J;
  238. if (BucketIdx >= IPHR_HASH ||
  239. BucketStarts[BucketIdx] == BucketCursors[BucketIdx])
  240. continue;
  241. Word |= (1U << J);
  242. // Calculate what the offset of the first hash record in the chain would
  243. // be if it were inflated to contain 32-bit pointers. On a 32-bit system,
  244. // each record would be 12 bytes. See HROffsetCalc in gsi.h.
  245. const int SizeOfHROffsetCalc = 12;
  246. ulittle32_t ChainStartOff =
  247. ulittle32_t(BucketStarts[BucketIdx] * SizeOfHROffsetCalc);
  248. HashBuckets.push_back(ChainStartOff);
  249. }
  250. HashBitmap[I] = Word;
  251. }
  252. }
  253. GSIStreamBuilder::GSIStreamBuilder(msf::MSFBuilder &Msf)
  254. : Msf(Msf), PSH(std::make_unique<GSIHashStreamBuilder>()),
  255. GSH(std::make_unique<GSIHashStreamBuilder>()) {}
  256. GSIStreamBuilder::~GSIStreamBuilder() {}
  257. uint32_t GSIStreamBuilder::calculatePublicsHashStreamSize() const {
  258. uint32_t Size = 0;
  259. Size += sizeof(PublicsStreamHeader);
  260. Size += PSH->calculateSerializedLength();
  261. Size += Publics.size() * sizeof(uint32_t); // AddrMap
  262. // FIXME: Add thunk map and section offsets for incremental linking.
  263. return Size;
  264. }
  265. uint32_t GSIStreamBuilder::calculateGlobalsHashStreamSize() const {
  266. return GSH->calculateSerializedLength();
  267. }
  268. Error GSIStreamBuilder::finalizeMsfLayout() {
  269. // First we write public symbol records, then we write global symbol records.
  270. finalizePublicBuckets();
  271. finalizeGlobalBuckets(PSH->RecordByteSize);
  272. Expected<uint32_t> Idx = Msf.addStream(calculateGlobalsHashStreamSize());
  273. if (!Idx)
  274. return Idx.takeError();
  275. GlobalsStreamIndex = *Idx;
  276. Idx = Msf.addStream(calculatePublicsHashStreamSize());
  277. if (!Idx)
  278. return Idx.takeError();
  279. PublicsStreamIndex = *Idx;
  280. uint32_t RecordBytes = PSH->RecordByteSize + GSH->RecordByteSize;
  281. Idx = Msf.addStream(RecordBytes);
  282. if (!Idx)
  283. return Idx.takeError();
  284. RecordStreamIndex = *Idx;
  285. return Error::success();
  286. }
  287. void GSIStreamBuilder::addPublicSymbols(std::vector<BulkPublic> &&PublicsIn) {
  288. assert(Publics.empty() && PSH->RecordByteSize == 0 &&
  289. "publics can only be added once");
  290. Publics = std::move(PublicsIn);
  291. // Sort the symbols by name. PDBs contain lots of symbols, so use parallelism.
  292. parallelSort(Publics, [](const BulkPublic &L, const BulkPublic &R) {
  293. return L.getName() < R.getName();
  294. });
  295. // Assign offsets and calculate the length of the public symbol records.
  296. uint32_t SymOffset = 0;
  297. for (BulkPublic &Pub : Publics) {
  298. Pub.SymOffset = SymOffset;
  299. SymOffset += sizeOfPublic(Pub);
  300. }
  301. // Remember the length of the public stream records.
  302. PSH->RecordByteSize = SymOffset;
  303. }
  304. void GSIStreamBuilder::addGlobalSymbol(const ProcRefSym &Sym) {
  305. serializeAndAddGlobal(Sym);
  306. }
  307. void GSIStreamBuilder::addGlobalSymbol(const DataSym &Sym) {
  308. serializeAndAddGlobal(Sym);
  309. }
  310. void GSIStreamBuilder::addGlobalSymbol(const ConstantSym &Sym) {
  311. serializeAndAddGlobal(Sym);
  312. }
  313. template <typename T>
  314. void GSIStreamBuilder::serializeAndAddGlobal(const T &Symbol) {
  315. T Copy(Symbol);
  316. addGlobalSymbol(SymbolSerializer::writeOneSymbol(Copy, Msf.getAllocator(),
  317. CodeViewContainer::Pdb));
  318. }
  319. void GSIStreamBuilder::addGlobalSymbol(const codeview::CVSymbol &Symbol) {
  320. // Ignore duplicate typedefs and constants.
  321. if (Symbol.kind() == S_UDT || Symbol.kind() == S_CONSTANT) {
  322. auto Iter = GlobalsSeen.insert(Symbol);
  323. if (!Iter.second)
  324. return;
  325. }
  326. GSH->RecordByteSize += Symbol.length();
  327. Globals.push_back(Symbol);
  328. }
  329. // Serialize each public and write it.
  330. static Error writePublics(BinaryStreamWriter &Writer,
  331. ArrayRef<BulkPublic> Publics) {
  332. std::vector<uint8_t> Storage;
  333. for (const BulkPublic &Pub : Publics) {
  334. Storage.resize(sizeOfPublic(Pub));
  335. serializePublic(Storage.data(), Pub);
  336. if (Error E = Writer.writeBytes(Storage))
  337. return E;
  338. }
  339. return Error::success();
  340. }
  341. static Error writeRecords(BinaryStreamWriter &Writer,
  342. ArrayRef<CVSymbol> Records) {
  343. BinaryItemStream<CVSymbol> ItemStream(support::endianness::little);
  344. ItemStream.setItems(Records);
  345. BinaryStreamRef RecordsRef(ItemStream);
  346. return Writer.writeStreamRef(RecordsRef);
  347. }
  348. Error GSIStreamBuilder::commitSymbolRecordStream(
  349. WritableBinaryStreamRef Stream) {
  350. BinaryStreamWriter Writer(Stream);
  351. // Write public symbol records first, followed by global symbol records. This
  352. // must match the order that we assume in finalizeMsfLayout when computing
  353. // PSHZero and GSHZero.
  354. if (auto EC = writePublics(Writer, Publics))
  355. return EC;
  356. if (auto EC = writeRecords(Writer, Globals))
  357. return EC;
  358. return Error::success();
  359. }
  360. static std::vector<support::ulittle32_t>
  361. computeAddrMap(ArrayRef<BulkPublic> Publics) {
  362. // Build a parallel vector of indices into the Publics vector, and sort it by
  363. // address.
  364. std::vector<ulittle32_t> PubAddrMap;
  365. PubAddrMap.reserve(Publics.size());
  366. for (int I = 0, E = Publics.size(); I < E; ++I)
  367. PubAddrMap.push_back(ulittle32_t(I));
  368. auto AddrCmp = [Publics](const ulittle32_t &LIdx, const ulittle32_t &RIdx) {
  369. const BulkPublic &L = Publics[LIdx];
  370. const BulkPublic &R = Publics[RIdx];
  371. if (L.Segment != R.Segment)
  372. return L.Segment < R.Segment;
  373. if (L.Offset != R.Offset)
  374. return L.Offset < R.Offset;
  375. // parallelSort is unstable, so we have to do name comparison to ensure
  376. // that two names for the same location come out in a deterministic order.
  377. return L.getName() < R.getName();
  378. };
  379. parallelSort(PubAddrMap, AddrCmp);
  380. // Rewrite the public symbol indices into symbol offsets.
  381. for (ulittle32_t &Entry : PubAddrMap)
  382. Entry = Publics[Entry].SymOffset;
  383. return PubAddrMap;
  384. }
  385. Error GSIStreamBuilder::commitPublicsHashStream(
  386. WritableBinaryStreamRef Stream) {
  387. BinaryStreamWriter Writer(Stream);
  388. PublicsStreamHeader Header;
  389. // FIXME: Fill these in. They are for incremental linking.
  390. Header.SymHash = PSH->calculateSerializedLength();
  391. Header.AddrMap = Publics.size() * 4;
  392. Header.NumThunks = 0;
  393. Header.SizeOfThunk = 0;
  394. Header.ISectThunkTable = 0;
  395. memset(Header.Padding, 0, sizeof(Header.Padding));
  396. Header.OffThunkTable = 0;
  397. Header.NumSections = 0;
  398. if (auto EC = Writer.writeObject(Header))
  399. return EC;
  400. if (auto EC = PSH->commit(Writer))
  401. return EC;
  402. std::vector<support::ulittle32_t> PubAddrMap = computeAddrMap(Publics);
  403. assert(PubAddrMap.size() == Publics.size());
  404. if (auto EC = Writer.writeArray(makeArrayRef(PubAddrMap)))
  405. return EC;
  406. return Error::success();
  407. }
  408. Error GSIStreamBuilder::commitGlobalsHashStream(
  409. WritableBinaryStreamRef Stream) {
  410. BinaryStreamWriter Writer(Stream);
  411. return GSH->commit(Writer);
  412. }
  413. Error GSIStreamBuilder::commit(const msf::MSFLayout &Layout,
  414. WritableBinaryStreamRef Buffer) {
  415. auto GS = WritableMappedBlockStream::createIndexedStream(
  416. Layout, Buffer, getGlobalsStreamIndex(), Msf.getAllocator());
  417. auto PS = WritableMappedBlockStream::createIndexedStream(
  418. Layout, Buffer, getPublicsStreamIndex(), Msf.getAllocator());
  419. auto PRS = WritableMappedBlockStream::createIndexedStream(
  420. Layout, Buffer, getRecordStreamIndex(), Msf.getAllocator());
  421. if (auto EC = commitSymbolRecordStream(*PRS))
  422. return EC;
  423. if (auto EC = commitGlobalsHashStream(*GS))
  424. return EC;
  425. if (auto EC = commitPublicsHashStream(*PS))
  426. return EC;
  427. return Error::success();
  428. }