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