xref: /freebsd/contrib/llvm-project/lld/COFF/PDB.cpp (revision 0d8fe2373503aeac48492f28073049a8bfa4feb5)
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     return;
270   }
271 
272   // Try to guess whether /PDBSOURCEPATH is a unix path or a windows path.
273   // Since PDB's are more of a Windows thing, we make this conservative and only
274   // decide that it's a unix path if we're fairly certain.  Specifically, if
275   // it starts with a forward slash.
276   SmallString<128> absoluteFileName = config->pdbSourcePath;
277   sys::path::Style guessedStyle = absoluteFileName.startswith("/")
278                                       ? sys::path::Style::posix
279                                       : sys::path::Style::windows;
280   sys::path::append(absoluteFileName, guessedStyle, fileName);
281   sys::path::native(absoluteFileName, guessedStyle);
282   sys::path::remove_dots(absoluteFileName, true, guessedStyle);
283 
284   fileName = std::move(absoluteFileName);
285 }
286 
287 static void addTypeInfo(pdb::TpiStreamBuilder &tpiBuilder,
288                         TypeCollection &typeTable) {
289   // Start the TPI or IPI stream header.
290   tpiBuilder.setVersionHeader(pdb::PdbTpiV80);
291 
292   // Flatten the in memory type table and hash each type.
293   typeTable.ForEachRecord([&](TypeIndex ti, const CVType &type) {
294     auto hash = pdb::hashTypeRecord(type);
295     if (auto e = hash.takeError())
296       fatal("type hashing error");
297     tpiBuilder.addTypeRecord(type.RecordData, *hash);
298   });
299 }
300 
301 static void addGHashTypeInfo(pdb::PDBFileBuilder &builder) {
302   // Start the TPI or IPI stream header.
303   builder.getTpiBuilder().setVersionHeader(pdb::PdbTpiV80);
304   builder.getIpiBuilder().setVersionHeader(pdb::PdbTpiV80);
305   for_each(TpiSource::instances, [&](TpiSource *source) {
306     builder.getTpiBuilder().addTypeRecords(source->mergedTpi.recs,
307                                            source->mergedTpi.recSizes,
308                                            source->mergedTpi.recHashes);
309     builder.getIpiBuilder().addTypeRecords(source->mergedIpi.recs,
310                                            source->mergedIpi.recSizes,
311                                            source->mergedIpi.recHashes);
312   });
313 }
314 
315 static void
316 recordStringTableReferences(CVSymbol sym, uint32_t symOffset,
317                             std::vector<StringTableFixup> &stringTableFixups) {
318   // For now we only handle S_FILESTATIC, but we may need the same logic for
319   // S_DEFRANGE and S_DEFRANGE_SUBFIELD.  However, I cannot seem to generate any
320   // PDBs that contain these types of records, so because of the uncertainty
321   // they are omitted here until we can prove that it's necessary.
322   switch (sym.kind()) {
323   case SymbolKind::S_FILESTATIC: {
324     // FileStaticSym::ModFileOffset
325     uint32_t ref = *reinterpret_cast<const ulittle32_t *>(&sym.data()[8]);
326     stringTableFixups.push_back({ref, symOffset + 8});
327     break;
328   }
329   case SymbolKind::S_DEFRANGE:
330   case SymbolKind::S_DEFRANGE_SUBFIELD:
331     log("Not fixing up string table reference in S_DEFRANGE / "
332         "S_DEFRANGE_SUBFIELD record");
333     break;
334   default:
335     break;
336   }
337 }
338 
339 static SymbolKind symbolKind(ArrayRef<uint8_t> recordData) {
340   const RecordPrefix *prefix =
341       reinterpret_cast<const RecordPrefix *>(recordData.data());
342   return static_cast<SymbolKind>(uint16_t(prefix->RecordKind));
343 }
344 
345 /// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
346 static void translateIdSymbols(MutableArrayRef<uint8_t> &recordData,
347                                TypeMerger &tMerger, TpiSource *source) {
348   RecordPrefix *prefix = reinterpret_cast<RecordPrefix *>(recordData.data());
349 
350   SymbolKind kind = symbolKind(recordData);
351 
352   if (kind == SymbolKind::S_PROC_ID_END) {
353     prefix->RecordKind = SymbolKind::S_END;
354     return;
355   }
356 
357   // In an object file, GPROC32_ID has an embedded reference which refers to the
358   // single object file type index namespace.  This has already been translated
359   // to the PDB file's ID stream index space, but we need to convert this to a
360   // symbol that refers to the type stream index space.  So we remap again from
361   // ID index space to type index space.
362   if (kind == SymbolKind::S_GPROC32_ID || kind == SymbolKind::S_LPROC32_ID) {
363     SmallVector<TiReference, 1> refs;
364     auto content = recordData.drop_front(sizeof(RecordPrefix));
365     CVSymbol sym(recordData);
366     discoverTypeIndicesInSymbol(sym, refs);
367     assert(refs.size() == 1);
368     assert(refs.front().Count == 1);
369 
370     TypeIndex *ti =
371         reinterpret_cast<TypeIndex *>(content.data() + refs[0].Offset);
372     // `ti` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
373     // the IPI stream, whose `FunctionType` member refers to the TPI stream.
374     // Note that LF_FUNC_ID and LF_MFUNC_ID have the same record layout, and
375     // in both cases we just need the second type index.
376     if (!ti->isSimple() && !ti->isNoneType()) {
377       if (config->debugGHashes) {
378         auto idToType = tMerger.funcIdToType.find(*ti);
379         if (idToType == tMerger.funcIdToType.end()) {
380           warn(formatv("S_[GL]PROC32_ID record in {0} refers to PDB item "
381                        "index {1:X} which is not a LF_[M]FUNC_ID record",
382                        source->file->getName(), ti->getIndex()));
383           *ti = TypeIndex(SimpleTypeKind::NotTranslated);
384         } else {
385           *ti = idToType->second;
386         }
387       } else {
388         CVType funcIdData = tMerger.getIDTable().getType(*ti);
389         ArrayRef<uint8_t> tiBuf = funcIdData.data().slice(8, 4);
390         assert(tiBuf.size() == 4 && "corrupt LF_[M]FUNC_ID record");
391         *ti = *reinterpret_cast<const TypeIndex *>(tiBuf.data());
392       }
393     }
394 
395     kind = (kind == SymbolKind::S_GPROC32_ID) ? SymbolKind::S_GPROC32
396                                               : SymbolKind::S_LPROC32;
397     prefix->RecordKind = uint16_t(kind);
398   }
399 }
400 
401 namespace {
402 struct ScopeRecord {
403   ulittle32_t ptrParent;
404   ulittle32_t ptrEnd;
405 };
406 } // namespace
407 
408 /// Given a pointer to a symbol record that opens a scope, return a pointer to
409 /// the scope fields.
410 static ScopeRecord *getSymbolScopeFields(void *sym) {
411   return reinterpret_cast<ScopeRecord *>(reinterpret_cast<char *>(sym) +
412                                          sizeof(RecordPrefix));
413 }
414 
415 // To open a scope, push the offset of the current symbol record onto the
416 // stack.
417 static void scopeStackOpen(SmallVectorImpl<uint32_t> &stack,
418                            std::vector<uint8_t> &storage) {
419   stack.push_back(storage.size());
420 }
421 
422 // To close a scope, update the record that opened the scope.
423 static void scopeStackClose(SmallVectorImpl<uint32_t> &stack,
424                             std::vector<uint8_t> &storage,
425                             uint32_t storageBaseOffset, ObjFile *file) {
426   if (stack.empty()) {
427     warn("symbol scopes are not balanced in " + file->getName());
428     return;
429   }
430 
431   // Update ptrEnd of the record that opened the scope to point to the
432   // current record, if we are writing into the module symbol stream.
433   uint32_t offOpen = stack.pop_back_val();
434   uint32_t offEnd = storageBaseOffset + storage.size();
435   uint32_t offParent = stack.empty() ? 0 : (stack.back() + storageBaseOffset);
436   ScopeRecord *scopeRec = getSymbolScopeFields(&(storage)[offOpen]);
437   scopeRec->ptrParent = offParent;
438   scopeRec->ptrEnd = offEnd;
439 }
440 
441 static bool symbolGoesInModuleStream(const CVSymbol &sym,
442                                      unsigned symbolScopeDepth) {
443   switch (sym.kind()) {
444   case SymbolKind::S_GDATA32:
445   case SymbolKind::S_CONSTANT:
446   case SymbolKind::S_GTHREAD32:
447   // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
448   // since they are synthesized by the linker in response to S_GPROC32 and
449   // S_LPROC32, but if we do see them, don't put them in the module stream I
450   // guess.
451   case SymbolKind::S_PROCREF:
452   case SymbolKind::S_LPROCREF:
453     return false;
454   // S_UDT records go in the module stream if it is not a global S_UDT.
455   case SymbolKind::S_UDT:
456     return symbolScopeDepth > 0;
457   // S_GDATA32 does not go in the module stream, but S_LDATA32 does.
458   case SymbolKind::S_LDATA32:
459   case SymbolKind::S_LTHREAD32:
460   default:
461     return true;
462   }
463 }
464 
465 static bool symbolGoesInGlobalsStream(const CVSymbol &sym,
466                                       unsigned symbolScopeDepth) {
467   switch (sym.kind()) {
468   case SymbolKind::S_CONSTANT:
469   case SymbolKind::S_GDATA32:
470   case SymbolKind::S_GTHREAD32:
471   case SymbolKind::S_GPROC32:
472   case SymbolKind::S_LPROC32:
473   case SymbolKind::S_GPROC32_ID:
474   case SymbolKind::S_LPROC32_ID:
475   // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
476   // since they are synthesized by the linker in response to S_GPROC32 and
477   // S_LPROC32, but if we do see them, copy them straight through.
478   case SymbolKind::S_PROCREF:
479   case SymbolKind::S_LPROCREF:
480     return true;
481   // Records that go in the globals stream, unless they are function-local.
482   case SymbolKind::S_UDT:
483   case SymbolKind::S_LDATA32:
484   case SymbolKind::S_LTHREAD32:
485     return symbolScopeDepth == 0;
486   default:
487     return false;
488   }
489 }
490 
491 static void addGlobalSymbol(pdb::GSIStreamBuilder &builder, uint16_t modIndex,
492                             unsigned symOffset,
493                             std::vector<uint8_t> &symStorage) {
494   CVSymbol sym(makeArrayRef(symStorage));
495   switch (sym.kind()) {
496   case SymbolKind::S_CONSTANT:
497   case SymbolKind::S_UDT:
498   case SymbolKind::S_GDATA32:
499   case SymbolKind::S_GTHREAD32:
500   case SymbolKind::S_LTHREAD32:
501   case SymbolKind::S_LDATA32:
502   case SymbolKind::S_PROCREF:
503   case SymbolKind::S_LPROCREF: {
504     // sym is a temporary object, so we have to copy and reallocate the record
505     // to stabilize it.
506     uint8_t *mem = bAlloc.Allocate<uint8_t>(sym.length());
507     memcpy(mem, sym.data().data(), sym.length());
508     builder.addGlobalSymbol(CVSymbol(makeArrayRef(mem, sym.length())));
509     break;
510   }
511   case SymbolKind::S_GPROC32:
512   case SymbolKind::S_LPROC32: {
513     SymbolRecordKind k = SymbolRecordKind::ProcRefSym;
514     if (sym.kind() == SymbolKind::S_LPROC32)
515       k = SymbolRecordKind::LocalProcRef;
516     ProcRefSym ps(k);
517     ps.Module = modIndex;
518     // For some reason, MSVC seems to add one to this value.
519     ++ps.Module;
520     ps.Name = getSymbolName(sym);
521     ps.SumName = 0;
522     ps.SymOffset = symOffset;
523     builder.addGlobalSymbol(ps);
524     break;
525   }
526   default:
527     llvm_unreachable("Invalid symbol kind!");
528   }
529 }
530 
531 // Check if the given symbol record was padded for alignment. If so, zero out
532 // the padding bytes and update the record prefix with the new size.
533 static void fixRecordAlignment(MutableArrayRef<uint8_t> recordBytes,
534                                size_t oldSize) {
535   size_t alignedSize = recordBytes.size();
536   if (oldSize == alignedSize)
537     return;
538   reinterpret_cast<RecordPrefix *>(recordBytes.data())->RecordLen =
539       alignedSize - 2;
540   memset(recordBytes.data() + oldSize, 0, alignedSize - oldSize);
541 }
542 
543 // Replace any record with a skip record of the same size. This is useful when
544 // we have reserved size for a symbol record, but type index remapping fails.
545 static void replaceWithSkipRecord(MutableArrayRef<uint8_t> recordBytes) {
546   memset(recordBytes.data(), 0, recordBytes.size());
547   auto *prefix = reinterpret_cast<RecordPrefix *>(recordBytes.data());
548   prefix->RecordKind = SymbolKind::S_SKIP;
549   prefix->RecordLen = recordBytes.size() - 2;
550 }
551 
552 // Copy the symbol record, relocate it, and fix the alignment if necessary.
553 // Rewrite type indices in the record. Replace unrecognized symbol records with
554 // S_SKIP records.
555 void PDBLinker::writeSymbolRecord(SectionChunk *debugChunk,
556                                   ArrayRef<uint8_t> sectionContents,
557                                   CVSymbol sym, size_t alignedSize,
558                                   uint32_t &nextRelocIndex,
559                                   std::vector<uint8_t> &storage) {
560   // Allocate space for the new record at the end of the storage.
561   storage.resize(storage.size() + alignedSize);
562   auto recordBytes = MutableArrayRef<uint8_t>(storage).take_back(alignedSize);
563 
564   // Copy the symbol record and relocate it.
565   debugChunk->writeAndRelocateSubsection(sectionContents, sym.data(),
566                                          nextRelocIndex, recordBytes.data());
567   fixRecordAlignment(recordBytes, sym.length());
568 
569   // Re-map all the type index references.
570   TpiSource *source = debugChunk->file->debugTypesObj;
571   if (!source->remapTypesInSymbolRecord(recordBytes)) {
572     log("ignoring unknown symbol record with kind 0x" + utohexstr(sym.kind()));
573     replaceWithSkipRecord(recordBytes);
574   }
575 
576   // An object file may have S_xxx_ID symbols, but these get converted to
577   // "real" symbols in a PDB.
578   translateIdSymbols(recordBytes, tMerger, source);
579 }
580 
581 void PDBLinker::analyzeSymbolSubsection(
582     SectionChunk *debugChunk, uint32_t &moduleSymOffset,
583     uint32_t &nextRelocIndex, std::vector<StringTableFixup> &stringTableFixups,
584     BinaryStreamRef symData) {
585   ObjFile *file = debugChunk->file;
586   uint32_t moduleSymStart = moduleSymOffset;
587 
588   uint32_t scopeLevel = 0;
589   std::vector<uint8_t> storage;
590   ArrayRef<uint8_t> sectionContents = debugChunk->getContents();
591 
592   ArrayRef<uint8_t> symsBuffer;
593   cantFail(symData.readBytes(0, symData.getLength(), symsBuffer));
594 
595   if (symsBuffer.empty())
596     warn("empty symbols subsection in " + file->getName());
597 
598   Error ec = forEachCodeViewRecord<CVSymbol>(
599       symsBuffer, [&](CVSymbol sym) -> llvm::Error {
600         // Track the current scope.
601         if (symbolOpensScope(sym.kind()))
602           ++scopeLevel;
603         else if (symbolEndsScope(sym.kind()))
604           --scopeLevel;
605 
606         uint32_t alignedSize =
607             alignTo(sym.length(), alignOf(CodeViewContainer::Pdb));
608 
609         // Copy global records. Some global records (mainly procedures)
610         // reference the current offset into the module stream.
611         if (symbolGoesInGlobalsStream(sym, scopeLevel)) {
612           storage.clear();
613           writeSymbolRecord(debugChunk, sectionContents, sym, alignedSize,
614                             nextRelocIndex, storage);
615           addGlobalSymbol(builder.getGsiBuilder(),
616                           file->moduleDBI->getModuleIndex(), moduleSymOffset,
617                           storage);
618           ++globalSymbols;
619         }
620 
621         // Update the module stream offset and record any string table index
622         // references. There are very few of these and they will be rewritten
623         // later during PDB writing.
624         if (symbolGoesInModuleStream(sym, scopeLevel)) {
625           recordStringTableReferences(sym, moduleSymOffset, stringTableFixups);
626           moduleSymOffset += alignedSize;
627           ++moduleSymbols;
628         }
629 
630         return Error::success();
631       });
632 
633   // If we encountered corrupt records, ignore the whole subsection. If we wrote
634   // any partial records, undo that. For globals, we just keep what we have and
635   // continue.
636   if (ec) {
637     warn("corrupt symbol records in " + file->getName());
638     moduleSymOffset = moduleSymStart;
639     consumeError(std::move(ec));
640   }
641 }
642 
643 Error PDBLinker::writeAllModuleSymbolRecords(ObjFile *file,
644                                              BinaryStreamWriter &writer) {
645   std::vector<uint8_t> storage;
646   SmallVector<uint32_t, 4> scopes;
647 
648   // Visit all live .debug$S sections a second time, and write them to the PDB.
649   for (SectionChunk *debugChunk : file->getDebugChunks()) {
650     if (!debugChunk->live || debugChunk->getSize() == 0 ||
651         debugChunk->getSectionName() != ".debug$S")
652       continue;
653 
654     ArrayRef<uint8_t> sectionContents = debugChunk->getContents();
655     auto contents =
656         SectionChunk::consumeDebugMagic(sectionContents, ".debug$S");
657     DebugSubsectionArray subsections;
658     BinaryStreamReader reader(contents, support::little);
659     exitOnErr(reader.readArray(subsections, contents.size()));
660 
661     uint32_t nextRelocIndex = 0;
662     for (const DebugSubsectionRecord &ss : subsections) {
663       if (ss.kind() != DebugSubsectionKind::Symbols)
664         continue;
665 
666       uint32_t moduleSymStart = writer.getOffset();
667       scopes.clear();
668       storage.clear();
669       ArrayRef<uint8_t> symsBuffer;
670       BinaryStreamRef sr = ss.getRecordData();
671       cantFail(sr.readBytes(0, sr.getLength(), symsBuffer));
672       auto ec = forEachCodeViewRecord<CVSymbol>(
673           symsBuffer, [&](CVSymbol sym) -> llvm::Error {
674             // Track the current scope. Only update records in the postmerge
675             // pass.
676             if (symbolOpensScope(sym.kind()))
677               scopeStackOpen(scopes, storage);
678             else if (symbolEndsScope(sym.kind()))
679               scopeStackClose(scopes, storage, moduleSymStart, file);
680 
681             // Copy, relocate, and rewrite each module symbol.
682             if (symbolGoesInModuleStream(sym, scopes.size())) {
683               uint32_t alignedSize =
684                   alignTo(sym.length(), alignOf(CodeViewContainer::Pdb));
685               writeSymbolRecord(debugChunk, sectionContents, sym, alignedSize,
686                                 nextRelocIndex, storage);
687             }
688             return Error::success();
689           });
690 
691       // If we encounter corrupt records in the second pass, ignore them. We
692       // already warned about them in the first analysis pass.
693       if (ec) {
694         consumeError(std::move(ec));
695         storage.clear();
696       }
697 
698       // Writing bytes has a very high overhead, so write the entire subsection
699       // at once.
700       // TODO: Consider buffering symbols for the entire object file to reduce
701       // overhead even further.
702       if (Error e = writer.writeBytes(storage))
703         return e;
704     }
705   }
706 
707   return Error::success();
708 }
709 
710 Error PDBLinker::commitSymbolsForObject(void *ctx, void *obj,
711                                         BinaryStreamWriter &writer) {
712   return static_cast<PDBLinker *>(ctx)->writeAllModuleSymbolRecords(
713       static_cast<ObjFile *>(obj), writer);
714 }
715 
716 static pdb::SectionContrib createSectionContrib(const Chunk *c, uint32_t modi) {
717   OutputSection *os = c ? c->getOutputSection() : 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 (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(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() : StringRef(objName);
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(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(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(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 = def->getChunk()->getOutputSection();
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(addObjectsTimer);
1135 
1136   // Create module descriptors
1137   for_each(ObjFile::instances, [&](ObjFile *obj) { createModuleDBI(obj); });
1138 
1139   // Reorder dependency type sources to come first.
1140   TpiSource::sortDependencies();
1141 
1142   // Merge type information from input files using global type hashing.
1143   if (config->debugGHashes)
1144     tMerger.mergeTypesWithGHash();
1145 
1146   // Merge dependencies and then regular objects.
1147   for_each(TpiSource::dependencySources,
1148            [&](TpiSource *source) { addDebug(source); });
1149   for_each(TpiSource::objectSources,
1150            [&](TpiSource *source) { addDebug(source); });
1151 
1152   builder.getStringTableBuilder().setStrings(pdbStrTab);
1153   t1.stop();
1154 
1155   // Construct TPI and IPI stream contents.
1156   ScopedTimer t2(tpiStreamLayoutTimer);
1157   // Collect all the merged types.
1158   if (config->debugGHashes) {
1159     addGHashTypeInfo(builder);
1160   } else {
1161     addTypeInfo(builder.getTpiBuilder(), tMerger.getTypeTable());
1162     addTypeInfo(builder.getIpiBuilder(), tMerger.getIDTable());
1163   }
1164   t2.stop();
1165 
1166   if (config->showSummary) {
1167     for_each(TpiSource::instances, [&](TpiSource *source) {
1168       nbTypeRecords += source->nbTypeRecords;
1169       nbTypeRecordsBytes += source->nbTypeRecordsBytes;
1170     });
1171   }
1172 }
1173 
1174 void PDBLinker::addPublicsToPDB() {
1175   ScopedTimer t3(publicsLayoutTimer);
1176   // Compute the public symbols.
1177   auto &gsiBuilder = builder.getGsiBuilder();
1178   std::vector<pdb::BulkPublic> publics;
1179   symtab->forEachSymbol([&publics](Symbol *s) {
1180     // Only emit external, defined, live symbols that have a chunk. Static,
1181     // non-external symbols do not appear in the symbol table.
1182     auto *def = dyn_cast<Defined>(s);
1183     if (def && def->isLive() && def->getChunk())
1184       publics.push_back(createPublic(def));
1185   });
1186 
1187   if (!publics.empty()) {
1188     publicSymbols = publics.size();
1189     gsiBuilder.addPublicSymbols(std::move(publics));
1190   }
1191 }
1192 
1193 void PDBLinker::printStats() {
1194   if (!config->showSummary)
1195     return;
1196 
1197   SmallString<256> buffer;
1198   raw_svector_ostream stream(buffer);
1199 
1200   stream << center_justify("Summary", 80) << '\n'
1201          << std::string(80, '-') << '\n';
1202 
1203   auto print = [&](uint64_t v, StringRef s) {
1204     stream << format_decimal(v, 15) << " " << s << '\n';
1205   };
1206 
1207   print(ObjFile::instances.size(),
1208         "Input OBJ files (expanded from all cmd-line inputs)");
1209   print(TpiSource::countTypeServerPDBs(), "PDB type server dependencies");
1210   print(TpiSource::countPrecompObjs(), "Precomp OBJ dependencies");
1211   print(nbTypeRecords, "Input type records");
1212   print(nbTypeRecordsBytes, "Input type records bytes");
1213   print(builder.getTpiBuilder().getRecordCount(), "Merged TPI records");
1214   print(builder.getIpiBuilder().getRecordCount(), "Merged IPI records");
1215   print(pdbStrTab.size(), "Output PDB strings");
1216   print(globalSymbols, "Global symbol records");
1217   print(moduleSymbols, "Module symbol records");
1218   print(publicSymbols, "Public symbol records");
1219 
1220   auto printLargeInputTypeRecs = [&](StringRef name,
1221                                      ArrayRef<uint32_t> recCounts,
1222                                      TypeCollection &records) {
1223     // Figure out which type indices were responsible for the most duplicate
1224     // bytes in the input files. These should be frequently emitted LF_CLASS and
1225     // LF_FIELDLIST records.
1226     struct TypeSizeInfo {
1227       uint32_t typeSize;
1228       uint32_t dupCount;
1229       TypeIndex typeIndex;
1230       uint64_t totalInputSize() const { return uint64_t(dupCount) * typeSize; }
1231       bool operator<(const TypeSizeInfo &rhs) const {
1232         if (totalInputSize() == rhs.totalInputSize())
1233           return typeIndex < rhs.typeIndex;
1234         return totalInputSize() < rhs.totalInputSize();
1235       }
1236     };
1237     SmallVector<TypeSizeInfo, 0> tsis;
1238     for (auto e : enumerate(recCounts)) {
1239       TypeIndex typeIndex = TypeIndex::fromArrayIndex(e.index());
1240       uint32_t typeSize = records.getType(typeIndex).length();
1241       uint32_t dupCount = e.value();
1242       tsis.push_back({typeSize, dupCount, typeIndex});
1243     }
1244 
1245     if (!tsis.empty()) {
1246       stream << "\nTop 10 types responsible for the most " << name
1247              << " input:\n";
1248       stream << "       index     total bytes   count     size\n";
1249       llvm::sort(tsis);
1250       unsigned i = 0;
1251       for (const auto &tsi : reverse(tsis)) {
1252         stream << formatv("  {0,10:X}: {1,14:N} = {2,5:N} * {3,6:N}\n",
1253                           tsi.typeIndex.getIndex(), tsi.totalInputSize(),
1254                           tsi.dupCount, tsi.typeSize);
1255         if (++i >= 10)
1256           break;
1257       }
1258       stream
1259           << "Run llvm-pdbutil to print details about a particular record:\n";
1260       stream << formatv("llvm-pdbutil dump -{0}s -{0}-index {1:X} {2}\n",
1261                         (name == "TPI" ? "type" : "id"),
1262                         tsis.back().typeIndex.getIndex(), config->pdbPath);
1263     }
1264   };
1265 
1266   if (!config->debugGHashes) {
1267     // FIXME: Reimplement for ghash.
1268     printLargeInputTypeRecs("TPI", tMerger.tpiCounts, tMerger.getTypeTable());
1269     printLargeInputTypeRecs("IPI", tMerger.ipiCounts, tMerger.getIDTable());
1270   }
1271 
1272   message(buffer);
1273 }
1274 
1275 void PDBLinker::addNatvisFiles() {
1276   for (StringRef file : config->natvisFiles) {
1277     ErrorOr<std::unique_ptr<MemoryBuffer>> dataOrErr =
1278         MemoryBuffer::getFile(file);
1279     if (!dataOrErr) {
1280       warn("Cannot open input file: " + file);
1281       continue;
1282     }
1283     builder.addInjectedSource(file, std::move(*dataOrErr));
1284   }
1285 }
1286 
1287 void PDBLinker::addNamedStreams() {
1288   for (const auto &streamFile : config->namedStreams) {
1289     const StringRef stream = streamFile.getKey(), file = streamFile.getValue();
1290     ErrorOr<std::unique_ptr<MemoryBuffer>> dataOrErr =
1291         MemoryBuffer::getFile(file);
1292     if (!dataOrErr) {
1293       warn("Cannot open input file: " + file);
1294       continue;
1295     }
1296     exitOnErr(builder.addNamedStream(stream, (*dataOrErr)->getBuffer()));
1297   }
1298 }
1299 
1300 static codeview::CPUType toCodeViewMachine(COFF::MachineTypes machine) {
1301   switch (machine) {
1302   case COFF::IMAGE_FILE_MACHINE_AMD64:
1303     return codeview::CPUType::X64;
1304   case COFF::IMAGE_FILE_MACHINE_ARM:
1305     return codeview::CPUType::ARM7;
1306   case COFF::IMAGE_FILE_MACHINE_ARM64:
1307     return codeview::CPUType::ARM64;
1308   case COFF::IMAGE_FILE_MACHINE_ARMNT:
1309     return codeview::CPUType::ARMNT;
1310   case COFF::IMAGE_FILE_MACHINE_I386:
1311     return codeview::CPUType::Intel80386;
1312   default:
1313     llvm_unreachable("Unsupported CPU Type");
1314   }
1315 }
1316 
1317 // Mimic MSVC which surrounds arguments containing whitespace with quotes.
1318 // Double double-quotes are handled, so that the resulting string can be
1319 // executed again on the cmd-line.
1320 static std::string quote(ArrayRef<StringRef> args) {
1321   std::string r;
1322   r.reserve(256);
1323   for (StringRef a : args) {
1324     if (!r.empty())
1325       r.push_back(' ');
1326     bool hasWS = a.find(' ') != StringRef::npos;
1327     bool hasQ = a.find('"') != StringRef::npos;
1328     if (hasWS || hasQ)
1329       r.push_back('"');
1330     if (hasQ) {
1331       SmallVector<StringRef, 4> s;
1332       a.split(s, '"');
1333       r.append(join(s, "\"\""));
1334     } else {
1335       r.append(std::string(a));
1336     }
1337     if (hasWS || hasQ)
1338       r.push_back('"');
1339   }
1340   return r;
1341 }
1342 
1343 static void fillLinkerVerRecord(Compile3Sym &cs) {
1344   cs.Machine = toCodeViewMachine(config->machine);
1345   // Interestingly, if we set the string to 0.0.0.0, then when trying to view
1346   // local variables WinDbg emits an error that private symbols are not present.
1347   // By setting this to a valid MSVC linker version string, local variables are
1348   // displayed properly.   As such, even though it is not representative of
1349   // LLVM's version information, we need this for compatibility.
1350   cs.Flags = CompileSym3Flags::None;
1351   cs.VersionBackendBuild = 25019;
1352   cs.VersionBackendMajor = 14;
1353   cs.VersionBackendMinor = 10;
1354   cs.VersionBackendQFE = 0;
1355 
1356   // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
1357   // linker module (which is by definition a backend), so we don't need to do
1358   // anything here.  Also, it seems we can use "LLVM Linker" for the linker name
1359   // without any problems.  Only the backend version has to be hardcoded to a
1360   // magic number.
1361   cs.VersionFrontendBuild = 0;
1362   cs.VersionFrontendMajor = 0;
1363   cs.VersionFrontendMinor = 0;
1364   cs.VersionFrontendQFE = 0;
1365   cs.Version = "LLVM Linker";
1366   cs.setLanguage(SourceLanguage::Link);
1367 }
1368 
1369 static void addCommonLinkerModuleSymbols(StringRef path,
1370                                          pdb::DbiModuleDescriptorBuilder &mod) {
1371   ObjNameSym ons(SymbolRecordKind::ObjNameSym);
1372   EnvBlockSym ebs(SymbolRecordKind::EnvBlockSym);
1373   Compile3Sym cs(SymbolRecordKind::Compile3Sym);
1374   fillLinkerVerRecord(cs);
1375 
1376   ons.Name = "* Linker *";
1377   ons.Signature = 0;
1378 
1379   ArrayRef<StringRef> args = makeArrayRef(config->argv).drop_front();
1380   std::string argStr = quote(args);
1381   ebs.Fields.push_back("cwd");
1382   SmallString<64> cwd;
1383   if (config->pdbSourcePath.empty())
1384     sys::fs::current_path(cwd);
1385   else
1386     cwd = config->pdbSourcePath;
1387   ebs.Fields.push_back(cwd);
1388   ebs.Fields.push_back("exe");
1389   SmallString<64> exe = config->argv[0];
1390   pdbMakeAbsolute(exe);
1391   ebs.Fields.push_back(exe);
1392   ebs.Fields.push_back("pdb");
1393   ebs.Fields.push_back(path);
1394   ebs.Fields.push_back("cmd");
1395   ebs.Fields.push_back(argStr);
1396   mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1397       ons, bAlloc, CodeViewContainer::Pdb));
1398   mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1399       cs, bAlloc, CodeViewContainer::Pdb));
1400   mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1401       ebs, bAlloc, CodeViewContainer::Pdb));
1402 }
1403 
1404 static void addLinkerModuleCoffGroup(PartialSection *sec,
1405                                      pdb::DbiModuleDescriptorBuilder &mod,
1406                                      OutputSection &os) {
1407   // If there's a section, there's at least one chunk
1408   assert(!sec->chunks.empty());
1409   const Chunk *firstChunk = *sec->chunks.begin();
1410   const Chunk *lastChunk = *sec->chunks.rbegin();
1411 
1412   // Emit COFF group
1413   CoffGroupSym cgs(SymbolRecordKind::CoffGroupSym);
1414   cgs.Name = sec->name;
1415   cgs.Segment = os.sectionIndex;
1416   cgs.Offset = firstChunk->getRVA() - os.getRVA();
1417   cgs.Size = lastChunk->getRVA() + lastChunk->getSize() - firstChunk->getRVA();
1418   cgs.Characteristics = sec->characteristics;
1419 
1420   // Somehow .idata sections & sections groups in the debug symbol stream have
1421   // the "write" flag set. However the section header for the corresponding
1422   // .idata section doesn't have it.
1423   if (cgs.Name.startswith(".idata"))
1424     cgs.Characteristics |= llvm::COFF::IMAGE_SCN_MEM_WRITE;
1425 
1426   mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1427       cgs, bAlloc, CodeViewContainer::Pdb));
1428 }
1429 
1430 static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &mod,
1431                                          OutputSection &os) {
1432   SectionSym sym(SymbolRecordKind::SectionSym);
1433   sym.Alignment = 12; // 2^12 = 4KB
1434   sym.Characteristics = os.header.Characteristics;
1435   sym.Length = os.getVirtualSize();
1436   sym.Name = os.name;
1437   sym.Rva = os.getRVA();
1438   sym.SectionNumber = os.sectionIndex;
1439   mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1440       sym, bAlloc, CodeViewContainer::Pdb));
1441 
1442   // Skip COFF groups in MinGW because it adds a significant footprint to the
1443   // PDB, due to each function being in its own section
1444   if (config->mingw)
1445     return;
1446 
1447   // Output COFF groups for individual chunks of this section.
1448   for (PartialSection *sec : os.contribSections) {
1449     addLinkerModuleCoffGroup(sec, mod, os);
1450   }
1451 }
1452 
1453 // Add all import files as modules to the PDB.
1454 void PDBLinker::addImportFilesToPDB(ArrayRef<OutputSection *> outputSections) {
1455   if (ImportFile::instances.empty())
1456     return;
1457 
1458   std::map<std::string, llvm::pdb::DbiModuleDescriptorBuilder *> dllToModuleDbi;
1459 
1460   for (ImportFile *file : ImportFile::instances) {
1461     if (!file->live)
1462       continue;
1463 
1464     if (!file->thunkSym)
1465       continue;
1466 
1467     if (!file->thunkLive)
1468         continue;
1469 
1470     std::string dll = StringRef(file->dllName).lower();
1471     llvm::pdb::DbiModuleDescriptorBuilder *&mod = dllToModuleDbi[dll];
1472     if (!mod) {
1473       pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1474       SmallString<128> libPath = file->parentName;
1475       pdbMakeAbsolute(libPath);
1476       sys::path::native(libPath);
1477 
1478       // Name modules similar to MSVC's link.exe.
1479       // The first module is the simple dll filename
1480       llvm::pdb::DbiModuleDescriptorBuilder &firstMod =
1481           exitOnErr(dbiBuilder.addModuleInfo(file->dllName));
1482       firstMod.setObjFileName(libPath);
1483       pdb::SectionContrib sc =
1484           createSectionContrib(nullptr, llvm::pdb::kInvalidStreamIndex);
1485       firstMod.setFirstSectionContrib(sc);
1486 
1487       // The second module is where the import stream goes.
1488       mod = &exitOnErr(dbiBuilder.addModuleInfo("Import:" + file->dllName));
1489       mod->setObjFileName(libPath);
1490     }
1491 
1492     DefinedImportThunk *thunk = cast<DefinedImportThunk>(file->thunkSym);
1493     Chunk *thunkChunk = thunk->getChunk();
1494     OutputSection *thunkOS = thunkChunk->getOutputSection();
1495 
1496     ObjNameSym ons(SymbolRecordKind::ObjNameSym);
1497     Compile3Sym cs(SymbolRecordKind::Compile3Sym);
1498     Thunk32Sym ts(SymbolRecordKind::Thunk32Sym);
1499     ScopeEndSym es(SymbolRecordKind::ScopeEndSym);
1500 
1501     ons.Name = file->dllName;
1502     ons.Signature = 0;
1503 
1504     fillLinkerVerRecord(cs);
1505 
1506     ts.Name = thunk->getName();
1507     ts.Parent = 0;
1508     ts.End = 0;
1509     ts.Next = 0;
1510     ts.Thunk = ThunkOrdinal::Standard;
1511     ts.Length = thunkChunk->getSize();
1512     ts.Segment = thunkOS->sectionIndex;
1513     ts.Offset = thunkChunk->getRVA() - thunkOS->getRVA();
1514 
1515     mod->addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1516         ons, bAlloc, CodeViewContainer::Pdb));
1517     mod->addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1518         cs, bAlloc, CodeViewContainer::Pdb));
1519 
1520     CVSymbol newSym = codeview::SymbolSerializer::writeOneSymbol(
1521         ts, bAlloc, CodeViewContainer::Pdb);
1522 
1523     // Write ptrEnd for the S_THUNK32.
1524     ScopeRecord *thunkSymScope =
1525         getSymbolScopeFields(const_cast<uint8_t *>(newSym.data().data()));
1526 
1527     mod->addSymbol(newSym);
1528 
1529     newSym = codeview::SymbolSerializer::writeOneSymbol(es, bAlloc,
1530                                                         CodeViewContainer::Pdb);
1531     thunkSymScope->ptrEnd = mod->getNextSymbolOffset();
1532 
1533     mod->addSymbol(newSym);
1534 
1535     pdb::SectionContrib sc =
1536         createSectionContrib(thunk->getChunk(), mod->getModuleIndex());
1537     mod->setFirstSectionContrib(sc);
1538   }
1539 }
1540 
1541 // Creates a PDB file.
1542 void lld::coff::createPDB(SymbolTable *symtab,
1543                           ArrayRef<OutputSection *> outputSections,
1544                           ArrayRef<uint8_t> sectionTable,
1545                           llvm::codeview::DebugInfo *buildId) {
1546   ScopedTimer t1(totalPdbLinkTimer);
1547   PDBLinker pdb(symtab);
1548 
1549   pdb.initialize(buildId);
1550   pdb.addObjectsToPDB();
1551   pdb.addImportFilesToPDB(outputSections);
1552   pdb.addSections(outputSections, sectionTable);
1553   pdb.addNatvisFiles();
1554   pdb.addNamedStreams();
1555   pdb.addPublicsToPDB();
1556 
1557   ScopedTimer t2(diskCommitTimer);
1558   codeview::GUID guid;
1559   pdb.commit(&guid);
1560   memcpy(&buildId->PDB70.Signature, &guid, 16);
1561 
1562   t2.stop();
1563   t1.stop();
1564   pdb.printStats();
1565 }
1566 
1567 void PDBLinker::initialize(llvm::codeview::DebugInfo *buildId) {
1568   exitOnErr(builder.initialize(4096)); // 4096 is blocksize
1569 
1570   buildId->Signature.CVSignature = OMF::Signature::PDB70;
1571   // Signature is set to a hash of the PDB contents when the PDB is done.
1572   memset(buildId->PDB70.Signature, 0, 16);
1573   buildId->PDB70.Age = 1;
1574 
1575   // Create streams in MSF for predefined streams, namely
1576   // PDB, TPI, DBI and IPI.
1577   for (int i = 0; i < (int)pdb::kSpecialStreamCount; ++i)
1578     exitOnErr(builder.getMsfBuilder().addStream(0));
1579 
1580   // Add an Info stream.
1581   auto &infoBuilder = builder.getInfoBuilder();
1582   infoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
1583   infoBuilder.setHashPDBContentsToGUID(true);
1584 
1585   // Add an empty DBI stream.
1586   pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1587   dbiBuilder.setAge(buildId->PDB70.Age);
1588   dbiBuilder.setVersionHeader(pdb::PdbDbiV70);
1589   dbiBuilder.setMachineType(config->machine);
1590   // Technically we are not link.exe 14.11, but there are known cases where
1591   // debugging tools on Windows expect Microsoft-specific version numbers or
1592   // they fail to work at all.  Since we know we produce PDBs that are
1593   // compatible with LINK 14.11, we set that version number here.
1594   dbiBuilder.setBuildNumber(14, 11);
1595 }
1596 
1597 void PDBLinker::addSections(ArrayRef<OutputSection *> outputSections,
1598                             ArrayRef<uint8_t> sectionTable) {
1599   // It's not entirely clear what this is, but the * Linker * module uses it.
1600   pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1601   nativePath = config->pdbPath;
1602   pdbMakeAbsolute(nativePath);
1603   uint32_t pdbFilePathNI = dbiBuilder.addECName(nativePath);
1604   auto &linkerModule = exitOnErr(dbiBuilder.addModuleInfo("* Linker *"));
1605   linkerModule.setPdbFilePathNI(pdbFilePathNI);
1606   addCommonLinkerModuleSymbols(nativePath, linkerModule);
1607 
1608   // Add section contributions. They must be ordered by ascending RVA.
1609   for (OutputSection *os : outputSections) {
1610     addLinkerModuleSectionSymbol(linkerModule, *os);
1611     for (Chunk *c : os->chunks) {
1612       pdb::SectionContrib sc =
1613           createSectionContrib(c, linkerModule.getModuleIndex());
1614       builder.getDbiBuilder().addSectionContrib(sc);
1615     }
1616   }
1617 
1618   // The * Linker * first section contrib is only used along with /INCREMENTAL,
1619   // to provide trampolines thunks for incremental function patching. Set this
1620   // as "unused" because LLD doesn't support /INCREMENTAL link.
1621   pdb::SectionContrib sc =
1622       createSectionContrib(nullptr, llvm::pdb::kInvalidStreamIndex);
1623   linkerModule.setFirstSectionContrib(sc);
1624 
1625   // Add Section Map stream.
1626   ArrayRef<object::coff_section> sections = {
1627       (const object::coff_section *)sectionTable.data(),
1628       sectionTable.size() / sizeof(object::coff_section)};
1629   dbiBuilder.createSectionMap(sections);
1630 
1631   // Add COFF section header stream.
1632   exitOnErr(
1633       dbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, sectionTable));
1634 }
1635 
1636 void PDBLinker::commit(codeview::GUID *guid) {
1637   ExitOnError exitOnErr((config->pdbPath + ": ").str());
1638   // Write to a file.
1639   exitOnErr(builder.commit(config->pdbPath, guid));
1640 }
1641 
1642 static uint32_t getSecrelReloc() {
1643   switch (config->machine) {
1644   case AMD64:
1645     return COFF::IMAGE_REL_AMD64_SECREL;
1646   case I386:
1647     return COFF::IMAGE_REL_I386_SECREL;
1648   case ARMNT:
1649     return COFF::IMAGE_REL_ARM_SECREL;
1650   case ARM64:
1651     return COFF::IMAGE_REL_ARM64_SECREL;
1652   default:
1653     llvm_unreachable("unknown machine type");
1654   }
1655 }
1656 
1657 // Try to find a line table for the given offset Addr into the given chunk C.
1658 // If a line table was found, the line table, the string and checksum tables
1659 // that are used to interpret the line table, and the offset of Addr in the line
1660 // table are stored in the output arguments. Returns whether a line table was
1661 // found.
1662 static bool findLineTable(const SectionChunk *c, uint32_t addr,
1663                           DebugStringTableSubsectionRef &cvStrTab,
1664                           DebugChecksumsSubsectionRef &checksums,
1665                           DebugLinesSubsectionRef &lines,
1666                           uint32_t &offsetInLinetable) {
1667   ExitOnError exitOnErr;
1668   uint32_t secrelReloc = getSecrelReloc();
1669 
1670   for (SectionChunk *dbgC : c->file->getDebugChunks()) {
1671     if (dbgC->getSectionName() != ".debug$S")
1672       continue;
1673 
1674     // Build a mapping of SECREL relocations in dbgC that refer to `c`.
1675     DenseMap<uint32_t, uint32_t> secrels;
1676     for (const coff_relocation &r : dbgC->getRelocs()) {
1677       if (r.Type != secrelReloc)
1678         continue;
1679 
1680       if (auto *s = dyn_cast_or_null<DefinedRegular>(
1681               c->file->getSymbols()[r.SymbolTableIndex]))
1682         if (s->getChunk() == c)
1683           secrels[r.VirtualAddress] = s->getValue();
1684     }
1685 
1686     ArrayRef<uint8_t> contents =
1687         SectionChunk::consumeDebugMagic(dbgC->getContents(), ".debug$S");
1688     DebugSubsectionArray subsections;
1689     BinaryStreamReader reader(contents, support::little);
1690     exitOnErr(reader.readArray(subsections, contents.size()));
1691 
1692     for (const DebugSubsectionRecord &ss : subsections) {
1693       switch (ss.kind()) {
1694       case DebugSubsectionKind::StringTable: {
1695         assert(!cvStrTab.valid() &&
1696                "Encountered multiple string table subsections!");
1697         exitOnErr(cvStrTab.initialize(ss.getRecordData()));
1698         break;
1699       }
1700       case DebugSubsectionKind::FileChecksums:
1701         assert(!checksums.valid() &&
1702                "Encountered multiple checksum subsections!");
1703         exitOnErr(checksums.initialize(ss.getRecordData()));
1704         break;
1705       case DebugSubsectionKind::Lines: {
1706         ArrayRef<uint8_t> bytes;
1707         auto ref = ss.getRecordData();
1708         exitOnErr(ref.readLongestContiguousChunk(0, bytes));
1709         size_t offsetInDbgC = bytes.data() - dbgC->getContents().data();
1710 
1711         // Check whether this line table refers to C.
1712         auto i = secrels.find(offsetInDbgC);
1713         if (i == secrels.end())
1714           break;
1715 
1716         // Check whether this line table covers Addr in C.
1717         DebugLinesSubsectionRef linesTmp;
1718         exitOnErr(linesTmp.initialize(BinaryStreamReader(ref)));
1719         uint32_t offsetInC = i->second + linesTmp.header()->RelocOffset;
1720         if (addr < offsetInC || addr >= offsetInC + linesTmp.header()->CodeSize)
1721           break;
1722 
1723         assert(!lines.header() &&
1724                "Encountered multiple line tables for function!");
1725         exitOnErr(lines.initialize(BinaryStreamReader(ref)));
1726         offsetInLinetable = addr - offsetInC;
1727         break;
1728       }
1729       default:
1730         break;
1731       }
1732 
1733       if (cvStrTab.valid() && checksums.valid() && lines.header())
1734         return true;
1735     }
1736   }
1737 
1738   return false;
1739 }
1740 
1741 // Use CodeView line tables to resolve a file and line number for the given
1742 // offset into the given chunk and return them, or None if a line table was
1743 // not found.
1744 Optional<std::pair<StringRef, uint32_t>>
1745 lld::coff::getFileLineCodeView(const SectionChunk *c, uint32_t addr) {
1746   ExitOnError exitOnErr;
1747 
1748   DebugStringTableSubsectionRef cvStrTab;
1749   DebugChecksumsSubsectionRef checksums;
1750   DebugLinesSubsectionRef lines;
1751   uint32_t offsetInLinetable;
1752 
1753   if (!findLineTable(c, addr, cvStrTab, checksums, lines, offsetInLinetable))
1754     return None;
1755 
1756   Optional<uint32_t> nameIndex;
1757   Optional<uint32_t> lineNumber;
1758   for (LineColumnEntry &entry : lines) {
1759     for (const LineNumberEntry &ln : entry.LineNumbers) {
1760       LineInfo li(ln.Flags);
1761       if (ln.Offset > offsetInLinetable) {
1762         if (!nameIndex) {
1763           nameIndex = entry.NameIndex;
1764           lineNumber = li.getStartLine();
1765         }
1766         StringRef filename =
1767             exitOnErr(getFileName(cvStrTab, checksums, *nameIndex));
1768         return std::make_pair(filename, *lineNumber);
1769       }
1770       nameIndex = entry.NameIndex;
1771       lineNumber = li.getStartLine();
1772     }
1773   }
1774   if (!nameIndex)
1775     return None;
1776   StringRef filename = exitOnErr(getFileName(cvStrTab, checksums, *nameIndex));
1777   return std::make_pair(filename, *lineNumber);
1778 }
1779