xref: /freebsd/contrib/llvm-project/lld/COFF/PDB.cpp (revision fcaf7f8644a9988098ac6be2165bce3ea4786e91)
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     default:
815       warn("ignoring unknown debug$S subsection kind 0x" +
816            utohexstr(uint32_t(ss.kind())) + " in file " + toString(&file));
817       break;
818     }
819   }
820 }
821 
822 void DebugSHandler::advanceRelocIndex(SectionChunk *sc,
823                                       ArrayRef<uint8_t> subsec) {
824   ptrdiff_t vaBegin = subsec.data() - sc->getContents().data();
825   assert(vaBegin > 0);
826   auto relocs = sc->getRelocs();
827   for (; nextRelocIndex < relocs.size(); ++nextRelocIndex) {
828     if (relocs[nextRelocIndex].VirtualAddress >= vaBegin)
829       break;
830   }
831 }
832 
833 namespace {
834 /// Wrapper class for unrelocated line and inlinee line subsections, which
835 /// require only relocation and type index remapping to add to the PDB.
836 class UnrelocatedDebugSubsection : public DebugSubsection {
837 public:
838   UnrelocatedDebugSubsection(DebugSubsectionKind k, SectionChunk *debugChunk,
839                              ArrayRef<uint8_t> subsec, uint32_t relocIndex)
840       : DebugSubsection(k), debugChunk(debugChunk), subsec(subsec),
841         relocIndex(relocIndex) {}
842 
843   Error commit(BinaryStreamWriter &writer) const override;
844   uint32_t calculateSerializedSize() const override { return subsec.size(); }
845 
846   SectionChunk *debugChunk;
847   ArrayRef<uint8_t> subsec;
848   uint32_t relocIndex;
849 };
850 } // namespace
851 
852 Error UnrelocatedDebugSubsection::commit(BinaryStreamWriter &writer) const {
853   std::vector<uint8_t> relocatedBytes(subsec.size());
854   uint32_t tmpRelocIndex = relocIndex;
855   debugChunk->writeAndRelocateSubsection(debugChunk->getContents(), subsec,
856                                          tmpRelocIndex, relocatedBytes.data());
857 
858   // Remap type indices in inlinee line records in place. Skip the remapping if
859   // there is no type source info.
860   if (kind() == DebugSubsectionKind::InlineeLines &&
861       debugChunk->file->debugTypesObj) {
862     TpiSource *source = debugChunk->file->debugTypesObj;
863     DebugInlineeLinesSubsectionRef inlineeLines;
864     BinaryStreamReader storageReader(relocatedBytes, support::little);
865     exitOnErr(inlineeLines.initialize(storageReader));
866     for (const InlineeSourceLine &line : inlineeLines) {
867       TypeIndex &inlinee = *const_cast<TypeIndex *>(&line.Header->Inlinee);
868       if (!source->remapTypeIndex(inlinee, TiRefKind::IndexRef)) {
869         log("bad inlinee line record in " + debugChunk->file->getName() +
870             " with bad inlinee index 0x" + utohexstr(inlinee.getIndex()));
871       }
872     }
873   }
874 
875   return writer.writeBytes(relocatedBytes);
876 }
877 
878 void DebugSHandler::addUnrelocatedSubsection(SectionChunk *debugChunk,
879                                              const DebugSubsectionRecord &ss) {
880   ArrayRef<uint8_t> subsec;
881   BinaryStreamRef sr = ss.getRecordData();
882   cantFail(sr.readBytes(0, sr.getLength(), subsec));
883   advanceRelocIndex(debugChunk, subsec);
884   file.moduleDBI->addDebugSubsection(
885       std::make_shared<UnrelocatedDebugSubsection>(ss.kind(), debugChunk,
886                                                    subsec, nextRelocIndex));
887 }
888 
889 void DebugSHandler::addFrameDataSubsection(SectionChunk *debugChunk,
890                                            const DebugSubsectionRecord &ss) {
891   // We need to re-write string table indices here, so save off all
892   // frame data subsections until we've processed the entire list of
893   // subsections so that we can be sure we have the string table.
894   ArrayRef<uint8_t> subsec;
895   BinaryStreamRef sr = ss.getRecordData();
896   cantFail(sr.readBytes(0, sr.getLength(), subsec));
897   advanceRelocIndex(debugChunk, subsec);
898   frameDataSubsecs.push_back({debugChunk, subsec, nextRelocIndex});
899 }
900 
901 static Expected<StringRef>
902 getFileName(const DebugStringTableSubsectionRef &strings,
903             const DebugChecksumsSubsectionRef &checksums, uint32_t fileID) {
904   auto iter = checksums.getArray().at(fileID);
905   if (iter == checksums.getArray().end())
906     return make_error<CodeViewError>(cv_error_code::no_records);
907   uint32_t offset = iter->FileNameOffset;
908   return strings.getString(offset);
909 }
910 
911 void DebugSHandler::finish() {
912   pdb::DbiStreamBuilder &dbiBuilder = linker.builder.getDbiBuilder();
913 
914   // If we found any symbol records for the module symbol stream, defer them.
915   if (moduleStreamSize > kSymbolStreamMagicSize)
916     file.moduleDBI->addUnmergedSymbols(&file, moduleStreamSize -
917                                                   kSymbolStreamMagicSize);
918 
919   // We should have seen all debug subsections across the entire object file now
920   // which means that if a StringTable subsection and Checksums subsection were
921   // present, now is the time to handle them.
922   if (!cvStrTab.valid()) {
923     if (checksums.valid())
924       fatal(".debug$S sections with a checksums subsection must also contain a "
925             "string table subsection");
926 
927     if (!stringTableFixups.empty())
928       warn("No StringTable subsection was encountered, but there are string "
929            "table references");
930     return;
931   }
932 
933   // Handle FPO data. Each subsection begins with a single image base
934   // relocation, which is then added to the RvaStart of each frame data record
935   // when it is added to the PDB. The string table indices for the FPO program
936   // must also be rewritten to use the PDB string table.
937   for (const UnrelocatedFpoData &subsec : frameDataSubsecs) {
938     // Relocate the first four bytes of the subection and reinterpret them as a
939     // 32 bit integer.
940     SectionChunk *debugChunk = subsec.debugChunk;
941     ArrayRef<uint8_t> subsecData = subsec.subsecData;
942     uint32_t relocIndex = subsec.relocIndex;
943     auto unrelocatedRvaStart = subsecData.take_front(sizeof(uint32_t));
944     uint8_t relocatedRvaStart[sizeof(uint32_t)];
945     debugChunk->writeAndRelocateSubsection(debugChunk->getContents(),
946                                            unrelocatedRvaStart, relocIndex,
947                                            &relocatedRvaStart[0]);
948     uint32_t rvaStart;
949     memcpy(&rvaStart, &relocatedRvaStart[0], sizeof(uint32_t));
950 
951     // Copy each frame data record, add in rvaStart, translate string table
952     // indices, and add the record to the PDB.
953     DebugFrameDataSubsectionRef fds;
954     BinaryStreamReader reader(subsecData, support::little);
955     exitOnErr(fds.initialize(reader));
956     for (codeview::FrameData fd : fds) {
957       fd.RvaStart += rvaStart;
958       fd.FrameFunc =
959           translateStringTableIndex(fd.FrameFunc, cvStrTab, linker.pdbStrTab);
960       dbiBuilder.addNewFpoData(fd);
961     }
962   }
963 
964   // Translate the fixups and pass them off to the module builder so they will
965   // be applied during writing.
966   for (StringTableFixup &ref : stringTableFixups) {
967     ref.StrTabOffset =
968         translateStringTableIndex(ref.StrTabOffset, cvStrTab, linker.pdbStrTab);
969   }
970   file.moduleDBI->setStringTableFixups(std::move(stringTableFixups));
971 
972   // Make a new file checksum table that refers to offsets in the PDB-wide
973   // string table. Generally the string table subsection appears after the
974   // checksum table, so we have to do this after looping over all the
975   // subsections. The new checksum table must have the exact same layout and
976   // size as the original. Otherwise, the file references in the line and
977   // inlinee line tables will be incorrect.
978   auto newChecksums = std::make_unique<DebugChecksumsSubsection>(linker.pdbStrTab);
979   for (const FileChecksumEntry &fc : checksums) {
980     SmallString<128> filename =
981         exitOnErr(cvStrTab.getString(fc.FileNameOffset));
982     pdbMakeAbsolute(filename);
983     exitOnErr(dbiBuilder.addModuleSourceFile(*file.moduleDBI, filename));
984     newChecksums->addChecksum(filename, fc.Kind, fc.Checksum);
985   }
986   assert(checksums.getArray().getUnderlyingStream().getLength() ==
987              newChecksums->calculateSerializedSize() &&
988          "file checksum table must have same layout");
989 
990   file.moduleDBI->addDebugSubsection(std::move(newChecksums));
991 }
992 
993 static void warnUnusable(InputFile *f, Error e) {
994   if (!config->warnDebugInfoUnusable) {
995     consumeError(std::move(e));
996     return;
997   }
998   auto msg = "Cannot use debug info for '" + toString(f) + "' [LNK4099]";
999   if (e)
1000     warn(msg + "\n>>> failed to load reference " + toString(std::move(e)));
1001   else
1002     warn(msg);
1003 }
1004 
1005 // Allocate memory for a .debug$S / .debug$F section and relocate it.
1006 static ArrayRef<uint8_t> relocateDebugChunk(SectionChunk &debugChunk) {
1007   uint8_t *buffer = bAlloc().Allocate<uint8_t>(debugChunk.getSize());
1008   assert(debugChunk.getOutputSectionIdx() == 0 &&
1009          "debug sections should not be in output sections");
1010   debugChunk.writeTo(buffer);
1011   return makeArrayRef(buffer, debugChunk.getSize());
1012 }
1013 
1014 void PDBLinker::addDebugSymbols(TpiSource *source) {
1015   // If this TpiSource doesn't have an object file, it must be from a type
1016   // server PDB. Type server PDBs do not contain symbols, so stop here.
1017   if (!source->file)
1018     return;
1019 
1020   ScopedTimer t(ctx.symbolMergingTimer);
1021   pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1022   DebugSHandler dsh(*this, *source->file, source);
1023   // Now do all live .debug$S and .debug$F sections.
1024   for (SectionChunk *debugChunk : source->file->getDebugChunks()) {
1025     if (!debugChunk->live || debugChunk->getSize() == 0)
1026       continue;
1027 
1028     bool isDebugS = debugChunk->getSectionName() == ".debug$S";
1029     bool isDebugF = debugChunk->getSectionName() == ".debug$F";
1030     if (!isDebugS && !isDebugF)
1031       continue;
1032 
1033     if (isDebugS) {
1034       dsh.handleDebugS(debugChunk);
1035     } else if (isDebugF) {
1036       // Handle old FPO data .debug$F sections. These are relatively rare.
1037       ArrayRef<uint8_t> relocatedDebugContents =
1038           relocateDebugChunk(*debugChunk);
1039       FixedStreamArray<object::FpoData> fpoRecords;
1040       BinaryStreamReader reader(relocatedDebugContents, support::little);
1041       uint32_t count = relocatedDebugContents.size() / sizeof(object::FpoData);
1042       exitOnErr(reader.readArray(fpoRecords, count));
1043 
1044       // These are already relocated and don't refer to the string table, so we
1045       // can just copy it.
1046       for (const object::FpoData &fd : fpoRecords)
1047         dbiBuilder.addOldFpoData(fd);
1048     }
1049   }
1050 
1051   // Do any post-processing now that all .debug$S sections have been processed.
1052   dsh.finish();
1053 }
1054 
1055 // Add a module descriptor for every object file. We need to put an absolute
1056 // path to the object into the PDB. If this is a plain object, we make its
1057 // path absolute. If it's an object in an archive, we make the archive path
1058 // absolute.
1059 void PDBLinker::createModuleDBI(ObjFile *file) {
1060   pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1061   SmallString<128> objName;
1062 
1063   bool inArchive = !file->parentName.empty();
1064   objName = inArchive ? file->parentName : file->getName();
1065   pdbMakeAbsolute(objName);
1066   StringRef modName = inArchive ? file->getName() : objName.str();
1067 
1068   file->moduleDBI = &exitOnErr(dbiBuilder.addModuleInfo(modName));
1069   file->moduleDBI->setObjFileName(objName);
1070   file->moduleDBI->setMergeSymbolsCallback(this, &commitSymbolsForObject);
1071 
1072   ArrayRef<Chunk *> chunks = file->getChunks();
1073   uint32_t modi = file->moduleDBI->getModuleIndex();
1074 
1075   for (Chunk *c : chunks) {
1076     auto *secChunk = dyn_cast<SectionChunk>(c);
1077     if (!secChunk || !secChunk->live)
1078       continue;
1079     pdb::SectionContrib sc = createSectionContrib(ctx, secChunk, modi);
1080     file->moduleDBI->setFirstSectionContrib(sc);
1081     break;
1082   }
1083 }
1084 
1085 void PDBLinker::addDebug(TpiSource *source) {
1086   // Before we can process symbol substreams from .debug$S, we need to process
1087   // type information, file checksums, and the string table. Add type info to
1088   // the PDB first, so that we can get the map from object file type and item
1089   // indices to PDB type and item indices.  If we are using ghashes, types have
1090   // already been merged.
1091   if (!config->debugGHashes) {
1092     ScopedTimer t(ctx.typeMergingTimer);
1093     if (Error e = source->mergeDebugT(&tMerger)) {
1094       // If type merging failed, ignore the symbols.
1095       warnUnusable(source->file, std::move(e));
1096       return;
1097     }
1098   }
1099 
1100   // If type merging failed, ignore the symbols.
1101   Error typeError = std::move(source->typeMergingError);
1102   if (typeError) {
1103     warnUnusable(source->file, std::move(typeError));
1104     return;
1105   }
1106 
1107   addDebugSymbols(source);
1108 }
1109 
1110 static pdb::BulkPublic createPublic(COFFLinkerContext &ctx, Defined *def) {
1111   pdb::BulkPublic pub;
1112   pub.Name = def->getName().data();
1113   pub.NameLen = def->getName().size();
1114 
1115   PublicSymFlags flags = PublicSymFlags::None;
1116   if (auto *d = dyn_cast<DefinedCOFF>(def)) {
1117     if (d->getCOFFSymbol().isFunctionDefinition())
1118       flags = PublicSymFlags::Function;
1119   } else if (isa<DefinedImportThunk>(def)) {
1120     flags = PublicSymFlags::Function;
1121   }
1122   pub.setFlags(flags);
1123 
1124   OutputSection *os = ctx.getOutputSection(def->getChunk());
1125   assert(os && "all publics should be in final image");
1126   pub.Offset = def->getRVA() - os->getRVA();
1127   pub.Segment = os->sectionIndex;
1128   return pub;
1129 }
1130 
1131 // Add all object files to the PDB. Merge .debug$T sections into IpiData and
1132 // TpiData.
1133 void PDBLinker::addObjectsToPDB() {
1134   ScopedTimer t1(ctx.addObjectsTimer);
1135 
1136   // Create module descriptors
1137   for (ObjFile *obj : ctx.objFileInstances)
1138     createModuleDBI(obj);
1139 
1140   // Reorder dependency type sources to come first.
1141   tMerger.sortDependencies();
1142 
1143   // Merge type information from input files using global type hashing.
1144   if (config->debugGHashes)
1145     tMerger.mergeTypesWithGHash();
1146 
1147   // Merge dependencies and then regular objects.
1148   for (TpiSource *source : tMerger.dependencySources)
1149     addDebug(source);
1150   for (TpiSource *source : tMerger.objectSources)
1151     addDebug(source);
1152 
1153   builder.getStringTableBuilder().setStrings(pdbStrTab);
1154   t1.stop();
1155 
1156   // Construct TPI and IPI stream contents.
1157   ScopedTimer t2(ctx.tpiStreamLayoutTimer);
1158   // Collect all the merged types.
1159   if (config->debugGHashes) {
1160     addGHashTypeInfo(ctx, builder);
1161   } else {
1162     addTypeInfo(builder.getTpiBuilder(), tMerger.getTypeTable());
1163     addTypeInfo(builder.getIpiBuilder(), tMerger.getIDTable());
1164   }
1165   t2.stop();
1166 
1167   if (config->showSummary) {
1168     for (TpiSource *source : ctx.tpiSourceList) {
1169       nbTypeRecords += source->nbTypeRecords;
1170       nbTypeRecordsBytes += source->nbTypeRecordsBytes;
1171     }
1172   }
1173 }
1174 
1175 void PDBLinker::addPublicsToPDB() {
1176   ScopedTimer t3(ctx.publicsLayoutTimer);
1177   // Compute the public symbols.
1178   auto &gsiBuilder = builder.getGsiBuilder();
1179   std::vector<pdb::BulkPublic> publics;
1180   ctx.symtab.forEachSymbol([&publics, this](Symbol *s) {
1181     // Only emit external, defined, live symbols that have a chunk. Static,
1182     // non-external symbols do not appear in the symbol table.
1183     auto *def = dyn_cast<Defined>(s);
1184     if (def && def->isLive() && def->getChunk()) {
1185       // Don't emit a public symbol for coverage data symbols. LLVM code
1186       // coverage (and PGO) create a __profd_ and __profc_ symbol for every
1187       // function. C++ mangled names are long, and tend to dominate symbol size.
1188       // Including these names triples the size of the public stream, which
1189       // results in bloated PDB files. These symbols generally are not helpful
1190       // for debugging, so suppress them.
1191       StringRef name = def->getName();
1192       if (name.data()[0] == '_' && name.data()[1] == '_') {
1193         // Drop the '_' prefix for x86.
1194         if (config->machine == I386)
1195           name = name.drop_front(1);
1196         if (name.startswith("__profd_") || name.startswith("__profc_") ||
1197             name.startswith("__covrec_")) {
1198           return;
1199         }
1200       }
1201       publics.push_back(createPublic(ctx, def));
1202     }
1203   });
1204 
1205   if (!publics.empty()) {
1206     publicSymbols = publics.size();
1207     gsiBuilder.addPublicSymbols(std::move(publics));
1208   }
1209 }
1210 
1211 void PDBLinker::printStats() {
1212   if (!config->showSummary)
1213     return;
1214 
1215   SmallString<256> buffer;
1216   raw_svector_ostream stream(buffer);
1217 
1218   stream << center_justify("Summary", 80) << '\n'
1219          << std::string(80, '-') << '\n';
1220 
1221   auto print = [&](uint64_t v, StringRef s) {
1222     stream << format_decimal(v, 15) << " " << s << '\n';
1223   };
1224 
1225   print(ctx.objFileInstances.size(),
1226         "Input OBJ files (expanded from all cmd-line inputs)");
1227   print(ctx.typeServerSourceMappings.size(), "PDB type server dependencies");
1228   print(ctx.precompSourceMappings.size(), "Precomp OBJ dependencies");
1229   print(nbTypeRecords, "Input type records");
1230   print(nbTypeRecordsBytes, "Input type records bytes");
1231   print(builder.getTpiBuilder().getRecordCount(), "Merged TPI records");
1232   print(builder.getIpiBuilder().getRecordCount(), "Merged IPI records");
1233   print(pdbStrTab.size(), "Output PDB strings");
1234   print(globalSymbols, "Global symbol records");
1235   print(moduleSymbols, "Module symbol records");
1236   print(publicSymbols, "Public symbol records");
1237 
1238   auto printLargeInputTypeRecs = [&](StringRef name,
1239                                      ArrayRef<uint32_t> recCounts,
1240                                      TypeCollection &records) {
1241     // Figure out which type indices were responsible for the most duplicate
1242     // bytes in the input files. These should be frequently emitted LF_CLASS and
1243     // LF_FIELDLIST records.
1244     struct TypeSizeInfo {
1245       uint32_t typeSize;
1246       uint32_t dupCount;
1247       TypeIndex typeIndex;
1248       uint64_t totalInputSize() const { return uint64_t(dupCount) * typeSize; }
1249       bool operator<(const TypeSizeInfo &rhs) const {
1250         if (totalInputSize() == rhs.totalInputSize())
1251           return typeIndex < rhs.typeIndex;
1252         return totalInputSize() < rhs.totalInputSize();
1253       }
1254     };
1255     SmallVector<TypeSizeInfo, 0> tsis;
1256     for (auto e : enumerate(recCounts)) {
1257       TypeIndex typeIndex = TypeIndex::fromArrayIndex(e.index());
1258       uint32_t typeSize = records.getType(typeIndex).length();
1259       uint32_t dupCount = e.value();
1260       tsis.push_back({typeSize, dupCount, typeIndex});
1261     }
1262 
1263     if (!tsis.empty()) {
1264       stream << "\nTop 10 types responsible for the most " << name
1265              << " input:\n";
1266       stream << "       index     total bytes   count     size\n";
1267       llvm::sort(tsis);
1268       unsigned i = 0;
1269       for (const auto &tsi : reverse(tsis)) {
1270         stream << formatv("  {0,10:X}: {1,14:N} = {2,5:N} * {3,6:N}\n",
1271                           tsi.typeIndex.getIndex(), tsi.totalInputSize(),
1272                           tsi.dupCount, tsi.typeSize);
1273         if (++i >= 10)
1274           break;
1275       }
1276       stream
1277           << "Run llvm-pdbutil to print details about a particular record:\n";
1278       stream << formatv("llvm-pdbutil dump -{0}s -{0}-index {1:X} {2}\n",
1279                         (name == "TPI" ? "type" : "id"),
1280                         tsis.back().typeIndex.getIndex(), config->pdbPath);
1281     }
1282   };
1283 
1284   if (!config->debugGHashes) {
1285     // FIXME: Reimplement for ghash.
1286     printLargeInputTypeRecs("TPI", tMerger.tpiCounts, tMerger.getTypeTable());
1287     printLargeInputTypeRecs("IPI", tMerger.ipiCounts, tMerger.getIDTable());
1288   }
1289 
1290   message(buffer);
1291 }
1292 
1293 void PDBLinker::addNatvisFiles() {
1294   for (StringRef file : config->natvisFiles) {
1295     ErrorOr<std::unique_ptr<MemoryBuffer>> dataOrErr =
1296         MemoryBuffer::getFile(file);
1297     if (!dataOrErr) {
1298       warn("Cannot open input file: " + file);
1299       continue;
1300     }
1301     std::unique_ptr<MemoryBuffer> data = std::move(*dataOrErr);
1302 
1303     // Can't use takeBuffer() here since addInjectedSource() takes ownership.
1304     if (driver->tar)
1305       driver->tar->append(relativeToRoot(data->getBufferIdentifier()),
1306                           data->getBuffer());
1307 
1308     builder.addInjectedSource(file, std::move(data));
1309   }
1310 }
1311 
1312 void PDBLinker::addNamedStreams() {
1313   for (const auto &streamFile : config->namedStreams) {
1314     const StringRef stream = streamFile.getKey(), file = streamFile.getValue();
1315     ErrorOr<std::unique_ptr<MemoryBuffer>> dataOrErr =
1316         MemoryBuffer::getFile(file);
1317     if (!dataOrErr) {
1318       warn("Cannot open input file: " + file);
1319       continue;
1320     }
1321     std::unique_ptr<MemoryBuffer> data = std::move(*dataOrErr);
1322     exitOnErr(builder.addNamedStream(stream, data->getBuffer()));
1323     driver->takeBuffer(std::move(data));
1324   }
1325 }
1326 
1327 static codeview::CPUType toCodeViewMachine(COFF::MachineTypes machine) {
1328   switch (machine) {
1329   case COFF::IMAGE_FILE_MACHINE_AMD64:
1330     return codeview::CPUType::X64;
1331   case COFF::IMAGE_FILE_MACHINE_ARM:
1332     return codeview::CPUType::ARM7;
1333   case COFF::IMAGE_FILE_MACHINE_ARM64:
1334     return codeview::CPUType::ARM64;
1335   case COFF::IMAGE_FILE_MACHINE_ARMNT:
1336     return codeview::CPUType::ARMNT;
1337   case COFF::IMAGE_FILE_MACHINE_I386:
1338     return codeview::CPUType::Intel80386;
1339   default:
1340     llvm_unreachable("Unsupported CPU Type");
1341   }
1342 }
1343 
1344 // Mimic MSVC which surrounds arguments containing whitespace with quotes.
1345 // Double double-quotes are handled, so that the resulting string can be
1346 // executed again on the cmd-line.
1347 static std::string quote(ArrayRef<StringRef> args) {
1348   std::string r;
1349   r.reserve(256);
1350   for (StringRef a : args) {
1351     if (!r.empty())
1352       r.push_back(' ');
1353     bool hasWS = a.contains(' ');
1354     bool hasQ = a.contains('"');
1355     if (hasWS || hasQ)
1356       r.push_back('"');
1357     if (hasQ) {
1358       SmallVector<StringRef, 4> s;
1359       a.split(s, '"');
1360       r.append(join(s, "\"\""));
1361     } else {
1362       r.append(std::string(a));
1363     }
1364     if (hasWS || hasQ)
1365       r.push_back('"');
1366   }
1367   return r;
1368 }
1369 
1370 static void fillLinkerVerRecord(Compile3Sym &cs) {
1371   cs.Machine = toCodeViewMachine(config->machine);
1372   // Interestingly, if we set the string to 0.0.0.0, then when trying to view
1373   // local variables WinDbg emits an error that private symbols are not present.
1374   // By setting this to a valid MSVC linker version string, local variables are
1375   // displayed properly.   As such, even though it is not representative of
1376   // LLVM's version information, we need this for compatibility.
1377   cs.Flags = CompileSym3Flags::None;
1378   cs.VersionBackendBuild = 25019;
1379   cs.VersionBackendMajor = 14;
1380   cs.VersionBackendMinor = 10;
1381   cs.VersionBackendQFE = 0;
1382 
1383   // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
1384   // linker module (which is by definition a backend), so we don't need to do
1385   // anything here.  Also, it seems we can use "LLVM Linker" for the linker name
1386   // without any problems.  Only the backend version has to be hardcoded to a
1387   // magic number.
1388   cs.VersionFrontendBuild = 0;
1389   cs.VersionFrontendMajor = 0;
1390   cs.VersionFrontendMinor = 0;
1391   cs.VersionFrontendQFE = 0;
1392   cs.Version = "LLVM Linker";
1393   cs.setLanguage(SourceLanguage::Link);
1394 }
1395 
1396 static void addCommonLinkerModuleSymbols(StringRef path,
1397                                          pdb::DbiModuleDescriptorBuilder &mod) {
1398   ObjNameSym ons(SymbolRecordKind::ObjNameSym);
1399   EnvBlockSym ebs(SymbolRecordKind::EnvBlockSym);
1400   Compile3Sym cs(SymbolRecordKind::Compile3Sym);
1401   fillLinkerVerRecord(cs);
1402 
1403   ons.Name = "* Linker *";
1404   ons.Signature = 0;
1405 
1406   ArrayRef<StringRef> args = makeArrayRef(config->argv).drop_front();
1407   std::string argStr = quote(args);
1408   ebs.Fields.push_back("cwd");
1409   SmallString<64> cwd;
1410   if (config->pdbSourcePath.empty())
1411     sys::fs::current_path(cwd);
1412   else
1413     cwd = config->pdbSourcePath;
1414   ebs.Fields.push_back(cwd);
1415   ebs.Fields.push_back("exe");
1416   SmallString<64> exe = config->argv[0];
1417   pdbMakeAbsolute(exe);
1418   ebs.Fields.push_back(exe);
1419   ebs.Fields.push_back("pdb");
1420   ebs.Fields.push_back(path);
1421   ebs.Fields.push_back("cmd");
1422   ebs.Fields.push_back(argStr);
1423   llvm::BumpPtrAllocator &bAlloc = lld::bAlloc();
1424   mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1425       ons, bAlloc, CodeViewContainer::Pdb));
1426   mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1427       cs, bAlloc, CodeViewContainer::Pdb));
1428   mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1429       ebs, bAlloc, CodeViewContainer::Pdb));
1430 }
1431 
1432 static void addLinkerModuleCoffGroup(PartialSection *sec,
1433                                      pdb::DbiModuleDescriptorBuilder &mod,
1434                                      OutputSection &os) {
1435   // If there's a section, there's at least one chunk
1436   assert(!sec->chunks.empty());
1437   const Chunk *firstChunk = *sec->chunks.begin();
1438   const Chunk *lastChunk = *sec->chunks.rbegin();
1439 
1440   // Emit COFF group
1441   CoffGroupSym cgs(SymbolRecordKind::CoffGroupSym);
1442   cgs.Name = sec->name;
1443   cgs.Segment = os.sectionIndex;
1444   cgs.Offset = firstChunk->getRVA() - os.getRVA();
1445   cgs.Size = lastChunk->getRVA() + lastChunk->getSize() - firstChunk->getRVA();
1446   cgs.Characteristics = sec->characteristics;
1447 
1448   // Somehow .idata sections & sections groups in the debug symbol stream have
1449   // the "write" flag set. However the section header for the corresponding
1450   // .idata section doesn't have it.
1451   if (cgs.Name.startswith(".idata"))
1452     cgs.Characteristics |= llvm::COFF::IMAGE_SCN_MEM_WRITE;
1453 
1454   mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1455       cgs, bAlloc(), CodeViewContainer::Pdb));
1456 }
1457 
1458 static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &mod,
1459                                          OutputSection &os) {
1460   SectionSym sym(SymbolRecordKind::SectionSym);
1461   sym.Alignment = 12; // 2^12 = 4KB
1462   sym.Characteristics = os.header.Characteristics;
1463   sym.Length = os.getVirtualSize();
1464   sym.Name = os.name;
1465   sym.Rva = os.getRVA();
1466   sym.SectionNumber = os.sectionIndex;
1467   mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1468       sym, bAlloc(), CodeViewContainer::Pdb));
1469 
1470   // Skip COFF groups in MinGW because it adds a significant footprint to the
1471   // PDB, due to each function being in its own section
1472   if (config->mingw)
1473     return;
1474 
1475   // Output COFF groups for individual chunks of this section.
1476   for (PartialSection *sec : os.contribSections) {
1477     addLinkerModuleCoffGroup(sec, mod, os);
1478   }
1479 }
1480 
1481 // Add all import files as modules to the PDB.
1482 void PDBLinker::addImportFilesToPDB() {
1483   if (ctx.importFileInstances.empty())
1484     return;
1485 
1486   std::map<std::string, llvm::pdb::DbiModuleDescriptorBuilder *> dllToModuleDbi;
1487 
1488   for (ImportFile *file : ctx.importFileInstances) {
1489     if (!file->live)
1490       continue;
1491 
1492     if (!file->thunkSym)
1493       continue;
1494 
1495     if (!file->thunkLive)
1496         continue;
1497 
1498     std::string dll = StringRef(file->dllName).lower();
1499     llvm::pdb::DbiModuleDescriptorBuilder *&mod = dllToModuleDbi[dll];
1500     if (!mod) {
1501       pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1502       SmallString<128> libPath = file->parentName;
1503       pdbMakeAbsolute(libPath);
1504       sys::path::native(libPath);
1505 
1506       // Name modules similar to MSVC's link.exe.
1507       // The first module is the simple dll filename
1508       llvm::pdb::DbiModuleDescriptorBuilder &firstMod =
1509           exitOnErr(dbiBuilder.addModuleInfo(file->dllName));
1510       firstMod.setObjFileName(libPath);
1511       pdb::SectionContrib sc =
1512           createSectionContrib(ctx, nullptr, llvm::pdb::kInvalidStreamIndex);
1513       firstMod.setFirstSectionContrib(sc);
1514 
1515       // The second module is where the import stream goes.
1516       mod = &exitOnErr(dbiBuilder.addModuleInfo("Import:" + file->dllName));
1517       mod->setObjFileName(libPath);
1518     }
1519 
1520     DefinedImportThunk *thunk = cast<DefinedImportThunk>(file->thunkSym);
1521     Chunk *thunkChunk = thunk->getChunk();
1522     OutputSection *thunkOS = ctx.getOutputSection(thunkChunk);
1523 
1524     ObjNameSym ons(SymbolRecordKind::ObjNameSym);
1525     Compile3Sym cs(SymbolRecordKind::Compile3Sym);
1526     Thunk32Sym ts(SymbolRecordKind::Thunk32Sym);
1527     ScopeEndSym es(SymbolRecordKind::ScopeEndSym);
1528 
1529     ons.Name = file->dllName;
1530     ons.Signature = 0;
1531 
1532     fillLinkerVerRecord(cs);
1533 
1534     ts.Name = thunk->getName();
1535     ts.Parent = 0;
1536     ts.End = 0;
1537     ts.Next = 0;
1538     ts.Thunk = ThunkOrdinal::Standard;
1539     ts.Length = thunkChunk->getSize();
1540     ts.Segment = thunkOS->sectionIndex;
1541     ts.Offset = thunkChunk->getRVA() - thunkOS->getRVA();
1542 
1543     llvm::BumpPtrAllocator &bAlloc = lld::bAlloc();
1544     mod->addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1545         ons, bAlloc, CodeViewContainer::Pdb));
1546     mod->addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1547         cs, bAlloc, CodeViewContainer::Pdb));
1548 
1549     CVSymbol newSym = codeview::SymbolSerializer::writeOneSymbol(
1550         ts, bAlloc, CodeViewContainer::Pdb);
1551 
1552     // Write ptrEnd for the S_THUNK32.
1553     ScopeRecord *thunkSymScope =
1554         getSymbolScopeFields(const_cast<uint8_t *>(newSym.data().data()));
1555 
1556     mod->addSymbol(newSym);
1557 
1558     newSym = codeview::SymbolSerializer::writeOneSymbol(es, bAlloc,
1559                                                         CodeViewContainer::Pdb);
1560     thunkSymScope->ptrEnd = mod->getNextSymbolOffset();
1561 
1562     mod->addSymbol(newSym);
1563 
1564     pdb::SectionContrib sc =
1565         createSectionContrib(ctx, thunk->getChunk(), mod->getModuleIndex());
1566     mod->setFirstSectionContrib(sc);
1567   }
1568 }
1569 
1570 // Creates a PDB file.
1571 void lld::coff::createPDB(COFFLinkerContext &ctx,
1572                           ArrayRef<uint8_t> sectionTable,
1573                           llvm::codeview::DebugInfo *buildId) {
1574   ScopedTimer t1(ctx.totalPdbLinkTimer);
1575   PDBLinker pdb(ctx);
1576 
1577   pdb.initialize(buildId);
1578   pdb.addObjectsToPDB();
1579   pdb.addImportFilesToPDB();
1580   pdb.addSections(sectionTable);
1581   pdb.addNatvisFiles();
1582   pdb.addNamedStreams();
1583   pdb.addPublicsToPDB();
1584 
1585   ScopedTimer t2(ctx.diskCommitTimer);
1586   codeview::GUID guid;
1587   pdb.commit(&guid);
1588   memcpy(&buildId->PDB70.Signature, &guid, 16);
1589 
1590   t2.stop();
1591   t1.stop();
1592   pdb.printStats();
1593 }
1594 
1595 void PDBLinker::initialize(llvm::codeview::DebugInfo *buildId) {
1596   exitOnErr(builder.initialize(config->pdbPageSize));
1597 
1598   buildId->Signature.CVSignature = OMF::Signature::PDB70;
1599   // Signature is set to a hash of the PDB contents when the PDB is done.
1600   memset(buildId->PDB70.Signature, 0, 16);
1601   buildId->PDB70.Age = 1;
1602 
1603   // Create streams in MSF for predefined streams, namely
1604   // PDB, TPI, DBI and IPI.
1605   for (int i = 0; i < (int)pdb::kSpecialStreamCount; ++i)
1606     exitOnErr(builder.getMsfBuilder().addStream(0));
1607 
1608   // Add an Info stream.
1609   auto &infoBuilder = builder.getInfoBuilder();
1610   infoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
1611   infoBuilder.setHashPDBContentsToGUID(true);
1612 
1613   // Add an empty DBI stream.
1614   pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1615   dbiBuilder.setAge(buildId->PDB70.Age);
1616   dbiBuilder.setVersionHeader(pdb::PdbDbiV70);
1617   dbiBuilder.setMachineType(config->machine);
1618   // Technically we are not link.exe 14.11, but there are known cases where
1619   // debugging tools on Windows expect Microsoft-specific version numbers or
1620   // they fail to work at all.  Since we know we produce PDBs that are
1621   // compatible with LINK 14.11, we set that version number here.
1622   dbiBuilder.setBuildNumber(14, 11);
1623 }
1624 
1625 void PDBLinker::addSections(ArrayRef<uint8_t> sectionTable) {
1626   // It's not entirely clear what this is, but the * Linker * module uses it.
1627   pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1628   nativePath = config->pdbPath;
1629   pdbMakeAbsolute(nativePath);
1630   uint32_t pdbFilePathNI = dbiBuilder.addECName(nativePath);
1631   auto &linkerModule = exitOnErr(dbiBuilder.addModuleInfo("* Linker *"));
1632   linkerModule.setPdbFilePathNI(pdbFilePathNI);
1633   addCommonLinkerModuleSymbols(nativePath, linkerModule);
1634 
1635   // Add section contributions. They must be ordered by ascending RVA.
1636   for (OutputSection *os : ctx.outputSections) {
1637     addLinkerModuleSectionSymbol(linkerModule, *os);
1638     for (Chunk *c : os->chunks) {
1639       pdb::SectionContrib sc =
1640           createSectionContrib(ctx, c, linkerModule.getModuleIndex());
1641       builder.getDbiBuilder().addSectionContrib(sc);
1642     }
1643   }
1644 
1645   // The * Linker * first section contrib is only used along with /INCREMENTAL,
1646   // to provide trampolines thunks for incremental function patching. Set this
1647   // as "unused" because LLD doesn't support /INCREMENTAL link.
1648   pdb::SectionContrib sc =
1649       createSectionContrib(ctx, nullptr, llvm::pdb::kInvalidStreamIndex);
1650   linkerModule.setFirstSectionContrib(sc);
1651 
1652   // Add Section Map stream.
1653   ArrayRef<object::coff_section> sections = {
1654       (const object::coff_section *)sectionTable.data(),
1655       sectionTable.size() / sizeof(object::coff_section)};
1656   dbiBuilder.createSectionMap(sections);
1657 
1658   // Add COFF section header stream.
1659   exitOnErr(
1660       dbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, sectionTable));
1661 }
1662 
1663 void PDBLinker::commit(codeview::GUID *guid) {
1664   // Print an error and continue if PDB writing fails. This is done mainly so
1665   // the user can see the output of /time and /summary, which is very helpful
1666   // when trying to figure out why a PDB file is too large.
1667   if (Error e = builder.commit(config->pdbPath, guid)) {
1668     checkError(std::move(e));
1669     error("failed to write PDB file " + Twine(config->pdbPath));
1670   }
1671 }
1672 
1673 static uint32_t getSecrelReloc() {
1674   switch (config->machine) {
1675   case AMD64:
1676     return COFF::IMAGE_REL_AMD64_SECREL;
1677   case I386:
1678     return COFF::IMAGE_REL_I386_SECREL;
1679   case ARMNT:
1680     return COFF::IMAGE_REL_ARM_SECREL;
1681   case ARM64:
1682     return COFF::IMAGE_REL_ARM64_SECREL;
1683   default:
1684     llvm_unreachable("unknown machine type");
1685   }
1686 }
1687 
1688 // Try to find a line table for the given offset Addr into the given chunk C.
1689 // If a line table was found, the line table, the string and checksum tables
1690 // that are used to interpret the line table, and the offset of Addr in the line
1691 // table are stored in the output arguments. Returns whether a line table was
1692 // found.
1693 static bool findLineTable(const SectionChunk *c, uint32_t addr,
1694                           DebugStringTableSubsectionRef &cvStrTab,
1695                           DebugChecksumsSubsectionRef &checksums,
1696                           DebugLinesSubsectionRef &lines,
1697                           uint32_t &offsetInLinetable) {
1698   ExitOnError exitOnErr;
1699   uint32_t secrelReloc = getSecrelReloc();
1700 
1701   for (SectionChunk *dbgC : c->file->getDebugChunks()) {
1702     if (dbgC->getSectionName() != ".debug$S")
1703       continue;
1704 
1705     // Build a mapping of SECREL relocations in dbgC that refer to `c`.
1706     DenseMap<uint32_t, uint32_t> secrels;
1707     for (const coff_relocation &r : dbgC->getRelocs()) {
1708       if (r.Type != secrelReloc)
1709         continue;
1710 
1711       if (auto *s = dyn_cast_or_null<DefinedRegular>(
1712               c->file->getSymbols()[r.SymbolTableIndex]))
1713         if (s->getChunk() == c)
1714           secrels[r.VirtualAddress] = s->getValue();
1715     }
1716 
1717     ArrayRef<uint8_t> contents =
1718         SectionChunk::consumeDebugMagic(dbgC->getContents(), ".debug$S");
1719     DebugSubsectionArray subsections;
1720     BinaryStreamReader reader(contents, support::little);
1721     exitOnErr(reader.readArray(subsections, contents.size()));
1722 
1723     for (const DebugSubsectionRecord &ss : subsections) {
1724       switch (ss.kind()) {
1725       case DebugSubsectionKind::StringTable: {
1726         assert(!cvStrTab.valid() &&
1727                "Encountered multiple string table subsections!");
1728         exitOnErr(cvStrTab.initialize(ss.getRecordData()));
1729         break;
1730       }
1731       case DebugSubsectionKind::FileChecksums:
1732         assert(!checksums.valid() &&
1733                "Encountered multiple checksum subsections!");
1734         exitOnErr(checksums.initialize(ss.getRecordData()));
1735         break;
1736       case DebugSubsectionKind::Lines: {
1737         ArrayRef<uint8_t> bytes;
1738         auto ref = ss.getRecordData();
1739         exitOnErr(ref.readLongestContiguousChunk(0, bytes));
1740         size_t offsetInDbgC = bytes.data() - dbgC->getContents().data();
1741 
1742         // Check whether this line table refers to C.
1743         auto i = secrels.find(offsetInDbgC);
1744         if (i == secrels.end())
1745           break;
1746 
1747         // Check whether this line table covers Addr in C.
1748         DebugLinesSubsectionRef linesTmp;
1749         exitOnErr(linesTmp.initialize(BinaryStreamReader(ref)));
1750         uint32_t offsetInC = i->second + linesTmp.header()->RelocOffset;
1751         if (addr < offsetInC || addr >= offsetInC + linesTmp.header()->CodeSize)
1752           break;
1753 
1754         assert(!lines.header() &&
1755                "Encountered multiple line tables for function!");
1756         exitOnErr(lines.initialize(BinaryStreamReader(ref)));
1757         offsetInLinetable = addr - offsetInC;
1758         break;
1759       }
1760       default:
1761         break;
1762       }
1763 
1764       if (cvStrTab.valid() && checksums.valid() && lines.header())
1765         return true;
1766     }
1767   }
1768 
1769   return false;
1770 }
1771 
1772 // Use CodeView line tables to resolve a file and line number for the given
1773 // offset into the given chunk and return them, or None if a line table was
1774 // not found.
1775 Optional<std::pair<StringRef, uint32_t>>
1776 lld::coff::getFileLineCodeView(const SectionChunk *c, uint32_t addr) {
1777   ExitOnError exitOnErr;
1778 
1779   DebugStringTableSubsectionRef cvStrTab;
1780   DebugChecksumsSubsectionRef checksums;
1781   DebugLinesSubsectionRef lines;
1782   uint32_t offsetInLinetable;
1783 
1784   if (!findLineTable(c, addr, cvStrTab, checksums, lines, offsetInLinetable))
1785     return None;
1786 
1787   Optional<uint32_t> nameIndex;
1788   Optional<uint32_t> lineNumber;
1789   for (const LineColumnEntry &entry : lines) {
1790     for (const LineNumberEntry &ln : entry.LineNumbers) {
1791       LineInfo li(ln.Flags);
1792       if (ln.Offset > offsetInLinetable) {
1793         if (!nameIndex) {
1794           nameIndex = entry.NameIndex;
1795           lineNumber = li.getStartLine();
1796         }
1797         StringRef filename =
1798             exitOnErr(getFileName(cvStrTab, checksums, *nameIndex));
1799         return std::make_pair(filename, *lineNumber);
1800       }
1801       nameIndex = entry.NameIndex;
1802       lineNumber = li.getStartLine();
1803     }
1804   }
1805   if (!nameIndex)
1806     return None;
1807   StringRef filename = exitOnErr(getFileName(cvStrTab, checksums, *nameIndex));
1808   return std::make_pair(filename, *lineNumber);
1809 }
1810