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
{
186 COFFLinkerContext
&ctx
;
189 /// The object file whose .debug$S sections we're processing.
192 /// The DEBUG_S_STRINGTABLE subsection. These strings are referred to by
193 /// index from other records in the .debug$S section. All of these strings
194 /// need to be added to the global PDB string table, and all references to
195 /// these strings need to have their indices re-written to refer to the
196 /// global PDB string table.
197 DebugStringTableSubsectionRef cvStrTab
;
199 /// The DEBUG_S_FILECHKSMS subsection. As above, these are referred to
200 /// by other records in the .debug$S section and need to be merged into the
202 DebugChecksumsSubsectionRef checksums
;
204 /// The DEBUG_S_FRAMEDATA subsection(s). There can be more than one of
205 /// these and they need not appear in any specific order. However, they
206 /// contain string table references which need to be re-written, so we
207 /// collect them all here and re-write them after all subsections have been
208 /// discovered and processed.
209 std::vector
<UnrelocatedFpoData
> frameDataSubsecs
;
211 /// List of string table references in symbol records. Later they will be
212 /// applied to the symbols during PDB writing.
213 std::vector
<StringTableFixup
> stringTableFixups
;
215 /// Sum of the size of all module symbol records across all .debug$S sections.
216 /// Includes record realignment and the size of the symbol stream magic
218 uint32_t moduleStreamSize
= kSymbolStreamMagicSize
;
220 /// Next relocation index in the current .debug$S section. Resets every
221 /// handleDebugS call.
222 uint32_t nextRelocIndex
= 0;
224 void advanceRelocIndex(SectionChunk
*debugChunk
, ArrayRef
<uint8_t> subsec
);
226 void addUnrelocatedSubsection(SectionChunk
*debugChunk
,
227 const DebugSubsectionRecord
&ss
);
229 void addFrameDataSubsection(SectionChunk
*debugChunk
,
230 const DebugSubsectionRecord
&ss
);
233 DebugSHandler(COFFLinkerContext
&ctx
, PDBLinker
&linker
, ObjFile
&file
)
234 : ctx(ctx
), linker(linker
), file(file
) {}
236 void handleDebugS(SectionChunk
*debugChunk
);
242 // Visual Studio's debugger requires absolute paths in various places in the
243 // PDB to work without additional configuration:
244 // https://docs.microsoft.com/en-us/visualstudio/debugger/debug-source-files-common-properties-solution-property-pages-dialog-box
245 void PDBLinker::pdbMakeAbsolute(SmallVectorImpl
<char> &fileName
) {
246 // The default behavior is to produce paths that are valid within the context
247 // of the machine that you perform the link on. If the linker is running on
248 // a POSIX system, we will output absolute POSIX paths. If the linker is
249 // running on a Windows system, we will output absolute Windows paths. If the
250 // user desires any other kind of behavior, they should explicitly pass
251 // /pdbsourcepath, in which case we will treat the exact string the user
252 // passed in as the gospel and not normalize, canonicalize it.
253 if (sys::path::is_absolute(fileName
, sys::path::Style::windows
) ||
254 sys::path::is_absolute(fileName
, sys::path::Style::posix
))
257 // It's not absolute in any path syntax. Relative paths necessarily refer to
258 // the local file system, so we can make it native without ending up with a
260 if (ctx
.config
.pdbSourcePath
.empty()) {
261 sys::path::native(fileName
);
262 sys::fs::make_absolute(fileName
);
263 sys::path::remove_dots(fileName
, true);
267 // Try to guess whether /PDBSOURCEPATH is a unix path or a windows path.
268 // Since PDB's are more of a Windows thing, we make this conservative and only
269 // decide that it's a unix path if we're fairly certain. Specifically, if
270 // it starts with a forward slash.
271 SmallString
<128> absoluteFileName
= ctx
.config
.pdbSourcePath
;
272 sys::path::Style guessedStyle
= absoluteFileName
.starts_with("/")
273 ? sys::path::Style::posix
274 : sys::path::Style::windows
;
275 sys::path::append(absoluteFileName
, guessedStyle
, fileName
);
276 sys::path::native(absoluteFileName
, guessedStyle
);
277 sys::path::remove_dots(absoluteFileName
, true, guessedStyle
);
279 fileName
= std::move(absoluteFileName
);
282 static void addTypeInfo(pdb::TpiStreamBuilder
&tpiBuilder
,
283 TypeCollection
&typeTable
) {
284 // Start the TPI or IPI stream header.
285 tpiBuilder
.setVersionHeader(pdb::PdbTpiV80
);
287 // Flatten the in memory type table and hash each type.
288 typeTable
.ForEachRecord([&](TypeIndex ti
, const CVType
&type
) {
289 auto hash
= pdb::hashTypeRecord(type
);
290 if (auto e
= hash
.takeError())
291 fatal("type hashing error");
292 tpiBuilder
.addTypeRecord(type
.RecordData
, *hash
);
296 static void addGHashTypeInfo(COFFLinkerContext
&ctx
,
297 pdb::PDBFileBuilder
&builder
) {
298 // Start the TPI or IPI stream header.
299 builder
.getTpiBuilder().setVersionHeader(pdb::PdbTpiV80
);
300 builder
.getIpiBuilder().setVersionHeader(pdb::PdbTpiV80
);
301 for (TpiSource
*source
: ctx
.tpiSourceList
) {
302 builder
.getTpiBuilder().addTypeRecords(source
->mergedTpi
.recs
,
303 source
->mergedTpi
.recSizes
,
304 source
->mergedTpi
.recHashes
);
305 builder
.getIpiBuilder().addTypeRecords(source
->mergedIpi
.recs
,
306 source
->mergedIpi
.recSizes
,
307 source
->mergedIpi
.recHashes
);
312 recordStringTableReferences(CVSymbol sym
, uint32_t symOffset
,
313 std::vector
<StringTableFixup
> &stringTableFixups
) {
314 // For now we only handle S_FILESTATIC, but we may need the same logic for
315 // S_DEFRANGE and S_DEFRANGE_SUBFIELD. However, I cannot seem to generate any
316 // PDBs that contain these types of records, so because of the uncertainty
317 // they are omitted here until we can prove that it's necessary.
318 switch (sym
.kind()) {
319 case SymbolKind::S_FILESTATIC
: {
320 // FileStaticSym::ModFileOffset
321 uint32_t ref
= *reinterpret_cast<const ulittle32_t
*>(&sym
.data()[8]);
322 stringTableFixups
.push_back({ref
, symOffset
+ 8});
325 case SymbolKind::S_DEFRANGE
:
326 case SymbolKind::S_DEFRANGE_SUBFIELD
:
327 log("Not fixing up string table reference in S_DEFRANGE / "
328 "S_DEFRANGE_SUBFIELD record");
335 static SymbolKind
symbolKind(ArrayRef
<uint8_t> recordData
) {
336 const RecordPrefix
*prefix
=
337 reinterpret_cast<const RecordPrefix
*>(recordData
.data());
338 return static_cast<SymbolKind
>(uint16_t(prefix
->RecordKind
));
341 /// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
342 void PDBLinker::translateIdSymbols(MutableArrayRef
<uint8_t> &recordData
,
344 RecordPrefix
*prefix
= reinterpret_cast<RecordPrefix
*>(recordData
.data());
346 SymbolKind kind
= symbolKind(recordData
);
348 if (kind
== SymbolKind::S_PROC_ID_END
) {
349 prefix
->RecordKind
= SymbolKind::S_END
;
353 // In an object file, GPROC32_ID has an embedded reference which refers to the
354 // single object file type index namespace. This has already been translated
355 // to the PDB file's ID stream index space, but we need to convert this to a
356 // symbol that refers to the type stream index space. So we remap again from
357 // ID index space to type index space.
358 if (kind
== SymbolKind::S_GPROC32_ID
|| kind
== SymbolKind::S_LPROC32_ID
) {
359 SmallVector
<TiReference
, 1> refs
;
360 auto content
= recordData
.drop_front(sizeof(RecordPrefix
));
361 CVSymbol
sym(recordData
);
362 discoverTypeIndicesInSymbol(sym
, refs
);
363 assert(refs
.size() == 1);
364 assert(refs
.front().Count
== 1);
367 reinterpret_cast<TypeIndex
*>(content
.data() + refs
[0].Offset
);
368 // `ti` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
369 // the IPI stream, whose `FunctionType` member refers to the TPI stream.
370 // Note that LF_FUNC_ID and LF_MFUNC_ID have the same record layout, and
371 // in both cases we just need the second type index.
372 if (!ti
->isSimple() && !ti
->isNoneType()) {
373 TypeIndex newType
= TypeIndex(SimpleTypeKind::NotTranslated
);
374 if (ctx
.config
.debugGHashes
) {
375 auto idToType
= tMerger
.funcIdToType
.find(*ti
);
376 if (idToType
!= tMerger
.funcIdToType
.end())
377 newType
= idToType
->second
;
379 if (tMerger
.getIDTable().contains(*ti
)) {
380 CVType funcIdData
= tMerger
.getIDTable().getType(*ti
);
381 if (funcIdData
.length() >= 8 && (funcIdData
.kind() == LF_FUNC_ID
||
382 funcIdData
.kind() == LF_MFUNC_ID
)) {
383 newType
= *reinterpret_cast<const TypeIndex
*>(&funcIdData
.data()[8]);
387 if (newType
== TypeIndex(SimpleTypeKind::NotTranslated
)) {
388 Warn(ctx
) << formatv(
389 "procedure symbol record for `{0}` in {1} refers to PDB "
390 "item index {2:X} which is not a valid function ID record",
391 getSymbolName(CVSymbol(recordData
)), source
->file
->getName(),
397 kind
= (kind
== SymbolKind::S_GPROC32_ID
) ? SymbolKind::S_GPROC32
398 : SymbolKind::S_LPROC32
;
399 prefix
->RecordKind
= uint16_t(kind
);
405 ulittle32_t ptrParent
;
410 /// Given a pointer to a symbol record that opens a scope, return a pointer to
411 /// the scope fields.
412 static ScopeRecord
*getSymbolScopeFields(void *sym
) {
413 return reinterpret_cast<ScopeRecord
*>(reinterpret_cast<char *>(sym
) +
414 sizeof(RecordPrefix
));
417 // To open a scope, push the offset of the current symbol record onto the
419 static void scopeStackOpen(SmallVectorImpl
<uint32_t> &stack
,
420 std::vector
<uint8_t> &storage
) {
421 stack
.push_back(storage
.size());
424 // To close a scope, update the record that opened the scope.
425 static void scopeStackClose(COFFLinkerContext
&ctx
,
426 SmallVectorImpl
<uint32_t> &stack
,
427 std::vector
<uint8_t> &storage
,
428 uint32_t storageBaseOffset
, ObjFile
*file
) {
430 Warn(ctx
) << "symbol scopes are not balanced in " << file
->getName();
434 // Update ptrEnd of the record that opened the scope to point to the
435 // current record, if we are writing into the module symbol stream.
436 uint32_t offOpen
= stack
.pop_back_val();
437 uint32_t offEnd
= storageBaseOffset
+ storage
.size();
438 uint32_t offParent
= stack
.empty() ? 0 : (stack
.back() + storageBaseOffset
);
439 ScopeRecord
*scopeRec
= getSymbolScopeFields(&(storage
)[offOpen
]);
440 scopeRec
->ptrParent
= offParent
;
441 scopeRec
->ptrEnd
= offEnd
;
444 static bool symbolGoesInModuleStream(const CVSymbol
&sym
,
445 unsigned symbolScopeDepth
) {
446 switch (sym
.kind()) {
447 case SymbolKind::S_GDATA32
:
448 case SymbolKind::S_GTHREAD32
:
449 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
450 // since they are synthesized by the linker in response to S_GPROC32 and
451 // S_LPROC32, but if we do see them, don't put them in the module stream I
453 case SymbolKind::S_PROCREF
:
454 case SymbolKind::S_LPROCREF
:
456 // S_UDT and S_CONSTANT records go in the module stream if it is not a global record.
457 case SymbolKind::S_UDT
:
458 case SymbolKind::S_CONSTANT
:
459 return symbolScopeDepth
> 0;
460 // S_GDATA32 does not go in the module stream, but S_LDATA32 does.
461 case SymbolKind::S_LDATA32
:
462 case SymbolKind::S_LTHREAD32
:
468 static bool symbolGoesInGlobalsStream(const CVSymbol
&sym
,
469 unsigned symbolScopeDepth
) {
470 switch (sym
.kind()) {
471 case SymbolKind::S_GDATA32
:
472 case SymbolKind::S_GTHREAD32
:
473 case SymbolKind::S_GPROC32
:
474 case SymbolKind::S_LPROC32
:
475 case SymbolKind::S_GPROC32_ID
:
476 case SymbolKind::S_LPROC32_ID
:
477 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
478 // since they are synthesized by the linker in response to S_GPROC32 and
479 // S_LPROC32, but if we do see them, copy them straight through.
480 case SymbolKind::S_PROCREF
:
481 case SymbolKind::S_LPROCREF
:
483 // Records that go in the globals stream, unless they are function-local.
484 case SymbolKind::S_UDT
:
485 case SymbolKind::S_LDATA32
:
486 case SymbolKind::S_LTHREAD32
:
487 case SymbolKind::S_CONSTANT
:
488 return symbolScopeDepth
== 0;
494 static void addGlobalSymbol(pdb::GSIStreamBuilder
&builder
, uint16_t modIndex
,
496 std::vector
<uint8_t> &symStorage
) {
497 CVSymbol sym
{ArrayRef(symStorage
)};
498 switch (sym
.kind()) {
499 case SymbolKind::S_CONSTANT
:
500 case SymbolKind::S_UDT
:
501 case SymbolKind::S_GDATA32
:
502 case SymbolKind::S_GTHREAD32
:
503 case SymbolKind::S_LTHREAD32
:
504 case SymbolKind::S_LDATA32
:
505 case SymbolKind::S_PROCREF
:
506 case SymbolKind::S_LPROCREF
: {
507 // sym is a temporary object, so we have to copy and reallocate the record
509 uint8_t *mem
= bAlloc().Allocate
<uint8_t>(sym
.length());
510 memcpy(mem
, sym
.data().data(), sym
.length());
511 builder
.addGlobalSymbol(CVSymbol(ArrayRef(mem
, sym
.length())));
514 case SymbolKind::S_GPROC32
:
515 case SymbolKind::S_LPROC32
: {
516 SymbolRecordKind k
= SymbolRecordKind::ProcRefSym
;
517 if (sym
.kind() == SymbolKind::S_LPROC32
)
518 k
= SymbolRecordKind::LocalProcRef
;
520 ps
.Module
= modIndex
;
521 // For some reason, MSVC seems to add one to this value.
523 ps
.Name
= getSymbolName(sym
);
525 ps
.SymOffset
= symOffset
;
526 builder
.addGlobalSymbol(ps
);
530 llvm_unreachable("Invalid symbol kind!");
534 // Check if the given symbol record was padded for alignment. If so, zero out
535 // the padding bytes and update the record prefix with the new size.
536 static void fixRecordAlignment(MutableArrayRef
<uint8_t> recordBytes
,
538 size_t alignedSize
= recordBytes
.size();
539 if (oldSize
== alignedSize
)
541 reinterpret_cast<RecordPrefix
*>(recordBytes
.data())->RecordLen
=
543 memset(recordBytes
.data() + oldSize
, 0, alignedSize
- oldSize
);
546 // Replace any record with a skip record of the same size. This is useful when
547 // we have reserved size for a symbol record, but type index remapping fails.
548 static void replaceWithSkipRecord(MutableArrayRef
<uint8_t> recordBytes
) {
549 memset(recordBytes
.data(), 0, recordBytes
.size());
550 auto *prefix
= reinterpret_cast<RecordPrefix
*>(recordBytes
.data());
551 prefix
->RecordKind
= SymbolKind::S_SKIP
;
552 prefix
->RecordLen
= recordBytes
.size() - 2;
555 // Copy the symbol record, relocate it, and fix the alignment if necessary.
556 // Rewrite type indices in the record. Replace unrecognized symbol records with
558 void PDBLinker::writeSymbolRecord(SectionChunk
*debugChunk
,
559 ArrayRef
<uint8_t> sectionContents
,
560 CVSymbol sym
, size_t alignedSize
,
561 uint32_t &nextRelocIndex
,
562 std::vector
<uint8_t> &storage
) {
563 // Allocate space for the new record at the end of the storage.
564 storage
.resize(storage
.size() + alignedSize
);
565 auto recordBytes
= MutableArrayRef
<uint8_t>(storage
).take_back(alignedSize
);
567 // Copy the symbol record and relocate it.
568 debugChunk
->writeAndRelocateSubsection(sectionContents
, sym
.data(),
569 nextRelocIndex
, recordBytes
.data());
570 fixRecordAlignment(recordBytes
, sym
.length());
572 // Re-map all the type index references.
573 TpiSource
*source
= debugChunk
->file
->debugTypesObj
;
574 if (!source
->remapTypesInSymbolRecord(recordBytes
)) {
575 Log(ctx
) << "ignoring unknown symbol record with kind 0x"
576 << utohexstr(sym
.kind());
577 replaceWithSkipRecord(recordBytes
);
580 // An object file may have S_xxx_ID symbols, but these get converted to
581 // "real" symbols in a PDB.
582 translateIdSymbols(recordBytes
, source
);
585 void PDBLinker::analyzeSymbolSubsection(
586 SectionChunk
*debugChunk
, uint32_t &moduleSymOffset
,
587 uint32_t &nextRelocIndex
, std::vector
<StringTableFixup
> &stringTableFixups
,
588 BinaryStreamRef symData
) {
589 ObjFile
*file
= debugChunk
->file
;
590 uint32_t moduleSymStart
= moduleSymOffset
;
592 uint32_t scopeLevel
= 0;
593 std::vector
<uint8_t> storage
;
594 ArrayRef
<uint8_t> sectionContents
= debugChunk
->getContents();
596 ArrayRef
<uint8_t> symsBuffer
;
597 cantFail(symData
.readBytes(0, symData
.getLength(), symsBuffer
));
599 if (symsBuffer
.empty())
600 Warn(ctx
) << "empty symbols subsection in " << file
->getName();
602 Error ec
= forEachCodeViewRecord
<CVSymbol
>(
603 symsBuffer
, [&](CVSymbol sym
) -> llvm::Error
{
604 // Track the current scope.
605 if (symbolOpensScope(sym
.kind()))
607 else if (symbolEndsScope(sym
.kind()))
610 uint32_t alignedSize
=
611 alignTo(sym
.length(), alignOf(CodeViewContainer::Pdb
));
613 // Copy global records. Some global records (mainly procedures)
614 // reference the current offset into the module stream.
615 if (symbolGoesInGlobalsStream(sym
, scopeLevel
)) {
617 writeSymbolRecord(debugChunk
, sectionContents
, sym
, alignedSize
,
618 nextRelocIndex
, storage
);
619 addGlobalSymbol(builder
.getGsiBuilder(),
620 file
->moduleDBI
->getModuleIndex(), moduleSymOffset
,
625 // Update the module stream offset and record any string table index
626 // references. There are very few of these and they will be rewritten
627 // later during PDB writing.
628 if (symbolGoesInModuleStream(sym
, scopeLevel
)) {
629 recordStringTableReferences(sym
, moduleSymOffset
, stringTableFixups
);
630 moduleSymOffset
+= alignedSize
;
634 return Error::success();
637 // If we encountered corrupt records, ignore the whole subsection. If we wrote
638 // any partial records, undo that. For globals, we just keep what we have and
641 Warn(ctx
) << "corrupt symbol records in " << file
->getName();
642 moduleSymOffset
= moduleSymStart
;
643 consumeError(std::move(ec
));
647 Error
PDBLinker::writeAllModuleSymbolRecords(ObjFile
*file
,
648 BinaryStreamWriter
&writer
) {
649 ExitOnError exitOnErr
;
650 std::vector
<uint8_t> storage
;
651 SmallVector
<uint32_t, 4> scopes
;
653 // Visit all live .debug$S sections a second time, and write them to the PDB.
654 for (SectionChunk
*debugChunk
: file
->getDebugChunks()) {
655 if (!debugChunk
->live
|| debugChunk
->getSize() == 0 ||
656 debugChunk
->getSectionName() != ".debug$S")
659 ArrayRef
<uint8_t> sectionContents
= debugChunk
->getContents();
661 SectionChunk::consumeDebugMagic(sectionContents
, ".debug$S");
662 DebugSubsectionArray subsections
;
663 BinaryStreamReader
reader(contents
, llvm::endianness::little
);
664 exitOnErr(reader
.readArray(subsections
, contents
.size()));
666 uint32_t nextRelocIndex
= 0;
667 for (const DebugSubsectionRecord
&ss
: subsections
) {
668 if (ss
.kind() != DebugSubsectionKind::Symbols
)
671 uint32_t moduleSymStart
= writer
.getOffset();
674 ArrayRef
<uint8_t> symsBuffer
;
675 BinaryStreamRef sr
= ss
.getRecordData();
676 cantFail(sr
.readBytes(0, sr
.getLength(), symsBuffer
));
677 auto ec
= forEachCodeViewRecord
<CVSymbol
>(
678 symsBuffer
, [&](CVSymbol sym
) -> llvm::Error
{
679 // Track the current scope. Only update records in the postmerge
681 if (symbolOpensScope(sym
.kind()))
682 scopeStackOpen(scopes
, storage
);
683 else if (symbolEndsScope(sym
.kind()))
684 scopeStackClose(ctx
, scopes
, storage
, moduleSymStart
, file
);
686 // Copy, relocate, and rewrite each module symbol.
687 if (symbolGoesInModuleStream(sym
, scopes
.size())) {
688 uint32_t alignedSize
=
689 alignTo(sym
.length(), alignOf(CodeViewContainer::Pdb
));
690 writeSymbolRecord(debugChunk
, sectionContents
, sym
, alignedSize
,
691 nextRelocIndex
, storage
);
693 return Error::success();
696 // If we encounter corrupt records in the second pass, ignore them. We
697 // already warned about them in the first analysis pass.
699 consumeError(std::move(ec
));
703 // Writing bytes has a very high overhead, so write the entire subsection
705 // TODO: Consider buffering symbols for the entire object file to reduce
706 // overhead even further.
707 if (Error e
= writer
.writeBytes(storage
))
712 return Error::success();
715 Error
PDBLinker::commitSymbolsForObject(void *ctx
, void *obj
,
716 BinaryStreamWriter
&writer
) {
717 return static_cast<PDBLinker
*>(ctx
)->writeAllModuleSymbolRecords(
718 static_cast<ObjFile
*>(obj
), writer
);
721 static pdb::SectionContrib
createSectionContrib(COFFLinkerContext
&ctx
,
722 const Chunk
*c
, uint32_t modi
) {
723 OutputSection
*os
= c
? ctx
.getOutputSection(c
) : nullptr;
724 pdb::SectionContrib sc
;
725 memset(&sc
, 0, sizeof(sc
));
726 sc
.ISect
= os
? os
->sectionIndex
: llvm::pdb::kInvalidStreamIndex
;
727 sc
.Off
= c
&& os
? c
->getRVA() - os
->getRVA() : 0;
728 sc
.Size
= c
? c
->getSize() : -1;
729 if (auto *secChunk
= dyn_cast_or_null
<SectionChunk
>(c
)) {
730 sc
.Characteristics
= secChunk
->header
->Characteristics
;
731 sc
.Imod
= secChunk
->file
->moduleDBI
->getModuleIndex();
732 ArrayRef
<uint8_t> contents
= secChunk
->getContents();
734 crc
.update(contents
);
735 sc
.DataCrc
= crc
.getCRC();
737 sc
.Characteristics
= os
? os
->header
.Characteristics
: 0;
740 sc
.RelocCrc
= 0; // FIXME
746 translateStringTableIndex(COFFLinkerContext
&ctx
, uint32_t objIndex
,
747 const DebugStringTableSubsectionRef
&objStrTable
,
748 DebugStringTableSubsection
&pdbStrTable
) {
749 auto expectedString
= objStrTable
.getString(objIndex
);
750 if (!expectedString
) {
751 Warn(ctx
) << "Invalid string table reference";
752 consumeError(expectedString
.takeError());
756 return pdbStrTable
.insert(*expectedString
);
759 void DebugSHandler::handleDebugS(SectionChunk
*debugChunk
) {
760 // Note that we are processing the *unrelocated* section contents. They will
761 // be relocated later during PDB writing.
762 ArrayRef
<uint8_t> contents
= debugChunk
->getContents();
763 contents
= SectionChunk::consumeDebugMagic(contents
, ".debug$S");
764 DebugSubsectionArray subsections
;
765 BinaryStreamReader
reader(contents
, llvm::endianness::little
);
766 ExitOnError exitOnErr
;
767 exitOnErr(reader
.readArray(subsections
, contents
.size()));
768 debugChunk
->sortRelocations();
770 // Reset the relocation index, since this is a new section.
773 for (const DebugSubsectionRecord
&ss
: subsections
) {
774 // Ignore subsections with the 'ignore' bit. Some versions of the Visual C++
775 // runtime have subsections with this bit set.
776 if (uint32_t(ss
.kind()) & codeview::SubsectionIgnoreFlag
)
780 case DebugSubsectionKind::StringTable
: {
781 assert(!cvStrTab
.valid() &&
782 "Encountered multiple string table subsections!");
783 exitOnErr(cvStrTab
.initialize(ss
.getRecordData()));
786 case DebugSubsectionKind::FileChecksums
:
787 assert(!checksums
.valid() &&
788 "Encountered multiple checksum subsections!");
789 exitOnErr(checksums
.initialize(ss
.getRecordData()));
791 case DebugSubsectionKind::Lines
:
792 case DebugSubsectionKind::InlineeLines
:
793 addUnrelocatedSubsection(debugChunk
, ss
);
795 case DebugSubsectionKind::FrameData
:
796 addFrameDataSubsection(debugChunk
, ss
);
798 case DebugSubsectionKind::Symbols
:
799 linker
.analyzeSymbolSubsection(debugChunk
, moduleStreamSize
,
800 nextRelocIndex
, stringTableFixups
,
804 case DebugSubsectionKind::CrossScopeImports
:
805 case DebugSubsectionKind::CrossScopeExports
:
806 // These appear to relate to cross-module optimization, so we might use
807 // these for ThinLTO.
810 case DebugSubsectionKind::ILLines
:
811 case DebugSubsectionKind::FuncMDTokenMap
:
812 case DebugSubsectionKind::TypeMDTokenMap
:
813 case DebugSubsectionKind::MergedAssemblyInput
:
814 // These appear to relate to .Net assembly info.
817 case DebugSubsectionKind::CoffSymbolRVA
:
818 // Unclear what this is for.
821 case DebugSubsectionKind::XfgHashType
:
822 case DebugSubsectionKind::XfgHashVirtual
:
826 Warn(ctx
) << "ignoring unknown debug$S subsection kind 0x"
827 << utohexstr(uint32_t(ss
.kind())) << " in file "
834 void DebugSHandler::advanceRelocIndex(SectionChunk
*sc
,
835 ArrayRef
<uint8_t> subsec
) {
836 ptrdiff_t vaBegin
= subsec
.data() - sc
->getContents().data();
838 auto relocs
= sc
->getRelocs();
839 for (; nextRelocIndex
< relocs
.size(); ++nextRelocIndex
) {
840 if (relocs
[nextRelocIndex
].VirtualAddress
>= (uint32_t)vaBegin
)
846 /// Wrapper class for unrelocated line and inlinee line subsections, which
847 /// require only relocation and type index remapping to add to the PDB.
848 class UnrelocatedDebugSubsection
: public DebugSubsection
{
850 UnrelocatedDebugSubsection(DebugSubsectionKind k
, SectionChunk
*debugChunk
,
851 ArrayRef
<uint8_t> subsec
, uint32_t relocIndex
)
852 : DebugSubsection(k
), debugChunk(debugChunk
), subsec(subsec
),
853 relocIndex(relocIndex
) {}
855 Error
commit(BinaryStreamWriter
&writer
) const override
;
856 uint32_t calculateSerializedSize() const override
{ return subsec
.size(); }
858 SectionChunk
*debugChunk
;
859 ArrayRef
<uint8_t> subsec
;
864 Error
UnrelocatedDebugSubsection::commit(BinaryStreamWriter
&writer
) const {
865 std::vector
<uint8_t> relocatedBytes(subsec
.size());
866 uint32_t tmpRelocIndex
= relocIndex
;
867 debugChunk
->writeAndRelocateSubsection(debugChunk
->getContents(), subsec
,
868 tmpRelocIndex
, relocatedBytes
.data());
870 // Remap type indices in inlinee line records in place. Skip the remapping if
871 // there is no type source info.
872 if (kind() == DebugSubsectionKind::InlineeLines
&&
873 debugChunk
->file
->debugTypesObj
) {
874 TpiSource
*source
= debugChunk
->file
->debugTypesObj
;
875 DebugInlineeLinesSubsectionRef inlineeLines
;
876 BinaryStreamReader
storageReader(relocatedBytes
, llvm::endianness::little
);
877 ExitOnError exitOnErr
;
878 exitOnErr(inlineeLines
.initialize(storageReader
));
879 for (const InlineeSourceLine
&line
: inlineeLines
) {
880 TypeIndex
&inlinee
= *const_cast<TypeIndex
*>(&line
.Header
->Inlinee
);
881 if (!source
->remapTypeIndex(inlinee
, TiRefKind::IndexRef
)) {
882 log("bad inlinee line record in " + debugChunk
->file
->getName() +
883 " with bad inlinee index 0x" + utohexstr(inlinee
.getIndex()));
888 return writer
.writeBytes(relocatedBytes
);
891 void DebugSHandler::addUnrelocatedSubsection(SectionChunk
*debugChunk
,
892 const DebugSubsectionRecord
&ss
) {
893 ArrayRef
<uint8_t> subsec
;
894 BinaryStreamRef sr
= ss
.getRecordData();
895 cantFail(sr
.readBytes(0, sr
.getLength(), subsec
));
896 advanceRelocIndex(debugChunk
, subsec
);
897 file
.moduleDBI
->addDebugSubsection(
898 std::make_shared
<UnrelocatedDebugSubsection
>(ss
.kind(), debugChunk
,
899 subsec
, nextRelocIndex
));
902 void DebugSHandler::addFrameDataSubsection(SectionChunk
*debugChunk
,
903 const DebugSubsectionRecord
&ss
) {
904 // We need to re-write string table indices here, so save off all
905 // frame data subsections until we've processed the entire list of
906 // subsections so that we can be sure we have the string table.
907 ArrayRef
<uint8_t> subsec
;
908 BinaryStreamRef sr
= ss
.getRecordData();
909 cantFail(sr
.readBytes(0, sr
.getLength(), subsec
));
910 advanceRelocIndex(debugChunk
, subsec
);
911 frameDataSubsecs
.push_back({debugChunk
, subsec
, nextRelocIndex
});
914 static Expected
<StringRef
>
915 getFileName(const DebugStringTableSubsectionRef
&strings
,
916 const DebugChecksumsSubsectionRef
&checksums
, uint32_t fileID
) {
917 auto iter
= checksums
.getArray().at(fileID
);
918 if (iter
== checksums
.getArray().end())
919 return make_error
<CodeViewError
>(cv_error_code::no_records
);
920 uint32_t offset
= iter
->FileNameOffset
;
921 return strings
.getString(offset
);
924 void DebugSHandler::finish() {
925 pdb::DbiStreamBuilder
&dbiBuilder
= linker
.builder
.getDbiBuilder();
927 // If we found any symbol records for the module symbol stream, defer them.
928 if (moduleStreamSize
> kSymbolStreamMagicSize
)
929 file
.moduleDBI
->addUnmergedSymbols(&file
, moduleStreamSize
-
930 kSymbolStreamMagicSize
);
932 // We should have seen all debug subsections across the entire object file now
933 // which means that if a StringTable subsection and Checksums subsection were
934 // present, now is the time to handle them.
935 if (!cvStrTab
.valid()) {
936 if (checksums
.valid())
937 fatal(".debug$S sections with a checksums subsection must also contain a "
938 "string table subsection");
940 if (!stringTableFixups
.empty())
942 << "No StringTable subsection was encountered, but there are string "
947 ExitOnError exitOnErr
;
949 // Handle FPO data. Each subsection begins with a single image base
950 // relocation, which is then added to the RvaStart of each frame data record
951 // when it is added to the PDB. The string table indices for the FPO program
952 // must also be rewritten to use the PDB string table.
953 for (const UnrelocatedFpoData
&subsec
: frameDataSubsecs
) {
954 // Relocate the first four bytes of the subection and reinterpret them as a
955 // 32 bit little-endian integer.
956 SectionChunk
*debugChunk
= subsec
.debugChunk
;
957 ArrayRef
<uint8_t> subsecData
= subsec
.subsecData
;
958 uint32_t relocIndex
= subsec
.relocIndex
;
959 auto unrelocatedRvaStart
= subsecData
.take_front(sizeof(uint32_t));
960 uint8_t relocatedRvaStart
[sizeof(uint32_t)];
961 debugChunk
->writeAndRelocateSubsection(debugChunk
->getContents(),
962 unrelocatedRvaStart
, relocIndex
,
963 &relocatedRvaStart
[0]);
964 // Use of memcpy here avoids violating type-based aliasing rules.
965 support::ulittle32_t rvaStart
;
966 memcpy(&rvaStart
, &relocatedRvaStart
[0], sizeof(support::ulittle32_t
));
968 // Copy each frame data record, add in rvaStart, translate string table
969 // indices, and add the record to the PDB.
970 DebugFrameDataSubsectionRef fds
;
971 BinaryStreamReader
reader(subsecData
, llvm::endianness::little
);
972 exitOnErr(fds
.initialize(reader
));
973 for (codeview::FrameData fd
: fds
) {
974 fd
.RvaStart
+= rvaStart
;
975 fd
.FrameFunc
= translateStringTableIndex(ctx
, fd
.FrameFunc
, cvStrTab
,
977 dbiBuilder
.addNewFpoData(fd
);
981 // Translate the fixups and pass them off to the module builder so they will
982 // be applied during writing.
983 for (StringTableFixup
&ref
: stringTableFixups
) {
984 ref
.StrTabOffset
= translateStringTableIndex(ctx
, ref
.StrTabOffset
,
985 cvStrTab
, linker
.pdbStrTab
);
987 file
.moduleDBI
->setStringTableFixups(std::move(stringTableFixups
));
989 // Make a new file checksum table that refers to offsets in the PDB-wide
990 // string table. Generally the string table subsection appears after the
991 // checksum table, so we have to do this after looping over all the
992 // subsections. The new checksum table must have the exact same layout and
993 // size as the original. Otherwise, the file references in the line and
994 // inlinee line tables will be incorrect.
995 auto newChecksums
= std::make_unique
<DebugChecksumsSubsection
>(linker
.pdbStrTab
);
996 for (const FileChecksumEntry
&fc
: checksums
) {
997 SmallString
<128> filename
=
998 exitOnErr(cvStrTab
.getString(fc
.FileNameOffset
));
999 linker
.pdbMakeAbsolute(filename
);
1000 exitOnErr(dbiBuilder
.addModuleSourceFile(*file
.moduleDBI
, filename
));
1001 newChecksums
->addChecksum(filename
, fc
.Kind
, fc
.Checksum
);
1003 assert(checksums
.getArray().getUnderlyingStream().getLength() ==
1004 newChecksums
->calculateSerializedSize() &&
1005 "file checksum table must have same layout");
1007 file
.moduleDBI
->addDebugSubsection(std::move(newChecksums
));
1010 static void warnUnusable(InputFile
*f
, Error e
, bool shouldWarn
) {
1012 consumeError(std::move(e
));
1015 auto diag
= Warn(f
->symtab
.ctx
);
1016 diag
<< "Cannot use debug info for '" << f
<< "' [LNK4099]";
1018 diag
<< "\n>>> failed to load reference " << std::move(e
);
1021 // Allocate memory for a .debug$S / .debug$F section and relocate it.
1022 static ArrayRef
<uint8_t> relocateDebugChunk(SectionChunk
&debugChunk
) {
1023 uint8_t *buffer
= bAlloc().Allocate
<uint8_t>(debugChunk
.getSize());
1024 assert(debugChunk
.getOutputSectionIdx() == 0 &&
1025 "debug sections should not be in output sections");
1026 debugChunk
.writeTo(buffer
);
1027 return ArrayRef(buffer
, debugChunk
.getSize());
1030 void PDBLinker::addDebugSymbols(TpiSource
*source
) {
1031 // If this TpiSource doesn't have an object file, it must be from a type
1032 // server PDB. Type server PDBs do not contain symbols, so stop here.
1036 llvm::TimeTraceScope
timeScope("Merge symbols");
1037 ScopedTimer
t(ctx
.symbolMergingTimer
);
1038 ExitOnError exitOnErr
;
1039 pdb::DbiStreamBuilder
&dbiBuilder
= builder
.getDbiBuilder();
1040 DebugSHandler
dsh(ctx
, *this, *source
->file
);
1041 // Now do all live .debug$S and .debug$F sections.
1042 for (SectionChunk
*debugChunk
: source
->file
->getDebugChunks()) {
1043 if (!debugChunk
->live
|| debugChunk
->getSize() == 0)
1046 bool isDebugS
= debugChunk
->getSectionName() == ".debug$S";
1047 bool isDebugF
= debugChunk
->getSectionName() == ".debug$F";
1048 if (!isDebugS
&& !isDebugF
)
1052 dsh
.handleDebugS(debugChunk
);
1053 } else if (isDebugF
) {
1054 // Handle old FPO data .debug$F sections. These are relatively rare.
1055 ArrayRef
<uint8_t> relocatedDebugContents
=
1056 relocateDebugChunk(*debugChunk
);
1057 FixedStreamArray
<object::FpoData
> fpoRecords
;
1058 BinaryStreamReader
reader(relocatedDebugContents
,
1059 llvm::endianness::little
);
1060 uint32_t count
= relocatedDebugContents
.size() / sizeof(object::FpoData
);
1061 exitOnErr(reader
.readArray(fpoRecords
, count
));
1063 // These are already relocated and don't refer to the string table, so we
1064 // can just copy it.
1065 for (const object::FpoData
&fd
: fpoRecords
)
1066 dbiBuilder
.addOldFpoData(fd
);
1070 // Do any post-processing now that all .debug$S sections have been processed.
1074 // Add a module descriptor for every object file. We need to put an absolute
1075 // path to the object into the PDB. If this is a plain object, we make its
1076 // path absolute. If it's an object in an archive, we make the archive path
1078 void PDBLinker::createModuleDBI(ObjFile
*file
) {
1079 pdb::DbiStreamBuilder
&dbiBuilder
= builder
.getDbiBuilder();
1080 SmallString
<128> objName
;
1081 ExitOnError exitOnErr
;
1083 bool inArchive
= !file
->parentName
.empty();
1084 objName
= inArchive
? file
->parentName
: file
->getName();
1085 pdbMakeAbsolute(objName
);
1086 StringRef modName
= inArchive
? file
->getName() : objName
.str();
1088 file
->moduleDBI
= &exitOnErr(dbiBuilder
.addModuleInfo(modName
));
1089 file
->moduleDBI
->setObjFileName(objName
);
1090 file
->moduleDBI
->setMergeSymbolsCallback(this, &commitSymbolsForObject
);
1092 ArrayRef
<Chunk
*> chunks
= file
->getChunks();
1093 uint32_t modi
= file
->moduleDBI
->getModuleIndex();
1095 for (Chunk
*c
: chunks
) {
1096 auto *secChunk
= dyn_cast
<SectionChunk
>(c
);
1097 if (!secChunk
|| !secChunk
->live
)
1099 pdb::SectionContrib sc
= createSectionContrib(ctx
, secChunk
, modi
);
1100 file
->moduleDBI
->setFirstSectionContrib(sc
);
1105 void PDBLinker::addDebug(TpiSource
*source
) {
1106 // Before we can process symbol substreams from .debug$S, we need to process
1107 // type information, file checksums, and the string table. Add type info to
1108 // the PDB first, so that we can get the map from object file type and item
1109 // indices to PDB type and item indices. If we are using ghashes, types have
1110 // already been merged.
1111 if (!ctx
.config
.debugGHashes
) {
1112 llvm::TimeTraceScope
timeScope("Merge types (Non-GHASH)");
1113 ScopedTimer
t(ctx
.typeMergingTimer
);
1114 if (Error e
= source
->mergeDebugT(&tMerger
)) {
1115 // If type merging failed, ignore the symbols.
1116 warnUnusable(source
->file
, std::move(e
),
1117 ctx
.config
.warnDebugInfoUnusable
);
1122 // If type merging failed, ignore the symbols.
1123 Error typeError
= std::move(source
->typeMergingError
);
1125 warnUnusable(source
->file
, std::move(typeError
),
1126 ctx
.config
.warnDebugInfoUnusable
);
1130 addDebugSymbols(source
);
1133 static pdb::BulkPublic
createPublic(COFFLinkerContext
&ctx
, Defined
*def
) {
1134 pdb::BulkPublic pub
;
1135 pub
.Name
= def
->getName().data();
1136 pub
.NameLen
= def
->getName().size();
1138 PublicSymFlags flags
= PublicSymFlags::None
;
1139 if (auto *d
= dyn_cast
<DefinedCOFF
>(def
)) {
1140 if (d
->getCOFFSymbol().isFunctionDefinition())
1141 flags
= PublicSymFlags::Function
;
1142 } else if (isa
<DefinedImportThunk
>(def
)) {
1143 flags
= PublicSymFlags::Function
;
1145 pub
.setFlags(flags
);
1147 OutputSection
*os
= ctx
.getOutputSection(def
->getChunk());
1148 assert(os
&& "all publics should be in final image");
1149 pub
.Offset
= def
->getRVA() - os
->getRVA();
1150 pub
.Segment
= os
->sectionIndex
;
1154 // Add all object files to the PDB. Merge .debug$T sections into IpiData and
1156 void PDBLinker::addObjectsToPDB() {
1158 llvm::TimeTraceScope
timeScope("Add objects to PDB");
1159 ScopedTimer
t1(ctx
.addObjectsTimer
);
1161 // Create module descriptors
1162 for (ObjFile
*obj
: ctx
.objFileInstances
)
1163 createModuleDBI(obj
);
1165 // Reorder dependency type sources to come first.
1166 tMerger
.sortDependencies();
1168 // Merge type information from input files using global type hashing.
1169 if (ctx
.config
.debugGHashes
)
1170 tMerger
.mergeTypesWithGHash();
1172 // Merge dependencies and then regular objects.
1174 llvm::TimeTraceScope
timeScope("Merge debug info (dependencies)");
1175 for (TpiSource
*source
: tMerger
.dependencySources
)
1179 llvm::TimeTraceScope
timeScope("Merge debug info (objects)");
1180 for (TpiSource
*source
: tMerger
.objectSources
)
1184 builder
.getStringTableBuilder().setStrings(pdbStrTab
);
1187 // Construct TPI and IPI stream contents.
1189 llvm::TimeTraceScope
timeScope("TPI/IPI stream layout");
1190 ScopedTimer
t2(ctx
.tpiStreamLayoutTimer
);
1192 // Collect all the merged types.
1193 if (ctx
.config
.debugGHashes
) {
1194 addGHashTypeInfo(ctx
, builder
);
1196 addTypeInfo(builder
.getTpiBuilder(), tMerger
.getTypeTable());
1197 addTypeInfo(builder
.getIpiBuilder(), tMerger
.getIDTable());
1201 if (ctx
.config
.showSummary
) {
1202 for (TpiSource
*source
: ctx
.tpiSourceList
) {
1203 nbTypeRecords
+= source
->nbTypeRecords
;
1204 nbTypeRecordsBytes
+= source
->nbTypeRecordsBytes
;
1209 void PDBLinker::addPublicsToPDB() {
1210 llvm::TimeTraceScope
timeScope("Publics layout");
1211 ScopedTimer
t3(ctx
.publicsLayoutTimer
);
1212 // Compute the public symbols.
1213 auto &gsiBuilder
= builder
.getGsiBuilder();
1214 std::vector
<pdb::BulkPublic
> publics
;
1215 ctx
.symtab
.forEachSymbol([&publics
, this](Symbol
*s
) {
1216 // Only emit external, defined, live symbols that have a chunk. Static,
1217 // non-external symbols do not appear in the symbol table.
1218 auto *def
= dyn_cast
<Defined
>(s
);
1219 if (def
&& def
->isLive() && def
->getChunk()) {
1220 // Don't emit a public symbol for coverage data symbols. LLVM code
1221 // coverage (and PGO) create a __profd_ and __profc_ symbol for every
1222 // function. C++ mangled names are long, and tend to dominate symbol size.
1223 // Including these names triples the size of the public stream, which
1224 // results in bloated PDB files. These symbols generally are not helpful
1225 // for debugging, so suppress them.
1226 StringRef name
= def
->getName();
1227 if (name
.data()[0] == '_' && name
.data()[1] == '_') {
1228 // Drop the '_' prefix for x86.
1229 if (ctx
.config
.machine
== I386
)
1230 name
= name
.drop_front(1);
1231 if (name
.starts_with("__profd_") || name
.starts_with("__profc_") ||
1232 name
.starts_with("__covrec_")) {
1236 publics
.push_back(createPublic(ctx
, def
));
1240 if (!publics
.empty()) {
1241 publicSymbols
= publics
.size();
1242 gsiBuilder
.addPublicSymbols(std::move(publics
));
1246 void PDBLinker::printStats() {
1247 if (!ctx
.config
.showSummary
)
1250 SmallString
<256> buffer
;
1251 raw_svector_ostream
stream(buffer
);
1253 stream
<< center_justify("Summary", 80) << '\n'
1254 << std::string(80, '-') << '\n';
1256 auto print
= [&](uint64_t v
, StringRef s
) {
1257 stream
<< format_decimal(v
, 15) << " " << s
<< '\n';
1260 print(ctx
.objFileInstances
.size(),
1261 "Input OBJ files (expanded from all cmd-line inputs)");
1262 print(ctx
.typeServerSourceMappings
.size(), "PDB type server dependencies");
1263 print(ctx
.precompSourceMappings
.size(), "Precomp OBJ dependencies");
1264 print(nbTypeRecords
, "Input type records");
1265 print(nbTypeRecordsBytes
, "Input type records bytes");
1266 print(builder
.getTpiBuilder().getRecordCount(), "Merged TPI records");
1267 print(builder
.getIpiBuilder().getRecordCount(), "Merged IPI records");
1268 print(pdbStrTab
.size(), "Output PDB strings");
1269 print(globalSymbols
, "Global symbol records");
1270 print(moduleSymbols
, "Module symbol records");
1271 print(publicSymbols
, "Public symbol records");
1273 auto printLargeInputTypeRecs
= [&](StringRef name
,
1274 ArrayRef
<uint32_t> recCounts
,
1275 TypeCollection
&records
) {
1276 // Figure out which type indices were responsible for the most duplicate
1277 // bytes in the input files. These should be frequently emitted LF_CLASS and
1278 // LF_FIELDLIST records.
1279 struct TypeSizeInfo
{
1282 TypeIndex typeIndex
;
1283 uint64_t totalInputSize() const { return uint64_t(dupCount
) * typeSize
; }
1284 bool operator<(const TypeSizeInfo
&rhs
) const {
1285 if (totalInputSize() == rhs
.totalInputSize())
1286 return typeIndex
< rhs
.typeIndex
;
1287 return totalInputSize() < rhs
.totalInputSize();
1290 SmallVector
<TypeSizeInfo
, 0> tsis
;
1291 for (auto e
: enumerate(recCounts
)) {
1292 TypeIndex typeIndex
= TypeIndex::fromArrayIndex(e
.index());
1293 uint32_t typeSize
= records
.getType(typeIndex
).length();
1294 uint32_t dupCount
= e
.value();
1295 tsis
.push_back({typeSize
, dupCount
, typeIndex
});
1298 if (!tsis
.empty()) {
1299 stream
<< "\nTop 10 types responsible for the most " << name
1301 stream
<< " index total bytes count size\n";
1304 for (const auto &tsi
: reverse(tsis
)) {
1305 stream
<< formatv(" {0,10:X}: {1,14:N} = {2,5:N} * {3,6:N}\n",
1306 tsi
.typeIndex
.getIndex(), tsi
.totalInputSize(),
1307 tsi
.dupCount
, tsi
.typeSize
);
1312 << "Run llvm-pdbutil to print details about a particular record:\n";
1313 stream
<< formatv("llvm-pdbutil dump -{0}s -{0}-index {1:X} {2}\n",
1314 (name
== "TPI" ? "type" : "id"),
1315 tsis
.back().typeIndex
.getIndex(), ctx
.config
.pdbPath
);
1319 if (!ctx
.config
.debugGHashes
) {
1320 // FIXME: Reimplement for ghash.
1321 printLargeInputTypeRecs("TPI", tMerger
.tpiCounts
, tMerger
.getTypeTable());
1322 printLargeInputTypeRecs("IPI", tMerger
.ipiCounts
, tMerger
.getIDTable());
1328 void PDBLinker::addNatvisFiles() {
1329 llvm::TimeTraceScope
timeScope("Natvis files");
1330 for (StringRef file
: ctx
.config
.natvisFiles
) {
1331 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> dataOrErr
=
1332 MemoryBuffer::getFile(file
);
1334 Warn(ctx
) << "Cannot open input file: " << file
;
1337 std::unique_ptr
<MemoryBuffer
> data
= std::move(*dataOrErr
);
1339 // Can't use takeBuffer() here since addInjectedSource() takes ownership.
1341 ctx
.driver
.tar
->append(relativeToRoot(data
->getBufferIdentifier()),
1344 builder
.addInjectedSource(file
, std::move(data
));
1348 void PDBLinker::addNamedStreams() {
1349 llvm::TimeTraceScope
timeScope("Named streams");
1350 ExitOnError exitOnErr
;
1351 for (const auto &streamFile
: ctx
.config
.namedStreams
) {
1352 const StringRef stream
= streamFile
.getKey(), file
= streamFile
.getValue();
1353 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> dataOrErr
=
1354 MemoryBuffer::getFile(file
);
1356 Warn(ctx
) << "Cannot open input file: " << file
;
1359 std::unique_ptr
<MemoryBuffer
> data
= std::move(*dataOrErr
);
1360 exitOnErr(builder
.addNamedStream(stream
, data
->getBuffer()));
1361 ctx
.driver
.takeBuffer(std::move(data
));
1365 static codeview::CPUType
toCodeViewMachine(COFF::MachineTypes machine
) {
1367 case COFF::IMAGE_FILE_MACHINE_AMD64
:
1368 return codeview::CPUType::X64
;
1369 case COFF::IMAGE_FILE_MACHINE_ARM
:
1370 return codeview::CPUType::ARM7
;
1371 case COFF::IMAGE_FILE_MACHINE_ARM64
:
1372 return codeview::CPUType::ARM64
;
1373 case COFF::IMAGE_FILE_MACHINE_ARM64EC
:
1374 return codeview::CPUType::ARM64EC
;
1375 case COFF::IMAGE_FILE_MACHINE_ARM64X
:
1376 return codeview::CPUType::ARM64X
;
1377 case COFF::IMAGE_FILE_MACHINE_ARMNT
:
1378 return codeview::CPUType::ARMNT
;
1379 case COFF::IMAGE_FILE_MACHINE_I386
:
1380 return codeview::CPUType::Intel80386
;
1382 llvm_unreachable("Unsupported CPU Type");
1386 // Mimic MSVC which surrounds arguments containing whitespace with quotes.
1387 // Double double-quotes are handled, so that the resulting string can be
1388 // executed again on the cmd-line.
1389 static std::string
quote(ArrayRef
<StringRef
> args
) {
1392 for (StringRef a
: args
) {
1395 bool hasWS
= a
.contains(' ');
1396 bool hasQ
= a
.contains('"');
1400 SmallVector
<StringRef
, 4> s
;
1402 r
.append(join(s
, "\"\""));
1404 r
.append(std::string(a
));
1412 static void fillLinkerVerRecord(Compile3Sym
&cs
, MachineTypes machine
) {
1413 cs
.Machine
= toCodeViewMachine(machine
);
1414 // Interestingly, if we set the string to 0.0.0.0, then when trying to view
1415 // local variables WinDbg emits an error that private symbols are not present.
1416 // By setting this to a valid MSVC linker version string, local variables are
1417 // displayed properly. As such, even though it is not representative of
1418 // LLVM's version information, we need this for compatibility.
1419 cs
.Flags
= CompileSym3Flags::None
;
1420 cs
.VersionBackendBuild
= 25019;
1421 cs
.VersionBackendMajor
= 14;
1422 cs
.VersionBackendMinor
= 10;
1423 cs
.VersionBackendQFE
= 0;
1425 // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
1426 // linker module (which is by definition a backend), so we don't need to do
1427 // anything here. Also, it seems we can use "LLVM Linker" for the linker name
1428 // without any problems. Only the backend version has to be hardcoded to a
1430 cs
.VersionFrontendBuild
= 0;
1431 cs
.VersionFrontendMajor
= 0;
1432 cs
.VersionFrontendMinor
= 0;
1433 cs
.VersionFrontendQFE
= 0;
1434 cs
.Version
= "LLVM Linker";
1435 cs
.setLanguage(SourceLanguage::Link
);
1438 void PDBLinker::addCommonLinkerModuleSymbols(
1439 StringRef path
, pdb::DbiModuleDescriptorBuilder
&mod
) {
1440 ObjNameSym
ons(SymbolRecordKind::ObjNameSym
);
1441 EnvBlockSym
ebs(SymbolRecordKind::EnvBlockSym
);
1442 Compile3Sym
cs(SymbolRecordKind::Compile3Sym
);
1444 MachineTypes machine
= ctx
.config
.machine
;
1445 // MSVC uses the ARM64X machine type for ARM64EC targets in the common linker
1447 if (isArm64EC(machine
))
1449 fillLinkerVerRecord(cs
, machine
);
1451 ons
.Name
= "* Linker *";
1454 ArrayRef
<StringRef
> args
= ArrayRef(ctx
.config
.argv
).drop_front();
1455 std::string argStr
= quote(args
);
1456 ebs
.Fields
.push_back("cwd");
1457 SmallString
<64> cwd
;
1458 if (ctx
.config
.pdbSourcePath
.empty())
1459 sys::fs::current_path(cwd
);
1461 cwd
= ctx
.config
.pdbSourcePath
;
1462 ebs
.Fields
.push_back(cwd
);
1463 ebs
.Fields
.push_back("exe");
1464 SmallString
<64> exe
= ctx
.config
.argv
[0];
1465 pdbMakeAbsolute(exe
);
1466 ebs
.Fields
.push_back(exe
);
1467 ebs
.Fields
.push_back("pdb");
1468 ebs
.Fields
.push_back(path
);
1469 ebs
.Fields
.push_back("cmd");
1470 ebs
.Fields
.push_back(argStr
);
1471 llvm::BumpPtrAllocator
&bAlloc
= lld::bAlloc();
1472 mod
.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1473 ons
, bAlloc
, CodeViewContainer::Pdb
));
1474 mod
.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1475 cs
, bAlloc
, CodeViewContainer::Pdb
));
1476 mod
.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1477 ebs
, bAlloc
, CodeViewContainer::Pdb
));
1480 static void addLinkerModuleCoffGroup(PartialSection
*sec
,
1481 pdb::DbiModuleDescriptorBuilder
&mod
,
1482 OutputSection
&os
) {
1483 // If there's a section, there's at least one chunk
1484 assert(!sec
->chunks
.empty());
1485 const Chunk
*firstChunk
= *sec
->chunks
.begin();
1486 const Chunk
*lastChunk
= *sec
->chunks
.rbegin();
1489 CoffGroupSym
cgs(SymbolRecordKind::CoffGroupSym
);
1490 cgs
.Name
= sec
->name
;
1491 cgs
.Segment
= os
.sectionIndex
;
1492 cgs
.Offset
= firstChunk
->getRVA() - os
.getRVA();
1493 cgs
.Size
= lastChunk
->getRVA() + lastChunk
->getSize() - firstChunk
->getRVA();
1494 cgs
.Characteristics
= sec
->characteristics
;
1496 // Somehow .idata sections & sections groups in the debug symbol stream have
1497 // the "write" flag set. However the section header for the corresponding
1498 // .idata section doesn't have it.
1499 if (cgs
.Name
.starts_with(".idata"))
1500 cgs
.Characteristics
|= llvm::COFF::IMAGE_SCN_MEM_WRITE
;
1502 mod
.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1503 cgs
, bAlloc(), CodeViewContainer::Pdb
));
1506 static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder
&mod
,
1507 OutputSection
&os
, bool isMinGW
) {
1508 SectionSym
sym(SymbolRecordKind::SectionSym
);
1509 sym
.Alignment
= 12; // 2^12 = 4KB
1510 sym
.Characteristics
= os
.header
.Characteristics
;
1511 sym
.Length
= os
.getVirtualSize();
1513 sym
.Rva
= os
.getRVA();
1514 sym
.SectionNumber
= os
.sectionIndex
;
1515 mod
.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1516 sym
, bAlloc(), CodeViewContainer::Pdb
));
1518 // Skip COFF groups in MinGW because it adds a significant footprint to the
1519 // PDB, due to each function being in its own section
1523 // Output COFF groups for individual chunks of this section.
1524 for (PartialSection
*sec
: os
.contribSections
) {
1525 addLinkerModuleCoffGroup(sec
, mod
, os
);
1529 // Add all import files as modules to the PDB.
1530 void PDBLinker::addImportFilesToPDB() {
1531 if (ctx
.importFileInstances
.empty())
1534 llvm::TimeTraceScope
timeScope("Import files");
1535 ExitOnError exitOnErr
;
1536 std::map
<std::string
, llvm::pdb::DbiModuleDescriptorBuilder
*> dllToModuleDbi
;
1538 for (ImportFile
*file
: ctx
.importFileInstances
) {
1542 if (!file
->thunkSym
)
1545 if (!file
->thunkSym
->isLive())
1548 std::string dll
= StringRef(file
->dllName
).lower();
1549 llvm::pdb::DbiModuleDescriptorBuilder
*&mod
= dllToModuleDbi
[dll
];
1551 pdb::DbiStreamBuilder
&dbiBuilder
= builder
.getDbiBuilder();
1552 SmallString
<128> libPath
= file
->parentName
;
1553 pdbMakeAbsolute(libPath
);
1554 sys::path::native(libPath
);
1556 // Name modules similar to MSVC's link.exe.
1557 // The first module is the simple dll filename
1558 llvm::pdb::DbiModuleDescriptorBuilder
&firstMod
=
1559 exitOnErr(dbiBuilder
.addModuleInfo(file
->dllName
));
1560 firstMod
.setObjFileName(libPath
);
1561 pdb::SectionContrib sc
=
1562 createSectionContrib(ctx
, nullptr, llvm::pdb::kInvalidStreamIndex
);
1563 firstMod
.setFirstSectionContrib(sc
);
1565 // The second module is where the import stream goes.
1566 mod
= &exitOnErr(dbiBuilder
.addModuleInfo("Import:" + file
->dllName
));
1567 mod
->setObjFileName(libPath
);
1570 DefinedImportThunk
*thunk
= cast
<DefinedImportThunk
>(file
->thunkSym
);
1571 Chunk
*thunkChunk
= thunk
->getChunk();
1572 OutputSection
*thunkOS
= ctx
.getOutputSection(thunkChunk
);
1574 ObjNameSym
ons(SymbolRecordKind::ObjNameSym
);
1575 Compile3Sym
cs(SymbolRecordKind::Compile3Sym
);
1576 Thunk32Sym
ts(SymbolRecordKind::Thunk32Sym
);
1577 ScopeEndSym
es(SymbolRecordKind::ScopeEndSym
);
1579 ons
.Name
= file
->dllName
;
1582 fillLinkerVerRecord(cs
, ctx
.config
.machine
);
1584 ts
.Name
= thunk
->getName();
1588 ts
.Thunk
= ThunkOrdinal::Standard
;
1589 ts
.Length
= thunkChunk
->getSize();
1590 ts
.Segment
= thunkOS
->sectionIndex
;
1591 ts
.Offset
= thunkChunk
->getRVA() - thunkOS
->getRVA();
1593 llvm::BumpPtrAllocator
&bAlloc
= lld::bAlloc();
1594 mod
->addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1595 ons
, bAlloc
, CodeViewContainer::Pdb
));
1596 mod
->addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1597 cs
, bAlloc
, CodeViewContainer::Pdb
));
1599 CVSymbol newSym
= codeview::SymbolSerializer::writeOneSymbol(
1600 ts
, bAlloc
, CodeViewContainer::Pdb
);
1602 // Write ptrEnd for the S_THUNK32.
1603 ScopeRecord
*thunkSymScope
=
1604 getSymbolScopeFields(const_cast<uint8_t *>(newSym
.data().data()));
1606 mod
->addSymbol(newSym
);
1608 newSym
= codeview::SymbolSerializer::writeOneSymbol(es
, bAlloc
,
1609 CodeViewContainer::Pdb
);
1610 thunkSymScope
->ptrEnd
= mod
->getNextSymbolOffset();
1612 mod
->addSymbol(newSym
);
1614 pdb::SectionContrib sc
=
1615 createSectionContrib(ctx
, thunk
->getChunk(), mod
->getModuleIndex());
1616 mod
->setFirstSectionContrib(sc
);
1620 // Creates a PDB file.
1621 void lld::coff::createPDB(COFFLinkerContext
&ctx
,
1622 ArrayRef
<uint8_t> sectionTable
,
1623 llvm::codeview::DebugInfo
*buildId
) {
1624 llvm::TimeTraceScope
timeScope("PDB file");
1625 ScopedTimer
t1(ctx
.totalPdbLinkTimer
);
1629 pdb
.initialize(buildId
);
1630 pdb
.addObjectsToPDB();
1631 pdb
.addImportFilesToPDB();
1632 pdb
.addSections(sectionTable
);
1633 pdb
.addNatvisFiles();
1634 pdb
.addNamedStreams();
1635 pdb
.addPublicsToPDB();
1638 llvm::TimeTraceScope
timeScope("Commit PDB file to disk");
1639 ScopedTimer
t2(ctx
.diskCommitTimer
);
1640 codeview::GUID guid
;
1642 memcpy(&buildId
->PDB70
.Signature
, &guid
, 16);
1648 // Manually start this profile point to measure ~PDBLinker().
1649 if (getTimeTraceProfilerInstance() != nullptr)
1650 timeTraceProfilerBegin("PDBLinker destructor", StringRef(""));
1652 // Manually end this profile point to measure ~PDBLinker().
1653 if (getTimeTraceProfilerInstance() != nullptr)
1654 timeTraceProfilerEnd();
1657 void PDBLinker::initialize(llvm::codeview::DebugInfo
*buildId
) {
1658 ExitOnError exitOnErr
;
1659 exitOnErr(builder
.initialize(ctx
.config
.pdbPageSize
));
1661 buildId
->Signature
.CVSignature
= OMF::Signature::PDB70
;
1662 // Signature is set to a hash of the PDB contents when the PDB is done.
1663 memset(buildId
->PDB70
.Signature
, 0, 16);
1664 buildId
->PDB70
.Age
= 1;
1666 // Create streams in MSF for predefined streams, namely
1667 // PDB, TPI, DBI and IPI.
1668 for (int i
= 0; i
< (int)pdb::kSpecialStreamCount
; ++i
)
1669 exitOnErr(builder
.getMsfBuilder().addStream(0));
1671 // Add an Info stream.
1672 auto &infoBuilder
= builder
.getInfoBuilder();
1673 infoBuilder
.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70
);
1674 infoBuilder
.setHashPDBContentsToGUID(true);
1676 // Add an empty DBI stream.
1677 pdb::DbiStreamBuilder
&dbiBuilder
= builder
.getDbiBuilder();
1678 dbiBuilder
.setAge(buildId
->PDB70
.Age
);
1679 dbiBuilder
.setVersionHeader(pdb::PdbDbiV70
);
1680 dbiBuilder
.setMachineType(ctx
.config
.machine
);
1681 // Technically we are not link.exe 14.11, but there are known cases where
1682 // debugging tools on Windows expect Microsoft-specific version numbers or
1683 // they fail to work at all. Since we know we produce PDBs that are
1684 // compatible with LINK 14.11, we set that version number here.
1685 dbiBuilder
.setBuildNumber(14, 11);
1688 void PDBLinker::addSections(ArrayRef
<uint8_t> sectionTable
) {
1689 llvm::TimeTraceScope
timeScope("PDB output sections");
1690 ExitOnError exitOnErr
;
1691 // It's not entirely clear what this is, but the * Linker * module uses it.
1692 pdb::DbiStreamBuilder
&dbiBuilder
= builder
.getDbiBuilder();
1693 nativePath
= ctx
.config
.pdbPath
;
1694 pdbMakeAbsolute(nativePath
);
1695 uint32_t pdbFilePathNI
= dbiBuilder
.addECName(nativePath
);
1696 auto &linkerModule
= exitOnErr(dbiBuilder
.addModuleInfo("* Linker *"));
1697 linkerModule
.setPdbFilePathNI(pdbFilePathNI
);
1698 addCommonLinkerModuleSymbols(nativePath
, linkerModule
);
1700 // Add section contributions. They must be ordered by ascending RVA.
1701 for (OutputSection
*os
: ctx
.outputSections
) {
1702 addLinkerModuleSectionSymbol(linkerModule
, *os
, ctx
.config
.mingw
);
1703 for (Chunk
*c
: os
->chunks
) {
1704 pdb::SectionContrib sc
=
1705 createSectionContrib(ctx
, c
, linkerModule
.getModuleIndex());
1706 builder
.getDbiBuilder().addSectionContrib(sc
);
1710 // The * Linker * first section contrib is only used along with /INCREMENTAL,
1711 // to provide trampolines thunks for incremental function patching. Set this
1712 // as "unused" because LLD doesn't support /INCREMENTAL link.
1713 pdb::SectionContrib sc
=
1714 createSectionContrib(ctx
, nullptr, llvm::pdb::kInvalidStreamIndex
);
1715 linkerModule
.setFirstSectionContrib(sc
);
1717 // Add Section Map stream.
1718 ArrayRef
<object::coff_section
> sections
= {
1719 (const object::coff_section
*)sectionTable
.data(),
1720 sectionTable
.size() / sizeof(object::coff_section
)};
1721 dbiBuilder
.createSectionMap(sections
);
1723 // Add COFF section header stream.
1725 dbiBuilder
.addDbgStream(pdb::DbgHeaderType::SectionHdr
, sectionTable
));
1728 void PDBLinker::commit(codeview::GUID
*guid
) {
1729 // Print an error and continue if PDB writing fails. This is done mainly so
1730 // the user can see the output of /time and /summary, which is very helpful
1731 // when trying to figure out why a PDB file is too large.
1732 if (Error e
= builder
.commit(ctx
.config
.pdbPath
, guid
)) {
1733 e
= handleErrors(std::move(e
), [&](const llvm::msf::MSFError
&me
) {
1734 Err(ctx
) << me
.message();
1735 if (me
.isPageOverflow())
1736 Err(ctx
) << "try setting a larger /pdbpagesize";
1738 checkError(std::move(e
));
1739 Err(ctx
) << "failed to write PDB file " << Twine(ctx
.config
.pdbPath
);
1743 static uint32_t getSecrelReloc(Triple::ArchType arch
) {
1745 case Triple::x86_64
:
1746 return COFF::IMAGE_REL_AMD64_SECREL
;
1748 return COFF::IMAGE_REL_I386_SECREL
;
1750 return COFF::IMAGE_REL_ARM_SECREL
;
1751 case Triple::aarch64
:
1752 return COFF::IMAGE_REL_ARM64_SECREL
;
1754 llvm_unreachable("unknown machine type");
1758 // Try to find a line table for the given offset Addr into the given chunk C.
1759 // If a line table was found, the line table, the string and checksum tables
1760 // that are used to interpret the line table, and the offset of Addr in the line
1761 // table are stored in the output arguments. Returns whether a line table was
1763 static bool findLineTable(const SectionChunk
*c
, uint32_t addr
,
1764 DebugStringTableSubsectionRef
&cvStrTab
,
1765 DebugChecksumsSubsectionRef
&checksums
,
1766 DebugLinesSubsectionRef
&lines
,
1767 uint32_t &offsetInLinetable
) {
1768 ExitOnError exitOnErr
;
1769 const uint32_t secrelReloc
= getSecrelReloc(c
->getArch());
1771 for (SectionChunk
*dbgC
: c
->file
->getDebugChunks()) {
1772 if (dbgC
->getSectionName() != ".debug$S")
1775 // Build a mapping of SECREL relocations in dbgC that refer to `c`.
1776 DenseMap
<uint32_t, uint32_t> secrels
;
1777 for (const coff_relocation
&r
: dbgC
->getRelocs()) {
1778 if (r
.Type
!= secrelReloc
)
1781 if (auto *s
= dyn_cast_or_null
<DefinedRegular
>(
1782 c
->file
->getSymbols()[r
.SymbolTableIndex
]))
1783 if (s
->getChunk() == c
)
1784 secrels
[r
.VirtualAddress
] = s
->getValue();
1787 ArrayRef
<uint8_t> contents
=
1788 SectionChunk::consumeDebugMagic(dbgC
->getContents(), ".debug$S");
1789 DebugSubsectionArray subsections
;
1790 BinaryStreamReader
reader(contents
, llvm::endianness::little
);
1791 exitOnErr(reader
.readArray(subsections
, contents
.size()));
1793 for (const DebugSubsectionRecord
&ss
: subsections
) {
1794 switch (ss
.kind()) {
1795 case DebugSubsectionKind::StringTable
: {
1796 assert(!cvStrTab
.valid() &&
1797 "Encountered multiple string table subsections!");
1798 exitOnErr(cvStrTab
.initialize(ss
.getRecordData()));
1801 case DebugSubsectionKind::FileChecksums
:
1802 assert(!checksums
.valid() &&
1803 "Encountered multiple checksum subsections!");
1804 exitOnErr(checksums
.initialize(ss
.getRecordData()));
1806 case DebugSubsectionKind::Lines
: {
1807 ArrayRef
<uint8_t> bytes
;
1808 auto ref
= ss
.getRecordData();
1809 exitOnErr(ref
.readLongestContiguousChunk(0, bytes
));
1810 size_t offsetInDbgC
= bytes
.data() - dbgC
->getContents().data();
1812 // Check whether this line table refers to C.
1813 auto i
= secrels
.find(offsetInDbgC
);
1814 if (i
== secrels
.end())
1817 // Check whether this line table covers Addr in C.
1818 DebugLinesSubsectionRef linesTmp
;
1819 exitOnErr(linesTmp
.initialize(BinaryStreamReader(ref
)));
1820 uint32_t offsetInC
= i
->second
+ linesTmp
.header()->RelocOffset
;
1821 if (addr
< offsetInC
|| addr
>= offsetInC
+ linesTmp
.header()->CodeSize
)
1824 assert(!lines
.header() &&
1825 "Encountered multiple line tables for function!");
1826 exitOnErr(lines
.initialize(BinaryStreamReader(ref
)));
1827 offsetInLinetable
= addr
- offsetInC
;
1834 if (cvStrTab
.valid() && checksums
.valid() && lines
.header())
1842 // Use CodeView line tables to resolve a file and line number for the given
1843 // offset into the given chunk and return them, or std::nullopt if a line table
1845 std::optional
<std::pair
<StringRef
, uint32_t>>
1846 lld::coff::getFileLineCodeView(const SectionChunk
*c
, uint32_t addr
) {
1847 ExitOnError exitOnErr
;
1849 DebugStringTableSubsectionRef cvStrTab
;
1850 DebugChecksumsSubsectionRef checksums
;
1851 DebugLinesSubsectionRef lines
;
1852 uint32_t offsetInLinetable
;
1854 if (!findLineTable(c
, addr
, cvStrTab
, checksums
, lines
, offsetInLinetable
))
1855 return std::nullopt
;
1857 std::optional
<uint32_t> nameIndex
;
1858 std::optional
<uint32_t> lineNumber
;
1859 for (const LineColumnEntry
&entry
: lines
) {
1860 for (const LineNumberEntry
&ln
: entry
.LineNumbers
) {
1861 LineInfo
li(ln
.Flags
);
1862 if (ln
.Offset
> offsetInLinetable
) {
1864 nameIndex
= entry
.NameIndex
;
1865 lineNumber
= li
.getStartLine();
1867 StringRef filename
=
1868 exitOnErr(getFileName(cvStrTab
, checksums
, *nameIndex
));
1869 return std::make_pair(filename
, *lineNumber
);
1871 nameIndex
= entry
.NameIndex
;
1872 lineNumber
= li
.getStartLine();
1876 return std::nullopt
;
1877 StringRef filename
= exitOnErr(getFileName(cvStrTab
, checksums
, *nameIndex
));
1878 return std::make_pair(filename
, *lineNumber
);