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