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