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