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