Path: blob/main/contrib/llvm-project/lld/COFF/PDB.cpp
34870 views
//===- PDB.cpp ------------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "PDB.h"9#include "COFFLinkerContext.h"10#include "Chunks.h"11#include "Config.h"12#include "DebugTypes.h"13#include "Driver.h"14#include "SymbolTable.h"15#include "Symbols.h"16#include "TypeMerger.h"17#include "Writer.h"18#include "lld/Common/Timer.h"19#include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"20#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"21#include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"22#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"23#include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"24#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"25#include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"26#include "llvm/DebugInfo/CodeView/RecordName.h"27#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"28#include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h"29#include "llvm/DebugInfo/CodeView/SymbolSerializer.h"30#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"31#include "llvm/DebugInfo/MSF/MSFBuilder.h"32#include "llvm/DebugInfo/MSF/MSFCommon.h"33#include "llvm/DebugInfo/MSF/MSFError.h"34#include "llvm/DebugInfo/PDB/GenericError.h"35#include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"36#include "llvm/DebugInfo/PDB/Native/DbiStream.h"37#include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"38#include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h"39#include "llvm/DebugInfo/PDB/Native/InfoStream.h"40#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"41#include "llvm/DebugInfo/PDB/Native/NativeSession.h"42#include "llvm/DebugInfo/PDB/Native/PDBFile.h"43#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"44#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"45#include "llvm/DebugInfo/PDB/Native/TpiHashing.h"46#include "llvm/DebugInfo/PDB/Native/TpiStream.h"47#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"48#include "llvm/DebugInfo/PDB/PDB.h"49#include "llvm/Object/COFF.h"50#include "llvm/Object/CVDebugRecord.h"51#include "llvm/Support/BinaryByteStream.h"52#include "llvm/Support/CRC.h"53#include "llvm/Support/Endian.h"54#include "llvm/Support/Errc.h"55#include "llvm/Support/FormatAdapters.h"56#include "llvm/Support/FormatVariadic.h"57#include "llvm/Support/Path.h"58#include "llvm/Support/ScopedPrinter.h"59#include "llvm/Support/TimeProfiler.h"60#include <memory>61#include <optional>6263using namespace llvm;64using namespace llvm::codeview;65using namespace lld;66using namespace lld::coff;6768using llvm::object::coff_section;69using llvm::pdb::StringTableFixup;7071namespace {72class DebugSHandler;7374class PDBLinker {75friend DebugSHandler;7677public:78PDBLinker(COFFLinkerContext &ctx)79: builder(bAlloc()), tMerger(ctx, bAlloc()), ctx(ctx) {80// This isn't strictly necessary, but link.exe usually puts an empty string81// as the first "valid" string in the string table, so we do the same in82// order to maintain as much byte-for-byte compatibility as possible.83pdbStrTab.insert("");84}8586/// Emit the basic PDB structure: initial streams, headers, etc.87void initialize(llvm::codeview::DebugInfo *buildId);8889/// Add natvis files specified on the command line.90void addNatvisFiles();9192/// Add named streams specified on the command line.93void addNamedStreams();9495/// Link CodeView from each object file in the symbol table into the PDB.96void addObjectsToPDB();9798/// Add every live, defined public symbol to the PDB.99void addPublicsToPDB();100101/// Link info for each import file in the symbol table into the PDB.102void addImportFilesToPDB();103104void createModuleDBI(ObjFile *file);105106/// Link CodeView from a single object file into the target (output) PDB.107/// When a precompiled headers object is linked, its TPI map might be provided108/// externally.109void addDebug(TpiSource *source);110111void addDebugSymbols(TpiSource *source);112113// Analyze the symbol records to separate module symbols from global symbols,114// find string references, and calculate how large the symbol stream will be115// in the PDB.116void analyzeSymbolSubsection(SectionChunk *debugChunk,117uint32_t &moduleSymOffset,118uint32_t &nextRelocIndex,119std::vector<StringTableFixup> &stringTableFixups,120BinaryStreamRef symData);121122// Write all module symbols from all live debug symbol subsections of the123// given object file into the given stream writer.124Error writeAllModuleSymbolRecords(ObjFile *file, BinaryStreamWriter &writer);125126// Callback to copy and relocate debug symbols during PDB file writing.127static Error commitSymbolsForObject(void *ctx, void *obj,128BinaryStreamWriter &writer);129130// Copy the symbol record, relocate it, and fix the alignment if necessary.131// Rewrite type indices in the record. Replace unrecognized symbol records132// with S_SKIP records.133void writeSymbolRecord(SectionChunk *debugChunk,134ArrayRef<uint8_t> sectionContents, CVSymbol sym,135size_t alignedSize, uint32_t &nextRelocIndex,136std::vector<uint8_t> &storage);137138/// Add the section map and section contributions to the PDB.139void addSections(ArrayRef<uint8_t> sectionTable);140141/// Write the PDB to disk and store the Guid generated for it in *Guid.142void commit(codeview::GUID *guid);143144// Print statistics regarding the final PDB145void printStats();146147private:148void pdbMakeAbsolute(SmallVectorImpl<char> &fileName);149void translateIdSymbols(MutableArrayRef<uint8_t> &recordData,150TpiSource *source);151void addCommonLinkerModuleSymbols(StringRef path,152pdb::DbiModuleDescriptorBuilder &mod);153154pdb::PDBFileBuilder builder;155156TypeMerger tMerger;157158COFFLinkerContext &ctx;159160/// PDBs use a single global string table for filenames in the file checksum161/// table.162DebugStringTableSubsection pdbStrTab;163164llvm::SmallString<128> nativePath;165166// For statistics167uint64_t globalSymbols = 0;168uint64_t moduleSymbols = 0;169uint64_t publicSymbols = 0;170uint64_t nbTypeRecords = 0;171uint64_t nbTypeRecordsBytes = 0;172};173174/// Represents an unrelocated DEBUG_S_FRAMEDATA subsection.175struct UnrelocatedFpoData {176SectionChunk *debugChunk = nullptr;177ArrayRef<uint8_t> subsecData;178uint32_t relocIndex = 0;179};180181/// The size of the magic bytes at the beginning of a symbol section or stream.182enum : uint32_t { kSymbolStreamMagicSize = 4 };183184class DebugSHandler {185PDBLinker &linker;186187/// The object file whose .debug$S sections we're processing.188ObjFile &file;189190/// The DEBUG_S_STRINGTABLE subsection. These strings are referred to by191/// index from other records in the .debug$S section. All of these strings192/// need to be added to the global PDB string table, and all references to193/// these strings need to have their indices re-written to refer to the194/// global PDB string table.195DebugStringTableSubsectionRef cvStrTab;196197/// The DEBUG_S_FILECHKSMS subsection. As above, these are referred to198/// by other records in the .debug$S section and need to be merged into the199/// PDB.200DebugChecksumsSubsectionRef checksums;201202/// The DEBUG_S_FRAMEDATA subsection(s). There can be more than one of203/// these and they need not appear in any specific order. However, they204/// contain string table references which need to be re-written, so we205/// collect them all here and re-write them after all subsections have been206/// discovered and processed.207std::vector<UnrelocatedFpoData> frameDataSubsecs;208209/// List of string table references in symbol records. Later they will be210/// applied to the symbols during PDB writing.211std::vector<StringTableFixup> stringTableFixups;212213/// Sum of the size of all module symbol records across all .debug$S sections.214/// Includes record realignment and the size of the symbol stream magic215/// prefix.216uint32_t moduleStreamSize = kSymbolStreamMagicSize;217218/// Next relocation index in the current .debug$S section. Resets every219/// handleDebugS call.220uint32_t nextRelocIndex = 0;221222void advanceRelocIndex(SectionChunk *debugChunk, ArrayRef<uint8_t> subsec);223224void addUnrelocatedSubsection(SectionChunk *debugChunk,225const DebugSubsectionRecord &ss);226227void addFrameDataSubsection(SectionChunk *debugChunk,228const DebugSubsectionRecord &ss);229230public:231DebugSHandler(PDBLinker &linker, ObjFile &file)232: linker(linker), file(file) {}233234void handleDebugS(SectionChunk *debugChunk);235236void finish();237};238}239240// Visual Studio's debugger requires absolute paths in various places in the241// PDB to work without additional configuration:242// https://docs.microsoft.com/en-us/visualstudio/debugger/debug-source-files-common-properties-solution-property-pages-dialog-box243void PDBLinker::pdbMakeAbsolute(SmallVectorImpl<char> &fileName) {244// The default behavior is to produce paths that are valid within the context245// of the machine that you perform the link on. If the linker is running on246// a POSIX system, we will output absolute POSIX paths. If the linker is247// running on a Windows system, we will output absolute Windows paths. If the248// user desires any other kind of behavior, they should explicitly pass249// /pdbsourcepath, in which case we will treat the exact string the user250// passed in as the gospel and not normalize, canonicalize it.251if (sys::path::is_absolute(fileName, sys::path::Style::windows) ||252sys::path::is_absolute(fileName, sys::path::Style::posix))253return;254255// It's not absolute in any path syntax. Relative paths necessarily refer to256// the local file system, so we can make it native without ending up with a257// nonsensical path.258if (ctx.config.pdbSourcePath.empty()) {259sys::path::native(fileName);260sys::fs::make_absolute(fileName);261sys::path::remove_dots(fileName, true);262return;263}264265// Try to guess whether /PDBSOURCEPATH is a unix path or a windows path.266// Since PDB's are more of a Windows thing, we make this conservative and only267// decide that it's a unix path if we're fairly certain. Specifically, if268// it starts with a forward slash.269SmallString<128> absoluteFileName = ctx.config.pdbSourcePath;270sys::path::Style guessedStyle = absoluteFileName.starts_with("/")271? sys::path::Style::posix272: sys::path::Style::windows;273sys::path::append(absoluteFileName, guessedStyle, fileName);274sys::path::native(absoluteFileName, guessedStyle);275sys::path::remove_dots(absoluteFileName, true, guessedStyle);276277fileName = std::move(absoluteFileName);278}279280static void addTypeInfo(pdb::TpiStreamBuilder &tpiBuilder,281TypeCollection &typeTable) {282// Start the TPI or IPI stream header.283tpiBuilder.setVersionHeader(pdb::PdbTpiV80);284285// Flatten the in memory type table and hash each type.286typeTable.ForEachRecord([&](TypeIndex ti, const CVType &type) {287auto hash = pdb::hashTypeRecord(type);288if (auto e = hash.takeError())289fatal("type hashing error");290tpiBuilder.addTypeRecord(type.RecordData, *hash);291});292}293294static void addGHashTypeInfo(COFFLinkerContext &ctx,295pdb::PDBFileBuilder &builder) {296// Start the TPI or IPI stream header.297builder.getTpiBuilder().setVersionHeader(pdb::PdbTpiV80);298builder.getIpiBuilder().setVersionHeader(pdb::PdbTpiV80);299for (TpiSource *source : ctx.tpiSourceList) {300builder.getTpiBuilder().addTypeRecords(source->mergedTpi.recs,301source->mergedTpi.recSizes,302source->mergedTpi.recHashes);303builder.getIpiBuilder().addTypeRecords(source->mergedIpi.recs,304source->mergedIpi.recSizes,305source->mergedIpi.recHashes);306}307}308309static void310recordStringTableReferences(CVSymbol sym, uint32_t symOffset,311std::vector<StringTableFixup> &stringTableFixups) {312// For now we only handle S_FILESTATIC, but we may need the same logic for313// S_DEFRANGE and S_DEFRANGE_SUBFIELD. However, I cannot seem to generate any314// PDBs that contain these types of records, so because of the uncertainty315// they are omitted here until we can prove that it's necessary.316switch (sym.kind()) {317case SymbolKind::S_FILESTATIC: {318// FileStaticSym::ModFileOffset319uint32_t ref = *reinterpret_cast<const ulittle32_t *>(&sym.data()[8]);320stringTableFixups.push_back({ref, symOffset + 8});321break;322}323case SymbolKind::S_DEFRANGE:324case SymbolKind::S_DEFRANGE_SUBFIELD:325log("Not fixing up string table reference in S_DEFRANGE / "326"S_DEFRANGE_SUBFIELD record");327break;328default:329break;330}331}332333static SymbolKind symbolKind(ArrayRef<uint8_t> recordData) {334const RecordPrefix *prefix =335reinterpret_cast<const RecordPrefix *>(recordData.data());336return static_cast<SymbolKind>(uint16_t(prefix->RecordKind));337}338339/// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32340void PDBLinker::translateIdSymbols(MutableArrayRef<uint8_t> &recordData,341TpiSource *source) {342RecordPrefix *prefix = reinterpret_cast<RecordPrefix *>(recordData.data());343344SymbolKind kind = symbolKind(recordData);345346if (kind == SymbolKind::S_PROC_ID_END) {347prefix->RecordKind = SymbolKind::S_END;348return;349}350351// In an object file, GPROC32_ID has an embedded reference which refers to the352// single object file type index namespace. This has already been translated353// to the PDB file's ID stream index space, but we need to convert this to a354// symbol that refers to the type stream index space. So we remap again from355// ID index space to type index space.356if (kind == SymbolKind::S_GPROC32_ID || kind == SymbolKind::S_LPROC32_ID) {357SmallVector<TiReference, 1> refs;358auto content = recordData.drop_front(sizeof(RecordPrefix));359CVSymbol sym(recordData);360discoverTypeIndicesInSymbol(sym, refs);361assert(refs.size() == 1);362assert(refs.front().Count == 1);363364TypeIndex *ti =365reinterpret_cast<TypeIndex *>(content.data() + refs[0].Offset);366// `ti` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in367// the IPI stream, whose `FunctionType` member refers to the TPI stream.368// Note that LF_FUNC_ID and LF_MFUNC_ID have the same record layout, and369// in both cases we just need the second type index.370if (!ti->isSimple() && !ti->isNoneType()) {371TypeIndex newType = TypeIndex(SimpleTypeKind::NotTranslated);372if (ctx.config.debugGHashes) {373auto idToType = tMerger.funcIdToType.find(*ti);374if (idToType != tMerger.funcIdToType.end())375newType = idToType->second;376} else {377if (tMerger.getIDTable().contains(*ti)) {378CVType funcIdData = tMerger.getIDTable().getType(*ti);379if (funcIdData.length() >= 8 && (funcIdData.kind() == LF_FUNC_ID ||380funcIdData.kind() == LF_MFUNC_ID)) {381newType = *reinterpret_cast<const TypeIndex *>(&funcIdData.data()[8]);382}383}384}385if (newType == TypeIndex(SimpleTypeKind::NotTranslated)) {386warn(formatv("procedure symbol record for `{0}` in {1} refers to PDB "387"item index {2:X} which is not a valid function ID record",388getSymbolName(CVSymbol(recordData)),389source->file->getName(), ti->getIndex()));390}391*ti = newType;392}393394kind = (kind == SymbolKind::S_GPROC32_ID) ? SymbolKind::S_GPROC32395: SymbolKind::S_LPROC32;396prefix->RecordKind = uint16_t(kind);397}398}399400namespace {401struct ScopeRecord {402ulittle32_t ptrParent;403ulittle32_t ptrEnd;404};405} // namespace406407/// Given a pointer to a symbol record that opens a scope, return a pointer to408/// the scope fields.409static ScopeRecord *getSymbolScopeFields(void *sym) {410return reinterpret_cast<ScopeRecord *>(reinterpret_cast<char *>(sym) +411sizeof(RecordPrefix));412}413414// To open a scope, push the offset of the current symbol record onto the415// stack.416static void scopeStackOpen(SmallVectorImpl<uint32_t> &stack,417std::vector<uint8_t> &storage) {418stack.push_back(storage.size());419}420421// To close a scope, update the record that opened the scope.422static void scopeStackClose(SmallVectorImpl<uint32_t> &stack,423std::vector<uint8_t> &storage,424uint32_t storageBaseOffset, ObjFile *file) {425if (stack.empty()) {426warn("symbol scopes are not balanced in " + file->getName());427return;428}429430// Update ptrEnd of the record that opened the scope to point to the431// current record, if we are writing into the module symbol stream.432uint32_t offOpen = stack.pop_back_val();433uint32_t offEnd = storageBaseOffset + storage.size();434uint32_t offParent = stack.empty() ? 0 : (stack.back() + storageBaseOffset);435ScopeRecord *scopeRec = getSymbolScopeFields(&(storage)[offOpen]);436scopeRec->ptrParent = offParent;437scopeRec->ptrEnd = offEnd;438}439440static bool symbolGoesInModuleStream(const CVSymbol &sym,441unsigned symbolScopeDepth) {442switch (sym.kind()) {443case SymbolKind::S_GDATA32:444case SymbolKind::S_GTHREAD32:445// We really should not be seeing S_PROCREF and S_LPROCREF in the first place446// since they are synthesized by the linker in response to S_GPROC32 and447// S_LPROC32, but if we do see them, don't put them in the module stream I448// guess.449case SymbolKind::S_PROCREF:450case SymbolKind::S_LPROCREF:451return false;452// S_UDT and S_CONSTANT records go in the module stream if it is not a global record.453case SymbolKind::S_UDT:454case SymbolKind::S_CONSTANT:455return symbolScopeDepth > 0;456// S_GDATA32 does not go in the module stream, but S_LDATA32 does.457case SymbolKind::S_LDATA32:458case SymbolKind::S_LTHREAD32:459default:460return true;461}462}463464static bool symbolGoesInGlobalsStream(const CVSymbol &sym,465unsigned symbolScopeDepth) {466switch (sym.kind()) {467case SymbolKind::S_GDATA32:468case SymbolKind::S_GTHREAD32:469case SymbolKind::S_GPROC32:470case SymbolKind::S_LPROC32:471case SymbolKind::S_GPROC32_ID:472case SymbolKind::S_LPROC32_ID:473// We really should not be seeing S_PROCREF and S_LPROCREF in the first place474// since they are synthesized by the linker in response to S_GPROC32 and475// S_LPROC32, but if we do see them, copy them straight through.476case SymbolKind::S_PROCREF:477case SymbolKind::S_LPROCREF:478return true;479// Records that go in the globals stream, unless they are function-local.480case SymbolKind::S_UDT:481case SymbolKind::S_LDATA32:482case SymbolKind::S_LTHREAD32:483case SymbolKind::S_CONSTANT:484return symbolScopeDepth == 0;485default:486return false;487}488}489490static void addGlobalSymbol(pdb::GSIStreamBuilder &builder, uint16_t modIndex,491unsigned symOffset,492std::vector<uint8_t> &symStorage) {493CVSymbol sym{ArrayRef(symStorage)};494switch (sym.kind()) {495case SymbolKind::S_CONSTANT:496case SymbolKind::S_UDT:497case SymbolKind::S_GDATA32:498case SymbolKind::S_GTHREAD32:499case SymbolKind::S_LTHREAD32:500case SymbolKind::S_LDATA32:501case SymbolKind::S_PROCREF:502case SymbolKind::S_LPROCREF: {503// sym is a temporary object, so we have to copy and reallocate the record504// to stabilize it.505uint8_t *mem = bAlloc().Allocate<uint8_t>(sym.length());506memcpy(mem, sym.data().data(), sym.length());507builder.addGlobalSymbol(CVSymbol(ArrayRef(mem, sym.length())));508break;509}510case SymbolKind::S_GPROC32:511case SymbolKind::S_LPROC32: {512SymbolRecordKind k = SymbolRecordKind::ProcRefSym;513if (sym.kind() == SymbolKind::S_LPROC32)514k = SymbolRecordKind::LocalProcRef;515ProcRefSym ps(k);516ps.Module = modIndex;517// For some reason, MSVC seems to add one to this value.518++ps.Module;519ps.Name = getSymbolName(sym);520ps.SumName = 0;521ps.SymOffset = symOffset;522builder.addGlobalSymbol(ps);523break;524}525default:526llvm_unreachable("Invalid symbol kind!");527}528}529530// Check if the given symbol record was padded for alignment. If so, zero out531// the padding bytes and update the record prefix with the new size.532static void fixRecordAlignment(MutableArrayRef<uint8_t> recordBytes,533size_t oldSize) {534size_t alignedSize = recordBytes.size();535if (oldSize == alignedSize)536return;537reinterpret_cast<RecordPrefix *>(recordBytes.data())->RecordLen =538alignedSize - 2;539memset(recordBytes.data() + oldSize, 0, alignedSize - oldSize);540}541542// Replace any record with a skip record of the same size. This is useful when543// we have reserved size for a symbol record, but type index remapping fails.544static void replaceWithSkipRecord(MutableArrayRef<uint8_t> recordBytes) {545memset(recordBytes.data(), 0, recordBytes.size());546auto *prefix = reinterpret_cast<RecordPrefix *>(recordBytes.data());547prefix->RecordKind = SymbolKind::S_SKIP;548prefix->RecordLen = recordBytes.size() - 2;549}550551// Copy the symbol record, relocate it, and fix the alignment if necessary.552// Rewrite type indices in the record. Replace unrecognized symbol records with553// S_SKIP records.554void PDBLinker::writeSymbolRecord(SectionChunk *debugChunk,555ArrayRef<uint8_t> sectionContents,556CVSymbol sym, size_t alignedSize,557uint32_t &nextRelocIndex,558std::vector<uint8_t> &storage) {559// Allocate space for the new record at the end of the storage.560storage.resize(storage.size() + alignedSize);561auto recordBytes = MutableArrayRef<uint8_t>(storage).take_back(alignedSize);562563// Copy the symbol record and relocate it.564debugChunk->writeAndRelocateSubsection(sectionContents, sym.data(),565nextRelocIndex, recordBytes.data());566fixRecordAlignment(recordBytes, sym.length());567568// Re-map all the type index references.569TpiSource *source = debugChunk->file->debugTypesObj;570if (!source->remapTypesInSymbolRecord(recordBytes)) {571log("ignoring unknown symbol record with kind 0x" + utohexstr(sym.kind()));572replaceWithSkipRecord(recordBytes);573}574575// An object file may have S_xxx_ID symbols, but these get converted to576// "real" symbols in a PDB.577translateIdSymbols(recordBytes, source);578}579580void PDBLinker::analyzeSymbolSubsection(581SectionChunk *debugChunk, uint32_t &moduleSymOffset,582uint32_t &nextRelocIndex, std::vector<StringTableFixup> &stringTableFixups,583BinaryStreamRef symData) {584ObjFile *file = debugChunk->file;585uint32_t moduleSymStart = moduleSymOffset;586587uint32_t scopeLevel = 0;588std::vector<uint8_t> storage;589ArrayRef<uint8_t> sectionContents = debugChunk->getContents();590591ArrayRef<uint8_t> symsBuffer;592cantFail(symData.readBytes(0, symData.getLength(), symsBuffer));593594if (symsBuffer.empty())595warn("empty symbols subsection in " + file->getName());596597Error ec = forEachCodeViewRecord<CVSymbol>(598symsBuffer, [&](CVSymbol sym) -> llvm::Error {599// Track the current scope.600if (symbolOpensScope(sym.kind()))601++scopeLevel;602else if (symbolEndsScope(sym.kind()))603--scopeLevel;604605uint32_t alignedSize =606alignTo(sym.length(), alignOf(CodeViewContainer::Pdb));607608// Copy global records. Some global records (mainly procedures)609// reference the current offset into the module stream.610if (symbolGoesInGlobalsStream(sym, scopeLevel)) {611storage.clear();612writeSymbolRecord(debugChunk, sectionContents, sym, alignedSize,613nextRelocIndex, storage);614addGlobalSymbol(builder.getGsiBuilder(),615file->moduleDBI->getModuleIndex(), moduleSymOffset,616storage);617++globalSymbols;618}619620// Update the module stream offset and record any string table index621// references. There are very few of these and they will be rewritten622// later during PDB writing.623if (symbolGoesInModuleStream(sym, scopeLevel)) {624recordStringTableReferences(sym, moduleSymOffset, stringTableFixups);625moduleSymOffset += alignedSize;626++moduleSymbols;627}628629return Error::success();630});631632// If we encountered corrupt records, ignore the whole subsection. If we wrote633// any partial records, undo that. For globals, we just keep what we have and634// continue.635if (ec) {636warn("corrupt symbol records in " + file->getName());637moduleSymOffset = moduleSymStart;638consumeError(std::move(ec));639}640}641642Error PDBLinker::writeAllModuleSymbolRecords(ObjFile *file,643BinaryStreamWriter &writer) {644ExitOnError exitOnErr;645std::vector<uint8_t> storage;646SmallVector<uint32_t, 4> scopes;647648// Visit all live .debug$S sections a second time, and write them to the PDB.649for (SectionChunk *debugChunk : file->getDebugChunks()) {650if (!debugChunk->live || debugChunk->getSize() == 0 ||651debugChunk->getSectionName() != ".debug$S")652continue;653654ArrayRef<uint8_t> sectionContents = debugChunk->getContents();655auto contents =656SectionChunk::consumeDebugMagic(sectionContents, ".debug$S");657DebugSubsectionArray subsections;658BinaryStreamReader reader(contents, llvm::endianness::little);659exitOnErr(reader.readArray(subsections, contents.size()));660661uint32_t nextRelocIndex = 0;662for (const DebugSubsectionRecord &ss : subsections) {663if (ss.kind() != DebugSubsectionKind::Symbols)664continue;665666uint32_t moduleSymStart = writer.getOffset();667scopes.clear();668storage.clear();669ArrayRef<uint8_t> symsBuffer;670BinaryStreamRef sr = ss.getRecordData();671cantFail(sr.readBytes(0, sr.getLength(), symsBuffer));672auto ec = forEachCodeViewRecord<CVSymbol>(673symsBuffer, [&](CVSymbol sym) -> llvm::Error {674// Track the current scope. Only update records in the postmerge675// pass.676if (symbolOpensScope(sym.kind()))677scopeStackOpen(scopes, storage);678else if (symbolEndsScope(sym.kind()))679scopeStackClose(scopes, storage, moduleSymStart, file);680681// Copy, relocate, and rewrite each module symbol.682if (symbolGoesInModuleStream(sym, scopes.size())) {683uint32_t alignedSize =684alignTo(sym.length(), alignOf(CodeViewContainer::Pdb));685writeSymbolRecord(debugChunk, sectionContents, sym, alignedSize,686nextRelocIndex, storage);687}688return Error::success();689});690691// If we encounter corrupt records in the second pass, ignore them. We692// already warned about them in the first analysis pass.693if (ec) {694consumeError(std::move(ec));695storage.clear();696}697698// Writing bytes has a very high overhead, so write the entire subsection699// at once.700// TODO: Consider buffering symbols for the entire object file to reduce701// overhead even further.702if (Error e = writer.writeBytes(storage))703return e;704}705}706707return Error::success();708}709710Error PDBLinker::commitSymbolsForObject(void *ctx, void *obj,711BinaryStreamWriter &writer) {712return static_cast<PDBLinker *>(ctx)->writeAllModuleSymbolRecords(713static_cast<ObjFile *>(obj), writer);714}715716static pdb::SectionContrib createSectionContrib(COFFLinkerContext &ctx,717const Chunk *c, uint32_t modi) {718OutputSection *os = c ? ctx.getOutputSection(c) : nullptr;719pdb::SectionContrib sc;720memset(&sc, 0, sizeof(sc));721sc.ISect = os ? os->sectionIndex : llvm::pdb::kInvalidStreamIndex;722sc.Off = c && os ? c->getRVA() - os->getRVA() : 0;723sc.Size = c ? c->getSize() : -1;724if (auto *secChunk = dyn_cast_or_null<SectionChunk>(c)) {725sc.Characteristics = secChunk->header->Characteristics;726sc.Imod = secChunk->file->moduleDBI->getModuleIndex();727ArrayRef<uint8_t> contents = secChunk->getContents();728JamCRC crc(0);729crc.update(contents);730sc.DataCrc = crc.getCRC();731} else {732sc.Characteristics = os ? os->header.Characteristics : 0;733sc.Imod = modi;734}735sc.RelocCrc = 0; // FIXME736737return sc;738}739740static uint32_t741translateStringTableIndex(uint32_t objIndex,742const DebugStringTableSubsectionRef &objStrTable,743DebugStringTableSubsection &pdbStrTable) {744auto expectedString = objStrTable.getString(objIndex);745if (!expectedString) {746warn("Invalid string table reference");747consumeError(expectedString.takeError());748return 0;749}750751return pdbStrTable.insert(*expectedString);752}753754void DebugSHandler::handleDebugS(SectionChunk *debugChunk) {755// Note that we are processing the *unrelocated* section contents. They will756// be relocated later during PDB writing.757ArrayRef<uint8_t> contents = debugChunk->getContents();758contents = SectionChunk::consumeDebugMagic(contents, ".debug$S");759DebugSubsectionArray subsections;760BinaryStreamReader reader(contents, llvm::endianness::little);761ExitOnError exitOnErr;762exitOnErr(reader.readArray(subsections, contents.size()));763debugChunk->sortRelocations();764765// Reset the relocation index, since this is a new section.766nextRelocIndex = 0;767768for (const DebugSubsectionRecord &ss : subsections) {769// Ignore subsections with the 'ignore' bit. Some versions of the Visual C++770// runtime have subsections with this bit set.771if (uint32_t(ss.kind()) & codeview::SubsectionIgnoreFlag)772continue;773774switch (ss.kind()) {775case DebugSubsectionKind::StringTable: {776assert(!cvStrTab.valid() &&777"Encountered multiple string table subsections!");778exitOnErr(cvStrTab.initialize(ss.getRecordData()));779break;780}781case DebugSubsectionKind::FileChecksums:782assert(!checksums.valid() &&783"Encountered multiple checksum subsections!");784exitOnErr(checksums.initialize(ss.getRecordData()));785break;786case DebugSubsectionKind::Lines:787case DebugSubsectionKind::InlineeLines:788addUnrelocatedSubsection(debugChunk, ss);789break;790case DebugSubsectionKind::FrameData:791addFrameDataSubsection(debugChunk, ss);792break;793case DebugSubsectionKind::Symbols:794linker.analyzeSymbolSubsection(debugChunk, moduleStreamSize,795nextRelocIndex, stringTableFixups,796ss.getRecordData());797break;798799case DebugSubsectionKind::CrossScopeImports:800case DebugSubsectionKind::CrossScopeExports:801// These appear to relate to cross-module optimization, so we might use802// these for ThinLTO.803break;804805case DebugSubsectionKind::ILLines:806case DebugSubsectionKind::FuncMDTokenMap:807case DebugSubsectionKind::TypeMDTokenMap:808case DebugSubsectionKind::MergedAssemblyInput:809// These appear to relate to .Net assembly info.810break;811812case DebugSubsectionKind::CoffSymbolRVA:813// Unclear what this is for.814break;815816case DebugSubsectionKind::XfgHashType:817case DebugSubsectionKind::XfgHashVirtual:818break;819820default:821warn("ignoring unknown debug$S subsection kind 0x" +822utohexstr(uint32_t(ss.kind())) + " in file " + toString(&file));823break;824}825}826}827828void DebugSHandler::advanceRelocIndex(SectionChunk *sc,829ArrayRef<uint8_t> subsec) {830ptrdiff_t vaBegin = subsec.data() - sc->getContents().data();831assert(vaBegin > 0);832auto relocs = sc->getRelocs();833for (; nextRelocIndex < relocs.size(); ++nextRelocIndex) {834if (relocs[nextRelocIndex].VirtualAddress >= (uint32_t)vaBegin)835break;836}837}838839namespace {840/// Wrapper class for unrelocated line and inlinee line subsections, which841/// require only relocation and type index remapping to add to the PDB.842class UnrelocatedDebugSubsection : public DebugSubsection {843public:844UnrelocatedDebugSubsection(DebugSubsectionKind k, SectionChunk *debugChunk,845ArrayRef<uint8_t> subsec, uint32_t relocIndex)846: DebugSubsection(k), debugChunk(debugChunk), subsec(subsec),847relocIndex(relocIndex) {}848849Error commit(BinaryStreamWriter &writer) const override;850uint32_t calculateSerializedSize() const override { return subsec.size(); }851852SectionChunk *debugChunk;853ArrayRef<uint8_t> subsec;854uint32_t relocIndex;855};856} // namespace857858Error UnrelocatedDebugSubsection::commit(BinaryStreamWriter &writer) const {859std::vector<uint8_t> relocatedBytes(subsec.size());860uint32_t tmpRelocIndex = relocIndex;861debugChunk->writeAndRelocateSubsection(debugChunk->getContents(), subsec,862tmpRelocIndex, relocatedBytes.data());863864// Remap type indices in inlinee line records in place. Skip the remapping if865// there is no type source info.866if (kind() == DebugSubsectionKind::InlineeLines &&867debugChunk->file->debugTypesObj) {868TpiSource *source = debugChunk->file->debugTypesObj;869DebugInlineeLinesSubsectionRef inlineeLines;870BinaryStreamReader storageReader(relocatedBytes, llvm::endianness::little);871ExitOnError exitOnErr;872exitOnErr(inlineeLines.initialize(storageReader));873for (const InlineeSourceLine &line : inlineeLines) {874TypeIndex &inlinee = *const_cast<TypeIndex *>(&line.Header->Inlinee);875if (!source->remapTypeIndex(inlinee, TiRefKind::IndexRef)) {876log("bad inlinee line record in " + debugChunk->file->getName() +877" with bad inlinee index 0x" + utohexstr(inlinee.getIndex()));878}879}880}881882return writer.writeBytes(relocatedBytes);883}884885void DebugSHandler::addUnrelocatedSubsection(SectionChunk *debugChunk,886const DebugSubsectionRecord &ss) {887ArrayRef<uint8_t> subsec;888BinaryStreamRef sr = ss.getRecordData();889cantFail(sr.readBytes(0, sr.getLength(), subsec));890advanceRelocIndex(debugChunk, subsec);891file.moduleDBI->addDebugSubsection(892std::make_shared<UnrelocatedDebugSubsection>(ss.kind(), debugChunk,893subsec, nextRelocIndex));894}895896void DebugSHandler::addFrameDataSubsection(SectionChunk *debugChunk,897const DebugSubsectionRecord &ss) {898// We need to re-write string table indices here, so save off all899// frame data subsections until we've processed the entire list of900// subsections so that we can be sure we have the string table.901ArrayRef<uint8_t> subsec;902BinaryStreamRef sr = ss.getRecordData();903cantFail(sr.readBytes(0, sr.getLength(), subsec));904advanceRelocIndex(debugChunk, subsec);905frameDataSubsecs.push_back({debugChunk, subsec, nextRelocIndex});906}907908static Expected<StringRef>909getFileName(const DebugStringTableSubsectionRef &strings,910const DebugChecksumsSubsectionRef &checksums, uint32_t fileID) {911auto iter = checksums.getArray().at(fileID);912if (iter == checksums.getArray().end())913return make_error<CodeViewError>(cv_error_code::no_records);914uint32_t offset = iter->FileNameOffset;915return strings.getString(offset);916}917918void DebugSHandler::finish() {919pdb::DbiStreamBuilder &dbiBuilder = linker.builder.getDbiBuilder();920921// If we found any symbol records for the module symbol stream, defer them.922if (moduleStreamSize > kSymbolStreamMagicSize)923file.moduleDBI->addUnmergedSymbols(&file, moduleStreamSize -924kSymbolStreamMagicSize);925926// We should have seen all debug subsections across the entire object file now927// which means that if a StringTable subsection and Checksums subsection were928// present, now is the time to handle them.929if (!cvStrTab.valid()) {930if (checksums.valid())931fatal(".debug$S sections with a checksums subsection must also contain a "932"string table subsection");933934if (!stringTableFixups.empty())935warn("No StringTable subsection was encountered, but there are string "936"table references");937return;938}939940ExitOnError exitOnErr;941942// Handle FPO data. Each subsection begins with a single image base943// relocation, which is then added to the RvaStart of each frame data record944// when it is added to the PDB. The string table indices for the FPO program945// must also be rewritten to use the PDB string table.946for (const UnrelocatedFpoData &subsec : frameDataSubsecs) {947// Relocate the first four bytes of the subection and reinterpret them as a948// 32 bit little-endian integer.949SectionChunk *debugChunk = subsec.debugChunk;950ArrayRef<uint8_t> subsecData = subsec.subsecData;951uint32_t relocIndex = subsec.relocIndex;952auto unrelocatedRvaStart = subsecData.take_front(sizeof(uint32_t));953uint8_t relocatedRvaStart[sizeof(uint32_t)];954debugChunk->writeAndRelocateSubsection(debugChunk->getContents(),955unrelocatedRvaStart, relocIndex,956&relocatedRvaStart[0]);957// Use of memcpy here avoids violating type-based aliasing rules.958support::ulittle32_t rvaStart;959memcpy(&rvaStart, &relocatedRvaStart[0], sizeof(support::ulittle32_t));960961// Copy each frame data record, add in rvaStart, translate string table962// indices, and add the record to the PDB.963DebugFrameDataSubsectionRef fds;964BinaryStreamReader reader(subsecData, llvm::endianness::little);965exitOnErr(fds.initialize(reader));966for (codeview::FrameData fd : fds) {967fd.RvaStart += rvaStart;968fd.FrameFunc =969translateStringTableIndex(fd.FrameFunc, cvStrTab, linker.pdbStrTab);970dbiBuilder.addNewFpoData(fd);971}972}973974// Translate the fixups and pass them off to the module builder so they will975// be applied during writing.976for (StringTableFixup &ref : stringTableFixups) {977ref.StrTabOffset =978translateStringTableIndex(ref.StrTabOffset, cvStrTab, linker.pdbStrTab);979}980file.moduleDBI->setStringTableFixups(std::move(stringTableFixups));981982// Make a new file checksum table that refers to offsets in the PDB-wide983// string table. Generally the string table subsection appears after the984// checksum table, so we have to do this after looping over all the985// subsections. The new checksum table must have the exact same layout and986// size as the original. Otherwise, the file references in the line and987// inlinee line tables will be incorrect.988auto newChecksums = std::make_unique<DebugChecksumsSubsection>(linker.pdbStrTab);989for (const FileChecksumEntry &fc : checksums) {990SmallString<128> filename =991exitOnErr(cvStrTab.getString(fc.FileNameOffset));992linker.pdbMakeAbsolute(filename);993exitOnErr(dbiBuilder.addModuleSourceFile(*file.moduleDBI, filename));994newChecksums->addChecksum(filename, fc.Kind, fc.Checksum);995}996assert(checksums.getArray().getUnderlyingStream().getLength() ==997newChecksums->calculateSerializedSize() &&998"file checksum table must have same layout");9991000file.moduleDBI->addDebugSubsection(std::move(newChecksums));1001}10021003static void warnUnusable(InputFile *f, Error e, bool shouldWarn) {1004if (!shouldWarn) {1005consumeError(std::move(e));1006return;1007}1008auto msg = "Cannot use debug info for '" + toString(f) + "' [LNK4099]";1009if (e)1010warn(msg + "\n>>> failed to load reference " + toString(std::move(e)));1011else1012warn(msg);1013}10141015// Allocate memory for a .debug$S / .debug$F section and relocate it.1016static ArrayRef<uint8_t> relocateDebugChunk(SectionChunk &debugChunk) {1017uint8_t *buffer = bAlloc().Allocate<uint8_t>(debugChunk.getSize());1018assert(debugChunk.getOutputSectionIdx() == 0 &&1019"debug sections should not be in output sections");1020debugChunk.writeTo(buffer);1021return ArrayRef(buffer, debugChunk.getSize());1022}10231024void PDBLinker::addDebugSymbols(TpiSource *source) {1025// If this TpiSource doesn't have an object file, it must be from a type1026// server PDB. Type server PDBs do not contain symbols, so stop here.1027if (!source->file)1028return;10291030llvm::TimeTraceScope timeScope("Merge symbols");1031ScopedTimer t(ctx.symbolMergingTimer);1032ExitOnError exitOnErr;1033pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();1034DebugSHandler dsh(*this, *source->file);1035// Now do all live .debug$S and .debug$F sections.1036for (SectionChunk *debugChunk : source->file->getDebugChunks()) {1037if (!debugChunk->live || debugChunk->getSize() == 0)1038continue;10391040bool isDebugS = debugChunk->getSectionName() == ".debug$S";1041bool isDebugF = debugChunk->getSectionName() == ".debug$F";1042if (!isDebugS && !isDebugF)1043continue;10441045if (isDebugS) {1046dsh.handleDebugS(debugChunk);1047} else if (isDebugF) {1048// Handle old FPO data .debug$F sections. These are relatively rare.1049ArrayRef<uint8_t> relocatedDebugContents =1050relocateDebugChunk(*debugChunk);1051FixedStreamArray<object::FpoData> fpoRecords;1052BinaryStreamReader reader(relocatedDebugContents,1053llvm::endianness::little);1054uint32_t count = relocatedDebugContents.size() / sizeof(object::FpoData);1055exitOnErr(reader.readArray(fpoRecords, count));10561057// These are already relocated and don't refer to the string table, so we1058// can just copy it.1059for (const object::FpoData &fd : fpoRecords)1060dbiBuilder.addOldFpoData(fd);1061}1062}10631064// Do any post-processing now that all .debug$S sections have been processed.1065dsh.finish();1066}10671068// Add a module descriptor for every object file. We need to put an absolute1069// path to the object into the PDB. If this is a plain object, we make its1070// path absolute. If it's an object in an archive, we make the archive path1071// absolute.1072void PDBLinker::createModuleDBI(ObjFile *file) {1073pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();1074SmallString<128> objName;1075ExitOnError exitOnErr;10761077bool inArchive = !file->parentName.empty();1078objName = inArchive ? file->parentName : file->getName();1079pdbMakeAbsolute(objName);1080StringRef modName = inArchive ? file->getName() : objName.str();10811082file->moduleDBI = &exitOnErr(dbiBuilder.addModuleInfo(modName));1083file->moduleDBI->setObjFileName(objName);1084file->moduleDBI->setMergeSymbolsCallback(this, &commitSymbolsForObject);10851086ArrayRef<Chunk *> chunks = file->getChunks();1087uint32_t modi = file->moduleDBI->getModuleIndex();10881089for (Chunk *c : chunks) {1090auto *secChunk = dyn_cast<SectionChunk>(c);1091if (!secChunk || !secChunk->live)1092continue;1093pdb::SectionContrib sc = createSectionContrib(ctx, secChunk, modi);1094file->moduleDBI->setFirstSectionContrib(sc);1095break;1096}1097}10981099void PDBLinker::addDebug(TpiSource *source) {1100// Before we can process symbol substreams from .debug$S, we need to process1101// type information, file checksums, and the string table. Add type info to1102// the PDB first, so that we can get the map from object file type and item1103// indices to PDB type and item indices. If we are using ghashes, types have1104// already been merged.1105if (!ctx.config.debugGHashes) {1106llvm::TimeTraceScope timeScope("Merge types (Non-GHASH)");1107ScopedTimer t(ctx.typeMergingTimer);1108if (Error e = source->mergeDebugT(&tMerger)) {1109// If type merging failed, ignore the symbols.1110warnUnusable(source->file, std::move(e),1111ctx.config.warnDebugInfoUnusable);1112return;1113}1114}11151116// If type merging failed, ignore the symbols.1117Error typeError = std::move(source->typeMergingError);1118if (typeError) {1119warnUnusable(source->file, std::move(typeError),1120ctx.config.warnDebugInfoUnusable);1121return;1122}11231124addDebugSymbols(source);1125}11261127static pdb::BulkPublic createPublic(COFFLinkerContext &ctx, Defined *def) {1128pdb::BulkPublic pub;1129pub.Name = def->getName().data();1130pub.NameLen = def->getName().size();11311132PublicSymFlags flags = PublicSymFlags::None;1133if (auto *d = dyn_cast<DefinedCOFF>(def)) {1134if (d->getCOFFSymbol().isFunctionDefinition())1135flags = PublicSymFlags::Function;1136} else if (isa<DefinedImportThunk>(def)) {1137flags = PublicSymFlags::Function;1138}1139pub.setFlags(flags);11401141OutputSection *os = ctx.getOutputSection(def->getChunk());1142assert(os && "all publics should be in final image");1143pub.Offset = def->getRVA() - os->getRVA();1144pub.Segment = os->sectionIndex;1145return pub;1146}11471148// Add all object files to the PDB. Merge .debug$T sections into IpiData and1149// TpiData.1150void PDBLinker::addObjectsToPDB() {1151{1152llvm::TimeTraceScope timeScope("Add objects to PDB");1153ScopedTimer t1(ctx.addObjectsTimer);11541155// Create module descriptors1156for (ObjFile *obj : ctx.objFileInstances)1157createModuleDBI(obj);11581159// Reorder dependency type sources to come first.1160tMerger.sortDependencies();11611162// Merge type information from input files using global type hashing.1163if (ctx.config.debugGHashes)1164tMerger.mergeTypesWithGHash();11651166// Merge dependencies and then regular objects.1167{1168llvm::TimeTraceScope timeScope("Merge debug info (dependencies)");1169for (TpiSource *source : tMerger.dependencySources)1170addDebug(source);1171}1172{1173llvm::TimeTraceScope timeScope("Merge debug info (objects)");1174for (TpiSource *source : tMerger.objectSources)1175addDebug(source);1176}11771178builder.getStringTableBuilder().setStrings(pdbStrTab);1179}11801181// Construct TPI and IPI stream contents.1182{1183llvm::TimeTraceScope timeScope("TPI/IPI stream layout");1184ScopedTimer t2(ctx.tpiStreamLayoutTimer);11851186// Collect all the merged types.1187if (ctx.config.debugGHashes) {1188addGHashTypeInfo(ctx, builder);1189} else {1190addTypeInfo(builder.getTpiBuilder(), tMerger.getTypeTable());1191addTypeInfo(builder.getIpiBuilder(), tMerger.getIDTable());1192}1193}11941195if (ctx.config.showSummary) {1196for (TpiSource *source : ctx.tpiSourceList) {1197nbTypeRecords += source->nbTypeRecords;1198nbTypeRecordsBytes += source->nbTypeRecordsBytes;1199}1200}1201}12021203void PDBLinker::addPublicsToPDB() {1204llvm::TimeTraceScope timeScope("Publics layout");1205ScopedTimer t3(ctx.publicsLayoutTimer);1206// Compute the public symbols.1207auto &gsiBuilder = builder.getGsiBuilder();1208std::vector<pdb::BulkPublic> publics;1209ctx.symtab.forEachSymbol([&publics, this](Symbol *s) {1210// Only emit external, defined, live symbols that have a chunk. Static,1211// non-external symbols do not appear in the symbol table.1212auto *def = dyn_cast<Defined>(s);1213if (def && def->isLive() && def->getChunk()) {1214// Don't emit a public symbol for coverage data symbols. LLVM code1215// coverage (and PGO) create a __profd_ and __profc_ symbol for every1216// function. C++ mangled names are long, and tend to dominate symbol size.1217// Including these names triples the size of the public stream, which1218// results in bloated PDB files. These symbols generally are not helpful1219// for debugging, so suppress them.1220StringRef name = def->getName();1221if (name.data()[0] == '_' && name.data()[1] == '_') {1222// Drop the '_' prefix for x86.1223if (ctx.config.machine == I386)1224name = name.drop_front(1);1225if (name.starts_with("__profd_") || name.starts_with("__profc_") ||1226name.starts_with("__covrec_")) {1227return;1228}1229}1230publics.push_back(createPublic(ctx, def));1231}1232});12331234if (!publics.empty()) {1235publicSymbols = publics.size();1236gsiBuilder.addPublicSymbols(std::move(publics));1237}1238}12391240void PDBLinker::printStats() {1241if (!ctx.config.showSummary)1242return;12431244SmallString<256> buffer;1245raw_svector_ostream stream(buffer);12461247stream << center_justify("Summary", 80) << '\n'1248<< std::string(80, '-') << '\n';12491250auto print = [&](uint64_t v, StringRef s) {1251stream << format_decimal(v, 15) << " " << s << '\n';1252};12531254print(ctx.objFileInstances.size(),1255"Input OBJ files (expanded from all cmd-line inputs)");1256print(ctx.typeServerSourceMappings.size(), "PDB type server dependencies");1257print(ctx.precompSourceMappings.size(), "Precomp OBJ dependencies");1258print(nbTypeRecords, "Input type records");1259print(nbTypeRecordsBytes, "Input type records bytes");1260print(builder.getTpiBuilder().getRecordCount(), "Merged TPI records");1261print(builder.getIpiBuilder().getRecordCount(), "Merged IPI records");1262print(pdbStrTab.size(), "Output PDB strings");1263print(globalSymbols, "Global symbol records");1264print(moduleSymbols, "Module symbol records");1265print(publicSymbols, "Public symbol records");12661267auto printLargeInputTypeRecs = [&](StringRef name,1268ArrayRef<uint32_t> recCounts,1269TypeCollection &records) {1270// Figure out which type indices were responsible for the most duplicate1271// bytes in the input files. These should be frequently emitted LF_CLASS and1272// LF_FIELDLIST records.1273struct TypeSizeInfo {1274uint32_t typeSize;1275uint32_t dupCount;1276TypeIndex typeIndex;1277uint64_t totalInputSize() const { return uint64_t(dupCount) * typeSize; }1278bool operator<(const TypeSizeInfo &rhs) const {1279if (totalInputSize() == rhs.totalInputSize())1280return typeIndex < rhs.typeIndex;1281return totalInputSize() < rhs.totalInputSize();1282}1283};1284SmallVector<TypeSizeInfo, 0> tsis;1285for (auto e : enumerate(recCounts)) {1286TypeIndex typeIndex = TypeIndex::fromArrayIndex(e.index());1287uint32_t typeSize = records.getType(typeIndex).length();1288uint32_t dupCount = e.value();1289tsis.push_back({typeSize, dupCount, typeIndex});1290}12911292if (!tsis.empty()) {1293stream << "\nTop 10 types responsible for the most " << name1294<< " input:\n";1295stream << " index total bytes count size\n";1296llvm::sort(tsis);1297unsigned i = 0;1298for (const auto &tsi : reverse(tsis)) {1299stream << formatv(" {0,10:X}: {1,14:N} = {2,5:N} * {3,6:N}\n",1300tsi.typeIndex.getIndex(), tsi.totalInputSize(),1301tsi.dupCount, tsi.typeSize);1302if (++i >= 10)1303break;1304}1305stream1306<< "Run llvm-pdbutil to print details about a particular record:\n";1307stream << formatv("llvm-pdbutil dump -{0}s -{0}-index {1:X} {2}\n",1308(name == "TPI" ? "type" : "id"),1309tsis.back().typeIndex.getIndex(), ctx.config.pdbPath);1310}1311};13121313if (!ctx.config.debugGHashes) {1314// FIXME: Reimplement for ghash.1315printLargeInputTypeRecs("TPI", tMerger.tpiCounts, tMerger.getTypeTable());1316printLargeInputTypeRecs("IPI", tMerger.ipiCounts, tMerger.getIDTable());1317}13181319message(buffer);1320}13211322void PDBLinker::addNatvisFiles() {1323llvm::TimeTraceScope timeScope("Natvis files");1324for (StringRef file : ctx.config.natvisFiles) {1325ErrorOr<std::unique_ptr<MemoryBuffer>> dataOrErr =1326MemoryBuffer::getFile(file);1327if (!dataOrErr) {1328warn("Cannot open input file: " + file);1329continue;1330}1331std::unique_ptr<MemoryBuffer> data = std::move(*dataOrErr);13321333// Can't use takeBuffer() here since addInjectedSource() takes ownership.1334if (ctx.driver.tar)1335ctx.driver.tar->append(relativeToRoot(data->getBufferIdentifier()),1336data->getBuffer());13371338builder.addInjectedSource(file, std::move(data));1339}1340}13411342void PDBLinker::addNamedStreams() {1343llvm::TimeTraceScope timeScope("Named streams");1344ExitOnError exitOnErr;1345for (const auto &streamFile : ctx.config.namedStreams) {1346const StringRef stream = streamFile.getKey(), file = streamFile.getValue();1347ErrorOr<std::unique_ptr<MemoryBuffer>> dataOrErr =1348MemoryBuffer::getFile(file);1349if (!dataOrErr) {1350warn("Cannot open input file: " + file);1351continue;1352}1353std::unique_ptr<MemoryBuffer> data = std::move(*dataOrErr);1354exitOnErr(builder.addNamedStream(stream, data->getBuffer()));1355ctx.driver.takeBuffer(std::move(data));1356}1357}13581359static codeview::CPUType toCodeViewMachine(COFF::MachineTypes machine) {1360switch (machine) {1361case COFF::IMAGE_FILE_MACHINE_AMD64:1362return codeview::CPUType::X64;1363case COFF::IMAGE_FILE_MACHINE_ARM:1364return codeview::CPUType::ARM7;1365case COFF::IMAGE_FILE_MACHINE_ARM64:1366return codeview::CPUType::ARM64;1367case COFF::IMAGE_FILE_MACHINE_ARMNT:1368return codeview::CPUType::ARMNT;1369case COFF::IMAGE_FILE_MACHINE_I386:1370return codeview::CPUType::Intel80386;1371default:1372llvm_unreachable("Unsupported CPU Type");1373}1374}13751376// Mimic MSVC which surrounds arguments containing whitespace with quotes.1377// Double double-quotes are handled, so that the resulting string can be1378// executed again on the cmd-line.1379static std::string quote(ArrayRef<StringRef> args) {1380std::string r;1381r.reserve(256);1382for (StringRef a : args) {1383if (!r.empty())1384r.push_back(' ');1385bool hasWS = a.contains(' ');1386bool hasQ = a.contains('"');1387if (hasWS || hasQ)1388r.push_back('"');1389if (hasQ) {1390SmallVector<StringRef, 4> s;1391a.split(s, '"');1392r.append(join(s, "\"\""));1393} else {1394r.append(std::string(a));1395}1396if (hasWS || hasQ)1397r.push_back('"');1398}1399return r;1400}14011402static void fillLinkerVerRecord(Compile3Sym &cs, MachineTypes machine) {1403cs.Machine = toCodeViewMachine(machine);1404// Interestingly, if we set the string to 0.0.0.0, then when trying to view1405// local variables WinDbg emits an error that private symbols are not present.1406// By setting this to a valid MSVC linker version string, local variables are1407// displayed properly. As such, even though it is not representative of1408// LLVM's version information, we need this for compatibility.1409cs.Flags = CompileSym3Flags::None;1410cs.VersionBackendBuild = 25019;1411cs.VersionBackendMajor = 14;1412cs.VersionBackendMinor = 10;1413cs.VersionBackendQFE = 0;14141415// MSVC also sets the frontend to 0.0.0.0 since this is specifically for the1416// linker module (which is by definition a backend), so we don't need to do1417// anything here. Also, it seems we can use "LLVM Linker" for the linker name1418// without any problems. Only the backend version has to be hardcoded to a1419// magic number.1420cs.VersionFrontendBuild = 0;1421cs.VersionFrontendMajor = 0;1422cs.VersionFrontendMinor = 0;1423cs.VersionFrontendQFE = 0;1424cs.Version = "LLVM Linker";1425cs.setLanguage(SourceLanguage::Link);1426}14271428void PDBLinker::addCommonLinkerModuleSymbols(1429StringRef path, pdb::DbiModuleDescriptorBuilder &mod) {1430ObjNameSym ons(SymbolRecordKind::ObjNameSym);1431EnvBlockSym ebs(SymbolRecordKind::EnvBlockSym);1432Compile3Sym cs(SymbolRecordKind::Compile3Sym);1433fillLinkerVerRecord(cs, ctx.config.machine);14341435ons.Name = "* Linker *";1436ons.Signature = 0;14371438ArrayRef<StringRef> args = ArrayRef(ctx.config.argv).drop_front();1439std::string argStr = quote(args);1440ebs.Fields.push_back("cwd");1441SmallString<64> cwd;1442if (ctx.config.pdbSourcePath.empty())1443sys::fs::current_path(cwd);1444else1445cwd = ctx.config.pdbSourcePath;1446ebs.Fields.push_back(cwd);1447ebs.Fields.push_back("exe");1448SmallString<64> exe = ctx.config.argv[0];1449pdbMakeAbsolute(exe);1450ebs.Fields.push_back(exe);1451ebs.Fields.push_back("pdb");1452ebs.Fields.push_back(path);1453ebs.Fields.push_back("cmd");1454ebs.Fields.push_back(argStr);1455llvm::BumpPtrAllocator &bAlloc = lld::bAlloc();1456mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(1457ons, bAlloc, CodeViewContainer::Pdb));1458mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(1459cs, bAlloc, CodeViewContainer::Pdb));1460mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(1461ebs, bAlloc, CodeViewContainer::Pdb));1462}14631464static void addLinkerModuleCoffGroup(PartialSection *sec,1465pdb::DbiModuleDescriptorBuilder &mod,1466OutputSection &os) {1467// If there's a section, there's at least one chunk1468assert(!sec->chunks.empty());1469const Chunk *firstChunk = *sec->chunks.begin();1470const Chunk *lastChunk = *sec->chunks.rbegin();14711472// Emit COFF group1473CoffGroupSym cgs(SymbolRecordKind::CoffGroupSym);1474cgs.Name = sec->name;1475cgs.Segment = os.sectionIndex;1476cgs.Offset = firstChunk->getRVA() - os.getRVA();1477cgs.Size = lastChunk->getRVA() + lastChunk->getSize() - firstChunk->getRVA();1478cgs.Characteristics = sec->characteristics;14791480// Somehow .idata sections & sections groups in the debug symbol stream have1481// the "write" flag set. However the section header for the corresponding1482// .idata section doesn't have it.1483if (cgs.Name.starts_with(".idata"))1484cgs.Characteristics |= llvm::COFF::IMAGE_SCN_MEM_WRITE;14851486mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(1487cgs, bAlloc(), CodeViewContainer::Pdb));1488}14891490static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &mod,1491OutputSection &os, bool isMinGW) {1492SectionSym sym(SymbolRecordKind::SectionSym);1493sym.Alignment = 12; // 2^12 = 4KB1494sym.Characteristics = os.header.Characteristics;1495sym.Length = os.getVirtualSize();1496sym.Name = os.name;1497sym.Rva = os.getRVA();1498sym.SectionNumber = os.sectionIndex;1499mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(1500sym, bAlloc(), CodeViewContainer::Pdb));15011502// Skip COFF groups in MinGW because it adds a significant footprint to the1503// PDB, due to each function being in its own section1504if (isMinGW)1505return;15061507// Output COFF groups for individual chunks of this section.1508for (PartialSection *sec : os.contribSections) {1509addLinkerModuleCoffGroup(sec, mod, os);1510}1511}15121513// Add all import files as modules to the PDB.1514void PDBLinker::addImportFilesToPDB() {1515if (ctx.importFileInstances.empty())1516return;15171518llvm::TimeTraceScope timeScope("Import files");1519ExitOnError exitOnErr;1520std::map<std::string, llvm::pdb::DbiModuleDescriptorBuilder *> dllToModuleDbi;15211522for (ImportFile *file : ctx.importFileInstances) {1523if (!file->live)1524continue;15251526if (!file->thunkSym)1527continue;15281529if (!file->thunkLive)1530continue;15311532std::string dll = StringRef(file->dllName).lower();1533llvm::pdb::DbiModuleDescriptorBuilder *&mod = dllToModuleDbi[dll];1534if (!mod) {1535pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();1536SmallString<128> libPath = file->parentName;1537pdbMakeAbsolute(libPath);1538sys::path::native(libPath);15391540// Name modules similar to MSVC's link.exe.1541// The first module is the simple dll filename1542llvm::pdb::DbiModuleDescriptorBuilder &firstMod =1543exitOnErr(dbiBuilder.addModuleInfo(file->dllName));1544firstMod.setObjFileName(libPath);1545pdb::SectionContrib sc =1546createSectionContrib(ctx, nullptr, llvm::pdb::kInvalidStreamIndex);1547firstMod.setFirstSectionContrib(sc);15481549// The second module is where the import stream goes.1550mod = &exitOnErr(dbiBuilder.addModuleInfo("Import:" + file->dllName));1551mod->setObjFileName(libPath);1552}15531554DefinedImportThunk *thunk = cast<DefinedImportThunk>(file->thunkSym);1555Chunk *thunkChunk = thunk->getChunk();1556OutputSection *thunkOS = ctx.getOutputSection(thunkChunk);15571558ObjNameSym ons(SymbolRecordKind::ObjNameSym);1559Compile3Sym cs(SymbolRecordKind::Compile3Sym);1560Thunk32Sym ts(SymbolRecordKind::Thunk32Sym);1561ScopeEndSym es(SymbolRecordKind::ScopeEndSym);15621563ons.Name = file->dllName;1564ons.Signature = 0;15651566fillLinkerVerRecord(cs, ctx.config.machine);15671568ts.Name = thunk->getName();1569ts.Parent = 0;1570ts.End = 0;1571ts.Next = 0;1572ts.Thunk = ThunkOrdinal::Standard;1573ts.Length = thunkChunk->getSize();1574ts.Segment = thunkOS->sectionIndex;1575ts.Offset = thunkChunk->getRVA() - thunkOS->getRVA();15761577llvm::BumpPtrAllocator &bAlloc = lld::bAlloc();1578mod->addSymbol(codeview::SymbolSerializer::writeOneSymbol(1579ons, bAlloc, CodeViewContainer::Pdb));1580mod->addSymbol(codeview::SymbolSerializer::writeOneSymbol(1581cs, bAlloc, CodeViewContainer::Pdb));15821583CVSymbol newSym = codeview::SymbolSerializer::writeOneSymbol(1584ts, bAlloc, CodeViewContainer::Pdb);15851586// Write ptrEnd for the S_THUNK32.1587ScopeRecord *thunkSymScope =1588getSymbolScopeFields(const_cast<uint8_t *>(newSym.data().data()));15891590mod->addSymbol(newSym);15911592newSym = codeview::SymbolSerializer::writeOneSymbol(es, bAlloc,1593CodeViewContainer::Pdb);1594thunkSymScope->ptrEnd = mod->getNextSymbolOffset();15951596mod->addSymbol(newSym);15971598pdb::SectionContrib sc =1599createSectionContrib(ctx, thunk->getChunk(), mod->getModuleIndex());1600mod->setFirstSectionContrib(sc);1601}1602}16031604// Creates a PDB file.1605void lld::coff::createPDB(COFFLinkerContext &ctx,1606ArrayRef<uint8_t> sectionTable,1607llvm::codeview::DebugInfo *buildId) {1608llvm::TimeTraceScope timeScope("PDB file");1609ScopedTimer t1(ctx.totalPdbLinkTimer);1610{1611PDBLinker pdb(ctx);16121613pdb.initialize(buildId);1614pdb.addObjectsToPDB();1615pdb.addImportFilesToPDB();1616pdb.addSections(sectionTable);1617pdb.addNatvisFiles();1618pdb.addNamedStreams();1619pdb.addPublicsToPDB();16201621{1622llvm::TimeTraceScope timeScope("Commit PDB file to disk");1623ScopedTimer t2(ctx.diskCommitTimer);1624codeview::GUID guid;1625pdb.commit(&guid);1626memcpy(&buildId->PDB70.Signature, &guid, 16);1627}16281629t1.stop();1630pdb.printStats();16311632// Manually start this profile point to measure ~PDBLinker().1633if (getTimeTraceProfilerInstance() != nullptr)1634timeTraceProfilerBegin("PDBLinker destructor", StringRef(""));1635}1636// Manually end this profile point to measure ~PDBLinker().1637if (getTimeTraceProfilerInstance() != nullptr)1638timeTraceProfilerEnd();1639}16401641void PDBLinker::initialize(llvm::codeview::DebugInfo *buildId) {1642ExitOnError exitOnErr;1643exitOnErr(builder.initialize(ctx.config.pdbPageSize));16441645buildId->Signature.CVSignature = OMF::Signature::PDB70;1646// Signature is set to a hash of the PDB contents when the PDB is done.1647memset(buildId->PDB70.Signature, 0, 16);1648buildId->PDB70.Age = 1;16491650// Create streams in MSF for predefined streams, namely1651// PDB, TPI, DBI and IPI.1652for (int i = 0; i < (int)pdb::kSpecialStreamCount; ++i)1653exitOnErr(builder.getMsfBuilder().addStream(0));16541655// Add an Info stream.1656auto &infoBuilder = builder.getInfoBuilder();1657infoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);1658infoBuilder.setHashPDBContentsToGUID(true);16591660// Add an empty DBI stream.1661pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();1662dbiBuilder.setAge(buildId->PDB70.Age);1663dbiBuilder.setVersionHeader(pdb::PdbDbiV70);1664dbiBuilder.setMachineType(ctx.config.machine);1665// Technically we are not link.exe 14.11, but there are known cases where1666// debugging tools on Windows expect Microsoft-specific version numbers or1667// they fail to work at all. Since we know we produce PDBs that are1668// compatible with LINK 14.11, we set that version number here.1669dbiBuilder.setBuildNumber(14, 11);1670}16711672void PDBLinker::addSections(ArrayRef<uint8_t> sectionTable) {1673llvm::TimeTraceScope timeScope("PDB output sections");1674ExitOnError exitOnErr;1675// It's not entirely clear what this is, but the * Linker * module uses it.1676pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();1677nativePath = ctx.config.pdbPath;1678pdbMakeAbsolute(nativePath);1679uint32_t pdbFilePathNI = dbiBuilder.addECName(nativePath);1680auto &linkerModule = exitOnErr(dbiBuilder.addModuleInfo("* Linker *"));1681linkerModule.setPdbFilePathNI(pdbFilePathNI);1682addCommonLinkerModuleSymbols(nativePath, linkerModule);16831684// Add section contributions. They must be ordered by ascending RVA.1685for (OutputSection *os : ctx.outputSections) {1686addLinkerModuleSectionSymbol(linkerModule, *os, ctx.config.mingw);1687for (Chunk *c : os->chunks) {1688pdb::SectionContrib sc =1689createSectionContrib(ctx, c, linkerModule.getModuleIndex());1690builder.getDbiBuilder().addSectionContrib(sc);1691}1692}16931694// The * Linker * first section contrib is only used along with /INCREMENTAL,1695// to provide trampolines thunks for incremental function patching. Set this1696// as "unused" because LLD doesn't support /INCREMENTAL link.1697pdb::SectionContrib sc =1698createSectionContrib(ctx, nullptr, llvm::pdb::kInvalidStreamIndex);1699linkerModule.setFirstSectionContrib(sc);17001701// Add Section Map stream.1702ArrayRef<object::coff_section> sections = {1703(const object::coff_section *)sectionTable.data(),1704sectionTable.size() / sizeof(object::coff_section)};1705dbiBuilder.createSectionMap(sections);17061707// Add COFF section header stream.1708exitOnErr(1709dbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, sectionTable));1710}17111712void PDBLinker::commit(codeview::GUID *guid) {1713// Print an error and continue if PDB writing fails. This is done mainly so1714// the user can see the output of /time and /summary, which is very helpful1715// when trying to figure out why a PDB file is too large.1716if (Error e = builder.commit(ctx.config.pdbPath, guid)) {1717e = handleErrors(std::move(e),1718[](const llvm::msf::MSFError &me) {1719error(me.message());1720if (me.isPageOverflow())1721error("try setting a larger /pdbpagesize");1722});1723checkError(std::move(e));1724error("failed to write PDB file " + Twine(ctx.config.pdbPath));1725}1726}17271728static uint32_t getSecrelReloc(Triple::ArchType arch) {1729switch (arch) {1730case Triple::x86_64:1731return COFF::IMAGE_REL_AMD64_SECREL;1732case Triple::x86:1733return COFF::IMAGE_REL_I386_SECREL;1734case Triple::thumb:1735return COFF::IMAGE_REL_ARM_SECREL;1736case Triple::aarch64:1737return COFF::IMAGE_REL_ARM64_SECREL;1738default:1739llvm_unreachable("unknown machine type");1740}1741}17421743// Try to find a line table for the given offset Addr into the given chunk C.1744// If a line table was found, the line table, the string and checksum tables1745// that are used to interpret the line table, and the offset of Addr in the line1746// table are stored in the output arguments. Returns whether a line table was1747// found.1748static bool findLineTable(const SectionChunk *c, uint32_t addr,1749DebugStringTableSubsectionRef &cvStrTab,1750DebugChecksumsSubsectionRef &checksums,1751DebugLinesSubsectionRef &lines,1752uint32_t &offsetInLinetable) {1753ExitOnError exitOnErr;1754const uint32_t secrelReloc = getSecrelReloc(c->getArch());17551756for (SectionChunk *dbgC : c->file->getDebugChunks()) {1757if (dbgC->getSectionName() != ".debug$S")1758continue;17591760// Build a mapping of SECREL relocations in dbgC that refer to `c`.1761DenseMap<uint32_t, uint32_t> secrels;1762for (const coff_relocation &r : dbgC->getRelocs()) {1763if (r.Type != secrelReloc)1764continue;17651766if (auto *s = dyn_cast_or_null<DefinedRegular>(1767c->file->getSymbols()[r.SymbolTableIndex]))1768if (s->getChunk() == c)1769secrels[r.VirtualAddress] = s->getValue();1770}17711772ArrayRef<uint8_t> contents =1773SectionChunk::consumeDebugMagic(dbgC->getContents(), ".debug$S");1774DebugSubsectionArray subsections;1775BinaryStreamReader reader(contents, llvm::endianness::little);1776exitOnErr(reader.readArray(subsections, contents.size()));17771778for (const DebugSubsectionRecord &ss : subsections) {1779switch (ss.kind()) {1780case DebugSubsectionKind::StringTable: {1781assert(!cvStrTab.valid() &&1782"Encountered multiple string table subsections!");1783exitOnErr(cvStrTab.initialize(ss.getRecordData()));1784break;1785}1786case DebugSubsectionKind::FileChecksums:1787assert(!checksums.valid() &&1788"Encountered multiple checksum subsections!");1789exitOnErr(checksums.initialize(ss.getRecordData()));1790break;1791case DebugSubsectionKind::Lines: {1792ArrayRef<uint8_t> bytes;1793auto ref = ss.getRecordData();1794exitOnErr(ref.readLongestContiguousChunk(0, bytes));1795size_t offsetInDbgC = bytes.data() - dbgC->getContents().data();17961797// Check whether this line table refers to C.1798auto i = secrels.find(offsetInDbgC);1799if (i == secrels.end())1800break;18011802// Check whether this line table covers Addr in C.1803DebugLinesSubsectionRef linesTmp;1804exitOnErr(linesTmp.initialize(BinaryStreamReader(ref)));1805uint32_t offsetInC = i->second + linesTmp.header()->RelocOffset;1806if (addr < offsetInC || addr >= offsetInC + linesTmp.header()->CodeSize)1807break;18081809assert(!lines.header() &&1810"Encountered multiple line tables for function!");1811exitOnErr(lines.initialize(BinaryStreamReader(ref)));1812offsetInLinetable = addr - offsetInC;1813break;1814}1815default:1816break;1817}18181819if (cvStrTab.valid() && checksums.valid() && lines.header())1820return true;1821}1822}18231824return false;1825}18261827// Use CodeView line tables to resolve a file and line number for the given1828// offset into the given chunk and return them, or std::nullopt if a line table1829// was not found.1830std::optional<std::pair<StringRef, uint32_t>>1831lld::coff::getFileLineCodeView(const SectionChunk *c, uint32_t addr) {1832ExitOnError exitOnErr;18331834DebugStringTableSubsectionRef cvStrTab;1835DebugChecksumsSubsectionRef checksums;1836DebugLinesSubsectionRef lines;1837uint32_t offsetInLinetable;18381839if (!findLineTable(c, addr, cvStrTab, checksums, lines, offsetInLinetable))1840return std::nullopt;18411842std::optional<uint32_t> nameIndex;1843std::optional<uint32_t> lineNumber;1844for (const LineColumnEntry &entry : lines) {1845for (const LineNumberEntry &ln : entry.LineNumbers) {1846LineInfo li(ln.Flags);1847if (ln.Offset > offsetInLinetable) {1848if (!nameIndex) {1849nameIndex = entry.NameIndex;1850lineNumber = li.getStartLine();1851}1852StringRef filename =1853exitOnErr(getFileName(cvStrTab, checksums, *nameIndex));1854return std::make_pair(filename, *lineNumber);1855}1856nameIndex = entry.NameIndex;1857lineNumber = li.getStartLine();1858}1859}1860if (!nameIndex)1861return std::nullopt;1862StringRef filename = exitOnErr(getFileName(cvStrTab, checksums, *nameIndex));1863return std::make_pair(filename, *lineNumber);1864}186518661867