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