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