1 //===- PDB.cpp ------------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
14 #include "SymbolTable.h"
17 #include "lld/Common/ErrorHandler.h"
18 #include "lld/Common/Timer.h"
19 #include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
20 #include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"
21 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
22 #include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
23 #include "llvm/DebugInfo/CodeView/RecordName.h"
24 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
25 #include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
26 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
27 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
28 #include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
29 #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
30 #include "llvm/DebugInfo/MSF/MSFBuilder.h"
31 #include "llvm/DebugInfo/MSF/MSFCommon.h"
32 #include "llvm/DebugInfo/PDB/GenericError.h"
33 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
34 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
35 #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
36 #include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h"
37 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
38 #include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
39 #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
40 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
41 #include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
42 #include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
43 #include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
44 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
45 #include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
46 #include "llvm/DebugInfo/PDB/PDB.h"
47 #include "llvm/Object/COFF.h"
48 #include "llvm/Object/CVDebugRecord.h"
49 #include "llvm/Support/BinaryByteStream.h"
50 #include "llvm/Support/Endian.h"
51 #include "llvm/Support/FormatVariadic.h"
52 #include "llvm/Support/JamCRC.h"
53 #include "llvm/Support/Path.h"
54 #include "llvm/Support/ScopedPrinter.h"
58 using namespace lld::coff;
60 using namespace llvm::codeview;
62 using llvm::object::coff_section;
64 static ExitOnError ExitOnErr;
66 static Timer TotalPdbLinkTimer("PDB Emission (Cumulative)", Timer::root());
68 static Timer AddObjectsTimer("Add Objects", TotalPdbLinkTimer);
69 static Timer TypeMergingTimer("Type Merging", AddObjectsTimer);
70 static Timer SymbolMergingTimer("Symbol Merging", AddObjectsTimer);
71 static Timer GlobalsLayoutTimer("Globals Stream Layout", TotalPdbLinkTimer);
72 static Timer TpiStreamLayoutTimer("TPI Stream Layout", TotalPdbLinkTimer);
73 static Timer DiskCommitTimer("Commit to Disk", TotalPdbLinkTimer);
76 /// Map from type index and item index in a type server PDB to the
77 /// corresponding index in the destination PDB.
79 SmallVector<TypeIndex, 0> TPIMap;
80 SmallVector<TypeIndex, 0> IPIMap;
81 bool IsTypeServerMap = false;
86 PDBLinker(SymbolTable *Symtab)
87 : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
88 IDTable(Alloc), GlobalTypeTable(Alloc), GlobalIDTable(Alloc) {
89 // This isn't strictly necessary, but link.exe usually puts an empty string
90 // as the first "valid" string in the string table, so we do the same in
91 // order to maintain as much byte-for-byte compatibility as possible.
95 /// Emit the basic PDB structure: initial streams, headers, etc.
96 void initialize(const llvm::codeview::DebugInfo &BuildId);
98 /// Add natvis files specified on the command line.
99 void addNatvisFiles();
101 /// Link CodeView from each object file in the symbol table into the PDB.
102 void addObjectsToPDB();
104 /// Link CodeView from a single object file into the PDB.
105 void addObjFile(ObjFile *File);
107 /// Produce a mapping from the type and item indices used in the object
108 /// file to those in the destination PDB.
110 /// If the object file uses a type server PDB (compiled with /Zi), merge TPI
111 /// and IPI from the type server PDB and return a map for it. Each unique type
112 /// server PDB is merged at most once, so this may return an existing index
115 /// If the object does not use a type server PDB (compiled with /Z7), we merge
116 /// all the type and item records from the .debug$S stream and fill in the
117 /// caller-provided ObjectIndexMap.
118 Expected<const CVIndexMap&> mergeDebugT(ObjFile *File,
119 CVIndexMap &ObjectIndexMap);
121 Expected<const CVIndexMap&> maybeMergeTypeServerPDB(ObjFile *File,
122 TypeServer2Record &TS);
124 /// Add the section map and section contributions to the PDB.
125 void addSections(ArrayRef<OutputSection *> OutputSections,
126 ArrayRef<uint8_t> SectionTable);
128 /// Write the PDB to disk.
132 BumpPtrAllocator Alloc;
136 pdb::PDBFileBuilder Builder;
138 /// Type records that will go into the PDB TPI stream.
139 MergingTypeTableBuilder TypeTable;
141 /// Item records that will go into the PDB IPI stream.
142 MergingTypeTableBuilder IDTable;
144 /// Type records that will go into the PDB TPI stream (for /DEBUG:GHASH)
145 GlobalTypeTableBuilder GlobalTypeTable;
147 /// Item records that will go into the PDB IPI stream (for /DEBUG:GHASH)
148 GlobalTypeTableBuilder GlobalIDTable;
150 /// PDBs use a single global string table for filenames in the file checksum
152 DebugStringTableSubsection PDBStrTab;
154 llvm::SmallString<128> NativePath;
156 /// A list of other PDBs which are loaded during the linking process and which
157 /// we need to keep around since the linking operation may reference pointers
158 /// inside of these PDBs.
159 llvm::SmallVector<std::unique_ptr<pdb::NativeSession>, 2> LoadedPDBs;
161 std::vector<pdb::SecMapEntry> SectionMap;
163 /// Type index mappings of type server PDBs that we've loaded so far.
164 std::map<GUID, CVIndexMap> TypeServerIndexMappings;
166 /// List of TypeServer PDBs which cannot be loaded.
167 /// Cached to prevent repeated load attempts.
168 std::set<GUID> MissingTypeServerPDBs;
172 static SectionChunk *findByName(ArrayRef<SectionChunk *> Sections,
174 for (SectionChunk *C : Sections)
175 if (C->getSectionName() == Name)
180 static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
182 // First 4 bytes are section magic.
184 fatal(SecName + " too short");
185 if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
186 fatal(SecName + " has an invalid magic");
187 return Data.slice(4);
190 static ArrayRef<uint8_t> getDebugSection(ObjFile *File, StringRef SecName) {
191 if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
192 return consumeDebugMagic(Sec->getContents(), SecName);
196 // A COFF .debug$H section is currently a clang extension. This function checks
197 // if a .debug$H section is in a format that we expect / understand, so that we
198 // can ignore any sections which are coincidentally also named .debug$H but do
199 // not contain a format we recognize.
200 static bool canUseDebugH(ArrayRef<uint8_t> DebugH) {
201 if (DebugH.size() < sizeof(object::debug_h_header))
204 reinterpret_cast<const object::debug_h_header *>(DebugH.data());
205 DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
206 return Header->Magic == COFF::DEBUG_HASHES_SECTION_MAGIC &&
207 Header->Version == 0 &&
208 Header->HashAlgorithm == uint16_t(GlobalTypeHashAlg::SHA1_8) &&
209 (DebugH.size() % 8 == 0);
212 static Optional<ArrayRef<uint8_t>> getDebugH(ObjFile *File) {
213 SectionChunk *Sec = findByName(File->getDebugChunks(), ".debug$H");
216 ArrayRef<uint8_t> Contents = Sec->getContents();
217 if (!canUseDebugH(Contents))
222 static ArrayRef<GloballyHashedType>
223 getHashesFromDebugH(ArrayRef<uint8_t> DebugH) {
224 assert(canUseDebugH(DebugH));
226 DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
227 uint32_t Count = DebugH.size() / sizeof(GloballyHashedType);
228 return {reinterpret_cast<const GloballyHashedType *>(DebugH.data()), Count};
231 static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
232 TypeCollection &TypeTable) {
233 // Start the TPI or IPI stream header.
234 TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
236 // Flatten the in memory type table and hash each type.
237 TypeTable.ForEachRecord([&](TypeIndex TI, const CVType &Type) {
238 auto Hash = pdb::hashTypeRecord(Type);
239 if (auto E = Hash.takeError())
240 fatal("type hashing error");
241 TpiBuilder.addTypeRecord(Type.RecordData, *Hash);
245 static Optional<TypeServer2Record>
246 maybeReadTypeServerRecord(CVTypeArray &Types) {
247 auto I = Types.begin();
248 if (I == Types.end())
250 const CVType &Type = *I;
251 if (Type.kind() != LF_TYPESERVER2)
253 TypeServer2Record TS;
254 if (auto EC = TypeDeserializer::deserializeAs(const_cast<CVType &>(Type), TS))
255 fatal("error reading type server record: " + toString(std::move(EC)));
256 return std::move(TS);
259 Expected<const CVIndexMap&> PDBLinker::mergeDebugT(ObjFile *File,
260 CVIndexMap &ObjectIndexMap) {
261 ScopedTimer T(TypeMergingTimer);
263 ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
265 return ObjectIndexMap;
267 BinaryByteStream Stream(Data, support::little);
269 BinaryStreamReader Reader(Stream);
270 if (auto EC = Reader.readArray(Types, Reader.getLength()))
271 fatal("Reader::readArray failed: " + toString(std::move(EC)));
273 // Look through type servers. If we've already seen this type server, don't
274 // merge any type information.
275 if (Optional<TypeServer2Record> TS = maybeReadTypeServerRecord(Types))
276 return maybeMergeTypeServerPDB(File, *TS);
278 // This is a /Z7 object. Fill in the temporary, caller-provided
280 if (Config->DebugGHashes) {
281 ArrayRef<GloballyHashedType> Hashes;
282 std::vector<GloballyHashedType> OwnedHashes;
283 if (Optional<ArrayRef<uint8_t>> DebugH = getDebugH(File))
284 Hashes = getHashesFromDebugH(*DebugH);
286 OwnedHashes = GloballyHashedType::hashTypes(Types);
287 Hashes = OwnedHashes;
290 if (auto Err = mergeTypeAndIdRecords(GlobalIDTable, GlobalTypeTable,
291 ObjectIndexMap.TPIMap, Types, Hashes))
292 fatal("codeview::mergeTypeAndIdRecords failed: " +
293 toString(std::move(Err)));
295 if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable,
296 ObjectIndexMap.TPIMap, Types))
297 fatal("codeview::mergeTypeAndIdRecords failed: " +
298 toString(std::move(Err)));
300 return ObjectIndexMap;
303 static Expected<std::unique_ptr<pdb::NativeSession>>
304 tryToLoadPDB(const GUID &GuidFromObj, StringRef TSPath) {
305 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(
306 TSPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
308 return errorCodeToError(MBOrErr.getError());
310 std::unique_ptr<pdb::IPDBSession> ThisSession;
311 if (auto EC = pdb::NativeSession::createFromPdb(
312 MemoryBuffer::getMemBuffer(Driver->takeBuffer(std::move(*MBOrErr)),
313 /*RequiresNullTerminator=*/false),
315 return std::move(EC);
317 std::unique_ptr<pdb::NativeSession> NS(
318 static_cast<pdb::NativeSession *>(ThisSession.release()));
319 pdb::PDBFile &File = NS->getPDBFile();
320 auto ExpectedInfo = File.getPDBInfoStream();
321 // All PDB Files should have an Info stream.
323 return ExpectedInfo.takeError();
325 // Just because a file with a matching name was found and it was an actual
326 // PDB file doesn't mean it matches. For it to match the InfoStream's GUID
327 // must match the GUID specified in the TypeServer2 record.
328 if (ExpectedInfo->getGuid() != GuidFromObj)
329 return make_error<pdb::GenericError>(
330 pdb::generic_error_code::type_server_not_found, TSPath);
332 return std::move(NS);
335 Expected<const CVIndexMap&> PDBLinker::maybeMergeTypeServerPDB(ObjFile *File,
336 TypeServer2Record &TS) {
337 const GUID& TSId = TS.getGuid();
338 StringRef TSPath = TS.getName();
340 // First, check if the PDB has previously failed to load.
341 if (MissingTypeServerPDBs.count(TSId))
342 return make_error<pdb::GenericError>(
343 pdb::generic_error_code::type_server_not_found, TSPath);
345 // Second, check if we already loaded a PDB with this GUID. Return the type
346 // index mapping if we have it.
347 auto Insertion = TypeServerIndexMappings.insert({TSId, CVIndexMap()});
348 CVIndexMap &IndexMap = Insertion.first->second;
349 if (!Insertion.second)
352 // Mark this map as a type server map.
353 IndexMap.IsTypeServerMap = true;
355 // Check for a PDB at:
356 // 1. The given file path
357 // 2. Next to the object file or archive file
358 auto ExpectedSession = tryToLoadPDB(TSId, TSPath);
359 if (!ExpectedSession) {
360 consumeError(ExpectedSession.takeError());
361 StringRef LocalPath =
362 !File->ParentName.empty() ? File->ParentName : File->getName();
363 SmallString<128> Path = sys::path::parent_path(LocalPath);
365 Path, sys::path::filename(TSPath, sys::path::Style::windows));
366 ExpectedSession = tryToLoadPDB(TSId, Path);
368 if (auto E = ExpectedSession.takeError()) {
369 TypeServerIndexMappings.erase(TSId);
370 MissingTypeServerPDBs.emplace(TSId);
374 pdb::NativeSession *Session = ExpectedSession->get();
376 // Keep a strong reference to this PDB, so that it's safe to hold pointers
378 LoadedPDBs.push_back(std::move(*ExpectedSession));
380 auto ExpectedTpi = Session->getPDBFile().getPDBTpiStream();
381 if (auto E = ExpectedTpi.takeError())
382 fatal("Type server does not have TPI stream: " + toString(std::move(E)));
383 auto ExpectedIpi = Session->getPDBFile().getPDBIpiStream();
384 if (auto E = ExpectedIpi.takeError())
385 fatal("Type server does not have TPI stream: " + toString(std::move(E)));
387 if (Config->DebugGHashes) {
388 // PDBs do not actually store global hashes, so when merging a type server
389 // PDB we have to synthesize global hashes. To do this, we first synthesize
390 // global hashes for the TPI stream, since it is independent, then we
391 // synthesize hashes for the IPI stream, using the hashes for the TPI stream
393 auto TpiHashes = GloballyHashedType::hashTypes(ExpectedTpi->typeArray());
395 GloballyHashedType::hashIds(ExpectedIpi->typeArray(), TpiHashes);
397 // Merge TPI first, because the IPI stream will reference type indices.
398 if (auto Err = mergeTypeRecords(GlobalTypeTable, IndexMap.TPIMap,
399 ExpectedTpi->typeArray(), TpiHashes))
400 fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
404 mergeIdRecords(GlobalIDTable, IndexMap.TPIMap, IndexMap.IPIMap,
405 ExpectedIpi->typeArray(), IpiHashes))
406 fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
408 // Merge TPI first, because the IPI stream will reference type indices.
409 if (auto Err = mergeTypeRecords(TypeTable, IndexMap.TPIMap,
410 ExpectedTpi->typeArray()))
411 fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
414 if (auto Err = mergeIdRecords(IDTable, IndexMap.TPIMap, IndexMap.IPIMap,
415 ExpectedIpi->typeArray()))
416 fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
422 static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
425 if (TI.toArrayIndex() >= TypeIndexMap.size())
427 TI = TypeIndexMap[TI.toArrayIndex()];
431 static void remapTypesInSymbolRecord(ObjFile *File, SymbolKind SymKind,
432 MutableArrayRef<uint8_t> Contents,
433 const CVIndexMap &IndexMap,
434 ArrayRef<TiReference> TypeRefs) {
435 for (const TiReference &Ref : TypeRefs) {
436 unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
437 if (Contents.size() < Ref.Offset + ByteSize)
438 fatal("symbol record too short");
440 // This can be an item index or a type index. Choose the appropriate map.
441 ArrayRef<TypeIndex> TypeOrItemMap = IndexMap.TPIMap;
442 bool IsItemIndex = Ref.Kind == TiRefKind::IndexRef;
443 if (IsItemIndex && IndexMap.IsTypeServerMap)
444 TypeOrItemMap = IndexMap.IPIMap;
446 MutableArrayRef<TypeIndex> TIs(
447 reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
448 for (TypeIndex &TI : TIs) {
449 if (!remapTypeIndex(TI, TypeOrItemMap)) {
450 log("ignoring symbol record of kind 0x" + utohexstr(SymKind) + " in " +
451 File->getName() + " with bad " + (IsItemIndex ? "item" : "type") +
452 " index 0x" + utohexstr(TI.getIndex()));
453 TI = TypeIndex(SimpleTypeKind::NotTranslated);
461 recordStringTableReferenceAtOffset(MutableArrayRef<uint8_t> Contents,
463 std::vector<ulittle32_t *> &StrTableRefs) {
465 Contents.drop_front(Offset).take_front(sizeof(support::ulittle32_t));
466 ulittle32_t *Index = reinterpret_cast<ulittle32_t *>(Contents.data());
467 StrTableRefs.push_back(Index);
471 recordStringTableReferences(SymbolKind Kind, MutableArrayRef<uint8_t> Contents,
472 std::vector<ulittle32_t *> &StrTableRefs) {
473 // For now we only handle S_FILESTATIC, but we may need the same logic for
474 // S_DEFRANGE and S_DEFRANGE_SUBFIELD. However, I cannot seem to generate any
475 // PDBs that contain these types of records, so because of the uncertainty
476 // they are omitted here until we can prove that it's necessary.
478 case SymbolKind::S_FILESTATIC:
479 // FileStaticSym::ModFileOffset
480 recordStringTableReferenceAtOffset(Contents, 4, StrTableRefs);
482 case SymbolKind::S_DEFRANGE:
483 case SymbolKind::S_DEFRANGE_SUBFIELD:
484 log("Not fixing up string table reference in S_DEFRANGE / "
485 "S_DEFRANGE_SUBFIELD record");
492 static SymbolKind symbolKind(ArrayRef<uint8_t> RecordData) {
493 const RecordPrefix *Prefix =
494 reinterpret_cast<const RecordPrefix *>(RecordData.data());
495 return static_cast<SymbolKind>(uint16_t(Prefix->RecordKind));
498 /// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
499 static void translateIdSymbols(MutableArrayRef<uint8_t> &RecordData,
500 TypeCollection &IDTable) {
501 RecordPrefix *Prefix = reinterpret_cast<RecordPrefix *>(RecordData.data());
503 SymbolKind Kind = symbolKind(RecordData);
505 if (Kind == SymbolKind::S_PROC_ID_END) {
506 Prefix->RecordKind = SymbolKind::S_END;
510 // In an object file, GPROC32_ID has an embedded reference which refers to the
511 // single object file type index namespace. This has already been translated
512 // to the PDB file's ID stream index space, but we need to convert this to a
513 // symbol that refers to the type stream index space. So we remap again from
514 // ID index space to type index space.
515 if (Kind == SymbolKind::S_GPROC32_ID || Kind == SymbolKind::S_LPROC32_ID) {
516 SmallVector<TiReference, 1> Refs;
517 auto Content = RecordData.drop_front(sizeof(RecordPrefix));
518 CVSymbol Sym(Kind, RecordData);
519 discoverTypeIndicesInSymbol(Sym, Refs);
520 assert(Refs.size() == 1);
521 assert(Refs.front().Count == 1);
524 reinterpret_cast<TypeIndex *>(Content.data() + Refs[0].Offset);
525 // `TI` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
526 // the IPI stream, whose `FunctionType` member refers to the TPI stream.
527 // Note that LF_FUNC_ID and LF_MEMFUNC_ID have the same record layout, and
528 // in both cases we just need the second type index.
529 if (!TI->isSimple() && !TI->isNoneType()) {
530 CVType FuncIdData = IDTable.getType(*TI);
531 SmallVector<TypeIndex, 2> Indices;
532 discoverTypeIndices(FuncIdData, Indices);
533 assert(Indices.size() == 2);
537 Kind = (Kind == SymbolKind::S_GPROC32_ID) ? SymbolKind::S_GPROC32
538 : SymbolKind::S_LPROC32;
539 Prefix->RecordKind = uint16_t(Kind);
543 /// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
544 /// The object file may not be aligned.
545 static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
546 BumpPtrAllocator &Alloc) {
547 size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
548 assert(Size >= 4 && "record too short");
549 assert(Size <= MaxRecordLength && "record too long");
550 void *Mem = Alloc.Allocate(Size, 4);
552 // Copy the symbol record and zero out any padding bytes.
553 MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
554 memcpy(NewData.data(), Sym.data().data(), Sym.length());
555 memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
557 // Update the record prefix length. It should point to the beginning of the
559 auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
560 Prefix->RecordLen = Size - 2;
564 /// Return true if this symbol opens a scope. This implies that the symbol has
565 /// "parent" and "end" fields, which contain the offset of the S_END or
566 /// S_INLINESITE_END record.
567 static bool symbolOpensScope(SymbolKind Kind) {
569 case SymbolKind::S_GPROC32:
570 case SymbolKind::S_LPROC32:
571 case SymbolKind::S_LPROC32_ID:
572 case SymbolKind::S_GPROC32_ID:
573 case SymbolKind::S_BLOCK32:
574 case SymbolKind::S_SEPCODE:
575 case SymbolKind::S_THUNK32:
576 case SymbolKind::S_INLINESITE:
577 case SymbolKind::S_INLINESITE2:
585 static bool symbolEndsScope(SymbolKind Kind) {
587 case SymbolKind::S_END:
588 case SymbolKind::S_PROC_ID_END:
589 case SymbolKind::S_INLINESITE_END:
598 ulittle32_t PtrParent;
603 ScopeRecord *OpeningRecord;
604 uint32_t ScopeOffset;
607 static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
608 uint32_t CurOffset, CVSymbol &Sym) {
609 assert(symbolOpensScope(Sym.kind()));
611 S.ScopeOffset = CurOffset;
612 S.OpeningRecord = const_cast<ScopeRecord *>(
613 reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
614 S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
618 static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
619 uint32_t CurOffset, ObjFile *File) {
621 warn("symbol scopes are not balanced in " + File->getName());
624 SymbolScope S = Stack.pop_back_val();
625 S.OpeningRecord->PtrEnd = CurOffset;
628 static bool symbolGoesInModuleStream(const CVSymbol &Sym) {
629 switch (Sym.kind()) {
630 case SymbolKind::S_GDATA32:
631 case SymbolKind::S_CONSTANT:
632 case SymbolKind::S_UDT:
633 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
634 // since they are synthesized by the linker in response to S_GPROC32 and
635 // S_LPROC32, but if we do see them, don't put them in the module stream I
637 case SymbolKind::S_PROCREF:
638 case SymbolKind::S_LPROCREF:
640 // S_GDATA32 does not go in the module stream, but S_LDATA32 does.
641 case SymbolKind::S_LDATA32:
647 static bool symbolGoesInGlobalsStream(const CVSymbol &Sym) {
648 switch (Sym.kind()) {
649 case SymbolKind::S_CONSTANT:
650 case SymbolKind::S_GDATA32:
651 // S_LDATA32 goes in both the module stream and the globals stream.
652 case SymbolKind::S_LDATA32:
653 case SymbolKind::S_GPROC32:
654 case SymbolKind::S_LPROC32:
655 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
656 // since they are synthesized by the linker in response to S_GPROC32 and
657 // S_LPROC32, but if we do see them, copy them straight through.
658 case SymbolKind::S_PROCREF:
659 case SymbolKind::S_LPROCREF:
661 // FIXME: For now, we drop all S_UDT symbols (i.e. they don't go in the
662 // globals stream or the modules stream). These have special handling which
663 // needs more investigation before we can get right, but by putting them all
664 // into the globals stream WinDbg fails to display local variables of class
665 // types saying that it cannot find the type Foo *. So as a stopgap just to
666 // keep things working, we drop them.
667 case SymbolKind::S_UDT:
673 static void addGlobalSymbol(pdb::GSIStreamBuilder &Builder, ObjFile &File,
674 const CVSymbol &Sym) {
675 switch (Sym.kind()) {
676 case SymbolKind::S_CONSTANT:
677 case SymbolKind::S_UDT:
678 case SymbolKind::S_GDATA32:
679 case SymbolKind::S_LDATA32:
680 case SymbolKind::S_PROCREF:
681 case SymbolKind::S_LPROCREF:
682 Builder.addGlobalSymbol(Sym);
684 case SymbolKind::S_GPROC32:
685 case SymbolKind::S_LPROC32: {
686 SymbolRecordKind K = SymbolRecordKind::ProcRefSym;
687 if (Sym.kind() == SymbolKind::S_LPROC32)
688 K = SymbolRecordKind::LocalProcRef;
690 PS.Module = static_cast<uint16_t>(File.ModuleDBI->getModuleIndex());
691 // For some reason, MSVC seems to add one to this value.
693 PS.Name = getSymbolName(Sym);
695 PS.SymOffset = File.ModuleDBI->getNextSymbolOffset();
696 Builder.addGlobalSymbol(PS);
700 llvm_unreachable("Invalid symbol kind!");
704 static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjFile *File,
705 pdb::GSIStreamBuilder &GsiBuilder,
706 const CVIndexMap &IndexMap,
707 TypeCollection &IDTable,
708 std::vector<ulittle32_t *> &StringTableRefs,
709 BinaryStreamRef SymData) {
710 // FIXME: Improve error recovery by warning and skipping records when
712 ArrayRef<uint8_t> SymsBuffer;
713 cantFail(SymData.readBytes(0, SymData.getLength(), SymsBuffer));
714 SmallVector<SymbolScope, 4> Scopes;
716 auto EC = forEachCodeViewRecord<CVSymbol>(
717 SymsBuffer, [&](const CVSymbol &Sym) -> llvm::Error {
718 // Discover type index references in the record. Skip it if we don't
719 // know where they are.
720 SmallVector<TiReference, 32> TypeRefs;
721 if (!discoverTypeIndicesInSymbol(Sym, TypeRefs)) {
722 log("ignoring unknown symbol record with kind 0x" +
723 utohexstr(Sym.kind()));
724 return Error::success();
727 // Copy the symbol record so we can mutate it.
728 MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
730 // Re-map all the type index references.
731 MutableArrayRef<uint8_t> Contents =
732 NewData.drop_front(sizeof(RecordPrefix));
733 remapTypesInSymbolRecord(File, Sym.kind(), Contents, IndexMap,
736 // An object file may have S_xxx_ID symbols, but these get converted to
737 // "real" symbols in a PDB.
738 translateIdSymbols(NewData, IDTable);
740 // If this record refers to an offset in the object file's string table,
741 // add that item to the global PDB string table and re-write the index.
742 recordStringTableReferences(Sym.kind(), Contents, StringTableRefs);
744 SymbolKind NewKind = symbolKind(NewData);
746 // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
747 CVSymbol NewSym(NewKind, NewData);
748 if (symbolOpensScope(NewKind))
749 scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(),
751 else if (symbolEndsScope(NewKind))
752 scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
754 // Add the symbol to the globals stream if necessary. Do this before
755 // adding the symbol to the module since we may need to get the next
756 // symbol offset, and writing to the module's symbol stream will update
758 if (symbolGoesInGlobalsStream(NewSym))
759 addGlobalSymbol(GsiBuilder, *File, NewSym);
761 // Add the symbol to the module.
762 if (symbolGoesInModuleStream(NewSym))
763 File->ModuleDBI->addSymbol(NewSym);
764 return Error::success();
766 cantFail(std::move(EC));
769 // Allocate memory for a .debug$S section and relocate it.
770 static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
771 SectionChunk *DebugChunk) {
772 uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk->getSize());
773 assert(DebugChunk->OutputSectionOff == 0 &&
774 "debug sections should not be in output sections");
775 DebugChunk->writeTo(Buffer);
776 return consumeDebugMagic(makeArrayRef(Buffer, DebugChunk->getSize()),
780 static pdb::SectionContrib createSectionContrib(const Chunk *C, uint32_t Modi) {
781 OutputSection *OS = C->getOutputSection();
782 pdb::SectionContrib SC;
783 memset(&SC, 0, sizeof(SC));
784 SC.ISect = OS->SectionIndex;
785 SC.Off = C->getRVA() - OS->getRVA();
786 SC.Size = C->getSize();
787 if (auto *SecChunk = dyn_cast<SectionChunk>(C)) {
788 SC.Characteristics = SecChunk->Header->Characteristics;
789 SC.Imod = SecChunk->File->ModuleDBI->getModuleIndex();
790 ArrayRef<uint8_t> Contents = SecChunk->getContents();
792 ArrayRef<char> CharContents = makeArrayRef(
793 reinterpret_cast<const char *>(Contents.data()), Contents.size());
794 CRC.update(CharContents);
795 SC.DataCrc = CRC.getCRC();
797 SC.Characteristics = OS->Header.Characteristics;
798 // FIXME: When we start creating DBI for import libraries, use those here.
801 SC.RelocCrc = 0; // FIXME
806 void PDBLinker::addObjFile(ObjFile *File) {
807 // Add a module descriptor for every object file. We need to put an absolute
808 // path to the object into the PDB. If this is a plain object, we make its
809 // path absolute. If it's an object in an archive, we make the archive path
811 bool InArchive = !File->ParentName.empty();
812 SmallString<128> Path = InArchive ? File->ParentName : File->getName();
813 sys::fs::make_absolute(Path);
814 sys::path::native(Path, sys::path::Style::windows);
815 StringRef Name = InArchive ? File->getName() : StringRef(Path);
817 File->ModuleDBI = &ExitOnErr(Builder.getDbiBuilder().addModuleInfo(Name));
818 File->ModuleDBI->setObjFileName(Path);
820 auto Chunks = File->getChunks();
821 uint32_t Modi = File->ModuleDBI->getModuleIndex();
822 for (Chunk *C : Chunks) {
823 auto *SecChunk = dyn_cast<SectionChunk>(C);
824 if (!SecChunk || !SecChunk->isLive())
826 pdb::SectionContrib SC = createSectionContrib(SecChunk, Modi);
827 File->ModuleDBI->setFirstSectionContrib(SC);
831 // Before we can process symbol substreams from .debug$S, we need to process
832 // type information, file checksums, and the string table. Add type info to
833 // the PDB first, so that we can get the map from object file type and item
834 // indices to PDB type and item indices.
835 CVIndexMap ObjectIndexMap;
836 auto IndexMapResult = mergeDebugT(File, ObjectIndexMap);
838 // If the .debug$T sections fail to merge, assume there is no debug info.
839 if (!IndexMapResult) {
840 warn("Type server PDB for " + Name + " is invalid, ignoring debug info. " +
841 toString(IndexMapResult.takeError()));
845 const CVIndexMap &IndexMap = *IndexMapResult;
847 ScopedTimer T(SymbolMergingTimer);
849 // Now do all live .debug$S sections.
850 DebugStringTableSubsectionRef CVStrTab;
851 DebugChecksumsSubsectionRef Checksums;
852 std::vector<ulittle32_t *> StringTableReferences;
853 for (SectionChunk *DebugChunk : File->getDebugChunks()) {
854 if (!DebugChunk->isLive() || DebugChunk->getSectionName() != ".debug$S")
857 ArrayRef<uint8_t> RelocatedDebugContents =
858 relocateDebugChunk(Alloc, DebugChunk);
859 if (RelocatedDebugContents.empty())
862 DebugSubsectionArray Subsections;
863 BinaryStreamReader Reader(RelocatedDebugContents, support::little);
864 ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
866 for (const DebugSubsectionRecord &SS : Subsections) {
868 case DebugSubsectionKind::StringTable: {
869 assert(!CVStrTab.valid() &&
870 "Encountered multiple string table subsections!");
871 ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
874 case DebugSubsectionKind::FileChecksums:
875 assert(!Checksums.valid() &&
876 "Encountered multiple checksum subsections!");
877 ExitOnErr(Checksums.initialize(SS.getRecordData()));
879 case DebugSubsectionKind::Lines:
880 // We can add the relocated line table directly to the PDB without
881 // modification because the file checksum offsets will stay the same.
882 File->ModuleDBI->addDebugSubsection(SS);
884 case DebugSubsectionKind::Symbols:
885 if (Config->DebugGHashes) {
886 mergeSymbolRecords(Alloc, File, Builder.getGsiBuilder(), IndexMap,
887 GlobalIDTable, StringTableReferences,
890 mergeSymbolRecords(Alloc, File, Builder.getGsiBuilder(), IndexMap,
891 IDTable, StringTableReferences,
896 // FIXME: Process the rest of the subsections.
902 // We should have seen all debug subsections across the entire object file now
903 // which means that if a StringTable subsection and Checksums subsection were
904 // present, now is the time to handle them.
905 if (!CVStrTab.valid()) {
906 if (Checksums.valid())
907 fatal(".debug$S sections with a checksums subsection must also contain a "
908 "string table subsection");
910 if (!StringTableReferences.empty())
911 warn("No StringTable subsection was encountered, but there are string "
916 // Rewrite each string table reference based on the value that the string
917 // assumes in the final PDB.
918 for (ulittle32_t *Ref : StringTableReferences) {
919 auto ExpectedString = CVStrTab.getString(*Ref);
920 if (!ExpectedString) {
921 warn("Invalid string table reference");
922 consumeError(ExpectedString.takeError());
926 *Ref = PDBStrTab.insert(*ExpectedString);
929 // Make a new file checksum table that refers to offsets in the PDB-wide
930 // string table. Generally the string table subsection appears after the
931 // checksum table, so we have to do this after looping over all the
933 auto NewChecksums = make_unique<DebugChecksumsSubsection>(PDBStrTab);
934 for (FileChecksumEntry &FC : Checksums) {
935 SmallString<128> FileName = ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
936 if (!sys::path::is_absolute(FileName) &&
937 !Config->PDBSourcePath.empty()) {
938 SmallString<128> AbsoluteFileName = Config->PDBSourcePath;
939 sys::path::append(AbsoluteFileName, FileName);
940 sys::path::native(AbsoluteFileName);
941 sys::path::remove_dots(AbsoluteFileName, /*remove_dot_dots=*/true);
942 FileName = std::move(AbsoluteFileName);
944 ExitOnErr(Builder.getDbiBuilder().addModuleSourceFile(*File->ModuleDBI,
946 NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
948 File->ModuleDBI->addDebugSubsection(std::move(NewChecksums));
951 static PublicSym32 createPublic(Defined *Def) {
952 PublicSym32 Pub(SymbolKind::S_PUB32);
953 Pub.Name = Def->getName();
954 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
955 if (D->getCOFFSymbol().isFunctionDefinition())
956 Pub.Flags = PublicSymFlags::Function;
957 } else if (isa<DefinedImportThunk>(Def)) {
958 Pub.Flags = PublicSymFlags::Function;
961 OutputSection *OS = Def->getChunk()->getOutputSection();
962 assert(OS && "all publics should be in final image");
963 Pub.Offset = Def->getRVA() - OS->getRVA();
964 Pub.Segment = OS->SectionIndex;
968 // Add all object files to the PDB. Merge .debug$T sections into IpiData and
970 void PDBLinker::addObjectsToPDB() {
971 ScopedTimer T1(AddObjectsTimer);
972 for (ObjFile *File : ObjFile::Instances)
975 Builder.getStringTableBuilder().setStrings(PDBStrTab);
978 // Construct TPI and IPI stream contents.
979 ScopedTimer T2(TpiStreamLayoutTimer);
980 if (Config->DebugGHashes) {
981 addTypeInfo(Builder.getTpiBuilder(), GlobalTypeTable);
982 addTypeInfo(Builder.getIpiBuilder(), GlobalIDTable);
984 addTypeInfo(Builder.getTpiBuilder(), TypeTable);
985 addTypeInfo(Builder.getIpiBuilder(), IDTable);
989 ScopedTimer T3(GlobalsLayoutTimer);
990 // Compute the public and global symbols.
991 auto &GsiBuilder = Builder.getGsiBuilder();
992 std::vector<PublicSym32> Publics;
993 Symtab->forEachSymbol([&Publics](Symbol *S) {
994 // Only emit defined, live symbols that have a chunk.
995 auto *Def = dyn_cast<Defined>(S);
996 if (Def && Def->isLive() && Def->getChunk())
997 Publics.push_back(createPublic(Def));
1000 if (!Publics.empty()) {
1001 // Sort the public symbols and add them to the stream.
1002 std::sort(Publics.begin(), Publics.end(),
1003 [](const PublicSym32 &L, const PublicSym32 &R) {
1004 return L.Name < R.Name;
1006 for (const PublicSym32 &Pub : Publics)
1007 GsiBuilder.addPublicSymbol(Pub);
1011 void PDBLinker::addNatvisFiles() {
1012 for (StringRef File : Config->NatvisFiles) {
1013 ErrorOr<std::unique_ptr<MemoryBuffer>> DataOrErr =
1014 MemoryBuffer::getFile(File);
1016 warn("Cannot open input file: " + File);
1019 Builder.addInjectedSource(File, std::move(*DataOrErr));
1023 static codeview::CPUType toCodeViewMachine(COFF::MachineTypes Machine) {
1025 case COFF::IMAGE_FILE_MACHINE_AMD64:
1026 return codeview::CPUType::X64;
1027 case COFF::IMAGE_FILE_MACHINE_ARM:
1028 return codeview::CPUType::ARM7;
1029 case COFF::IMAGE_FILE_MACHINE_ARM64:
1030 return codeview::CPUType::ARM64;
1031 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1032 return codeview::CPUType::ARMNT;
1033 case COFF::IMAGE_FILE_MACHINE_I386:
1034 return codeview::CPUType::Intel80386;
1036 llvm_unreachable("Unsupported CPU Type");
1040 static void addCommonLinkerModuleSymbols(StringRef Path,
1041 pdb::DbiModuleDescriptorBuilder &Mod,
1042 BumpPtrAllocator &Allocator) {
1043 ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
1044 Compile3Sym CS(SymbolRecordKind::Compile3Sym);
1045 EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
1047 ONS.Name = "* Linker *";
1050 CS.Machine = toCodeViewMachine(Config->Machine);
1051 // Interestingly, if we set the string to 0.0.0.0, then when trying to view
1052 // local variables WinDbg emits an error that private symbols are not present.
1053 // By setting this to a valid MSVC linker version string, local variables are
1054 // displayed properly. As such, even though it is not representative of
1055 // LLVM's version information, we need this for compatibility.
1056 CS.Flags = CompileSym3Flags::None;
1057 CS.VersionBackendBuild = 25019;
1058 CS.VersionBackendMajor = 14;
1059 CS.VersionBackendMinor = 10;
1060 CS.VersionBackendQFE = 0;
1062 // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
1063 // linker module (which is by definition a backend), so we don't need to do
1064 // anything here. Also, it seems we can use "LLVM Linker" for the linker name
1065 // without any problems. Only the backend version has to be hardcoded to a
1067 CS.VersionFrontendBuild = 0;
1068 CS.VersionFrontendMajor = 0;
1069 CS.VersionFrontendMinor = 0;
1070 CS.VersionFrontendQFE = 0;
1071 CS.Version = "LLVM Linker";
1072 CS.setLanguage(SourceLanguage::Link);
1074 ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
1075 std::string ArgStr = llvm::join(Args, " ");
1076 EBS.Fields.push_back("cwd");
1077 SmallString<64> cwd;
1078 sys::fs::current_path(cwd);
1079 EBS.Fields.push_back(cwd);
1080 EBS.Fields.push_back("exe");
1081 SmallString<64> exe = Config->Argv[0];
1082 llvm::sys::fs::make_absolute(exe);
1083 EBS.Fields.push_back(exe);
1084 EBS.Fields.push_back("pdb");
1085 EBS.Fields.push_back(Path);
1086 EBS.Fields.push_back("cmd");
1087 EBS.Fields.push_back(ArgStr);
1088 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1089 ONS, Allocator, CodeViewContainer::Pdb));
1090 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1091 CS, Allocator, CodeViewContainer::Pdb));
1092 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1093 EBS, Allocator, CodeViewContainer::Pdb));
1096 static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &Mod,
1098 BumpPtrAllocator &Allocator) {
1099 SectionSym Sym(SymbolRecordKind::SectionSym);
1100 Sym.Alignment = 12; // 2^12 = 4KB
1101 Sym.Characteristics = OS.Header.Characteristics;
1102 Sym.Length = OS.getVirtualSize();
1104 Sym.Rva = OS.getRVA();
1105 Sym.SectionNumber = OS.SectionIndex;
1106 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1107 Sym, Allocator, CodeViewContainer::Pdb));
1110 // Creates a PDB file.
1111 void coff::createPDB(SymbolTable *Symtab,
1112 ArrayRef<OutputSection *> OutputSections,
1113 ArrayRef<uint8_t> SectionTable,
1114 const llvm::codeview::DebugInfo &BuildId) {
1115 ScopedTimer T1(TotalPdbLinkTimer);
1116 PDBLinker PDB(Symtab);
1118 PDB.initialize(BuildId);
1119 PDB.addObjectsToPDB();
1120 PDB.addSections(OutputSections, SectionTable);
1121 PDB.addNatvisFiles();
1123 ScopedTimer T2(DiskCommitTimer);
1127 void PDBLinker::initialize(const llvm::codeview::DebugInfo &BuildId) {
1128 ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
1130 // Create streams in MSF for predefined streams, namely
1131 // PDB, TPI, DBI and IPI.
1132 for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
1133 ExitOnErr(Builder.getMsfBuilder().addStream(0));
1135 // Add an Info stream.
1136 auto &InfoBuilder = Builder.getInfoBuilder();
1138 memcpy(&uuid, &BuildId.PDB70.Signature, sizeof(uuid));
1139 InfoBuilder.setAge(BuildId.PDB70.Age);
1140 InfoBuilder.setGuid(uuid);
1141 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
1143 // Add an empty DBI stream.
1144 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
1145 DbiBuilder.setAge(BuildId.PDB70.Age);
1146 DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
1147 DbiBuilder.setMachineType(Config->Machine);
1148 // Technically we are not link.exe 14.11, but there are known cases where
1149 // debugging tools on Windows expect Microsoft-specific version numbers or
1150 // they fail to work at all. Since we know we produce PDBs that are
1151 // compatible with LINK 14.11, we set that version number here.
1152 DbiBuilder.setBuildNumber(14, 11);
1155 void PDBLinker::addSections(ArrayRef<OutputSection *> OutputSections,
1156 ArrayRef<uint8_t> SectionTable) {
1157 // It's not entirely clear what this is, but the * Linker * module uses it.
1158 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
1159 NativePath = Config->PDBPath;
1160 sys::fs::make_absolute(NativePath);
1161 sys::path::native(NativePath, sys::path::Style::windows);
1162 uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
1163 auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
1164 LinkerModule.setPdbFilePathNI(PdbFilePathNI);
1165 addCommonLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
1167 // Add section contributions. They must be ordered by ascending RVA.
1168 for (OutputSection *OS : OutputSections) {
1169 addLinkerModuleSectionSymbol(LinkerModule, *OS, Alloc);
1170 for (Chunk *C : OS->getChunks()) {
1171 pdb::SectionContrib SC =
1172 createSectionContrib(C, LinkerModule.getModuleIndex());
1173 Builder.getDbiBuilder().addSectionContrib(SC);
1177 // Add Section Map stream.
1178 ArrayRef<object::coff_section> Sections = {
1179 (const object::coff_section *)SectionTable.data(),
1180 SectionTable.size() / sizeof(object::coff_section)};
1181 SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
1182 DbiBuilder.setSectionMap(SectionMap);
1184 // Add COFF section header stream.
1186 DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
1189 void PDBLinker::commit() {
1191 ExitOnErr(Builder.commit(Config->PDBPath));
1194 static Expected<StringRef>
1195 getFileName(const DebugStringTableSubsectionRef &Strings,
1196 const DebugChecksumsSubsectionRef &Checksums, uint32_t FileID) {
1197 auto Iter = Checksums.getArray().at(FileID);
1198 if (Iter == Checksums.getArray().end())
1199 return make_error<CodeViewError>(cv_error_code::no_records);
1200 uint32_t Offset = Iter->FileNameOffset;
1201 return Strings.getString(Offset);
1204 static uint32_t getSecrelReloc() {
1205 switch (Config->Machine) {
1207 return COFF::IMAGE_REL_AMD64_SECREL;
1209 return COFF::IMAGE_REL_I386_SECREL;
1211 return COFF::IMAGE_REL_ARM_SECREL;
1213 return COFF::IMAGE_REL_ARM64_SECREL;
1215 llvm_unreachable("unknown machine type");
1219 // Try to find a line table for the given offset Addr into the given chunk C.
1220 // If a line table was found, the line table, the string and checksum tables
1221 // that are used to interpret the line table, and the offset of Addr in the line
1222 // table are stored in the output arguments. Returns whether a line table was
1224 static bool findLineTable(const SectionChunk *C, uint32_t Addr,
1225 DebugStringTableSubsectionRef &CVStrTab,
1226 DebugChecksumsSubsectionRef &Checksums,
1227 DebugLinesSubsectionRef &Lines,
1228 uint32_t &OffsetInLinetable) {
1229 ExitOnError ExitOnErr;
1230 uint32_t SecrelReloc = getSecrelReloc();
1232 for (SectionChunk *DbgC : C->File->getDebugChunks()) {
1233 if (DbgC->getSectionName() != ".debug$S")
1236 // Build a mapping of SECREL relocations in DbgC that refer to C.
1237 DenseMap<uint32_t, uint32_t> Secrels;
1238 for (const coff_relocation &R : DbgC->Relocs) {
1239 if (R.Type != SecrelReloc)
1242 if (auto *S = dyn_cast_or_null<DefinedRegular>(
1243 C->File->getSymbols()[R.SymbolTableIndex]))
1244 if (S->getChunk() == C)
1245 Secrels[R.VirtualAddress] = S->getValue();
1248 ArrayRef<uint8_t> Contents =
1249 consumeDebugMagic(DbgC->getContents(), ".debug$S");
1250 DebugSubsectionArray Subsections;
1251 BinaryStreamReader Reader(Contents, support::little);
1252 ExitOnErr(Reader.readArray(Subsections, Contents.size()));
1254 for (const DebugSubsectionRecord &SS : Subsections) {
1255 switch (SS.kind()) {
1256 case DebugSubsectionKind::StringTable: {
1257 assert(!CVStrTab.valid() &&
1258 "Encountered multiple string table subsections!");
1259 ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
1262 case DebugSubsectionKind::FileChecksums:
1263 assert(!Checksums.valid() &&
1264 "Encountered multiple checksum subsections!");
1265 ExitOnErr(Checksums.initialize(SS.getRecordData()));
1267 case DebugSubsectionKind::Lines: {
1268 ArrayRef<uint8_t> Bytes;
1269 auto Ref = SS.getRecordData();
1270 ExitOnErr(Ref.readLongestContiguousChunk(0, Bytes));
1271 size_t OffsetInDbgC = Bytes.data() - DbgC->getContents().data();
1273 // Check whether this line table refers to C.
1274 auto I = Secrels.find(OffsetInDbgC);
1275 if (I == Secrels.end())
1278 // Check whether this line table covers Addr in C.
1279 DebugLinesSubsectionRef LinesTmp;
1280 ExitOnErr(LinesTmp.initialize(BinaryStreamReader(Ref)));
1281 uint32_t OffsetInC = I->second + LinesTmp.header()->RelocOffset;
1282 if (Addr < OffsetInC || Addr >= OffsetInC + LinesTmp.header()->CodeSize)
1285 assert(!Lines.header() &&
1286 "Encountered multiple line tables for function!");
1287 ExitOnErr(Lines.initialize(BinaryStreamReader(Ref)));
1288 OffsetInLinetable = Addr - OffsetInC;
1295 if (CVStrTab.valid() && Checksums.valid() && Lines.header())
1303 // Use CodeView line tables to resolve a file and line number for the given
1304 // offset into the given chunk and return them, or {"", 0} if a line table was
1306 std::pair<StringRef, uint32_t> coff::getFileLine(const SectionChunk *C,
1308 ExitOnError ExitOnErr;
1310 DebugStringTableSubsectionRef CVStrTab;
1311 DebugChecksumsSubsectionRef Checksums;
1312 DebugLinesSubsectionRef Lines;
1313 uint32_t OffsetInLinetable;
1315 if (!findLineTable(C, Addr, CVStrTab, Checksums, Lines, OffsetInLinetable))
1319 uint32_t LineNumber;
1320 for (LineColumnEntry &Entry : Lines) {
1321 for (const LineNumberEntry &LN : Entry.LineNumbers) {
1322 if (LN.Offset > OffsetInLinetable) {
1323 StringRef Filename =
1324 ExitOnErr(getFileName(CVStrTab, Checksums, NameIndex));
1325 return {Filename, LineNumber};
1327 LineInfo LI(LN.Flags);
1328 NameIndex = Entry.NameIndex;
1329 LineNumber = LI.getStartLine();
1332 StringRef Filename = ExitOnErr(getFileName(CVStrTab, Checksums, NameIndex));
1333 return {Filename, LineNumber};