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