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