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