[WebAssembly] Fix asan issue from https://reviews.llvm.org/D121349
[llvm-project.git] / lld / COFF / PDB.cpp
blob2ceb4fb98031c262d04e994407bc0569e7668d9f
1 //===- PDB.cpp ------------------------------------------------------------===//
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 //===----------------------------------------------------------------------===//
9 #include "PDB.h"
10 #include "COFFLinkerContext.h"
11 #include "Chunks.h"
12 #include "Config.h"
13 #include "DebugTypes.h"
14 #include "Driver.h"
15 #include "SymbolTable.h"
16 #include "Symbols.h"
17 #include "TypeMerger.h"
18 #include "Writer.h"
19 #include "lld/Common/Timer.h"
20 #include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
21 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
22 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
23 #include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
24 #include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"
25 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
26 #include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
27 #include "llvm/DebugInfo/CodeView/RecordName.h"
28 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
29 #include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h"
30 #include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
31 #include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
32 #include "llvm/DebugInfo/MSF/MSFBuilder.h"
33 #include "llvm/DebugInfo/MSF/MSFCommon.h"
34 #include "llvm/DebugInfo/PDB/GenericError.h"
35 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
36 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
37 #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
38 #include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h"
39 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
40 #include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
41 #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
42 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
43 #include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
44 #include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
45 #include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
46 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
47 #include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
48 #include "llvm/DebugInfo/PDB/PDB.h"
49 #include "llvm/Object/COFF.h"
50 #include "llvm/Object/CVDebugRecord.h"
51 #include "llvm/Support/BinaryByteStream.h"
52 #include "llvm/Support/CRC.h"
53 #include "llvm/Support/Endian.h"
54 #include "llvm/Support/Errc.h"
55 #include "llvm/Support/FormatAdapters.h"
56 #include "llvm/Support/FormatVariadic.h"
57 #include "llvm/Support/Path.h"
58 #include "llvm/Support/ScopedPrinter.h"
59 #include <memory>
61 using namespace llvm;
62 using namespace llvm::codeview;
63 using namespace lld;
64 using namespace lld::coff;
66 using llvm::object::coff_section;
67 using llvm::pdb::StringTableFixup;
69 static ExitOnError exitOnErr;
71 namespace {
72 class DebugSHandler;
74 class PDBLinker {
75 friend DebugSHandler;
77 public:
78 PDBLinker(COFFLinkerContext &ctx)
79 : builder(bAlloc()), tMerger(ctx, bAlloc()), ctx(ctx) {
80 // This isn't strictly necessary, but link.exe usually puts an empty string
81 // as the first "valid" string in the string table, so we do the same in
82 // order to maintain as much byte-for-byte compatibility as possible.
83 pdbStrTab.insert("");
86 /// Emit the basic PDB structure: initial streams, headers, etc.
87 void initialize(llvm::codeview::DebugInfo *buildId);
89 /// Add natvis files specified on the command line.
90 void addNatvisFiles();
92 /// Add named streams specified on the command line.
93 void addNamedStreams();
95 /// Link CodeView from each object file in the symbol table into the PDB.
96 void addObjectsToPDB();
98 /// Add every live, defined public symbol to the PDB.
99 void addPublicsToPDB();
101 /// Link info for each import file in the symbol table into the PDB.
102 void addImportFilesToPDB();
104 void createModuleDBI(ObjFile *file);
106 /// Link CodeView from a single object file into the target (output) PDB.
107 /// When a precompiled headers object is linked, its TPI map might be provided
108 /// externally.
109 void addDebug(TpiSource *source);
111 void addDebugSymbols(TpiSource *source);
113 // Analyze the symbol records to separate module symbols from global symbols,
114 // find string references, and calculate how large the symbol stream will be
115 // in the PDB.
116 void analyzeSymbolSubsection(SectionChunk *debugChunk,
117 uint32_t &moduleSymOffset,
118 uint32_t &nextRelocIndex,
119 std::vector<StringTableFixup> &stringTableFixups,
120 BinaryStreamRef symData);
122 // Write all module symbols from all all live debug symbol subsections of the
123 // given object file into the given stream writer.
124 Error writeAllModuleSymbolRecords(ObjFile *file, BinaryStreamWriter &writer);
126 // Callback to copy and relocate debug symbols during PDB file writing.
127 static Error commitSymbolsForObject(void *ctx, void *obj,
128 BinaryStreamWriter &writer);
130 // Copy the symbol record, relocate it, and fix the alignment if necessary.
131 // Rewrite type indices in the record. Replace unrecognized symbol records
132 // with S_SKIP records.
133 void writeSymbolRecord(SectionChunk *debugChunk,
134 ArrayRef<uint8_t> sectionContents, CVSymbol sym,
135 size_t alignedSize, uint32_t &nextRelocIndex,
136 std::vector<uint8_t> &storage);
138 /// Add the section map and section contributions to the PDB.
139 void addSections(ArrayRef<uint8_t> sectionTable);
141 /// Write the PDB to disk and store the Guid generated for it in *Guid.
142 void commit(codeview::GUID *guid);
144 // Print statistics regarding the final PDB
145 void printStats();
147 private:
149 pdb::PDBFileBuilder builder;
151 TypeMerger tMerger;
153 COFFLinkerContext &ctx;
155 /// PDBs use a single global string table for filenames in the file checksum
156 /// table.
157 DebugStringTableSubsection pdbStrTab;
159 llvm::SmallString<128> nativePath;
161 // For statistics
162 uint64_t globalSymbols = 0;
163 uint64_t moduleSymbols = 0;
164 uint64_t publicSymbols = 0;
165 uint64_t nbTypeRecords = 0;
166 uint64_t nbTypeRecordsBytes = 0;
169 /// Represents an unrelocated DEBUG_S_FRAMEDATA subsection.
170 struct UnrelocatedFpoData {
171 SectionChunk *debugChunk = nullptr;
172 ArrayRef<uint8_t> subsecData;
173 uint32_t relocIndex = 0;
176 /// The size of the magic bytes at the beginning of a symbol section or stream.
177 enum : uint32_t { kSymbolStreamMagicSize = 4 };
179 class DebugSHandler {
180 PDBLinker &linker;
182 /// The object file whose .debug$S sections we're processing.
183 ObjFile &file;
185 /// The result of merging type indices.
186 TpiSource *source;
188 /// The DEBUG_S_STRINGTABLE subsection. These strings are referred to by
189 /// index from other records in the .debug$S section. All of these strings
190 /// need to be added to the global PDB string table, and all references to
191 /// these strings need to have their indices re-written to refer to the
192 /// global PDB string table.
193 DebugStringTableSubsectionRef cvStrTab;
195 /// The DEBUG_S_FILECHKSMS subsection. As above, these are referred to
196 /// by other records in the .debug$S section and need to be merged into the
197 /// PDB.
198 DebugChecksumsSubsectionRef checksums;
200 /// The DEBUG_S_FRAMEDATA subsection(s). There can be more than one of
201 /// these and they need not appear in any specific order. However, they
202 /// contain string table references which need to be re-written, so we
203 /// collect them all here and re-write them after all subsections have been
204 /// discovered and processed.
205 std::vector<UnrelocatedFpoData> frameDataSubsecs;
207 /// List of string table references in symbol records. Later they will be
208 /// applied to the symbols during PDB writing.
209 std::vector<StringTableFixup> stringTableFixups;
211 /// Sum of the size of all module symbol records across all .debug$S sections.
212 /// Includes record realignment and the size of the symbol stream magic
213 /// prefix.
214 uint32_t moduleStreamSize = kSymbolStreamMagicSize;
216 /// Next relocation index in the current .debug$S section. Resets every
217 /// handleDebugS call.
218 uint32_t nextRelocIndex = 0;
220 void advanceRelocIndex(SectionChunk *debugChunk, ArrayRef<uint8_t> subsec);
222 void addUnrelocatedSubsection(SectionChunk *debugChunk,
223 const DebugSubsectionRecord &ss);
225 void addFrameDataSubsection(SectionChunk *debugChunk,
226 const DebugSubsectionRecord &ss);
228 void recordStringTableReferences(CVSymbol sym, uint32_t symOffset);
230 public:
231 DebugSHandler(PDBLinker &linker, ObjFile &file, TpiSource *source)
232 : linker(linker), file(file), source(source) {}
234 void handleDebugS(SectionChunk *debugChunk);
236 void finish();
240 // Visual Studio's debugger requires absolute paths in various places in the
241 // PDB to work without additional configuration:
242 // https://docs.microsoft.com/en-us/visualstudio/debugger/debug-source-files-common-properties-solution-property-pages-dialog-box
243 static void pdbMakeAbsolute(SmallVectorImpl<char> &fileName) {
244 // The default behavior is to produce paths that are valid within the context
245 // of the machine that you perform the link on. If the linker is running on
246 // a POSIX system, we will output absolute POSIX paths. If the linker is
247 // running on a Windows system, we will output absolute Windows paths. If the
248 // user desires any other kind of behavior, they should explicitly pass
249 // /pdbsourcepath, in which case we will treat the exact string the user
250 // passed in as the gospel and not normalize, canonicalize it.
251 if (sys::path::is_absolute(fileName, sys::path::Style::windows) ||
252 sys::path::is_absolute(fileName, sys::path::Style::posix))
253 return;
255 // It's not absolute in any path syntax. Relative paths necessarily refer to
256 // the local file system, so we can make it native without ending up with a
257 // nonsensical path.
258 if (config->pdbSourcePath.empty()) {
259 sys::path::native(fileName);
260 sys::fs::make_absolute(fileName);
261 sys::path::remove_dots(fileName, true);
262 return;
265 // Try to guess whether /PDBSOURCEPATH is a unix path or a windows path.
266 // Since PDB's are more of a Windows thing, we make this conservative and only
267 // decide that it's a unix path if we're fairly certain. Specifically, if
268 // it starts with a forward slash.
269 SmallString<128> absoluteFileName = config->pdbSourcePath;
270 sys::path::Style guessedStyle = absoluteFileName.startswith("/")
271 ? sys::path::Style::posix
272 : sys::path::Style::windows;
273 sys::path::append(absoluteFileName, guessedStyle, fileName);
274 sys::path::native(absoluteFileName, guessedStyle);
275 sys::path::remove_dots(absoluteFileName, true, guessedStyle);
277 fileName = std::move(absoluteFileName);
280 static void addTypeInfo(pdb::TpiStreamBuilder &tpiBuilder,
281 TypeCollection &typeTable) {
282 // Start the TPI or IPI stream header.
283 tpiBuilder.setVersionHeader(pdb::PdbTpiV80);
285 // Flatten the in memory type table and hash each type.
286 typeTable.ForEachRecord([&](TypeIndex ti, const CVType &type) {
287 auto hash = pdb::hashTypeRecord(type);
288 if (auto e = hash.takeError())
289 fatal("type hashing error");
290 tpiBuilder.addTypeRecord(type.RecordData, *hash);
294 static void addGHashTypeInfo(COFFLinkerContext &ctx,
295 pdb::PDBFileBuilder &builder) {
296 // Start the TPI or IPI stream header.
297 builder.getTpiBuilder().setVersionHeader(pdb::PdbTpiV80);
298 builder.getIpiBuilder().setVersionHeader(pdb::PdbTpiV80);
299 for_each(ctx.tpiSourceList, [&](TpiSource *source) {
300 builder.getTpiBuilder().addTypeRecords(source->mergedTpi.recs,
301 source->mergedTpi.recSizes,
302 source->mergedTpi.recHashes);
303 builder.getIpiBuilder().addTypeRecords(source->mergedIpi.recs,
304 source->mergedIpi.recSizes,
305 source->mergedIpi.recHashes);
309 static void
310 recordStringTableReferences(CVSymbol sym, uint32_t symOffset,
311 std::vector<StringTableFixup> &stringTableFixups) {
312 // For now we only handle S_FILESTATIC, but we may need the same logic for
313 // S_DEFRANGE and S_DEFRANGE_SUBFIELD. However, I cannot seem to generate any
314 // PDBs that contain these types of records, so because of the uncertainty
315 // they are omitted here until we can prove that it's necessary.
316 switch (sym.kind()) {
317 case SymbolKind::S_FILESTATIC: {
318 // FileStaticSym::ModFileOffset
319 uint32_t ref = *reinterpret_cast<const ulittle32_t *>(&sym.data()[8]);
320 stringTableFixups.push_back({ref, symOffset + 8});
321 break;
323 case SymbolKind::S_DEFRANGE:
324 case SymbolKind::S_DEFRANGE_SUBFIELD:
325 log("Not fixing up string table reference in S_DEFRANGE / "
326 "S_DEFRANGE_SUBFIELD record");
327 break;
328 default:
329 break;
333 static SymbolKind symbolKind(ArrayRef<uint8_t> recordData) {
334 const RecordPrefix *prefix =
335 reinterpret_cast<const RecordPrefix *>(recordData.data());
336 return static_cast<SymbolKind>(uint16_t(prefix->RecordKind));
339 /// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
340 static void translateIdSymbols(MutableArrayRef<uint8_t> &recordData,
341 TypeMerger &tMerger, TpiSource *source) {
342 RecordPrefix *prefix = reinterpret_cast<RecordPrefix *>(recordData.data());
344 SymbolKind kind = symbolKind(recordData);
346 if (kind == SymbolKind::S_PROC_ID_END) {
347 prefix->RecordKind = SymbolKind::S_END;
348 return;
351 // In an object file, GPROC32_ID has an embedded reference which refers to the
352 // single object file type index namespace. This has already been translated
353 // to the PDB file's ID stream index space, but we need to convert this to a
354 // symbol that refers to the type stream index space. So we remap again from
355 // ID index space to type index space.
356 if (kind == SymbolKind::S_GPROC32_ID || kind == SymbolKind::S_LPROC32_ID) {
357 SmallVector<TiReference, 1> refs;
358 auto content = recordData.drop_front(sizeof(RecordPrefix));
359 CVSymbol sym(recordData);
360 discoverTypeIndicesInSymbol(sym, refs);
361 assert(refs.size() == 1);
362 assert(refs.front().Count == 1);
364 TypeIndex *ti =
365 reinterpret_cast<TypeIndex *>(content.data() + refs[0].Offset);
366 // `ti` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
367 // the IPI stream, whose `FunctionType` member refers to the TPI stream.
368 // Note that LF_FUNC_ID and LF_MFUNC_ID have the same record layout, and
369 // in both cases we just need the second type index.
370 if (!ti->isSimple() && !ti->isNoneType()) {
371 TypeIndex newType = TypeIndex(SimpleTypeKind::NotTranslated);
372 if (config->debugGHashes) {
373 auto idToType = tMerger.funcIdToType.find(*ti);
374 if (idToType != tMerger.funcIdToType.end())
375 newType = idToType->second;
376 } else {
377 if (tMerger.getIDTable().contains(*ti)) {
378 CVType funcIdData = tMerger.getIDTable().getType(*ti);
379 if (funcIdData.length() >= 8 && (funcIdData.kind() == LF_FUNC_ID ||
380 funcIdData.kind() == LF_MFUNC_ID)) {
381 newType = *reinterpret_cast<const TypeIndex *>(&funcIdData.data()[8]);
385 if (newType == TypeIndex(SimpleTypeKind::NotTranslated)) {
386 warn(formatv("procedure symbol record for `{0}` in {1} refers to PDB "
387 "item index {2:X} which is not a valid function ID record",
388 getSymbolName(CVSymbol(recordData)),
389 source->file->getName(), ti->getIndex()));
391 *ti = newType;
394 kind = (kind == SymbolKind::S_GPROC32_ID) ? SymbolKind::S_GPROC32
395 : SymbolKind::S_LPROC32;
396 prefix->RecordKind = uint16_t(kind);
400 namespace {
401 struct ScopeRecord {
402 ulittle32_t ptrParent;
403 ulittle32_t ptrEnd;
405 } // namespace
407 /// Given a pointer to a symbol record that opens a scope, return a pointer to
408 /// the scope fields.
409 static ScopeRecord *getSymbolScopeFields(void *sym) {
410 return reinterpret_cast<ScopeRecord *>(reinterpret_cast<char *>(sym) +
411 sizeof(RecordPrefix));
414 // To open a scope, push the offset of the current symbol record onto the
415 // stack.
416 static void scopeStackOpen(SmallVectorImpl<uint32_t> &stack,
417 std::vector<uint8_t> &storage) {
418 stack.push_back(storage.size());
421 // To close a scope, update the record that opened the scope.
422 static void scopeStackClose(SmallVectorImpl<uint32_t> &stack,
423 std::vector<uint8_t> &storage,
424 uint32_t storageBaseOffset, ObjFile *file) {
425 if (stack.empty()) {
426 warn("symbol scopes are not balanced in " + file->getName());
427 return;
430 // Update ptrEnd of the record that opened the scope to point to the
431 // current record, if we are writing into the module symbol stream.
432 uint32_t offOpen = stack.pop_back_val();
433 uint32_t offEnd = storageBaseOffset + storage.size();
434 uint32_t offParent = stack.empty() ? 0 : (stack.back() + storageBaseOffset);
435 ScopeRecord *scopeRec = getSymbolScopeFields(&(storage)[offOpen]);
436 scopeRec->ptrParent = offParent;
437 scopeRec->ptrEnd = offEnd;
440 static bool symbolGoesInModuleStream(const CVSymbol &sym,
441 unsigned symbolScopeDepth) {
442 switch (sym.kind()) {
443 case SymbolKind::S_GDATA32:
444 case SymbolKind::S_CONSTANT:
445 case SymbolKind::S_GTHREAD32:
446 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
447 // since they are synthesized by the linker in response to S_GPROC32 and
448 // S_LPROC32, but if we do see them, don't put them in the module stream I
449 // guess.
450 case SymbolKind::S_PROCREF:
451 case SymbolKind::S_LPROCREF:
452 return false;
453 // S_UDT records go in the module stream if it is not a global S_UDT.
454 case SymbolKind::S_UDT:
455 return symbolScopeDepth > 0;
456 // S_GDATA32 does not go in the module stream, but S_LDATA32 does.
457 case SymbolKind::S_LDATA32:
458 case SymbolKind::S_LTHREAD32:
459 default:
460 return true;
464 static bool symbolGoesInGlobalsStream(const CVSymbol &sym,
465 unsigned symbolScopeDepth) {
466 switch (sym.kind()) {
467 case SymbolKind::S_CONSTANT:
468 case SymbolKind::S_GDATA32:
469 case SymbolKind::S_GTHREAD32:
470 case SymbolKind::S_GPROC32:
471 case SymbolKind::S_LPROC32:
472 case SymbolKind::S_GPROC32_ID:
473 case SymbolKind::S_LPROC32_ID:
474 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
475 // since they are synthesized by the linker in response to S_GPROC32 and
476 // S_LPROC32, but if we do see them, copy them straight through.
477 case SymbolKind::S_PROCREF:
478 case SymbolKind::S_LPROCREF:
479 return true;
480 // Records that go in the globals stream, unless they are function-local.
481 case SymbolKind::S_UDT:
482 case SymbolKind::S_LDATA32:
483 case SymbolKind::S_LTHREAD32:
484 return symbolScopeDepth == 0;
485 default:
486 return false;
490 static void addGlobalSymbol(pdb::GSIStreamBuilder &builder, uint16_t modIndex,
491 unsigned symOffset,
492 std::vector<uint8_t> &symStorage) {
493 CVSymbol sym(makeArrayRef(symStorage));
494 switch (sym.kind()) {
495 case SymbolKind::S_CONSTANT:
496 case SymbolKind::S_UDT:
497 case SymbolKind::S_GDATA32:
498 case SymbolKind::S_GTHREAD32:
499 case SymbolKind::S_LTHREAD32:
500 case SymbolKind::S_LDATA32:
501 case SymbolKind::S_PROCREF:
502 case SymbolKind::S_LPROCREF: {
503 // sym is a temporary object, so we have to copy and reallocate the record
504 // to stabilize it.
505 uint8_t *mem = bAlloc().Allocate<uint8_t>(sym.length());
506 memcpy(mem, sym.data().data(), sym.length());
507 builder.addGlobalSymbol(CVSymbol(makeArrayRef(mem, sym.length())));
508 break;
510 case SymbolKind::S_GPROC32:
511 case SymbolKind::S_LPROC32: {
512 SymbolRecordKind k = SymbolRecordKind::ProcRefSym;
513 if (sym.kind() == SymbolKind::S_LPROC32)
514 k = SymbolRecordKind::LocalProcRef;
515 ProcRefSym ps(k);
516 ps.Module = modIndex;
517 // For some reason, MSVC seems to add one to this value.
518 ++ps.Module;
519 ps.Name = getSymbolName(sym);
520 ps.SumName = 0;
521 ps.SymOffset = symOffset;
522 builder.addGlobalSymbol(ps);
523 break;
525 default:
526 llvm_unreachable("Invalid symbol kind!");
530 // Check if the given symbol record was padded for alignment. If so, zero out
531 // the padding bytes and update the record prefix with the new size.
532 static void fixRecordAlignment(MutableArrayRef<uint8_t> recordBytes,
533 size_t oldSize) {
534 size_t alignedSize = recordBytes.size();
535 if (oldSize == alignedSize)
536 return;
537 reinterpret_cast<RecordPrefix *>(recordBytes.data())->RecordLen =
538 alignedSize - 2;
539 memset(recordBytes.data() + oldSize, 0, alignedSize - oldSize);
542 // Replace any record with a skip record of the same size. This is useful when
543 // we have reserved size for a symbol record, but type index remapping fails.
544 static void replaceWithSkipRecord(MutableArrayRef<uint8_t> recordBytes) {
545 memset(recordBytes.data(), 0, recordBytes.size());
546 auto *prefix = reinterpret_cast<RecordPrefix *>(recordBytes.data());
547 prefix->RecordKind = SymbolKind::S_SKIP;
548 prefix->RecordLen = recordBytes.size() - 2;
551 // Copy the symbol record, relocate it, and fix the alignment if necessary.
552 // Rewrite type indices in the record. Replace unrecognized symbol records with
553 // S_SKIP records.
554 void PDBLinker::writeSymbolRecord(SectionChunk *debugChunk,
555 ArrayRef<uint8_t> sectionContents,
556 CVSymbol sym, size_t alignedSize,
557 uint32_t &nextRelocIndex,
558 std::vector<uint8_t> &storage) {
559 // Allocate space for the new record at the end of the storage.
560 storage.resize(storage.size() + alignedSize);
561 auto recordBytes = MutableArrayRef<uint8_t>(storage).take_back(alignedSize);
563 // Copy the symbol record and relocate it.
564 debugChunk->writeAndRelocateSubsection(sectionContents, sym.data(),
565 nextRelocIndex, recordBytes.data());
566 fixRecordAlignment(recordBytes, sym.length());
568 // Re-map all the type index references.
569 TpiSource *source = debugChunk->file->debugTypesObj;
570 if (!source->remapTypesInSymbolRecord(recordBytes)) {
571 log("ignoring unknown symbol record with kind 0x" + utohexstr(sym.kind()));
572 replaceWithSkipRecord(recordBytes);
575 // An object file may have S_xxx_ID symbols, but these get converted to
576 // "real" symbols in a PDB.
577 translateIdSymbols(recordBytes, tMerger, source);
580 void PDBLinker::analyzeSymbolSubsection(
581 SectionChunk *debugChunk, uint32_t &moduleSymOffset,
582 uint32_t &nextRelocIndex, std::vector<StringTableFixup> &stringTableFixups,
583 BinaryStreamRef symData) {
584 ObjFile *file = debugChunk->file;
585 uint32_t moduleSymStart = moduleSymOffset;
587 uint32_t scopeLevel = 0;
588 std::vector<uint8_t> storage;
589 ArrayRef<uint8_t> sectionContents = debugChunk->getContents();
591 ArrayRef<uint8_t> symsBuffer;
592 cantFail(symData.readBytes(0, symData.getLength(), symsBuffer));
594 if (symsBuffer.empty())
595 warn("empty symbols subsection in " + file->getName());
597 Error ec = forEachCodeViewRecord<CVSymbol>(
598 symsBuffer, [&](CVSymbol sym) -> llvm::Error {
599 // Track the current scope.
600 if (symbolOpensScope(sym.kind()))
601 ++scopeLevel;
602 else if (symbolEndsScope(sym.kind()))
603 --scopeLevel;
605 uint32_t alignedSize =
606 alignTo(sym.length(), alignOf(CodeViewContainer::Pdb));
608 // Copy global records. Some global records (mainly procedures)
609 // reference the current offset into the module stream.
610 if (symbolGoesInGlobalsStream(sym, scopeLevel)) {
611 storage.clear();
612 writeSymbolRecord(debugChunk, sectionContents, sym, alignedSize,
613 nextRelocIndex, storage);
614 addGlobalSymbol(builder.getGsiBuilder(),
615 file->moduleDBI->getModuleIndex(), moduleSymOffset,
616 storage);
617 ++globalSymbols;
620 // Update the module stream offset and record any string table index
621 // references. There are very few of these and they will be rewritten
622 // later during PDB writing.
623 if (symbolGoesInModuleStream(sym, scopeLevel)) {
624 recordStringTableReferences(sym, moduleSymOffset, stringTableFixups);
625 moduleSymOffset += alignedSize;
626 ++moduleSymbols;
629 return Error::success();
632 // If we encountered corrupt records, ignore the whole subsection. If we wrote
633 // any partial records, undo that. For globals, we just keep what we have and
634 // continue.
635 if (ec) {
636 warn("corrupt symbol records in " + file->getName());
637 moduleSymOffset = moduleSymStart;
638 consumeError(std::move(ec));
642 Error PDBLinker::writeAllModuleSymbolRecords(ObjFile *file,
643 BinaryStreamWriter &writer) {
644 std::vector<uint8_t> storage;
645 SmallVector<uint32_t, 4> scopes;
647 // Visit all live .debug$S sections a second time, and write them to the PDB.
648 for (SectionChunk *debugChunk : file->getDebugChunks()) {
649 if (!debugChunk->live || debugChunk->getSize() == 0 ||
650 debugChunk->getSectionName() != ".debug$S")
651 continue;
653 ArrayRef<uint8_t> sectionContents = debugChunk->getContents();
654 auto contents =
655 SectionChunk::consumeDebugMagic(sectionContents, ".debug$S");
656 DebugSubsectionArray subsections;
657 BinaryStreamReader reader(contents, support::little);
658 exitOnErr(reader.readArray(subsections, contents.size()));
660 uint32_t nextRelocIndex = 0;
661 for (const DebugSubsectionRecord &ss : subsections) {
662 if (ss.kind() != DebugSubsectionKind::Symbols)
663 continue;
665 uint32_t moduleSymStart = writer.getOffset();
666 scopes.clear();
667 storage.clear();
668 ArrayRef<uint8_t> symsBuffer;
669 BinaryStreamRef sr = ss.getRecordData();
670 cantFail(sr.readBytes(0, sr.getLength(), symsBuffer));
671 auto ec = forEachCodeViewRecord<CVSymbol>(
672 symsBuffer, [&](CVSymbol sym) -> llvm::Error {
673 // Track the current scope. Only update records in the postmerge
674 // pass.
675 if (symbolOpensScope(sym.kind()))
676 scopeStackOpen(scopes, storage);
677 else if (symbolEndsScope(sym.kind()))
678 scopeStackClose(scopes, storage, moduleSymStart, file);
680 // Copy, relocate, and rewrite each module symbol.
681 if (symbolGoesInModuleStream(sym, scopes.size())) {
682 uint32_t alignedSize =
683 alignTo(sym.length(), alignOf(CodeViewContainer::Pdb));
684 writeSymbolRecord(debugChunk, sectionContents, sym, alignedSize,
685 nextRelocIndex, storage);
687 return Error::success();
690 // If we encounter corrupt records in the second pass, ignore them. We
691 // already warned about them in the first analysis pass.
692 if (ec) {
693 consumeError(std::move(ec));
694 storage.clear();
697 // Writing bytes has a very high overhead, so write the entire subsection
698 // at once.
699 // TODO: Consider buffering symbols for the entire object file to reduce
700 // overhead even further.
701 if (Error e = writer.writeBytes(storage))
702 return e;
706 return Error::success();
709 Error PDBLinker::commitSymbolsForObject(void *ctx, void *obj,
710 BinaryStreamWriter &writer) {
711 return static_cast<PDBLinker *>(ctx)->writeAllModuleSymbolRecords(
712 static_cast<ObjFile *>(obj), writer);
715 static pdb::SectionContrib createSectionContrib(COFFLinkerContext &ctx,
716 const Chunk *c, uint32_t modi) {
717 OutputSection *os = c ? ctx.getOutputSection(c) : nullptr;
718 pdb::SectionContrib sc;
719 memset(&sc, 0, sizeof(sc));
720 sc.ISect = os ? os->sectionIndex : llvm::pdb::kInvalidStreamIndex;
721 sc.Off = c && os ? c->getRVA() - os->getRVA() : 0;
722 sc.Size = c ? c->getSize() : -1;
723 if (auto *secChunk = dyn_cast_or_null<SectionChunk>(c)) {
724 sc.Characteristics = secChunk->header->Characteristics;
725 sc.Imod = secChunk->file->moduleDBI->getModuleIndex();
726 ArrayRef<uint8_t> contents = secChunk->getContents();
727 JamCRC crc(0);
728 crc.update(contents);
729 sc.DataCrc = crc.getCRC();
730 } else {
731 sc.Characteristics = os ? os->header.Characteristics : 0;
732 sc.Imod = modi;
734 sc.RelocCrc = 0; // FIXME
736 return sc;
739 static uint32_t
740 translateStringTableIndex(uint32_t objIndex,
741 const DebugStringTableSubsectionRef &objStrTable,
742 DebugStringTableSubsection &pdbStrTable) {
743 auto expectedString = objStrTable.getString(objIndex);
744 if (!expectedString) {
745 warn("Invalid string table reference");
746 consumeError(expectedString.takeError());
747 return 0;
750 return pdbStrTable.insert(*expectedString);
753 void DebugSHandler::handleDebugS(SectionChunk *debugChunk) {
754 // Note that we are processing the *unrelocated* section contents. They will
755 // be relocated later during PDB writing.
756 ArrayRef<uint8_t> contents = debugChunk->getContents();
757 contents = SectionChunk::consumeDebugMagic(contents, ".debug$S");
758 DebugSubsectionArray subsections;
759 BinaryStreamReader reader(contents, support::little);
760 exitOnErr(reader.readArray(subsections, contents.size()));
761 debugChunk->sortRelocations();
763 // Reset the relocation index, since this is a new section.
764 nextRelocIndex = 0;
766 for (const DebugSubsectionRecord &ss : subsections) {
767 // Ignore subsections with the 'ignore' bit. Some versions of the Visual C++
768 // runtime have subsections with this bit set.
769 if (uint32_t(ss.kind()) & codeview::SubsectionIgnoreFlag)
770 continue;
772 switch (ss.kind()) {
773 case DebugSubsectionKind::StringTable: {
774 assert(!cvStrTab.valid() &&
775 "Encountered multiple string table subsections!");
776 exitOnErr(cvStrTab.initialize(ss.getRecordData()));
777 break;
779 case DebugSubsectionKind::FileChecksums:
780 assert(!checksums.valid() &&
781 "Encountered multiple checksum subsections!");
782 exitOnErr(checksums.initialize(ss.getRecordData()));
783 break;
784 case DebugSubsectionKind::Lines:
785 case DebugSubsectionKind::InlineeLines:
786 addUnrelocatedSubsection(debugChunk, ss);
787 break;
788 case DebugSubsectionKind::FrameData:
789 addFrameDataSubsection(debugChunk, ss);
790 break;
791 case DebugSubsectionKind::Symbols:
792 linker.analyzeSymbolSubsection(debugChunk, moduleStreamSize,
793 nextRelocIndex, stringTableFixups,
794 ss.getRecordData());
795 break;
797 case DebugSubsectionKind::CrossScopeImports:
798 case DebugSubsectionKind::CrossScopeExports:
799 // These appear to relate to cross-module optimization, so we might use
800 // these for ThinLTO.
801 break;
803 case DebugSubsectionKind::ILLines:
804 case DebugSubsectionKind::FuncMDTokenMap:
805 case DebugSubsectionKind::TypeMDTokenMap:
806 case DebugSubsectionKind::MergedAssemblyInput:
807 // These appear to relate to .Net assembly info.
808 break;
810 case DebugSubsectionKind::CoffSymbolRVA:
811 // Unclear what this is for.
812 break;
814 default:
815 warn("ignoring unknown debug$S subsection kind 0x" +
816 utohexstr(uint32_t(ss.kind())) + " in file " + toString(&file));
817 break;
822 void DebugSHandler::advanceRelocIndex(SectionChunk *sc,
823 ArrayRef<uint8_t> subsec) {
824 ptrdiff_t vaBegin = subsec.data() - sc->getContents().data();
825 assert(vaBegin > 0);
826 auto relocs = sc->getRelocs();
827 for (; nextRelocIndex < relocs.size(); ++nextRelocIndex) {
828 if (relocs[nextRelocIndex].VirtualAddress >= vaBegin)
829 break;
833 namespace {
834 /// Wrapper class for unrelocated line and inlinee line subsections, which
835 /// require only relocation and type index remapping to add to the PDB.
836 class UnrelocatedDebugSubsection : public DebugSubsection {
837 public:
838 UnrelocatedDebugSubsection(DebugSubsectionKind k, SectionChunk *debugChunk,
839 ArrayRef<uint8_t> subsec, uint32_t relocIndex)
840 : DebugSubsection(k), debugChunk(debugChunk), subsec(subsec),
841 relocIndex(relocIndex) {}
843 Error commit(BinaryStreamWriter &writer) const override;
844 uint32_t calculateSerializedSize() const override { return subsec.size(); }
846 SectionChunk *debugChunk;
847 ArrayRef<uint8_t> subsec;
848 uint32_t relocIndex;
850 } // namespace
852 Error UnrelocatedDebugSubsection::commit(BinaryStreamWriter &writer) const {
853 std::vector<uint8_t> relocatedBytes(subsec.size());
854 uint32_t tmpRelocIndex = relocIndex;
855 debugChunk->writeAndRelocateSubsection(debugChunk->getContents(), subsec,
856 tmpRelocIndex, relocatedBytes.data());
858 // Remap type indices in inlinee line records in place. Skip the remapping if
859 // there is no type source info.
860 if (kind() == DebugSubsectionKind::InlineeLines &&
861 debugChunk->file->debugTypesObj) {
862 TpiSource *source = debugChunk->file->debugTypesObj;
863 DebugInlineeLinesSubsectionRef inlineeLines;
864 BinaryStreamReader storageReader(relocatedBytes, support::little);
865 exitOnErr(inlineeLines.initialize(storageReader));
866 for (const InlineeSourceLine &line : inlineeLines) {
867 TypeIndex &inlinee = *const_cast<TypeIndex *>(&line.Header->Inlinee);
868 if (!source->remapTypeIndex(inlinee, TiRefKind::IndexRef)) {
869 log("bad inlinee line record in " + debugChunk->file->getName() +
870 " with bad inlinee index 0x" + utohexstr(inlinee.getIndex()));
875 return writer.writeBytes(relocatedBytes);
878 void DebugSHandler::addUnrelocatedSubsection(SectionChunk *debugChunk,
879 const DebugSubsectionRecord &ss) {
880 ArrayRef<uint8_t> subsec;
881 BinaryStreamRef sr = ss.getRecordData();
882 cantFail(sr.readBytes(0, sr.getLength(), subsec));
883 advanceRelocIndex(debugChunk, subsec);
884 file.moduleDBI->addDebugSubsection(
885 std::make_shared<UnrelocatedDebugSubsection>(ss.kind(), debugChunk,
886 subsec, nextRelocIndex));
889 void DebugSHandler::addFrameDataSubsection(SectionChunk *debugChunk,
890 const DebugSubsectionRecord &ss) {
891 // We need to re-write string table indices here, so save off all
892 // frame data subsections until we've processed the entire list of
893 // subsections so that we can be sure we have the string table.
894 ArrayRef<uint8_t> subsec;
895 BinaryStreamRef sr = ss.getRecordData();
896 cantFail(sr.readBytes(0, sr.getLength(), subsec));
897 advanceRelocIndex(debugChunk, subsec);
898 frameDataSubsecs.push_back({debugChunk, subsec, nextRelocIndex});
901 static Expected<StringRef>
902 getFileName(const DebugStringTableSubsectionRef &strings,
903 const DebugChecksumsSubsectionRef &checksums, uint32_t fileID) {
904 auto iter = checksums.getArray().at(fileID);
905 if (iter == checksums.getArray().end())
906 return make_error<CodeViewError>(cv_error_code::no_records);
907 uint32_t offset = iter->FileNameOffset;
908 return strings.getString(offset);
911 void DebugSHandler::finish() {
912 pdb::DbiStreamBuilder &dbiBuilder = linker.builder.getDbiBuilder();
914 // If we found any symbol records for the module symbol stream, defer them.
915 if (moduleStreamSize > kSymbolStreamMagicSize)
916 file.moduleDBI->addUnmergedSymbols(&file, moduleStreamSize -
917 kSymbolStreamMagicSize);
919 // We should have seen all debug subsections across the entire object file now
920 // which means that if a StringTable subsection and Checksums subsection were
921 // present, now is the time to handle them.
922 if (!cvStrTab.valid()) {
923 if (checksums.valid())
924 fatal(".debug$S sections with a checksums subsection must also contain a "
925 "string table subsection");
927 if (!stringTableFixups.empty())
928 warn("No StringTable subsection was encountered, but there are string "
929 "table references");
930 return;
933 // Handle FPO data. Each subsection begins with a single image base
934 // relocation, which is then added to the RvaStart of each frame data record
935 // when it is added to the PDB. The string table indices for the FPO program
936 // must also be rewritten to use the PDB string table.
937 for (const UnrelocatedFpoData &subsec : frameDataSubsecs) {
938 // Relocate the first four bytes of the subection and reinterpret them as a
939 // 32 bit integer.
940 SectionChunk *debugChunk = subsec.debugChunk;
941 ArrayRef<uint8_t> subsecData = subsec.subsecData;
942 uint32_t relocIndex = subsec.relocIndex;
943 auto unrelocatedRvaStart = subsecData.take_front(sizeof(uint32_t));
944 uint8_t relocatedRvaStart[sizeof(uint32_t)];
945 debugChunk->writeAndRelocateSubsection(debugChunk->getContents(),
946 unrelocatedRvaStart, relocIndex,
947 &relocatedRvaStart[0]);
948 uint32_t rvaStart;
949 memcpy(&rvaStart, &relocatedRvaStart[0], sizeof(uint32_t));
951 // Copy each frame data record, add in rvaStart, translate string table
952 // indices, and add the record to the PDB.
953 DebugFrameDataSubsectionRef fds;
954 BinaryStreamReader reader(subsecData, support::little);
955 exitOnErr(fds.initialize(reader));
956 for (codeview::FrameData fd : fds) {
957 fd.RvaStart += rvaStart;
958 fd.FrameFunc =
959 translateStringTableIndex(fd.FrameFunc, cvStrTab, linker.pdbStrTab);
960 dbiBuilder.addNewFpoData(fd);
964 // Translate the fixups and pass them off to the module builder so they will
965 // be applied during writing.
966 for (StringTableFixup &ref : stringTableFixups) {
967 ref.StrTabOffset =
968 translateStringTableIndex(ref.StrTabOffset, cvStrTab, linker.pdbStrTab);
970 file.moduleDBI->setStringTableFixups(std::move(stringTableFixups));
972 // Make a new file checksum table that refers to offsets in the PDB-wide
973 // string table. Generally the string table subsection appears after the
974 // checksum table, so we have to do this after looping over all the
975 // subsections. The new checksum table must have the exact same layout and
976 // size as the original. Otherwise, the file references in the line and
977 // inlinee line tables will be incorrect.
978 auto newChecksums = std::make_unique<DebugChecksumsSubsection>(linker.pdbStrTab);
979 for (const FileChecksumEntry &fc : checksums) {
980 SmallString<128> filename =
981 exitOnErr(cvStrTab.getString(fc.FileNameOffset));
982 pdbMakeAbsolute(filename);
983 exitOnErr(dbiBuilder.addModuleSourceFile(*file.moduleDBI, filename));
984 newChecksums->addChecksum(filename, fc.Kind, fc.Checksum);
986 assert(checksums.getArray().getUnderlyingStream().getLength() ==
987 newChecksums->calculateSerializedSize() &&
988 "file checksum table must have same layout");
990 file.moduleDBI->addDebugSubsection(std::move(newChecksums));
993 static void warnUnusable(InputFile *f, Error e) {
994 if (!config->warnDebugInfoUnusable) {
995 consumeError(std::move(e));
996 return;
998 auto msg = "Cannot use debug info for '" + toString(f) + "' [LNK4099]";
999 if (e)
1000 warn(msg + "\n>>> failed to load reference " + toString(std::move(e)));
1001 else
1002 warn(msg);
1005 // Allocate memory for a .debug$S / .debug$F section and relocate it.
1006 static ArrayRef<uint8_t> relocateDebugChunk(SectionChunk &debugChunk) {
1007 uint8_t *buffer = bAlloc().Allocate<uint8_t>(debugChunk.getSize());
1008 assert(debugChunk.getOutputSectionIdx() == 0 &&
1009 "debug sections should not be in output sections");
1010 debugChunk.writeTo(buffer);
1011 return makeArrayRef(buffer, debugChunk.getSize());
1014 void PDBLinker::addDebugSymbols(TpiSource *source) {
1015 // If this TpiSource doesn't have an object file, it must be from a type
1016 // server PDB. Type server PDBs do not contain symbols, so stop here.
1017 if (!source->file)
1018 return;
1020 ScopedTimer t(ctx.symbolMergingTimer);
1021 pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1022 DebugSHandler dsh(*this, *source->file, source);
1023 // Now do all live .debug$S and .debug$F sections.
1024 for (SectionChunk *debugChunk : source->file->getDebugChunks()) {
1025 if (!debugChunk->live || debugChunk->getSize() == 0)
1026 continue;
1028 bool isDebugS = debugChunk->getSectionName() == ".debug$S";
1029 bool isDebugF = debugChunk->getSectionName() == ".debug$F";
1030 if (!isDebugS && !isDebugF)
1031 continue;
1033 if (isDebugS) {
1034 dsh.handleDebugS(debugChunk);
1035 } else if (isDebugF) {
1036 // Handle old FPO data .debug$F sections. These are relatively rare.
1037 ArrayRef<uint8_t> relocatedDebugContents =
1038 relocateDebugChunk(*debugChunk);
1039 FixedStreamArray<object::FpoData> fpoRecords;
1040 BinaryStreamReader reader(relocatedDebugContents, support::little);
1041 uint32_t count = relocatedDebugContents.size() / sizeof(object::FpoData);
1042 exitOnErr(reader.readArray(fpoRecords, count));
1044 // These are already relocated and don't refer to the string table, so we
1045 // can just copy it.
1046 for (const object::FpoData &fd : fpoRecords)
1047 dbiBuilder.addOldFpoData(fd);
1051 // Do any post-processing now that all .debug$S sections have been processed.
1052 dsh.finish();
1055 // Add a module descriptor for every object file. We need to put an absolute
1056 // path to the object into the PDB. If this is a plain object, we make its
1057 // path absolute. If it's an object in an archive, we make the archive path
1058 // absolute.
1059 void PDBLinker::createModuleDBI(ObjFile *file) {
1060 pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1061 SmallString<128> objName;
1063 bool inArchive = !file->parentName.empty();
1064 objName = inArchive ? file->parentName : file->getName();
1065 pdbMakeAbsolute(objName);
1066 StringRef modName = inArchive ? file->getName() : objName.str();
1068 file->moduleDBI = &exitOnErr(dbiBuilder.addModuleInfo(modName));
1069 file->moduleDBI->setObjFileName(objName);
1070 file->moduleDBI->setMergeSymbolsCallback(this, &commitSymbolsForObject);
1072 ArrayRef<Chunk *> chunks = file->getChunks();
1073 uint32_t modi = file->moduleDBI->getModuleIndex();
1075 for (Chunk *c : chunks) {
1076 auto *secChunk = dyn_cast<SectionChunk>(c);
1077 if (!secChunk || !secChunk->live)
1078 continue;
1079 pdb::SectionContrib sc = createSectionContrib(ctx, secChunk, modi);
1080 file->moduleDBI->setFirstSectionContrib(sc);
1081 break;
1085 void PDBLinker::addDebug(TpiSource *source) {
1086 // Before we can process symbol substreams from .debug$S, we need to process
1087 // type information, file checksums, and the string table. Add type info to
1088 // the PDB first, so that we can get the map from object file type and item
1089 // indices to PDB type and item indices. If we are using ghashes, types have
1090 // already been merged.
1091 if (!config->debugGHashes) {
1092 ScopedTimer t(ctx.typeMergingTimer);
1093 if (Error e = source->mergeDebugT(&tMerger)) {
1094 // If type merging failed, ignore the symbols.
1095 warnUnusable(source->file, std::move(e));
1096 return;
1100 // If type merging failed, ignore the symbols.
1101 Error typeError = std::move(source->typeMergingError);
1102 if (typeError) {
1103 warnUnusable(source->file, std::move(typeError));
1104 return;
1107 addDebugSymbols(source);
1110 static pdb::BulkPublic createPublic(COFFLinkerContext &ctx, Defined *def) {
1111 pdb::BulkPublic pub;
1112 pub.Name = def->getName().data();
1113 pub.NameLen = def->getName().size();
1115 PublicSymFlags flags = PublicSymFlags::None;
1116 if (auto *d = dyn_cast<DefinedCOFF>(def)) {
1117 if (d->getCOFFSymbol().isFunctionDefinition())
1118 flags = PublicSymFlags::Function;
1119 } else if (isa<DefinedImportThunk>(def)) {
1120 flags = PublicSymFlags::Function;
1122 pub.setFlags(flags);
1124 OutputSection *os = ctx.getOutputSection(def->getChunk());
1125 assert(os && "all publics should be in final image");
1126 pub.Offset = def->getRVA() - os->getRVA();
1127 pub.Segment = os->sectionIndex;
1128 return pub;
1131 // Add all object files to the PDB. Merge .debug$T sections into IpiData and
1132 // TpiData.
1133 void PDBLinker::addObjectsToPDB() {
1134 ScopedTimer t1(ctx.addObjectsTimer);
1136 // Create module descriptors
1137 for_each(ctx.objFileInstances, [&](ObjFile *obj) { createModuleDBI(obj); });
1139 // Reorder dependency type sources to come first.
1140 tMerger.sortDependencies();
1142 // Merge type information from input files using global type hashing.
1143 if (config->debugGHashes)
1144 tMerger.mergeTypesWithGHash();
1146 // Merge dependencies and then regular objects.
1147 for_each(tMerger.dependencySources,
1148 [&](TpiSource *source) { addDebug(source); });
1149 for_each(tMerger.objectSources, [&](TpiSource *source) { addDebug(source); });
1151 builder.getStringTableBuilder().setStrings(pdbStrTab);
1152 t1.stop();
1154 // Construct TPI and IPI stream contents.
1155 ScopedTimer t2(ctx.tpiStreamLayoutTimer);
1156 // Collect all the merged types.
1157 if (config->debugGHashes) {
1158 addGHashTypeInfo(ctx, builder);
1159 } else {
1160 addTypeInfo(builder.getTpiBuilder(), tMerger.getTypeTable());
1161 addTypeInfo(builder.getIpiBuilder(), tMerger.getIDTable());
1163 t2.stop();
1165 if (config->showSummary) {
1166 for_each(ctx.tpiSourceList, [&](TpiSource *source) {
1167 nbTypeRecords += source->nbTypeRecords;
1168 nbTypeRecordsBytes += source->nbTypeRecordsBytes;
1173 void PDBLinker::addPublicsToPDB() {
1174 ScopedTimer t3(ctx.publicsLayoutTimer);
1175 // Compute the public symbols.
1176 auto &gsiBuilder = builder.getGsiBuilder();
1177 std::vector<pdb::BulkPublic> publics;
1178 ctx.symtab.forEachSymbol([&publics, this](Symbol *s) {
1179 // Only emit external, defined, live symbols that have a chunk. Static,
1180 // non-external symbols do not appear in the symbol table.
1181 auto *def = dyn_cast<Defined>(s);
1182 if (def && def->isLive() && def->getChunk()) {
1183 // Don't emit a public symbol for coverage data symbols. LLVM code
1184 // coverage (and PGO) create a __profd_ and __profc_ symbol for every
1185 // function. C++ mangled names are long, and tend to dominate symbol size.
1186 // Including these names triples the size of the public stream, which
1187 // results in bloated PDB files. These symbols generally are not helpful
1188 // for debugging, so suppress them.
1189 StringRef name = def->getName();
1190 if (name.data()[0] == '_' && name.data()[1] == '_') {
1191 // Drop the '_' prefix for x86.
1192 if (config->machine == I386)
1193 name = name.drop_front(1);
1194 if (name.startswith("__profd_") || name.startswith("__profc_") ||
1195 name.startswith("__covrec_")) {
1196 return;
1199 publics.push_back(createPublic(ctx, def));
1203 if (!publics.empty()) {
1204 publicSymbols = publics.size();
1205 gsiBuilder.addPublicSymbols(std::move(publics));
1209 void PDBLinker::printStats() {
1210 if (!config->showSummary)
1211 return;
1213 SmallString<256> buffer;
1214 raw_svector_ostream stream(buffer);
1216 stream << center_justify("Summary", 80) << '\n'
1217 << std::string(80, '-') << '\n';
1219 auto print = [&](uint64_t v, StringRef s) {
1220 stream << format_decimal(v, 15) << " " << s << '\n';
1223 print(ctx.objFileInstances.size(),
1224 "Input OBJ files (expanded from all cmd-line inputs)");
1225 print(ctx.typeServerSourceMappings.size(), "PDB type server dependencies");
1226 print(ctx.precompSourceMappings.size(), "Precomp OBJ dependencies");
1227 print(nbTypeRecords, "Input type records");
1228 print(nbTypeRecordsBytes, "Input type records bytes");
1229 print(builder.getTpiBuilder().getRecordCount(), "Merged TPI records");
1230 print(builder.getIpiBuilder().getRecordCount(), "Merged IPI records");
1231 print(pdbStrTab.size(), "Output PDB strings");
1232 print(globalSymbols, "Global symbol records");
1233 print(moduleSymbols, "Module symbol records");
1234 print(publicSymbols, "Public symbol records");
1236 auto printLargeInputTypeRecs = [&](StringRef name,
1237 ArrayRef<uint32_t> recCounts,
1238 TypeCollection &records) {
1239 // Figure out which type indices were responsible for the most duplicate
1240 // bytes in the input files. These should be frequently emitted LF_CLASS and
1241 // LF_FIELDLIST records.
1242 struct TypeSizeInfo {
1243 uint32_t typeSize;
1244 uint32_t dupCount;
1245 TypeIndex typeIndex;
1246 uint64_t totalInputSize() const { return uint64_t(dupCount) * typeSize; }
1247 bool operator<(const TypeSizeInfo &rhs) const {
1248 if (totalInputSize() == rhs.totalInputSize())
1249 return typeIndex < rhs.typeIndex;
1250 return totalInputSize() < rhs.totalInputSize();
1253 SmallVector<TypeSizeInfo, 0> tsis;
1254 for (auto e : enumerate(recCounts)) {
1255 TypeIndex typeIndex = TypeIndex::fromArrayIndex(e.index());
1256 uint32_t typeSize = records.getType(typeIndex).length();
1257 uint32_t dupCount = e.value();
1258 tsis.push_back({typeSize, dupCount, typeIndex});
1261 if (!tsis.empty()) {
1262 stream << "\nTop 10 types responsible for the most " << name
1263 << " input:\n";
1264 stream << " index total bytes count size\n";
1265 llvm::sort(tsis);
1266 unsigned i = 0;
1267 for (const auto &tsi : reverse(tsis)) {
1268 stream << formatv(" {0,10:X}: {1,14:N} = {2,5:N} * {3,6:N}\n",
1269 tsi.typeIndex.getIndex(), tsi.totalInputSize(),
1270 tsi.dupCount, tsi.typeSize);
1271 if (++i >= 10)
1272 break;
1274 stream
1275 << "Run llvm-pdbutil to print details about a particular record:\n";
1276 stream << formatv("llvm-pdbutil dump -{0}s -{0}-index {1:X} {2}\n",
1277 (name == "TPI" ? "type" : "id"),
1278 tsis.back().typeIndex.getIndex(), config->pdbPath);
1282 if (!config->debugGHashes) {
1283 // FIXME: Reimplement for ghash.
1284 printLargeInputTypeRecs("TPI", tMerger.tpiCounts, tMerger.getTypeTable());
1285 printLargeInputTypeRecs("IPI", tMerger.ipiCounts, tMerger.getIDTable());
1288 message(buffer);
1291 void PDBLinker::addNatvisFiles() {
1292 for (StringRef file : config->natvisFiles) {
1293 ErrorOr<std::unique_ptr<MemoryBuffer>> dataOrErr =
1294 MemoryBuffer::getFile(file);
1295 if (!dataOrErr) {
1296 warn("Cannot open input file: " + file);
1297 continue;
1299 std::unique_ptr<MemoryBuffer> data = std::move(*dataOrErr);
1301 // Can't use takeBuffer() here since addInjectedSource() takes ownership.
1302 if (driver->tar)
1303 driver->tar->append(relativeToRoot(data->getBufferIdentifier()),
1304 data->getBuffer());
1306 builder.addInjectedSource(file, std::move(data));
1310 void PDBLinker::addNamedStreams() {
1311 for (const auto &streamFile : config->namedStreams) {
1312 const StringRef stream = streamFile.getKey(), file = streamFile.getValue();
1313 ErrorOr<std::unique_ptr<MemoryBuffer>> dataOrErr =
1314 MemoryBuffer::getFile(file);
1315 if (!dataOrErr) {
1316 warn("Cannot open input file: " + file);
1317 continue;
1319 std::unique_ptr<MemoryBuffer> data = std::move(*dataOrErr);
1320 exitOnErr(builder.addNamedStream(stream, data->getBuffer()));
1321 driver->takeBuffer(std::move(data));
1325 static codeview::CPUType toCodeViewMachine(COFF::MachineTypes machine) {
1326 switch (machine) {
1327 case COFF::IMAGE_FILE_MACHINE_AMD64:
1328 return codeview::CPUType::X64;
1329 case COFF::IMAGE_FILE_MACHINE_ARM:
1330 return codeview::CPUType::ARM7;
1331 case COFF::IMAGE_FILE_MACHINE_ARM64:
1332 return codeview::CPUType::ARM64;
1333 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1334 return codeview::CPUType::ARMNT;
1335 case COFF::IMAGE_FILE_MACHINE_I386:
1336 return codeview::CPUType::Intel80386;
1337 default:
1338 llvm_unreachable("Unsupported CPU Type");
1342 // Mimic MSVC which surrounds arguments containing whitespace with quotes.
1343 // Double double-quotes are handled, so that the resulting string can be
1344 // executed again on the cmd-line.
1345 static std::string quote(ArrayRef<StringRef> args) {
1346 std::string r;
1347 r.reserve(256);
1348 for (StringRef a : args) {
1349 if (!r.empty())
1350 r.push_back(' ');
1351 bool hasWS = a.contains(' ');
1352 bool hasQ = a.contains('"');
1353 if (hasWS || hasQ)
1354 r.push_back('"');
1355 if (hasQ) {
1356 SmallVector<StringRef, 4> s;
1357 a.split(s, '"');
1358 r.append(join(s, "\"\""));
1359 } else {
1360 r.append(std::string(a));
1362 if (hasWS || hasQ)
1363 r.push_back('"');
1365 return r;
1368 static void fillLinkerVerRecord(Compile3Sym &cs) {
1369 cs.Machine = toCodeViewMachine(config->machine);
1370 // Interestingly, if we set the string to 0.0.0.0, then when trying to view
1371 // local variables WinDbg emits an error that private symbols are not present.
1372 // By setting this to a valid MSVC linker version string, local variables are
1373 // displayed properly. As such, even though it is not representative of
1374 // LLVM's version information, we need this for compatibility.
1375 cs.Flags = CompileSym3Flags::None;
1376 cs.VersionBackendBuild = 25019;
1377 cs.VersionBackendMajor = 14;
1378 cs.VersionBackendMinor = 10;
1379 cs.VersionBackendQFE = 0;
1381 // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
1382 // linker module (which is by definition a backend), so we don't need to do
1383 // anything here. Also, it seems we can use "LLVM Linker" for the linker name
1384 // without any problems. Only the backend version has to be hardcoded to a
1385 // magic number.
1386 cs.VersionFrontendBuild = 0;
1387 cs.VersionFrontendMajor = 0;
1388 cs.VersionFrontendMinor = 0;
1389 cs.VersionFrontendQFE = 0;
1390 cs.Version = "LLVM Linker";
1391 cs.setLanguage(SourceLanguage::Link);
1394 static void addCommonLinkerModuleSymbols(StringRef path,
1395 pdb::DbiModuleDescriptorBuilder &mod) {
1396 ObjNameSym ons(SymbolRecordKind::ObjNameSym);
1397 EnvBlockSym ebs(SymbolRecordKind::EnvBlockSym);
1398 Compile3Sym cs(SymbolRecordKind::Compile3Sym);
1399 fillLinkerVerRecord(cs);
1401 ons.Name = "* Linker *";
1402 ons.Signature = 0;
1404 ArrayRef<StringRef> args = makeArrayRef(config->argv).drop_front();
1405 std::string argStr = quote(args);
1406 ebs.Fields.push_back("cwd");
1407 SmallString<64> cwd;
1408 if (config->pdbSourcePath.empty())
1409 sys::fs::current_path(cwd);
1410 else
1411 cwd = config->pdbSourcePath;
1412 ebs.Fields.push_back(cwd);
1413 ebs.Fields.push_back("exe");
1414 SmallString<64> exe = config->argv[0];
1415 pdbMakeAbsolute(exe);
1416 ebs.Fields.push_back(exe);
1417 ebs.Fields.push_back("pdb");
1418 ebs.Fields.push_back(path);
1419 ebs.Fields.push_back("cmd");
1420 ebs.Fields.push_back(argStr);
1421 llvm::BumpPtrAllocator &bAlloc = lld::bAlloc();
1422 mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1423 ons, bAlloc, CodeViewContainer::Pdb));
1424 mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1425 cs, bAlloc, CodeViewContainer::Pdb));
1426 mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1427 ebs, bAlloc, CodeViewContainer::Pdb));
1430 static void addLinkerModuleCoffGroup(PartialSection *sec,
1431 pdb::DbiModuleDescriptorBuilder &mod,
1432 OutputSection &os) {
1433 // If there's a section, there's at least one chunk
1434 assert(!sec->chunks.empty());
1435 const Chunk *firstChunk = *sec->chunks.begin();
1436 const Chunk *lastChunk = *sec->chunks.rbegin();
1438 // Emit COFF group
1439 CoffGroupSym cgs(SymbolRecordKind::CoffGroupSym);
1440 cgs.Name = sec->name;
1441 cgs.Segment = os.sectionIndex;
1442 cgs.Offset = firstChunk->getRVA() - os.getRVA();
1443 cgs.Size = lastChunk->getRVA() + lastChunk->getSize() - firstChunk->getRVA();
1444 cgs.Characteristics = sec->characteristics;
1446 // Somehow .idata sections & sections groups in the debug symbol stream have
1447 // the "write" flag set. However the section header for the corresponding
1448 // .idata section doesn't have it.
1449 if (cgs.Name.startswith(".idata"))
1450 cgs.Characteristics |= llvm::COFF::IMAGE_SCN_MEM_WRITE;
1452 mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1453 cgs, bAlloc(), CodeViewContainer::Pdb));
1456 static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &mod,
1457 OutputSection &os) {
1458 SectionSym sym(SymbolRecordKind::SectionSym);
1459 sym.Alignment = 12; // 2^12 = 4KB
1460 sym.Characteristics = os.header.Characteristics;
1461 sym.Length = os.getVirtualSize();
1462 sym.Name = os.name;
1463 sym.Rva = os.getRVA();
1464 sym.SectionNumber = os.sectionIndex;
1465 mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1466 sym, bAlloc(), CodeViewContainer::Pdb));
1468 // Skip COFF groups in MinGW because it adds a significant footprint to the
1469 // PDB, due to each function being in its own section
1470 if (config->mingw)
1471 return;
1473 // Output COFF groups for individual chunks of this section.
1474 for (PartialSection *sec : os.contribSections) {
1475 addLinkerModuleCoffGroup(sec, mod, os);
1479 // Add all import files as modules to the PDB.
1480 void PDBLinker::addImportFilesToPDB() {
1481 if (ctx.importFileInstances.empty())
1482 return;
1484 std::map<std::string, llvm::pdb::DbiModuleDescriptorBuilder *> dllToModuleDbi;
1486 for (ImportFile *file : ctx.importFileInstances) {
1487 if (!file->live)
1488 continue;
1490 if (!file->thunkSym)
1491 continue;
1493 if (!file->thunkLive)
1494 continue;
1496 std::string dll = StringRef(file->dllName).lower();
1497 llvm::pdb::DbiModuleDescriptorBuilder *&mod = dllToModuleDbi[dll];
1498 if (!mod) {
1499 pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1500 SmallString<128> libPath = file->parentName;
1501 pdbMakeAbsolute(libPath);
1502 sys::path::native(libPath);
1504 // Name modules similar to MSVC's link.exe.
1505 // The first module is the simple dll filename
1506 llvm::pdb::DbiModuleDescriptorBuilder &firstMod =
1507 exitOnErr(dbiBuilder.addModuleInfo(file->dllName));
1508 firstMod.setObjFileName(libPath);
1509 pdb::SectionContrib sc =
1510 createSectionContrib(ctx, nullptr, llvm::pdb::kInvalidStreamIndex);
1511 firstMod.setFirstSectionContrib(sc);
1513 // The second module is where the import stream goes.
1514 mod = &exitOnErr(dbiBuilder.addModuleInfo("Import:" + file->dllName));
1515 mod->setObjFileName(libPath);
1518 DefinedImportThunk *thunk = cast<DefinedImportThunk>(file->thunkSym);
1519 Chunk *thunkChunk = thunk->getChunk();
1520 OutputSection *thunkOS = ctx.getOutputSection(thunkChunk);
1522 ObjNameSym ons(SymbolRecordKind::ObjNameSym);
1523 Compile3Sym cs(SymbolRecordKind::Compile3Sym);
1524 Thunk32Sym ts(SymbolRecordKind::Thunk32Sym);
1525 ScopeEndSym es(SymbolRecordKind::ScopeEndSym);
1527 ons.Name = file->dllName;
1528 ons.Signature = 0;
1530 fillLinkerVerRecord(cs);
1532 ts.Name = thunk->getName();
1533 ts.Parent = 0;
1534 ts.End = 0;
1535 ts.Next = 0;
1536 ts.Thunk = ThunkOrdinal::Standard;
1537 ts.Length = thunkChunk->getSize();
1538 ts.Segment = thunkOS->sectionIndex;
1539 ts.Offset = thunkChunk->getRVA() - thunkOS->getRVA();
1541 llvm::BumpPtrAllocator &bAlloc = lld::bAlloc();
1542 mod->addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1543 ons, bAlloc, CodeViewContainer::Pdb));
1544 mod->addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1545 cs, bAlloc, CodeViewContainer::Pdb));
1547 CVSymbol newSym = codeview::SymbolSerializer::writeOneSymbol(
1548 ts, bAlloc, CodeViewContainer::Pdb);
1550 // Write ptrEnd for the S_THUNK32.
1551 ScopeRecord *thunkSymScope =
1552 getSymbolScopeFields(const_cast<uint8_t *>(newSym.data().data()));
1554 mod->addSymbol(newSym);
1556 newSym = codeview::SymbolSerializer::writeOneSymbol(es, bAlloc,
1557 CodeViewContainer::Pdb);
1558 thunkSymScope->ptrEnd = mod->getNextSymbolOffset();
1560 mod->addSymbol(newSym);
1562 pdb::SectionContrib sc =
1563 createSectionContrib(ctx, thunk->getChunk(), mod->getModuleIndex());
1564 mod->setFirstSectionContrib(sc);
1568 // Creates a PDB file.
1569 void lld::coff::createPDB(COFFLinkerContext &ctx,
1570 ArrayRef<uint8_t> sectionTable,
1571 llvm::codeview::DebugInfo *buildId) {
1572 ScopedTimer t1(ctx.totalPdbLinkTimer);
1573 PDBLinker pdb(ctx);
1575 pdb.initialize(buildId);
1576 pdb.addObjectsToPDB();
1577 pdb.addImportFilesToPDB();
1578 pdb.addSections(sectionTable);
1579 pdb.addNatvisFiles();
1580 pdb.addNamedStreams();
1581 pdb.addPublicsToPDB();
1583 ScopedTimer t2(ctx.diskCommitTimer);
1584 codeview::GUID guid;
1585 pdb.commit(&guid);
1586 memcpy(&buildId->PDB70.Signature, &guid, 16);
1588 t2.stop();
1589 t1.stop();
1590 pdb.printStats();
1593 void PDBLinker::initialize(llvm::codeview::DebugInfo *buildId) {
1594 exitOnErr(builder.initialize(config->pdbPageSize));
1596 buildId->Signature.CVSignature = OMF::Signature::PDB70;
1597 // Signature is set to a hash of the PDB contents when the PDB is done.
1598 memset(buildId->PDB70.Signature, 0, 16);
1599 buildId->PDB70.Age = 1;
1601 // Create streams in MSF for predefined streams, namely
1602 // PDB, TPI, DBI and IPI.
1603 for (int i = 0; i < (int)pdb::kSpecialStreamCount; ++i)
1604 exitOnErr(builder.getMsfBuilder().addStream(0));
1606 // Add an Info stream.
1607 auto &infoBuilder = builder.getInfoBuilder();
1608 infoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
1609 infoBuilder.setHashPDBContentsToGUID(true);
1611 // Add an empty DBI stream.
1612 pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1613 dbiBuilder.setAge(buildId->PDB70.Age);
1614 dbiBuilder.setVersionHeader(pdb::PdbDbiV70);
1615 dbiBuilder.setMachineType(config->machine);
1616 // Technically we are not link.exe 14.11, but there are known cases where
1617 // debugging tools on Windows expect Microsoft-specific version numbers or
1618 // they fail to work at all. Since we know we produce PDBs that are
1619 // compatible with LINK 14.11, we set that version number here.
1620 dbiBuilder.setBuildNumber(14, 11);
1623 void PDBLinker::addSections(ArrayRef<uint8_t> sectionTable) {
1624 // It's not entirely clear what this is, but the * Linker * module uses it.
1625 pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1626 nativePath = config->pdbPath;
1627 pdbMakeAbsolute(nativePath);
1628 uint32_t pdbFilePathNI = dbiBuilder.addECName(nativePath);
1629 auto &linkerModule = exitOnErr(dbiBuilder.addModuleInfo("* Linker *"));
1630 linkerModule.setPdbFilePathNI(pdbFilePathNI);
1631 addCommonLinkerModuleSymbols(nativePath, linkerModule);
1633 // Add section contributions. They must be ordered by ascending RVA.
1634 for (OutputSection *os : ctx.outputSections) {
1635 addLinkerModuleSectionSymbol(linkerModule, *os);
1636 for (Chunk *c : os->chunks) {
1637 pdb::SectionContrib sc =
1638 createSectionContrib(ctx, c, linkerModule.getModuleIndex());
1639 builder.getDbiBuilder().addSectionContrib(sc);
1643 // The * Linker * first section contrib is only used along with /INCREMENTAL,
1644 // to provide trampolines thunks for incremental function patching. Set this
1645 // as "unused" because LLD doesn't support /INCREMENTAL link.
1646 pdb::SectionContrib sc =
1647 createSectionContrib(ctx, nullptr, llvm::pdb::kInvalidStreamIndex);
1648 linkerModule.setFirstSectionContrib(sc);
1650 // Add Section Map stream.
1651 ArrayRef<object::coff_section> sections = {
1652 (const object::coff_section *)sectionTable.data(),
1653 sectionTable.size() / sizeof(object::coff_section)};
1654 dbiBuilder.createSectionMap(sections);
1656 // Add COFF section header stream.
1657 exitOnErr(
1658 dbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, sectionTable));
1661 void PDBLinker::commit(codeview::GUID *guid) {
1662 // Print an error and continue if PDB writing fails. This is done mainly so
1663 // the user can see the output of /time and /summary, which is very helpful
1664 // when trying to figure out why a PDB file is too large.
1665 if (Error e = builder.commit(config->pdbPath, guid)) {
1666 checkError(std::move(e));
1667 error("failed to write PDB file " + Twine(config->pdbPath));
1671 static uint32_t getSecrelReloc() {
1672 switch (config->machine) {
1673 case AMD64:
1674 return COFF::IMAGE_REL_AMD64_SECREL;
1675 case I386:
1676 return COFF::IMAGE_REL_I386_SECREL;
1677 case ARMNT:
1678 return COFF::IMAGE_REL_ARM_SECREL;
1679 case ARM64:
1680 return COFF::IMAGE_REL_ARM64_SECREL;
1681 default:
1682 llvm_unreachable("unknown machine type");
1686 // Try to find a line table for the given offset Addr into the given chunk C.
1687 // If a line table was found, the line table, the string and checksum tables
1688 // that are used to interpret the line table, and the offset of Addr in the line
1689 // table are stored in the output arguments. Returns whether a line table was
1690 // found.
1691 static bool findLineTable(const SectionChunk *c, uint32_t addr,
1692 DebugStringTableSubsectionRef &cvStrTab,
1693 DebugChecksumsSubsectionRef &checksums,
1694 DebugLinesSubsectionRef &lines,
1695 uint32_t &offsetInLinetable) {
1696 ExitOnError exitOnErr;
1697 uint32_t secrelReloc = getSecrelReloc();
1699 for (SectionChunk *dbgC : c->file->getDebugChunks()) {
1700 if (dbgC->getSectionName() != ".debug$S")
1701 continue;
1703 // Build a mapping of SECREL relocations in dbgC that refer to `c`.
1704 DenseMap<uint32_t, uint32_t> secrels;
1705 for (const coff_relocation &r : dbgC->getRelocs()) {
1706 if (r.Type != secrelReloc)
1707 continue;
1709 if (auto *s = dyn_cast_or_null<DefinedRegular>(
1710 c->file->getSymbols()[r.SymbolTableIndex]))
1711 if (s->getChunk() == c)
1712 secrels[r.VirtualAddress] = s->getValue();
1715 ArrayRef<uint8_t> contents =
1716 SectionChunk::consumeDebugMagic(dbgC->getContents(), ".debug$S");
1717 DebugSubsectionArray subsections;
1718 BinaryStreamReader reader(contents, support::little);
1719 exitOnErr(reader.readArray(subsections, contents.size()));
1721 for (const DebugSubsectionRecord &ss : subsections) {
1722 switch (ss.kind()) {
1723 case DebugSubsectionKind::StringTable: {
1724 assert(!cvStrTab.valid() &&
1725 "Encountered multiple string table subsections!");
1726 exitOnErr(cvStrTab.initialize(ss.getRecordData()));
1727 break;
1729 case DebugSubsectionKind::FileChecksums:
1730 assert(!checksums.valid() &&
1731 "Encountered multiple checksum subsections!");
1732 exitOnErr(checksums.initialize(ss.getRecordData()));
1733 break;
1734 case DebugSubsectionKind::Lines: {
1735 ArrayRef<uint8_t> bytes;
1736 auto ref = ss.getRecordData();
1737 exitOnErr(ref.readLongestContiguousChunk(0, bytes));
1738 size_t offsetInDbgC = bytes.data() - dbgC->getContents().data();
1740 // Check whether this line table refers to C.
1741 auto i = secrels.find(offsetInDbgC);
1742 if (i == secrels.end())
1743 break;
1745 // Check whether this line table covers Addr in C.
1746 DebugLinesSubsectionRef linesTmp;
1747 exitOnErr(linesTmp.initialize(BinaryStreamReader(ref)));
1748 uint32_t offsetInC = i->second + linesTmp.header()->RelocOffset;
1749 if (addr < offsetInC || addr >= offsetInC + linesTmp.header()->CodeSize)
1750 break;
1752 assert(!lines.header() &&
1753 "Encountered multiple line tables for function!");
1754 exitOnErr(lines.initialize(BinaryStreamReader(ref)));
1755 offsetInLinetable = addr - offsetInC;
1756 break;
1758 default:
1759 break;
1762 if (cvStrTab.valid() && checksums.valid() && lines.header())
1763 return true;
1767 return false;
1770 // Use CodeView line tables to resolve a file and line number for the given
1771 // offset into the given chunk and return them, or None if a line table was
1772 // not found.
1773 Optional<std::pair<StringRef, uint32_t>>
1774 lld::coff::getFileLineCodeView(const SectionChunk *c, uint32_t addr) {
1775 ExitOnError exitOnErr;
1777 DebugStringTableSubsectionRef cvStrTab;
1778 DebugChecksumsSubsectionRef checksums;
1779 DebugLinesSubsectionRef lines;
1780 uint32_t offsetInLinetable;
1782 if (!findLineTable(c, addr, cvStrTab, checksums, lines, offsetInLinetable))
1783 return None;
1785 Optional<uint32_t> nameIndex;
1786 Optional<uint32_t> lineNumber;
1787 for (const LineColumnEntry &entry : lines) {
1788 for (const LineNumberEntry &ln : entry.LineNumbers) {
1789 LineInfo li(ln.Flags);
1790 if (ln.Offset > offsetInLinetable) {
1791 if (!nameIndex) {
1792 nameIndex = entry.NameIndex;
1793 lineNumber = li.getStartLine();
1795 StringRef filename =
1796 exitOnErr(getFileName(cvStrTab, checksums, *nameIndex));
1797 return std::make_pair(filename, *lineNumber);
1799 nameIndex = entry.NameIndex;
1800 lineNumber = li.getStartLine();
1803 if (!nameIndex)
1804 return None;
1805 StringRef filename = exitOnErr(getFileName(cvStrTab, checksums, *nameIndex));
1806 return std::make_pair(filename, *lineNumber);