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