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