1 //===- PDB.cpp ------------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
10 #include "COFFLinkerContext.h"
13 #include "DebugTypes.h"
15 #include "SymbolTable.h"
17 #include "TypeMerger.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/MSF/MSFError.h"
35 #include "llvm/DebugInfo/PDB/GenericError.h"
36 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
37 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
38 #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
39 #include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h"
40 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
41 #include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
42 #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
43 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
44 #include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
45 #include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
46 #include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
47 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
48 #include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
49 #include "llvm/DebugInfo/PDB/PDB.h"
50 #include "llvm/Object/COFF.h"
51 #include "llvm/Object/CVDebugRecord.h"
52 #include "llvm/Support/BinaryByteStream.h"
53 #include "llvm/Support/CRC.h"
54 #include "llvm/Support/Endian.h"
55 #include "llvm/Support/Errc.h"
56 #include "llvm/Support/FormatAdapters.h"
57 #include "llvm/Support/FormatVariadic.h"
58 #include "llvm/Support/Path.h"
59 #include "llvm/Support/ScopedPrinter.h"
60 #include "llvm/Support/TimeProfiler.h"
65 using namespace llvm::codeview
;
67 using namespace lld::coff
;
69 using llvm::object::coff_section
;
70 using llvm::pdb::StringTableFixup
;
79 PDBLinker(COFFLinkerContext
&ctx
)
80 : builder(bAlloc()), tMerger(ctx
, bAlloc()), ctx(ctx
) {
81 // This isn't strictly necessary, but link.exe usually puts an empty string
82 // as the first "valid" string in the string table, so we do the same in
83 // order to maintain as much byte-for-byte compatibility as possible.
87 /// Emit the basic PDB structure: initial streams, headers, etc.
88 void initialize(llvm::codeview::DebugInfo
*buildId
);
90 /// Add natvis files specified on the command line.
91 void addNatvisFiles();
93 /// Add named streams specified on the command line.
94 void addNamedStreams();
96 /// Link CodeView from each object file in the symbol table into the PDB.
97 void addObjectsToPDB();
99 /// Add every live, defined public symbol to the PDB.
100 void addPublicsToPDB();
102 /// Link info for each import file in the symbol table into the PDB.
103 void addImportFilesToPDB();
105 void createModuleDBI(ObjFile
*file
);
107 /// Link CodeView from a single object file into the target (output) PDB.
108 /// When a precompiled headers object is linked, its TPI map might be provided
110 void addDebug(TpiSource
*source
);
112 void addDebugSymbols(TpiSource
*source
);
114 // Analyze the symbol records to separate module symbols from global symbols,
115 // find string references, and calculate how large the symbol stream will be
117 void analyzeSymbolSubsection(SectionChunk
*debugChunk
,
118 uint32_t &moduleSymOffset
,
119 uint32_t &nextRelocIndex
,
120 std::vector
<StringTableFixup
> &stringTableFixups
,
121 BinaryStreamRef symData
);
123 // Write all module symbols from all live debug symbol subsections of the
124 // given object file into the given stream writer.
125 Error
writeAllModuleSymbolRecords(ObjFile
*file
, BinaryStreamWriter
&writer
);
127 // Callback to copy and relocate debug symbols during PDB file writing.
128 static Error
commitSymbolsForObject(void *ctx
, void *obj
,
129 BinaryStreamWriter
&writer
);
131 // Copy the symbol record, relocate it, and fix the alignment if necessary.
132 // Rewrite type indices in the record. Replace unrecognized symbol records
133 // with S_SKIP records.
134 void writeSymbolRecord(SectionChunk
*debugChunk
,
135 ArrayRef
<uint8_t> sectionContents
, CVSymbol sym
,
136 size_t alignedSize
, uint32_t &nextRelocIndex
,
137 std::vector
<uint8_t> &storage
);
139 /// Add the section map and section contributions to the PDB.
140 void addSections(ArrayRef
<uint8_t> sectionTable
);
142 /// Write the PDB to disk and store the Guid generated for it in *Guid.
143 void commit(codeview::GUID
*guid
);
145 // Print statistics regarding the final PDB
149 void pdbMakeAbsolute(SmallVectorImpl
<char> &fileName
);
150 void translateIdSymbols(MutableArrayRef
<uint8_t> &recordData
,
152 void addCommonLinkerModuleSymbols(StringRef path
,
153 pdb::DbiModuleDescriptorBuilder
&mod
);
155 pdb::PDBFileBuilder builder
;
159 COFFLinkerContext
&ctx
;
161 /// PDBs use a single global string table for filenames in the file checksum
163 DebugStringTableSubsection pdbStrTab
;
165 llvm::SmallString
<128> nativePath
;
168 uint64_t globalSymbols
= 0;
169 uint64_t moduleSymbols
= 0;
170 uint64_t publicSymbols
= 0;
171 uint64_t nbTypeRecords
= 0;
172 uint64_t nbTypeRecordsBytes
= 0;
175 /// Represents an unrelocated DEBUG_S_FRAMEDATA subsection.
176 struct UnrelocatedFpoData
{
177 SectionChunk
*debugChunk
= nullptr;
178 ArrayRef
<uint8_t> subsecData
;
179 uint32_t relocIndex
= 0;
182 /// The size of the magic bytes at the beginning of a symbol section or stream.
183 enum : uint32_t { kSymbolStreamMagicSize
= 4 };
185 class DebugSHandler
{
188 /// The object file whose .debug$S sections we're processing.
191 /// The DEBUG_S_STRINGTABLE subsection. These strings are referred to by
192 /// index from other records in the .debug$S section. All of these strings
193 /// need to be added to the global PDB string table, and all references to
194 /// these strings need to have their indices re-written to refer to the
195 /// global PDB string table.
196 DebugStringTableSubsectionRef cvStrTab
;
198 /// The DEBUG_S_FILECHKSMS subsection. As above, these are referred to
199 /// by other records in the .debug$S section and need to be merged into the
201 DebugChecksumsSubsectionRef checksums
;
203 /// The DEBUG_S_FRAMEDATA subsection(s). There can be more than one of
204 /// these and they need not appear in any specific order. However, they
205 /// contain string table references which need to be re-written, so we
206 /// collect them all here and re-write them after all subsections have been
207 /// discovered and processed.
208 std::vector
<UnrelocatedFpoData
> frameDataSubsecs
;
210 /// List of string table references in symbol records. Later they will be
211 /// applied to the symbols during PDB writing.
212 std::vector
<StringTableFixup
> stringTableFixups
;
214 /// Sum of the size of all module symbol records across all .debug$S sections.
215 /// Includes record realignment and the size of the symbol stream magic
217 uint32_t moduleStreamSize
= kSymbolStreamMagicSize
;
219 /// Next relocation index in the current .debug$S section. Resets every
220 /// handleDebugS call.
221 uint32_t nextRelocIndex
= 0;
223 void advanceRelocIndex(SectionChunk
*debugChunk
, ArrayRef
<uint8_t> subsec
);
225 void addUnrelocatedSubsection(SectionChunk
*debugChunk
,
226 const DebugSubsectionRecord
&ss
);
228 void addFrameDataSubsection(SectionChunk
*debugChunk
,
229 const DebugSubsectionRecord
&ss
);
232 DebugSHandler(PDBLinker
&linker
, ObjFile
&file
)
233 : linker(linker
), file(file
) {}
235 void handleDebugS(SectionChunk
*debugChunk
);
241 // Visual Studio's debugger requires absolute paths in various places in the
242 // PDB to work without additional configuration:
243 // https://docs.microsoft.com/en-us/visualstudio/debugger/debug-source-files-common-properties-solution-property-pages-dialog-box
244 void PDBLinker::pdbMakeAbsolute(SmallVectorImpl
<char> &fileName
) {
245 // The default behavior is to produce paths that are valid within the context
246 // of the machine that you perform the link on. If the linker is running on
247 // a POSIX system, we will output absolute POSIX paths. If the linker is
248 // running on a Windows system, we will output absolute Windows paths. If the
249 // user desires any other kind of behavior, they should explicitly pass
250 // /pdbsourcepath, in which case we will treat the exact string the user
251 // passed in as the gospel and not normalize, canonicalize it.
252 if (sys::path::is_absolute(fileName
, sys::path::Style::windows
) ||
253 sys::path::is_absolute(fileName
, sys::path::Style::posix
))
256 // It's not absolute in any path syntax. Relative paths necessarily refer to
257 // the local file system, so we can make it native without ending up with a
259 if (ctx
.config
.pdbSourcePath
.empty()) {
260 sys::path::native(fileName
);
261 sys::fs::make_absolute(fileName
);
262 sys::path::remove_dots(fileName
, true);
266 // Try to guess whether /PDBSOURCEPATH is a unix path or a windows path.
267 // Since PDB's are more of a Windows thing, we make this conservative and only
268 // decide that it's a unix path if we're fairly certain. Specifically, if
269 // it starts with a forward slash.
270 SmallString
<128> absoluteFileName
= ctx
.config
.pdbSourcePath
;
271 sys::path::Style guessedStyle
= absoluteFileName
.starts_with("/")
272 ? sys::path::Style::posix
273 : sys::path::Style::windows
;
274 sys::path::append(absoluteFileName
, guessedStyle
, fileName
);
275 sys::path::native(absoluteFileName
, guessedStyle
);
276 sys::path::remove_dots(absoluteFileName
, true, guessedStyle
);
278 fileName
= std::move(absoluteFileName
);
281 static void addTypeInfo(pdb::TpiStreamBuilder
&tpiBuilder
,
282 TypeCollection
&typeTable
) {
283 // Start the TPI or IPI stream header.
284 tpiBuilder
.setVersionHeader(pdb::PdbTpiV80
);
286 // Flatten the in memory type table and hash each type.
287 typeTable
.ForEachRecord([&](TypeIndex ti
, const CVType
&type
) {
288 auto hash
= pdb::hashTypeRecord(type
);
289 if (auto e
= hash
.takeError())
290 fatal("type hashing error");
291 tpiBuilder
.addTypeRecord(type
.RecordData
, *hash
);
295 static void addGHashTypeInfo(COFFLinkerContext
&ctx
,
296 pdb::PDBFileBuilder
&builder
) {
297 // Start the TPI or IPI stream header.
298 builder
.getTpiBuilder().setVersionHeader(pdb::PdbTpiV80
);
299 builder
.getIpiBuilder().setVersionHeader(pdb::PdbTpiV80
);
300 for (TpiSource
*source
: ctx
.tpiSourceList
) {
301 builder
.getTpiBuilder().addTypeRecords(source
->mergedTpi
.recs
,
302 source
->mergedTpi
.recSizes
,
303 source
->mergedTpi
.recHashes
);
304 builder
.getIpiBuilder().addTypeRecords(source
->mergedIpi
.recs
,
305 source
->mergedIpi
.recSizes
,
306 source
->mergedIpi
.recHashes
);
311 recordStringTableReferences(CVSymbol sym
, uint32_t symOffset
,
312 std::vector
<StringTableFixup
> &stringTableFixups
) {
313 // For now we only handle S_FILESTATIC, but we may need the same logic for
314 // S_DEFRANGE and S_DEFRANGE_SUBFIELD. However, I cannot seem to generate any
315 // PDBs that contain these types of records, so because of the uncertainty
316 // they are omitted here until we can prove that it's necessary.
317 switch (sym
.kind()) {
318 case SymbolKind::S_FILESTATIC
: {
319 // FileStaticSym::ModFileOffset
320 uint32_t ref
= *reinterpret_cast<const ulittle32_t
*>(&sym
.data()[8]);
321 stringTableFixups
.push_back({ref
, symOffset
+ 8});
324 case SymbolKind::S_DEFRANGE
:
325 case SymbolKind::S_DEFRANGE_SUBFIELD
:
326 log("Not fixing up string table reference in S_DEFRANGE / "
327 "S_DEFRANGE_SUBFIELD record");
334 static SymbolKind
symbolKind(ArrayRef
<uint8_t> recordData
) {
335 const RecordPrefix
*prefix
=
336 reinterpret_cast<const RecordPrefix
*>(recordData
.data());
337 return static_cast<SymbolKind
>(uint16_t(prefix
->RecordKind
));
340 /// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
341 void PDBLinker::translateIdSymbols(MutableArrayRef
<uint8_t> &recordData
,
343 RecordPrefix
*prefix
= reinterpret_cast<RecordPrefix
*>(recordData
.data());
345 SymbolKind kind
= symbolKind(recordData
);
347 if (kind
== SymbolKind::S_PROC_ID_END
) {
348 prefix
->RecordKind
= SymbolKind::S_END
;
352 // In an object file, GPROC32_ID has an embedded reference which refers to the
353 // single object file type index namespace. This has already been translated
354 // to the PDB file's ID stream index space, but we need to convert this to a
355 // symbol that refers to the type stream index space. So we remap again from
356 // ID index space to type index space.
357 if (kind
== SymbolKind::S_GPROC32_ID
|| kind
== SymbolKind::S_LPROC32_ID
) {
358 SmallVector
<TiReference
, 1> refs
;
359 auto content
= recordData
.drop_front(sizeof(RecordPrefix
));
360 CVSymbol
sym(recordData
);
361 discoverTypeIndicesInSymbol(sym
, refs
);
362 assert(refs
.size() == 1);
363 assert(refs
.front().Count
== 1);
366 reinterpret_cast<TypeIndex
*>(content
.data() + refs
[0].Offset
);
367 // `ti` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
368 // the IPI stream, whose `FunctionType` member refers to the TPI stream.
369 // Note that LF_FUNC_ID and LF_MFUNC_ID have the same record layout, and
370 // in both cases we just need the second type index.
371 if (!ti
->isSimple() && !ti
->isNoneType()) {
372 TypeIndex newType
= TypeIndex(SimpleTypeKind::NotTranslated
);
373 if (ctx
.config
.debugGHashes
) {
374 auto idToType
= tMerger
.funcIdToType
.find(*ti
);
375 if (idToType
!= tMerger
.funcIdToType
.end())
376 newType
= idToType
->second
;
378 if (tMerger
.getIDTable().contains(*ti
)) {
379 CVType funcIdData
= tMerger
.getIDTable().getType(*ti
);
380 if (funcIdData
.length() >= 8 && (funcIdData
.kind() == LF_FUNC_ID
||
381 funcIdData
.kind() == LF_MFUNC_ID
)) {
382 newType
= *reinterpret_cast<const TypeIndex
*>(&funcIdData
.data()[8]);
386 if (newType
== TypeIndex(SimpleTypeKind::NotTranslated
)) {
387 warn(formatv("procedure symbol record for `{0}` in {1} refers to PDB "
388 "item index {2:X} which is not a valid function ID record",
389 getSymbolName(CVSymbol(recordData
)),
390 source
->file
->getName(), ti
->getIndex()));
395 kind
= (kind
== SymbolKind::S_GPROC32_ID
) ? SymbolKind::S_GPROC32
396 : SymbolKind::S_LPROC32
;
397 prefix
->RecordKind
= uint16_t(kind
);
403 ulittle32_t ptrParent
;
408 /// Given a pointer to a symbol record that opens a scope, return a pointer to
409 /// the scope fields.
410 static ScopeRecord
*getSymbolScopeFields(void *sym
) {
411 return reinterpret_cast<ScopeRecord
*>(reinterpret_cast<char *>(sym
) +
412 sizeof(RecordPrefix
));
415 // To open a scope, push the offset of the current symbol record onto the
417 static void scopeStackOpen(SmallVectorImpl
<uint32_t> &stack
,
418 std::vector
<uint8_t> &storage
) {
419 stack
.push_back(storage
.size());
422 // To close a scope, update the record that opened the scope.
423 static void scopeStackClose(SmallVectorImpl
<uint32_t> &stack
,
424 std::vector
<uint8_t> &storage
,
425 uint32_t storageBaseOffset
, ObjFile
*file
) {
427 warn("symbol scopes are not balanced in " + file
->getName());
431 // Update ptrEnd of the record that opened the scope to point to the
432 // current record, if we are writing into the module symbol stream.
433 uint32_t offOpen
= stack
.pop_back_val();
434 uint32_t offEnd
= storageBaseOffset
+ storage
.size();
435 uint32_t offParent
= stack
.empty() ? 0 : (stack
.back() + storageBaseOffset
);
436 ScopeRecord
*scopeRec
= getSymbolScopeFields(&(storage
)[offOpen
]);
437 scopeRec
->ptrParent
= offParent
;
438 scopeRec
->ptrEnd
= offEnd
;
441 static bool symbolGoesInModuleStream(const CVSymbol
&sym
,
442 unsigned symbolScopeDepth
) {
443 switch (sym
.kind()) {
444 case SymbolKind::S_GDATA32
:
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
450 case SymbolKind::S_PROCREF
:
451 case SymbolKind::S_LPROCREF
:
453 // S_UDT and S_CONSTANT records go in the module stream if it is not a global record.
454 case SymbolKind::S_UDT
:
455 case SymbolKind::S_CONSTANT
:
456 return symbolScopeDepth
> 0;
457 // S_GDATA32 does not go in the module stream, but S_LDATA32 does.
458 case SymbolKind::S_LDATA32
:
459 case SymbolKind::S_LTHREAD32
:
465 static bool symbolGoesInGlobalsStream(const CVSymbol
&sym
,
466 unsigned symbolScopeDepth
) {
467 switch (sym
.kind()) {
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
:
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 case SymbolKind::S_CONSTANT
:
485 return symbolScopeDepth
== 0;
491 static void addGlobalSymbol(pdb::GSIStreamBuilder
&builder
, uint16_t modIndex
,
493 std::vector
<uint8_t> &symStorage
) {
494 CVSymbol sym
{ArrayRef(symStorage
)};
495 switch (sym
.kind()) {
496 case SymbolKind::S_CONSTANT
:
497 case SymbolKind::S_UDT
:
498 case SymbolKind::S_GDATA32
:
499 case SymbolKind::S_GTHREAD32
:
500 case SymbolKind::S_LTHREAD32
:
501 case SymbolKind::S_LDATA32
:
502 case SymbolKind::S_PROCREF
:
503 case SymbolKind::S_LPROCREF
: {
504 // sym is a temporary object, so we have to copy and reallocate the record
506 uint8_t *mem
= bAlloc().Allocate
<uint8_t>(sym
.length());
507 memcpy(mem
, sym
.data().data(), sym
.length());
508 builder
.addGlobalSymbol(CVSymbol(ArrayRef(mem
, sym
.length())));
511 case SymbolKind::S_GPROC32
:
512 case SymbolKind::S_LPROC32
: {
513 SymbolRecordKind k
= SymbolRecordKind::ProcRefSym
;
514 if (sym
.kind() == SymbolKind::S_LPROC32
)
515 k
= SymbolRecordKind::LocalProcRef
;
517 ps
.Module
= modIndex
;
518 // For some reason, MSVC seems to add one to this value.
520 ps
.Name
= getSymbolName(sym
);
522 ps
.SymOffset
= symOffset
;
523 builder
.addGlobalSymbol(ps
);
527 llvm_unreachable("Invalid symbol kind!");
531 // Check if the given symbol record was padded for alignment. If so, zero out
532 // the padding bytes and update the record prefix with the new size.
533 static void fixRecordAlignment(MutableArrayRef
<uint8_t> recordBytes
,
535 size_t alignedSize
= recordBytes
.size();
536 if (oldSize
== alignedSize
)
538 reinterpret_cast<RecordPrefix
*>(recordBytes
.data())->RecordLen
=
540 memset(recordBytes
.data() + oldSize
, 0, alignedSize
- oldSize
);
543 // Replace any record with a skip record of the same size. This is useful when
544 // we have reserved size for a symbol record, but type index remapping fails.
545 static void replaceWithSkipRecord(MutableArrayRef
<uint8_t> recordBytes
) {
546 memset(recordBytes
.data(), 0, recordBytes
.size());
547 auto *prefix
= reinterpret_cast<RecordPrefix
*>(recordBytes
.data());
548 prefix
->RecordKind
= SymbolKind::S_SKIP
;
549 prefix
->RecordLen
= recordBytes
.size() - 2;
552 // Copy the symbol record, relocate it, and fix the alignment if necessary.
553 // Rewrite type indices in the record. Replace unrecognized symbol records with
555 void PDBLinker::writeSymbolRecord(SectionChunk
*debugChunk
,
556 ArrayRef
<uint8_t> sectionContents
,
557 CVSymbol sym
, size_t alignedSize
,
558 uint32_t &nextRelocIndex
,
559 std::vector
<uint8_t> &storage
) {
560 // Allocate space for the new record at the end of the storage.
561 storage
.resize(storage
.size() + alignedSize
);
562 auto recordBytes
= MutableArrayRef
<uint8_t>(storage
).take_back(alignedSize
);
564 // Copy the symbol record and relocate it.
565 debugChunk
->writeAndRelocateSubsection(sectionContents
, sym
.data(),
566 nextRelocIndex
, recordBytes
.data());
567 fixRecordAlignment(recordBytes
, sym
.length());
569 // Re-map all the type index references.
570 TpiSource
*source
= debugChunk
->file
->debugTypesObj
;
571 if (!source
->remapTypesInSymbolRecord(recordBytes
)) {
572 log("ignoring unknown symbol record with kind 0x" + utohexstr(sym
.kind()));
573 replaceWithSkipRecord(recordBytes
);
576 // An object file may have S_xxx_ID symbols, but these get converted to
577 // "real" symbols in a PDB.
578 translateIdSymbols(recordBytes
, source
);
581 void PDBLinker::analyzeSymbolSubsection(
582 SectionChunk
*debugChunk
, uint32_t &moduleSymOffset
,
583 uint32_t &nextRelocIndex
, std::vector
<StringTableFixup
> &stringTableFixups
,
584 BinaryStreamRef symData
) {
585 ObjFile
*file
= debugChunk
->file
;
586 uint32_t moduleSymStart
= moduleSymOffset
;
588 uint32_t scopeLevel
= 0;
589 std::vector
<uint8_t> storage
;
590 ArrayRef
<uint8_t> sectionContents
= debugChunk
->getContents();
592 ArrayRef
<uint8_t> symsBuffer
;
593 cantFail(symData
.readBytes(0, symData
.getLength(), symsBuffer
));
595 if (symsBuffer
.empty())
596 warn("empty symbols subsection in " + file
->getName());
598 Error ec
= forEachCodeViewRecord
<CVSymbol
>(
599 symsBuffer
, [&](CVSymbol sym
) -> llvm::Error
{
600 // Track the current scope.
601 if (symbolOpensScope(sym
.kind()))
603 else if (symbolEndsScope(sym
.kind()))
606 uint32_t alignedSize
=
607 alignTo(sym
.length(), alignOf(CodeViewContainer::Pdb
));
609 // Copy global records. Some global records (mainly procedures)
610 // reference the current offset into the module stream.
611 if (symbolGoesInGlobalsStream(sym
, scopeLevel
)) {
613 writeSymbolRecord(debugChunk
, sectionContents
, sym
, alignedSize
,
614 nextRelocIndex
, storage
);
615 addGlobalSymbol(builder
.getGsiBuilder(),
616 file
->moduleDBI
->getModuleIndex(), moduleSymOffset
,
621 // Update the module stream offset and record any string table index
622 // references. There are very few of these and they will be rewritten
623 // later during PDB writing.
624 if (symbolGoesInModuleStream(sym
, scopeLevel
)) {
625 recordStringTableReferences(sym
, moduleSymOffset
, stringTableFixups
);
626 moduleSymOffset
+= alignedSize
;
630 return Error::success();
633 // If we encountered corrupt records, ignore the whole subsection. If we wrote
634 // any partial records, undo that. For globals, we just keep what we have and
637 warn("corrupt symbol records in " + file
->getName());
638 moduleSymOffset
= moduleSymStart
;
639 consumeError(std::move(ec
));
643 Error
PDBLinker::writeAllModuleSymbolRecords(ObjFile
*file
,
644 BinaryStreamWriter
&writer
) {
645 ExitOnError exitOnErr
;
646 std::vector
<uint8_t> storage
;
647 SmallVector
<uint32_t, 4> scopes
;
649 // Visit all live .debug$S sections a second time, and write them to the PDB.
650 for (SectionChunk
*debugChunk
: file
->getDebugChunks()) {
651 if (!debugChunk
->live
|| debugChunk
->getSize() == 0 ||
652 debugChunk
->getSectionName() != ".debug$S")
655 ArrayRef
<uint8_t> sectionContents
= debugChunk
->getContents();
657 SectionChunk::consumeDebugMagic(sectionContents
, ".debug$S");
658 DebugSubsectionArray subsections
;
659 BinaryStreamReader
reader(contents
, llvm::endianness::little
);
660 exitOnErr(reader
.readArray(subsections
, contents
.size()));
662 uint32_t nextRelocIndex
= 0;
663 for (const DebugSubsectionRecord
&ss
: subsections
) {
664 if (ss
.kind() != DebugSubsectionKind::Symbols
)
667 uint32_t moduleSymStart
= writer
.getOffset();
670 ArrayRef
<uint8_t> symsBuffer
;
671 BinaryStreamRef sr
= ss
.getRecordData();
672 cantFail(sr
.readBytes(0, sr
.getLength(), symsBuffer
));
673 auto ec
= forEachCodeViewRecord
<CVSymbol
>(
674 symsBuffer
, [&](CVSymbol sym
) -> llvm::Error
{
675 // Track the current scope. Only update records in the postmerge
677 if (symbolOpensScope(sym
.kind()))
678 scopeStackOpen(scopes
, storage
);
679 else if (symbolEndsScope(sym
.kind()))
680 scopeStackClose(scopes
, storage
, moduleSymStart
, file
);
682 // Copy, relocate, and rewrite each module symbol.
683 if (symbolGoesInModuleStream(sym
, scopes
.size())) {
684 uint32_t alignedSize
=
685 alignTo(sym
.length(), alignOf(CodeViewContainer::Pdb
));
686 writeSymbolRecord(debugChunk
, sectionContents
, sym
, alignedSize
,
687 nextRelocIndex
, storage
);
689 return Error::success();
692 // If we encounter corrupt records in the second pass, ignore them. We
693 // already warned about them in the first analysis pass.
695 consumeError(std::move(ec
));
699 // Writing bytes has a very high overhead, so write the entire subsection
701 // TODO: Consider buffering symbols for the entire object file to reduce
702 // overhead even further.
703 if (Error e
= writer
.writeBytes(storage
))
708 return Error::success();
711 Error
PDBLinker::commitSymbolsForObject(void *ctx
, void *obj
,
712 BinaryStreamWriter
&writer
) {
713 return static_cast<PDBLinker
*>(ctx
)->writeAllModuleSymbolRecords(
714 static_cast<ObjFile
*>(obj
), writer
);
717 static pdb::SectionContrib
createSectionContrib(COFFLinkerContext
&ctx
,
718 const Chunk
*c
, uint32_t modi
) {
719 OutputSection
*os
= c
? ctx
.getOutputSection(c
) : nullptr;
720 pdb::SectionContrib sc
;
721 memset(&sc
, 0, sizeof(sc
));
722 sc
.ISect
= os
? os
->sectionIndex
: llvm::pdb::kInvalidStreamIndex
;
723 sc
.Off
= c
&& os
? c
->getRVA() - os
->getRVA() : 0;
724 sc
.Size
= c
? c
->getSize() : -1;
725 if (auto *secChunk
= dyn_cast_or_null
<SectionChunk
>(c
)) {
726 sc
.Characteristics
= secChunk
->header
->Characteristics
;
727 sc
.Imod
= secChunk
->file
->moduleDBI
->getModuleIndex();
728 ArrayRef
<uint8_t> contents
= secChunk
->getContents();
730 crc
.update(contents
);
731 sc
.DataCrc
= crc
.getCRC();
733 sc
.Characteristics
= os
? os
->header
.Characteristics
: 0;
736 sc
.RelocCrc
= 0; // FIXME
742 translateStringTableIndex(uint32_t objIndex
,
743 const DebugStringTableSubsectionRef
&objStrTable
,
744 DebugStringTableSubsection
&pdbStrTable
) {
745 auto expectedString
= objStrTable
.getString(objIndex
);
746 if (!expectedString
) {
747 warn("Invalid string table reference");
748 consumeError(expectedString
.takeError());
752 return pdbStrTable
.insert(*expectedString
);
755 void DebugSHandler::handleDebugS(SectionChunk
*debugChunk
) {
756 // Note that we are processing the *unrelocated* section contents. They will
757 // be relocated later during PDB writing.
758 ArrayRef
<uint8_t> contents
= debugChunk
->getContents();
759 contents
= SectionChunk::consumeDebugMagic(contents
, ".debug$S");
760 DebugSubsectionArray subsections
;
761 BinaryStreamReader
reader(contents
, llvm::endianness::little
);
762 ExitOnError exitOnErr
;
763 exitOnErr(reader
.readArray(subsections
, contents
.size()));
764 debugChunk
->sortRelocations();
766 // Reset the relocation index, since this is a new section.
769 for (const DebugSubsectionRecord
&ss
: subsections
) {
770 // Ignore subsections with the 'ignore' bit. Some versions of the Visual C++
771 // runtime have subsections with this bit set.
772 if (uint32_t(ss
.kind()) & codeview::SubsectionIgnoreFlag
)
776 case DebugSubsectionKind::StringTable
: {
777 assert(!cvStrTab
.valid() &&
778 "Encountered multiple string table subsections!");
779 exitOnErr(cvStrTab
.initialize(ss
.getRecordData()));
782 case DebugSubsectionKind::FileChecksums
:
783 assert(!checksums
.valid() &&
784 "Encountered multiple checksum subsections!");
785 exitOnErr(checksums
.initialize(ss
.getRecordData()));
787 case DebugSubsectionKind::Lines
:
788 case DebugSubsectionKind::InlineeLines
:
789 addUnrelocatedSubsection(debugChunk
, ss
);
791 case DebugSubsectionKind::FrameData
:
792 addFrameDataSubsection(debugChunk
, ss
);
794 case DebugSubsectionKind::Symbols
:
795 linker
.analyzeSymbolSubsection(debugChunk
, moduleStreamSize
,
796 nextRelocIndex
, stringTableFixups
,
800 case DebugSubsectionKind::CrossScopeImports
:
801 case DebugSubsectionKind::CrossScopeExports
:
802 // These appear to relate to cross-module optimization, so we might use
803 // these for ThinLTO.
806 case DebugSubsectionKind::ILLines
:
807 case DebugSubsectionKind::FuncMDTokenMap
:
808 case DebugSubsectionKind::TypeMDTokenMap
:
809 case DebugSubsectionKind::MergedAssemblyInput
:
810 // These appear to relate to .Net assembly info.
813 case DebugSubsectionKind::CoffSymbolRVA
:
814 // Unclear what this is for.
817 case DebugSubsectionKind::XfgHashType
:
818 case DebugSubsectionKind::XfgHashVirtual
:
822 warn("ignoring unknown debug$S subsection kind 0x" +
823 utohexstr(uint32_t(ss
.kind())) + " in file " + toString(&file
));
829 void DebugSHandler::advanceRelocIndex(SectionChunk
*sc
,
830 ArrayRef
<uint8_t> subsec
) {
831 ptrdiff_t vaBegin
= subsec
.data() - sc
->getContents().data();
833 auto relocs
= sc
->getRelocs();
834 for (; nextRelocIndex
< relocs
.size(); ++nextRelocIndex
) {
835 if (relocs
[nextRelocIndex
].VirtualAddress
>= (uint32_t)vaBegin
)
841 /// Wrapper class for unrelocated line and inlinee line subsections, which
842 /// require only relocation and type index remapping to add to the PDB.
843 class UnrelocatedDebugSubsection
: public DebugSubsection
{
845 UnrelocatedDebugSubsection(DebugSubsectionKind k
, SectionChunk
*debugChunk
,
846 ArrayRef
<uint8_t> subsec
, uint32_t relocIndex
)
847 : DebugSubsection(k
), debugChunk(debugChunk
), subsec(subsec
),
848 relocIndex(relocIndex
) {}
850 Error
commit(BinaryStreamWriter
&writer
) const override
;
851 uint32_t calculateSerializedSize() const override
{ return subsec
.size(); }
853 SectionChunk
*debugChunk
;
854 ArrayRef
<uint8_t> subsec
;
859 Error
UnrelocatedDebugSubsection::commit(BinaryStreamWriter
&writer
) const {
860 std::vector
<uint8_t> relocatedBytes(subsec
.size());
861 uint32_t tmpRelocIndex
= relocIndex
;
862 debugChunk
->writeAndRelocateSubsection(debugChunk
->getContents(), subsec
,
863 tmpRelocIndex
, relocatedBytes
.data());
865 // Remap type indices in inlinee line records in place. Skip the remapping if
866 // there is no type source info.
867 if (kind() == DebugSubsectionKind::InlineeLines
&&
868 debugChunk
->file
->debugTypesObj
) {
869 TpiSource
*source
= debugChunk
->file
->debugTypesObj
;
870 DebugInlineeLinesSubsectionRef inlineeLines
;
871 BinaryStreamReader
storageReader(relocatedBytes
, llvm::endianness::little
);
872 ExitOnError exitOnErr
;
873 exitOnErr(inlineeLines
.initialize(storageReader
));
874 for (const InlineeSourceLine
&line
: inlineeLines
) {
875 TypeIndex
&inlinee
= *const_cast<TypeIndex
*>(&line
.Header
->Inlinee
);
876 if (!source
->remapTypeIndex(inlinee
, TiRefKind::IndexRef
)) {
877 log("bad inlinee line record in " + debugChunk
->file
->getName() +
878 " with bad inlinee index 0x" + utohexstr(inlinee
.getIndex()));
883 return writer
.writeBytes(relocatedBytes
);
886 void DebugSHandler::addUnrelocatedSubsection(SectionChunk
*debugChunk
,
887 const DebugSubsectionRecord
&ss
) {
888 ArrayRef
<uint8_t> subsec
;
889 BinaryStreamRef sr
= ss
.getRecordData();
890 cantFail(sr
.readBytes(0, sr
.getLength(), subsec
));
891 advanceRelocIndex(debugChunk
, subsec
);
892 file
.moduleDBI
->addDebugSubsection(
893 std::make_shared
<UnrelocatedDebugSubsection
>(ss
.kind(), debugChunk
,
894 subsec
, nextRelocIndex
));
897 void DebugSHandler::addFrameDataSubsection(SectionChunk
*debugChunk
,
898 const DebugSubsectionRecord
&ss
) {
899 // We need to re-write string table indices here, so save off all
900 // frame data subsections until we've processed the entire list of
901 // subsections so that we can be sure we have the string table.
902 ArrayRef
<uint8_t> subsec
;
903 BinaryStreamRef sr
= ss
.getRecordData();
904 cantFail(sr
.readBytes(0, sr
.getLength(), subsec
));
905 advanceRelocIndex(debugChunk
, subsec
);
906 frameDataSubsecs
.push_back({debugChunk
, subsec
, nextRelocIndex
});
909 static Expected
<StringRef
>
910 getFileName(const DebugStringTableSubsectionRef
&strings
,
911 const DebugChecksumsSubsectionRef
&checksums
, uint32_t fileID
) {
912 auto iter
= checksums
.getArray().at(fileID
);
913 if (iter
== checksums
.getArray().end())
914 return make_error
<CodeViewError
>(cv_error_code::no_records
);
915 uint32_t offset
= iter
->FileNameOffset
;
916 return strings
.getString(offset
);
919 void DebugSHandler::finish() {
920 pdb::DbiStreamBuilder
&dbiBuilder
= linker
.builder
.getDbiBuilder();
922 // If we found any symbol records for the module symbol stream, defer them.
923 if (moduleStreamSize
> kSymbolStreamMagicSize
)
924 file
.moduleDBI
->addUnmergedSymbols(&file
, moduleStreamSize
-
925 kSymbolStreamMagicSize
);
927 // We should have seen all debug subsections across the entire object file now
928 // which means that if a StringTable subsection and Checksums subsection were
929 // present, now is the time to handle them.
930 if (!cvStrTab
.valid()) {
931 if (checksums
.valid())
932 fatal(".debug$S sections with a checksums subsection must also contain a "
933 "string table subsection");
935 if (!stringTableFixups
.empty())
936 warn("No StringTable subsection was encountered, but there are string "
941 ExitOnError exitOnErr
;
943 // Handle FPO data. Each subsection begins with a single image base
944 // relocation, which is then added to the RvaStart of each frame data record
945 // when it is added to the PDB. The string table indices for the FPO program
946 // must also be rewritten to use the PDB string table.
947 for (const UnrelocatedFpoData
&subsec
: frameDataSubsecs
) {
948 // Relocate the first four bytes of the subection and reinterpret them as a
949 // 32 bit little-endian integer.
950 SectionChunk
*debugChunk
= subsec
.debugChunk
;
951 ArrayRef
<uint8_t> subsecData
= subsec
.subsecData
;
952 uint32_t relocIndex
= subsec
.relocIndex
;
953 auto unrelocatedRvaStart
= subsecData
.take_front(sizeof(uint32_t));
954 uint8_t relocatedRvaStart
[sizeof(uint32_t)];
955 debugChunk
->writeAndRelocateSubsection(debugChunk
->getContents(),
956 unrelocatedRvaStart
, relocIndex
,
957 &relocatedRvaStart
[0]);
958 // Use of memcpy here avoids violating type-based aliasing rules.
959 support::ulittle32_t rvaStart
;
960 memcpy(&rvaStart
, &relocatedRvaStart
[0], sizeof(support::ulittle32_t
));
962 // Copy each frame data record, add in rvaStart, translate string table
963 // indices, and add the record to the PDB.
964 DebugFrameDataSubsectionRef fds
;
965 BinaryStreamReader
reader(subsecData
, llvm::endianness::little
);
966 exitOnErr(fds
.initialize(reader
));
967 for (codeview::FrameData fd
: fds
) {
968 fd
.RvaStart
+= rvaStart
;
970 translateStringTableIndex(fd
.FrameFunc
, cvStrTab
, linker
.pdbStrTab
);
971 dbiBuilder
.addNewFpoData(fd
);
975 // Translate the fixups and pass them off to the module builder so they will
976 // be applied during writing.
977 for (StringTableFixup
&ref
: stringTableFixups
) {
979 translateStringTableIndex(ref
.StrTabOffset
, cvStrTab
, linker
.pdbStrTab
);
981 file
.moduleDBI
->setStringTableFixups(std::move(stringTableFixups
));
983 // Make a new file checksum table that refers to offsets in the PDB-wide
984 // string table. Generally the string table subsection appears after the
985 // checksum table, so we have to do this after looping over all the
986 // subsections. The new checksum table must have the exact same layout and
987 // size as the original. Otherwise, the file references in the line and
988 // inlinee line tables will be incorrect.
989 auto newChecksums
= std::make_unique
<DebugChecksumsSubsection
>(linker
.pdbStrTab
);
990 for (const FileChecksumEntry
&fc
: checksums
) {
991 SmallString
<128> filename
=
992 exitOnErr(cvStrTab
.getString(fc
.FileNameOffset
));
993 linker
.pdbMakeAbsolute(filename
);
994 exitOnErr(dbiBuilder
.addModuleSourceFile(*file
.moduleDBI
, filename
));
995 newChecksums
->addChecksum(filename
, fc
.Kind
, fc
.Checksum
);
997 assert(checksums
.getArray().getUnderlyingStream().getLength() ==
998 newChecksums
->calculateSerializedSize() &&
999 "file checksum table must have same layout");
1001 file
.moduleDBI
->addDebugSubsection(std::move(newChecksums
));
1004 static void warnUnusable(InputFile
*f
, Error e
, bool shouldWarn
) {
1006 consumeError(std::move(e
));
1009 auto msg
= "Cannot use debug info for '" + toString(f
) + "' [LNK4099]";
1011 warn(msg
+ "\n>>> failed to load reference " + toString(std::move(e
)));
1016 // Allocate memory for a .debug$S / .debug$F section and relocate it.
1017 static ArrayRef
<uint8_t> relocateDebugChunk(SectionChunk
&debugChunk
) {
1018 uint8_t *buffer
= bAlloc().Allocate
<uint8_t>(debugChunk
.getSize());
1019 assert(debugChunk
.getOutputSectionIdx() == 0 &&
1020 "debug sections should not be in output sections");
1021 debugChunk
.writeTo(buffer
);
1022 return ArrayRef(buffer
, debugChunk
.getSize());
1025 void PDBLinker::addDebugSymbols(TpiSource
*source
) {
1026 // If this TpiSource doesn't have an object file, it must be from a type
1027 // server PDB. Type server PDBs do not contain symbols, so stop here.
1031 llvm::TimeTraceScope
timeScope("Merge symbols");
1032 ScopedTimer
t(ctx
.symbolMergingTimer
);
1033 ExitOnError exitOnErr
;
1034 pdb::DbiStreamBuilder
&dbiBuilder
= builder
.getDbiBuilder();
1035 DebugSHandler
dsh(*this, *source
->file
);
1036 // Now do all live .debug$S and .debug$F sections.
1037 for (SectionChunk
*debugChunk
: source
->file
->getDebugChunks()) {
1038 if (!debugChunk
->live
|| debugChunk
->getSize() == 0)
1041 bool isDebugS
= debugChunk
->getSectionName() == ".debug$S";
1042 bool isDebugF
= debugChunk
->getSectionName() == ".debug$F";
1043 if (!isDebugS
&& !isDebugF
)
1047 dsh
.handleDebugS(debugChunk
);
1048 } else if (isDebugF
) {
1049 // Handle old FPO data .debug$F sections. These are relatively rare.
1050 ArrayRef
<uint8_t> relocatedDebugContents
=
1051 relocateDebugChunk(*debugChunk
);
1052 FixedStreamArray
<object::FpoData
> fpoRecords
;
1053 BinaryStreamReader
reader(relocatedDebugContents
,
1054 llvm::endianness::little
);
1055 uint32_t count
= relocatedDebugContents
.size() / sizeof(object::FpoData
);
1056 exitOnErr(reader
.readArray(fpoRecords
, count
));
1058 // These are already relocated and don't refer to the string table, so we
1059 // can just copy it.
1060 for (const object::FpoData
&fd
: fpoRecords
)
1061 dbiBuilder
.addOldFpoData(fd
);
1065 // Do any post-processing now that all .debug$S sections have been processed.
1069 // Add a module descriptor for every object file. We need to put an absolute
1070 // path to the object into the PDB. If this is a plain object, we make its
1071 // path absolute. If it's an object in an archive, we make the archive path
1073 void PDBLinker::createModuleDBI(ObjFile
*file
) {
1074 pdb::DbiStreamBuilder
&dbiBuilder
= builder
.getDbiBuilder();
1075 SmallString
<128> objName
;
1076 ExitOnError exitOnErr
;
1078 bool inArchive
= !file
->parentName
.empty();
1079 objName
= inArchive
? file
->parentName
: file
->getName();
1080 pdbMakeAbsolute(objName
);
1081 StringRef modName
= inArchive
? file
->getName() : objName
.str();
1083 file
->moduleDBI
= &exitOnErr(dbiBuilder
.addModuleInfo(modName
));
1084 file
->moduleDBI
->setObjFileName(objName
);
1085 file
->moduleDBI
->setMergeSymbolsCallback(this, &commitSymbolsForObject
);
1087 ArrayRef
<Chunk
*> chunks
= file
->getChunks();
1088 uint32_t modi
= file
->moduleDBI
->getModuleIndex();
1090 for (Chunk
*c
: chunks
) {
1091 auto *secChunk
= dyn_cast
<SectionChunk
>(c
);
1092 if (!secChunk
|| !secChunk
->live
)
1094 pdb::SectionContrib sc
= createSectionContrib(ctx
, secChunk
, modi
);
1095 file
->moduleDBI
->setFirstSectionContrib(sc
);
1100 void PDBLinker::addDebug(TpiSource
*source
) {
1101 // Before we can process symbol substreams from .debug$S, we need to process
1102 // type information, file checksums, and the string table. Add type info to
1103 // the PDB first, so that we can get the map from object file type and item
1104 // indices to PDB type and item indices. If we are using ghashes, types have
1105 // already been merged.
1106 if (!ctx
.config
.debugGHashes
) {
1107 llvm::TimeTraceScope
timeScope("Merge types (Non-GHASH)");
1108 ScopedTimer
t(ctx
.typeMergingTimer
);
1109 if (Error e
= source
->mergeDebugT(&tMerger
)) {
1110 // If type merging failed, ignore the symbols.
1111 warnUnusable(source
->file
, std::move(e
),
1112 ctx
.config
.warnDebugInfoUnusable
);
1117 // If type merging failed, ignore the symbols.
1118 Error typeError
= std::move(source
->typeMergingError
);
1120 warnUnusable(source
->file
, std::move(typeError
),
1121 ctx
.config
.warnDebugInfoUnusable
);
1125 addDebugSymbols(source
);
1128 static pdb::BulkPublic
createPublic(COFFLinkerContext
&ctx
, Defined
*def
) {
1129 pdb::BulkPublic pub
;
1130 pub
.Name
= def
->getName().data();
1131 pub
.NameLen
= def
->getName().size();
1133 PublicSymFlags flags
= PublicSymFlags::None
;
1134 if (auto *d
= dyn_cast
<DefinedCOFF
>(def
)) {
1135 if (d
->getCOFFSymbol().isFunctionDefinition())
1136 flags
= PublicSymFlags::Function
;
1137 } else if (isa
<DefinedImportThunk
>(def
)) {
1138 flags
= PublicSymFlags::Function
;
1140 pub
.setFlags(flags
);
1142 OutputSection
*os
= ctx
.getOutputSection(def
->getChunk());
1143 assert(os
&& "all publics should be in final image");
1144 pub
.Offset
= def
->getRVA() - os
->getRVA();
1145 pub
.Segment
= os
->sectionIndex
;
1149 // Add all object files to the PDB. Merge .debug$T sections into IpiData and
1151 void PDBLinker::addObjectsToPDB() {
1153 llvm::TimeTraceScope
timeScope("Add objects to PDB");
1154 ScopedTimer
t1(ctx
.addObjectsTimer
);
1156 // Create module descriptors
1157 for (ObjFile
*obj
: ctx
.objFileInstances
)
1158 createModuleDBI(obj
);
1160 // Reorder dependency type sources to come first.
1161 tMerger
.sortDependencies();
1163 // Merge type information from input files using global type hashing.
1164 if (ctx
.config
.debugGHashes
)
1165 tMerger
.mergeTypesWithGHash();
1167 // Merge dependencies and then regular objects.
1169 llvm::TimeTraceScope
timeScope("Merge debug info (dependencies)");
1170 for (TpiSource
*source
: tMerger
.dependencySources
)
1174 llvm::TimeTraceScope
timeScope("Merge debug info (objects)");
1175 for (TpiSource
*source
: tMerger
.objectSources
)
1179 builder
.getStringTableBuilder().setStrings(pdbStrTab
);
1182 // Construct TPI and IPI stream contents.
1184 llvm::TimeTraceScope
timeScope("TPI/IPI stream layout");
1185 ScopedTimer
t2(ctx
.tpiStreamLayoutTimer
);
1187 // Collect all the merged types.
1188 if (ctx
.config
.debugGHashes
) {
1189 addGHashTypeInfo(ctx
, builder
);
1191 addTypeInfo(builder
.getTpiBuilder(), tMerger
.getTypeTable());
1192 addTypeInfo(builder
.getIpiBuilder(), tMerger
.getIDTable());
1196 if (ctx
.config
.showSummary
) {
1197 for (TpiSource
*source
: ctx
.tpiSourceList
) {
1198 nbTypeRecords
+= source
->nbTypeRecords
;
1199 nbTypeRecordsBytes
+= source
->nbTypeRecordsBytes
;
1204 void PDBLinker::addPublicsToPDB() {
1205 llvm::TimeTraceScope
timeScope("Publics layout");
1206 ScopedTimer
t3(ctx
.publicsLayoutTimer
);
1207 // Compute the public symbols.
1208 auto &gsiBuilder
= builder
.getGsiBuilder();
1209 std::vector
<pdb::BulkPublic
> publics
;
1210 ctx
.symtab
.forEachSymbol([&publics
, this](Symbol
*s
) {
1211 // Only emit external, defined, live symbols that have a chunk. Static,
1212 // non-external symbols do not appear in the symbol table.
1213 auto *def
= dyn_cast
<Defined
>(s
);
1214 if (def
&& def
->isLive() && def
->getChunk()) {
1215 // Don't emit a public symbol for coverage data symbols. LLVM code
1216 // coverage (and PGO) create a __profd_ and __profc_ symbol for every
1217 // function. C++ mangled names are long, and tend to dominate symbol size.
1218 // Including these names triples the size of the public stream, which
1219 // results in bloated PDB files. These symbols generally are not helpful
1220 // for debugging, so suppress them.
1221 StringRef name
= def
->getName();
1222 if (name
.data()[0] == '_' && name
.data()[1] == '_') {
1223 // Drop the '_' prefix for x86.
1224 if (ctx
.config
.machine
== I386
)
1225 name
= name
.drop_front(1);
1226 if (name
.starts_with("__profd_") || name
.starts_with("__profc_") ||
1227 name
.starts_with("__covrec_")) {
1231 publics
.push_back(createPublic(ctx
, def
));
1235 if (!publics
.empty()) {
1236 publicSymbols
= publics
.size();
1237 gsiBuilder
.addPublicSymbols(std::move(publics
));
1241 void PDBLinker::printStats() {
1242 if (!ctx
.config
.showSummary
)
1245 SmallString
<256> buffer
;
1246 raw_svector_ostream
stream(buffer
);
1248 stream
<< center_justify("Summary", 80) << '\n'
1249 << std::string(80, '-') << '\n';
1251 auto print
= [&](uint64_t v
, StringRef s
) {
1252 stream
<< format_decimal(v
, 15) << " " << s
<< '\n';
1255 print(ctx
.objFileInstances
.size(),
1256 "Input OBJ files (expanded from all cmd-line inputs)");
1257 print(ctx
.typeServerSourceMappings
.size(), "PDB type server dependencies");
1258 print(ctx
.precompSourceMappings
.size(), "Precomp OBJ dependencies");
1259 print(nbTypeRecords
, "Input type records");
1260 print(nbTypeRecordsBytes
, "Input type records bytes");
1261 print(builder
.getTpiBuilder().getRecordCount(), "Merged TPI records");
1262 print(builder
.getIpiBuilder().getRecordCount(), "Merged IPI records");
1263 print(pdbStrTab
.size(), "Output PDB strings");
1264 print(globalSymbols
, "Global symbol records");
1265 print(moduleSymbols
, "Module symbol records");
1266 print(publicSymbols
, "Public symbol records");
1268 auto printLargeInputTypeRecs
= [&](StringRef name
,
1269 ArrayRef
<uint32_t> recCounts
,
1270 TypeCollection
&records
) {
1271 // Figure out which type indices were responsible for the most duplicate
1272 // bytes in the input files. These should be frequently emitted LF_CLASS and
1273 // LF_FIELDLIST records.
1274 struct TypeSizeInfo
{
1277 TypeIndex typeIndex
;
1278 uint64_t totalInputSize() const { return uint64_t(dupCount
) * typeSize
; }
1279 bool operator<(const TypeSizeInfo
&rhs
) const {
1280 if (totalInputSize() == rhs
.totalInputSize())
1281 return typeIndex
< rhs
.typeIndex
;
1282 return totalInputSize() < rhs
.totalInputSize();
1285 SmallVector
<TypeSizeInfo
, 0> tsis
;
1286 for (auto e
: enumerate(recCounts
)) {
1287 TypeIndex typeIndex
= TypeIndex::fromArrayIndex(e
.index());
1288 uint32_t typeSize
= records
.getType(typeIndex
).length();
1289 uint32_t dupCount
= e
.value();
1290 tsis
.push_back({typeSize
, dupCount
, typeIndex
});
1293 if (!tsis
.empty()) {
1294 stream
<< "\nTop 10 types responsible for the most " << name
1296 stream
<< " index total bytes count size\n";
1299 for (const auto &tsi
: reverse(tsis
)) {
1300 stream
<< formatv(" {0,10:X}: {1,14:N} = {2,5:N} * {3,6:N}\n",
1301 tsi
.typeIndex
.getIndex(), tsi
.totalInputSize(),
1302 tsi
.dupCount
, tsi
.typeSize
);
1307 << "Run llvm-pdbutil to print details about a particular record:\n";
1308 stream
<< formatv("llvm-pdbutil dump -{0}s -{0}-index {1:X} {2}\n",
1309 (name
== "TPI" ? "type" : "id"),
1310 tsis
.back().typeIndex
.getIndex(), ctx
.config
.pdbPath
);
1314 if (!ctx
.config
.debugGHashes
) {
1315 // FIXME: Reimplement for ghash.
1316 printLargeInputTypeRecs("TPI", tMerger
.tpiCounts
, tMerger
.getTypeTable());
1317 printLargeInputTypeRecs("IPI", tMerger
.ipiCounts
, tMerger
.getIDTable());
1323 void PDBLinker::addNatvisFiles() {
1324 llvm::TimeTraceScope
timeScope("Natvis files");
1325 for (StringRef file
: ctx
.config
.natvisFiles
) {
1326 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> dataOrErr
=
1327 MemoryBuffer::getFile(file
);
1329 warn("Cannot open input file: " + file
);
1332 std::unique_ptr
<MemoryBuffer
> data
= std::move(*dataOrErr
);
1334 // Can't use takeBuffer() here since addInjectedSource() takes ownership.
1336 ctx
.driver
.tar
->append(relativeToRoot(data
->getBufferIdentifier()),
1339 builder
.addInjectedSource(file
, std::move(data
));
1343 void PDBLinker::addNamedStreams() {
1344 llvm::TimeTraceScope
timeScope("Named streams");
1345 ExitOnError exitOnErr
;
1346 for (const auto &streamFile
: ctx
.config
.namedStreams
) {
1347 const StringRef stream
= streamFile
.getKey(), file
= streamFile
.getValue();
1348 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> dataOrErr
=
1349 MemoryBuffer::getFile(file
);
1351 warn("Cannot open input file: " + file
);
1354 std::unique_ptr
<MemoryBuffer
> data
= std::move(*dataOrErr
);
1355 exitOnErr(builder
.addNamedStream(stream
, data
->getBuffer()));
1356 ctx
.driver
.takeBuffer(std::move(data
));
1360 static codeview::CPUType
toCodeViewMachine(COFF::MachineTypes machine
) {
1362 case COFF::IMAGE_FILE_MACHINE_AMD64
:
1363 return codeview::CPUType::X64
;
1364 case COFF::IMAGE_FILE_MACHINE_ARM
:
1365 return codeview::CPUType::ARM7
;
1366 case COFF::IMAGE_FILE_MACHINE_ARM64
:
1367 return codeview::CPUType::ARM64
;
1368 case COFF::IMAGE_FILE_MACHINE_ARM64EC
:
1369 return codeview::CPUType::ARM64EC
;
1370 case COFF::IMAGE_FILE_MACHINE_ARM64X
:
1371 return codeview::CPUType::ARM64X
;
1372 case COFF::IMAGE_FILE_MACHINE_ARMNT
:
1373 return codeview::CPUType::ARMNT
;
1374 case COFF::IMAGE_FILE_MACHINE_I386
:
1375 return codeview::CPUType::Intel80386
;
1377 llvm_unreachable("Unsupported CPU Type");
1381 // Mimic MSVC which surrounds arguments containing whitespace with quotes.
1382 // Double double-quotes are handled, so that the resulting string can be
1383 // executed again on the cmd-line.
1384 static std::string
quote(ArrayRef
<StringRef
> args
) {
1387 for (StringRef a
: args
) {
1390 bool hasWS
= a
.contains(' ');
1391 bool hasQ
= a
.contains('"');
1395 SmallVector
<StringRef
, 4> s
;
1397 r
.append(join(s
, "\"\""));
1399 r
.append(std::string(a
));
1407 static void fillLinkerVerRecord(Compile3Sym
&cs
, MachineTypes machine
) {
1408 cs
.Machine
= toCodeViewMachine(machine
);
1409 // Interestingly, if we set the string to 0.0.0.0, then when trying to view
1410 // local variables WinDbg emits an error that private symbols are not present.
1411 // By setting this to a valid MSVC linker version string, local variables are
1412 // displayed properly. As such, even though it is not representative of
1413 // LLVM's version information, we need this for compatibility.
1414 cs
.Flags
= CompileSym3Flags::None
;
1415 cs
.VersionBackendBuild
= 25019;
1416 cs
.VersionBackendMajor
= 14;
1417 cs
.VersionBackendMinor
= 10;
1418 cs
.VersionBackendQFE
= 0;
1420 // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
1421 // linker module (which is by definition a backend), so we don't need to do
1422 // anything here. Also, it seems we can use "LLVM Linker" for the linker name
1423 // without any problems. Only the backend version has to be hardcoded to a
1425 cs
.VersionFrontendBuild
= 0;
1426 cs
.VersionFrontendMajor
= 0;
1427 cs
.VersionFrontendMinor
= 0;
1428 cs
.VersionFrontendQFE
= 0;
1429 cs
.Version
= "LLVM Linker";
1430 cs
.setLanguage(SourceLanguage::Link
);
1433 void PDBLinker::addCommonLinkerModuleSymbols(
1434 StringRef path
, pdb::DbiModuleDescriptorBuilder
&mod
) {
1435 ObjNameSym
ons(SymbolRecordKind::ObjNameSym
);
1436 EnvBlockSym
ebs(SymbolRecordKind::EnvBlockSym
);
1437 Compile3Sym
cs(SymbolRecordKind::Compile3Sym
);
1439 MachineTypes machine
= ctx
.config
.machine
;
1440 // MSVC uses the ARM64X machine type for ARM64EC targets in the common linker
1442 if (isArm64EC(machine
))
1444 fillLinkerVerRecord(cs
, machine
);
1446 ons
.Name
= "* Linker *";
1449 ArrayRef
<StringRef
> args
= ArrayRef(ctx
.config
.argv
).drop_front();
1450 std::string argStr
= quote(args
);
1451 ebs
.Fields
.push_back("cwd");
1452 SmallString
<64> cwd
;
1453 if (ctx
.config
.pdbSourcePath
.empty())
1454 sys::fs::current_path(cwd
);
1456 cwd
= ctx
.config
.pdbSourcePath
;
1457 ebs
.Fields
.push_back(cwd
);
1458 ebs
.Fields
.push_back("exe");
1459 SmallString
<64> exe
= ctx
.config
.argv
[0];
1460 pdbMakeAbsolute(exe
);
1461 ebs
.Fields
.push_back(exe
);
1462 ebs
.Fields
.push_back("pdb");
1463 ebs
.Fields
.push_back(path
);
1464 ebs
.Fields
.push_back("cmd");
1465 ebs
.Fields
.push_back(argStr
);
1466 llvm::BumpPtrAllocator
&bAlloc
= lld::bAlloc();
1467 mod
.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1468 ons
, bAlloc
, CodeViewContainer::Pdb
));
1469 mod
.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1470 cs
, bAlloc
, CodeViewContainer::Pdb
));
1471 mod
.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1472 ebs
, bAlloc
, CodeViewContainer::Pdb
));
1475 static void addLinkerModuleCoffGroup(PartialSection
*sec
,
1476 pdb::DbiModuleDescriptorBuilder
&mod
,
1477 OutputSection
&os
) {
1478 // If there's a section, there's at least one chunk
1479 assert(!sec
->chunks
.empty());
1480 const Chunk
*firstChunk
= *sec
->chunks
.begin();
1481 const Chunk
*lastChunk
= *sec
->chunks
.rbegin();
1484 CoffGroupSym
cgs(SymbolRecordKind::CoffGroupSym
);
1485 cgs
.Name
= sec
->name
;
1486 cgs
.Segment
= os
.sectionIndex
;
1487 cgs
.Offset
= firstChunk
->getRVA() - os
.getRVA();
1488 cgs
.Size
= lastChunk
->getRVA() + lastChunk
->getSize() - firstChunk
->getRVA();
1489 cgs
.Characteristics
= sec
->characteristics
;
1491 // Somehow .idata sections & sections groups in the debug symbol stream have
1492 // the "write" flag set. However the section header for the corresponding
1493 // .idata section doesn't have it.
1494 if (cgs
.Name
.starts_with(".idata"))
1495 cgs
.Characteristics
|= llvm::COFF::IMAGE_SCN_MEM_WRITE
;
1497 mod
.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1498 cgs
, bAlloc(), CodeViewContainer::Pdb
));
1501 static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder
&mod
,
1502 OutputSection
&os
, bool isMinGW
) {
1503 SectionSym
sym(SymbolRecordKind::SectionSym
);
1504 sym
.Alignment
= 12; // 2^12 = 4KB
1505 sym
.Characteristics
= os
.header
.Characteristics
;
1506 sym
.Length
= os
.getVirtualSize();
1508 sym
.Rva
= os
.getRVA();
1509 sym
.SectionNumber
= os
.sectionIndex
;
1510 mod
.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1511 sym
, bAlloc(), CodeViewContainer::Pdb
));
1513 // Skip COFF groups in MinGW because it adds a significant footprint to the
1514 // PDB, due to each function being in its own section
1518 // Output COFF groups for individual chunks of this section.
1519 for (PartialSection
*sec
: os
.contribSections
) {
1520 addLinkerModuleCoffGroup(sec
, mod
, os
);
1524 // Add all import files as modules to the PDB.
1525 void PDBLinker::addImportFilesToPDB() {
1526 if (ctx
.importFileInstances
.empty())
1529 llvm::TimeTraceScope
timeScope("Import files");
1530 ExitOnError exitOnErr
;
1531 std::map
<std::string
, llvm::pdb::DbiModuleDescriptorBuilder
*> dllToModuleDbi
;
1533 for (ImportFile
*file
: ctx
.importFileInstances
) {
1537 if (!file
->thunkSym
)
1540 if (!file
->thunkSym
->isLive())
1543 std::string dll
= StringRef(file
->dllName
).lower();
1544 llvm::pdb::DbiModuleDescriptorBuilder
*&mod
= dllToModuleDbi
[dll
];
1546 pdb::DbiStreamBuilder
&dbiBuilder
= builder
.getDbiBuilder();
1547 SmallString
<128> libPath
= file
->parentName
;
1548 pdbMakeAbsolute(libPath
);
1549 sys::path::native(libPath
);
1551 // Name modules similar to MSVC's link.exe.
1552 // The first module is the simple dll filename
1553 llvm::pdb::DbiModuleDescriptorBuilder
&firstMod
=
1554 exitOnErr(dbiBuilder
.addModuleInfo(file
->dllName
));
1555 firstMod
.setObjFileName(libPath
);
1556 pdb::SectionContrib sc
=
1557 createSectionContrib(ctx
, nullptr, llvm::pdb::kInvalidStreamIndex
);
1558 firstMod
.setFirstSectionContrib(sc
);
1560 // The second module is where the import stream goes.
1561 mod
= &exitOnErr(dbiBuilder
.addModuleInfo("Import:" + file
->dllName
));
1562 mod
->setObjFileName(libPath
);
1565 DefinedImportThunk
*thunk
= cast
<DefinedImportThunk
>(file
->thunkSym
);
1566 Chunk
*thunkChunk
= thunk
->getChunk();
1567 OutputSection
*thunkOS
= ctx
.getOutputSection(thunkChunk
);
1569 ObjNameSym
ons(SymbolRecordKind::ObjNameSym
);
1570 Compile3Sym
cs(SymbolRecordKind::Compile3Sym
);
1571 Thunk32Sym
ts(SymbolRecordKind::Thunk32Sym
);
1572 ScopeEndSym
es(SymbolRecordKind::ScopeEndSym
);
1574 ons
.Name
= file
->dllName
;
1577 fillLinkerVerRecord(cs
, ctx
.config
.machine
);
1579 ts
.Name
= thunk
->getName();
1583 ts
.Thunk
= ThunkOrdinal::Standard
;
1584 ts
.Length
= thunkChunk
->getSize();
1585 ts
.Segment
= thunkOS
->sectionIndex
;
1586 ts
.Offset
= thunkChunk
->getRVA() - thunkOS
->getRVA();
1588 llvm::BumpPtrAllocator
&bAlloc
= lld::bAlloc();
1589 mod
->addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1590 ons
, bAlloc
, CodeViewContainer::Pdb
));
1591 mod
->addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1592 cs
, bAlloc
, CodeViewContainer::Pdb
));
1594 CVSymbol newSym
= codeview::SymbolSerializer::writeOneSymbol(
1595 ts
, bAlloc
, CodeViewContainer::Pdb
);
1597 // Write ptrEnd for the S_THUNK32.
1598 ScopeRecord
*thunkSymScope
=
1599 getSymbolScopeFields(const_cast<uint8_t *>(newSym
.data().data()));
1601 mod
->addSymbol(newSym
);
1603 newSym
= codeview::SymbolSerializer::writeOneSymbol(es
, bAlloc
,
1604 CodeViewContainer::Pdb
);
1605 thunkSymScope
->ptrEnd
= mod
->getNextSymbolOffset();
1607 mod
->addSymbol(newSym
);
1609 pdb::SectionContrib sc
=
1610 createSectionContrib(ctx
, thunk
->getChunk(), mod
->getModuleIndex());
1611 mod
->setFirstSectionContrib(sc
);
1615 // Creates a PDB file.
1616 void lld::coff::createPDB(COFFLinkerContext
&ctx
,
1617 ArrayRef
<uint8_t> sectionTable
,
1618 llvm::codeview::DebugInfo
*buildId
) {
1619 llvm::TimeTraceScope
timeScope("PDB file");
1620 ScopedTimer
t1(ctx
.totalPdbLinkTimer
);
1624 pdb
.initialize(buildId
);
1625 pdb
.addObjectsToPDB();
1626 pdb
.addImportFilesToPDB();
1627 pdb
.addSections(sectionTable
);
1628 pdb
.addNatvisFiles();
1629 pdb
.addNamedStreams();
1630 pdb
.addPublicsToPDB();
1633 llvm::TimeTraceScope
timeScope("Commit PDB file to disk");
1634 ScopedTimer
t2(ctx
.diskCommitTimer
);
1635 codeview::GUID guid
;
1637 memcpy(&buildId
->PDB70
.Signature
, &guid
, 16);
1643 // Manually start this profile point to measure ~PDBLinker().
1644 if (getTimeTraceProfilerInstance() != nullptr)
1645 timeTraceProfilerBegin("PDBLinker destructor", StringRef(""));
1647 // Manually end this profile point to measure ~PDBLinker().
1648 if (getTimeTraceProfilerInstance() != nullptr)
1649 timeTraceProfilerEnd();
1652 void PDBLinker::initialize(llvm::codeview::DebugInfo
*buildId
) {
1653 ExitOnError exitOnErr
;
1654 exitOnErr(builder
.initialize(ctx
.config
.pdbPageSize
));
1656 buildId
->Signature
.CVSignature
= OMF::Signature::PDB70
;
1657 // Signature is set to a hash of the PDB contents when the PDB is done.
1658 memset(buildId
->PDB70
.Signature
, 0, 16);
1659 buildId
->PDB70
.Age
= 1;
1661 // Create streams in MSF for predefined streams, namely
1662 // PDB, TPI, DBI and IPI.
1663 for (int i
= 0; i
< (int)pdb::kSpecialStreamCount
; ++i
)
1664 exitOnErr(builder
.getMsfBuilder().addStream(0));
1666 // Add an Info stream.
1667 auto &infoBuilder
= builder
.getInfoBuilder();
1668 infoBuilder
.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70
);
1669 infoBuilder
.setHashPDBContentsToGUID(true);
1671 // Add an empty DBI stream.
1672 pdb::DbiStreamBuilder
&dbiBuilder
= builder
.getDbiBuilder();
1673 dbiBuilder
.setAge(buildId
->PDB70
.Age
);
1674 dbiBuilder
.setVersionHeader(pdb::PdbDbiV70
);
1675 dbiBuilder
.setMachineType(ctx
.config
.machine
);
1676 // Technically we are not link.exe 14.11, but there are known cases where
1677 // debugging tools on Windows expect Microsoft-specific version numbers or
1678 // they fail to work at all. Since we know we produce PDBs that are
1679 // compatible with LINK 14.11, we set that version number here.
1680 dbiBuilder
.setBuildNumber(14, 11);
1683 void PDBLinker::addSections(ArrayRef
<uint8_t> sectionTable
) {
1684 llvm::TimeTraceScope
timeScope("PDB output sections");
1685 ExitOnError exitOnErr
;
1686 // It's not entirely clear what this is, but the * Linker * module uses it.
1687 pdb::DbiStreamBuilder
&dbiBuilder
= builder
.getDbiBuilder();
1688 nativePath
= ctx
.config
.pdbPath
;
1689 pdbMakeAbsolute(nativePath
);
1690 uint32_t pdbFilePathNI
= dbiBuilder
.addECName(nativePath
);
1691 auto &linkerModule
= exitOnErr(dbiBuilder
.addModuleInfo("* Linker *"));
1692 linkerModule
.setPdbFilePathNI(pdbFilePathNI
);
1693 addCommonLinkerModuleSymbols(nativePath
, linkerModule
);
1695 // Add section contributions. They must be ordered by ascending RVA.
1696 for (OutputSection
*os
: ctx
.outputSections
) {
1697 addLinkerModuleSectionSymbol(linkerModule
, *os
, ctx
.config
.mingw
);
1698 for (Chunk
*c
: os
->chunks
) {
1699 pdb::SectionContrib sc
=
1700 createSectionContrib(ctx
, c
, linkerModule
.getModuleIndex());
1701 builder
.getDbiBuilder().addSectionContrib(sc
);
1705 // The * Linker * first section contrib is only used along with /INCREMENTAL,
1706 // to provide trampolines thunks for incremental function patching. Set this
1707 // as "unused" because LLD doesn't support /INCREMENTAL link.
1708 pdb::SectionContrib sc
=
1709 createSectionContrib(ctx
, nullptr, llvm::pdb::kInvalidStreamIndex
);
1710 linkerModule
.setFirstSectionContrib(sc
);
1712 // Add Section Map stream.
1713 ArrayRef
<object::coff_section
> sections
= {
1714 (const object::coff_section
*)sectionTable
.data(),
1715 sectionTable
.size() / sizeof(object::coff_section
)};
1716 dbiBuilder
.createSectionMap(sections
);
1718 // Add COFF section header stream.
1720 dbiBuilder
.addDbgStream(pdb::DbgHeaderType::SectionHdr
, sectionTable
));
1723 void PDBLinker::commit(codeview::GUID
*guid
) {
1724 // Print an error and continue if PDB writing fails. This is done mainly so
1725 // the user can see the output of /time and /summary, which is very helpful
1726 // when trying to figure out why a PDB file is too large.
1727 if (Error e
= builder
.commit(ctx
.config
.pdbPath
, guid
)) {
1728 e
= handleErrors(std::move(e
),
1729 [](const llvm::msf::MSFError
&me
) {
1730 error(me
.message());
1731 if (me
.isPageOverflow())
1732 error("try setting a larger /pdbpagesize");
1734 checkError(std::move(e
));
1735 error("failed to write PDB file " + Twine(ctx
.config
.pdbPath
));
1739 static uint32_t getSecrelReloc(Triple::ArchType arch
) {
1741 case Triple::x86_64
:
1742 return COFF::IMAGE_REL_AMD64_SECREL
;
1744 return COFF::IMAGE_REL_I386_SECREL
;
1746 return COFF::IMAGE_REL_ARM_SECREL
;
1747 case Triple::aarch64
:
1748 return COFF::IMAGE_REL_ARM64_SECREL
;
1750 llvm_unreachable("unknown machine type");
1754 // Try to find a line table for the given offset Addr into the given chunk C.
1755 // If a line table was found, the line table, the string and checksum tables
1756 // that are used to interpret the line table, and the offset of Addr in the line
1757 // table are stored in the output arguments. Returns whether a line table was
1759 static bool findLineTable(const SectionChunk
*c
, uint32_t addr
,
1760 DebugStringTableSubsectionRef
&cvStrTab
,
1761 DebugChecksumsSubsectionRef
&checksums
,
1762 DebugLinesSubsectionRef
&lines
,
1763 uint32_t &offsetInLinetable
) {
1764 ExitOnError exitOnErr
;
1765 const uint32_t secrelReloc
= getSecrelReloc(c
->getArch());
1767 for (SectionChunk
*dbgC
: c
->file
->getDebugChunks()) {
1768 if (dbgC
->getSectionName() != ".debug$S")
1771 // Build a mapping of SECREL relocations in dbgC that refer to `c`.
1772 DenseMap
<uint32_t, uint32_t> secrels
;
1773 for (const coff_relocation
&r
: dbgC
->getRelocs()) {
1774 if (r
.Type
!= secrelReloc
)
1777 if (auto *s
= dyn_cast_or_null
<DefinedRegular
>(
1778 c
->file
->getSymbols()[r
.SymbolTableIndex
]))
1779 if (s
->getChunk() == c
)
1780 secrels
[r
.VirtualAddress
] = s
->getValue();
1783 ArrayRef
<uint8_t> contents
=
1784 SectionChunk::consumeDebugMagic(dbgC
->getContents(), ".debug$S");
1785 DebugSubsectionArray subsections
;
1786 BinaryStreamReader
reader(contents
, llvm::endianness::little
);
1787 exitOnErr(reader
.readArray(subsections
, contents
.size()));
1789 for (const DebugSubsectionRecord
&ss
: subsections
) {
1790 switch (ss
.kind()) {
1791 case DebugSubsectionKind::StringTable
: {
1792 assert(!cvStrTab
.valid() &&
1793 "Encountered multiple string table subsections!");
1794 exitOnErr(cvStrTab
.initialize(ss
.getRecordData()));
1797 case DebugSubsectionKind::FileChecksums
:
1798 assert(!checksums
.valid() &&
1799 "Encountered multiple checksum subsections!");
1800 exitOnErr(checksums
.initialize(ss
.getRecordData()));
1802 case DebugSubsectionKind::Lines
: {
1803 ArrayRef
<uint8_t> bytes
;
1804 auto ref
= ss
.getRecordData();
1805 exitOnErr(ref
.readLongestContiguousChunk(0, bytes
));
1806 size_t offsetInDbgC
= bytes
.data() - dbgC
->getContents().data();
1808 // Check whether this line table refers to C.
1809 auto i
= secrels
.find(offsetInDbgC
);
1810 if (i
== secrels
.end())
1813 // Check whether this line table covers Addr in C.
1814 DebugLinesSubsectionRef linesTmp
;
1815 exitOnErr(linesTmp
.initialize(BinaryStreamReader(ref
)));
1816 uint32_t offsetInC
= i
->second
+ linesTmp
.header()->RelocOffset
;
1817 if (addr
< offsetInC
|| addr
>= offsetInC
+ linesTmp
.header()->CodeSize
)
1820 assert(!lines
.header() &&
1821 "Encountered multiple line tables for function!");
1822 exitOnErr(lines
.initialize(BinaryStreamReader(ref
)));
1823 offsetInLinetable
= addr
- offsetInC
;
1830 if (cvStrTab
.valid() && checksums
.valid() && lines
.header())
1838 // Use CodeView line tables to resolve a file and line number for the given
1839 // offset into the given chunk and return them, or std::nullopt if a line table
1841 std::optional
<std::pair
<StringRef
, uint32_t>>
1842 lld::coff::getFileLineCodeView(const SectionChunk
*c
, uint32_t addr
) {
1843 ExitOnError exitOnErr
;
1845 DebugStringTableSubsectionRef cvStrTab
;
1846 DebugChecksumsSubsectionRef checksums
;
1847 DebugLinesSubsectionRef lines
;
1848 uint32_t offsetInLinetable
;
1850 if (!findLineTable(c
, addr
, cvStrTab
, checksums
, lines
, offsetInLinetable
))
1851 return std::nullopt
;
1853 std::optional
<uint32_t> nameIndex
;
1854 std::optional
<uint32_t> lineNumber
;
1855 for (const LineColumnEntry
&entry
: lines
) {
1856 for (const LineNumberEntry
&ln
: entry
.LineNumbers
) {
1857 LineInfo
li(ln
.Flags
);
1858 if (ln
.Offset
> offsetInLinetable
) {
1860 nameIndex
= entry
.NameIndex
;
1861 lineNumber
= li
.getStartLine();
1863 StringRef filename
=
1864 exitOnErr(getFileName(cvStrTab
, checksums
, *nameIndex
));
1865 return std::make_pair(filename
, *lineNumber
);
1867 nameIndex
= entry
.NameIndex
;
1868 lineNumber
= li
.getStartLine();
1872 return std::nullopt
;
1873 StringRef filename
= exitOnErr(getFileName(cvStrTab
, checksums
, *nameIndex
));
1874 return std::make_pair(filename
, *lineNumber
);