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