xref: /llvm-project-15.0.7/lld/COFF/PDB.cpp (revision a895a446)
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 Timer lld::coff::loadGHashTimer("Global Type Hashing", totalPdbLinkTimer);
70 Timer lld::coff::mergeGHashTimer("GHash Type Merging", totalPdbLinkTimer);
71 static Timer addObjectsTimer("Add Objects", totalPdbLinkTimer);
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   // Iterate every symbol to check if any need to be realigned, and if so, how
504   // much space we need to allocate for them.
505   bool needsRealignment = false;
506   unsigned totalRealignedSize = 0;
507   auto ec = forEachCodeViewRecord<CVSymbol>(
508       symsBuffer, [&](CVSymbol sym) -> llvm::Error {
509         unsigned realignedSize =
510             alignTo(sym.length(), alignOf(CodeViewContainer::Pdb));
511         needsRealignment |= realignedSize != sym.length();
512         totalRealignedSize += realignedSize;
513         return Error::success();
514       });
515 
516   // If any of the symbol record lengths was corrupt, ignore them all, warn
517   // about it, and move on.
518   if (ec) {
519     warn("corrupt symbol records in " + file->getName());
520     consumeError(std::move(ec));
521     return;
522   }
523 
524   // If any symbol needed realignment, allocate enough contiguous memory for
525   // them all. Typically symbol subsections are small enough that this will not
526   // cause fragmentation.
527   MutableArrayRef<uint8_t> alignedSymbolMem;
528   if (needsRealignment) {
529     void *alignedData =
530         bAlloc.Allocate(totalRealignedSize, alignOf(CodeViewContainer::Pdb));
531     alignedSymbolMem = makeMutableArrayRef(
532         reinterpret_cast<uint8_t *>(alignedData), totalRealignedSize);
533   }
534 
535   // Iterate again, this time doing the real work.
536   unsigned curSymOffset = file->moduleDBI->getNextSymbolOffset();
537   ArrayRef<uint8_t> bulkSymbols;
538   cantFail(forEachCodeViewRecord<CVSymbol>(
539       symsBuffer, [&](CVSymbol sym) -> llvm::Error {
540         // Align the record if required.
541         MutableArrayRef<uint8_t> recordBytes;
542         if (needsRealignment) {
543           recordBytes = copyAndAlignSymbol(sym, alignedSymbolMem);
544           sym = CVSymbol(recordBytes);
545         } else {
546           // Otherwise, we can actually mutate the symbol directly, since we
547           // copied it to apply relocations.
548           recordBytes = makeMutableArrayRef(
549               const_cast<uint8_t *>(sym.data().data()), sym.length());
550         }
551 
552         // Re-map all the type index references.
553         if (!source->remapTypesInSymbolRecord(recordBytes)) {
554           log("error remapping types in symbol of kind 0x" +
555               utohexstr(sym.kind()) + ", ignoring");
556           return Error::success();
557         }
558 
559         // An object file may have S_xxx_ID symbols, but these get converted to
560         // "real" symbols in a PDB.
561         translateIdSymbols(recordBytes, tMerger, source);
562         sym = CVSymbol(recordBytes);
563 
564         // If this record refers to an offset in the object file's string table,
565         // add that item to the global PDB string table and re-write the index.
566         recordStringTableReferences(sym.kind(), recordBytes, stringTableRefs);
567 
568         // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
569         if (symbolOpensScope(sym.kind()))
570           scopeStackOpen(scopes, curSymOffset, sym);
571         else if (symbolEndsScope(sym.kind()))
572           scopeStackClose(scopes, curSymOffset, file);
573 
574         // Add the symbol to the globals stream if necessary.  Do this before
575         // adding the symbol to the module since we may need to get the next
576         // symbol offset, and writing to the module's symbol stream will update
577         // that offset.
578         if (symbolGoesInGlobalsStream(sym, !scopes.empty())) {
579           addGlobalSymbol(builder.getGsiBuilder(),
580                           file->moduleDBI->getModuleIndex(), curSymOffset, sym);
581           ++globalSymbols;
582         }
583 
584         if (symbolGoesInModuleStream(sym, scopes.empty())) {
585           // Add symbols to the module in bulk. If this symbol is contiguous
586           // with the previous run of symbols to add, combine the ranges. If
587           // not, close the previous range of symbols and start a new one.
588           if (sym.data().data() == bulkSymbols.end()) {
589             bulkSymbols = makeArrayRef(bulkSymbols.data(),
590                                        bulkSymbols.size() + sym.length());
591           } else {
592             file->moduleDBI->addSymbolsInBulk(bulkSymbols);
593             bulkSymbols = recordBytes;
594           }
595           curSymOffset += sym.length();
596           ++moduleSymbols;
597         }
598         return Error::success();
599       }));
600 
601   // Add any remaining symbols we've accumulated.
602   file->moduleDBI->addSymbolsInBulk(bulkSymbols);
603 }
604 
605 static pdb::SectionContrib createSectionContrib(const Chunk *c, uint32_t modi) {
606   OutputSection *os = c ? c->getOutputSection() : nullptr;
607   pdb::SectionContrib sc;
608   memset(&sc, 0, sizeof(sc));
609   sc.ISect = os ? os->sectionIndex : llvm::pdb::kInvalidStreamIndex;
610   sc.Off = c && os ? c->getRVA() - os->getRVA() : 0;
611   sc.Size = c ? c->getSize() : -1;
612   if (auto *secChunk = dyn_cast_or_null<SectionChunk>(c)) {
613     sc.Characteristics = secChunk->header->Characteristics;
614     sc.Imod = secChunk->file->moduleDBI->getModuleIndex();
615     ArrayRef<uint8_t> contents = secChunk->getContents();
616     JamCRC crc(0);
617     crc.update(contents);
618     sc.DataCrc = crc.getCRC();
619   } else {
620     sc.Characteristics = os ? os->header.Characteristics : 0;
621     sc.Imod = modi;
622   }
623   sc.RelocCrc = 0; // FIXME
624 
625   return sc;
626 }
627 
628 static uint32_t
629 translateStringTableIndex(uint32_t objIndex,
630                           const DebugStringTableSubsectionRef &objStrTable,
631                           DebugStringTableSubsection &pdbStrTable) {
632   auto expectedString = objStrTable.getString(objIndex);
633   if (!expectedString) {
634     warn("Invalid string table reference");
635     consumeError(expectedString.takeError());
636     return 0;
637   }
638 
639   return pdbStrTable.insert(*expectedString);
640 }
641 
642 void DebugSHandler::handleDebugS(ArrayRef<uint8_t> relocatedDebugContents) {
643   relocatedDebugContents =
644       SectionChunk::consumeDebugMagic(relocatedDebugContents, ".debug$S");
645 
646   DebugSubsectionArray subsections;
647   BinaryStreamReader reader(relocatedDebugContents, support::little);
648   exitOnErr(reader.readArray(subsections, relocatedDebugContents.size()));
649 
650   for (const DebugSubsectionRecord &ss : subsections) {
651     // Ignore subsections with the 'ignore' bit. Some versions of the Visual C++
652     // runtime have subsections with this bit set.
653     if (uint32_t(ss.kind()) & codeview::SubsectionIgnoreFlag)
654       continue;
655 
656     switch (ss.kind()) {
657     case DebugSubsectionKind::StringTable: {
658       assert(!cvStrTab.valid() &&
659              "Encountered multiple string table subsections!");
660       exitOnErr(cvStrTab.initialize(ss.getRecordData()));
661       break;
662     }
663     case DebugSubsectionKind::FileChecksums:
664       assert(!checksums.valid() &&
665              "Encountered multiple checksum subsections!");
666       exitOnErr(checksums.initialize(ss.getRecordData()));
667       break;
668     case DebugSubsectionKind::Lines:
669       // We can add the relocated line table directly to the PDB without
670       // modification because the file checksum offsets will stay the same.
671       file.moduleDBI->addDebugSubsection(ss);
672       break;
673     case DebugSubsectionKind::InlineeLines:
674       // The inlinee lines subsection also has file checksum table references
675       // that can be used directly, but it contains function id references that
676       // must be remapped.
677       mergeInlineeLines(ss);
678       break;
679     case DebugSubsectionKind::FrameData: {
680       // We need to re-write string table indices here, so save off all
681       // frame data subsections until we've processed the entire list of
682       // subsections so that we can be sure we have the string table.
683       DebugFrameDataSubsectionRef fds;
684       exitOnErr(fds.initialize(ss.getRecordData()));
685       newFpoFrames.push_back(std::move(fds));
686       break;
687     }
688     case DebugSubsectionKind::Symbols: {
689       linker.mergeSymbolRecords(source, stringTableReferences,
690                                 ss.getRecordData());
691       break;
692     }
693 
694     case DebugSubsectionKind::CrossScopeImports:
695     case DebugSubsectionKind::CrossScopeExports:
696       // These appear to relate to cross-module optimization, so we might use
697       // these for ThinLTO.
698       break;
699 
700     case DebugSubsectionKind::ILLines:
701     case DebugSubsectionKind::FuncMDTokenMap:
702     case DebugSubsectionKind::TypeMDTokenMap:
703     case DebugSubsectionKind::MergedAssemblyInput:
704       // These appear to relate to .Net assembly info.
705       break;
706 
707     case DebugSubsectionKind::CoffSymbolRVA:
708       // Unclear what this is for.
709       break;
710 
711     default:
712       warn("ignoring unknown debug$S subsection kind 0x" +
713            utohexstr(uint32_t(ss.kind())) + " in file " + toString(&file));
714       break;
715     }
716   }
717 }
718 
719 static Expected<StringRef>
720 getFileName(const DebugStringTableSubsectionRef &strings,
721             const DebugChecksumsSubsectionRef &checksums, uint32_t fileID) {
722   auto iter = checksums.getArray().at(fileID);
723   if (iter == checksums.getArray().end())
724     return make_error<CodeViewError>(cv_error_code::no_records);
725   uint32_t offset = iter->FileNameOffset;
726   return strings.getString(offset);
727 }
728 
729 void DebugSHandler::mergeInlineeLines(
730     const DebugSubsectionRecord &inlineeSubsection) {
731   DebugInlineeLinesSubsectionRef inlineeLines;
732   exitOnErr(inlineeLines.initialize(inlineeSubsection.getRecordData()));
733   if (!source) {
734     warn("ignoring inlinee lines section in file that lacks type information");
735     return;
736   }
737 
738   // Remap type indices in inlinee line records in place.
739   for (const InlineeSourceLine &line : inlineeLines) {
740     TypeIndex &inlinee = *const_cast<TypeIndex *>(&line.Header->Inlinee);
741     if (!source->remapTypeIndex(inlinee, TiRefKind::IndexRef)) {
742       log("bad inlinee line record in " + file.getName() +
743           " with bad inlinee index 0x" + utohexstr(inlinee.getIndex()));
744     }
745   }
746 
747   // Add the modified inlinee line subsection directly.
748   file.moduleDBI->addDebugSubsection(inlineeSubsection);
749 }
750 
751 void DebugSHandler::finish() {
752   pdb::DbiStreamBuilder &dbiBuilder = linker.builder.getDbiBuilder();
753 
754   // We should have seen all debug subsections across the entire object file now
755   // which means that if a StringTable subsection and Checksums subsection were
756   // present, now is the time to handle them.
757   if (!cvStrTab.valid()) {
758     if (checksums.valid())
759       fatal(".debug$S sections with a checksums subsection must also contain a "
760             "string table subsection");
761 
762     if (!stringTableReferences.empty())
763       warn("No StringTable subsection was encountered, but there are string "
764            "table references");
765     return;
766   }
767 
768   // Rewrite string table indices in the Fpo Data and symbol records to refer to
769   // the global PDB string table instead of the object file string table.
770   for (DebugFrameDataSubsectionRef &fds : newFpoFrames) {
771     const ulittle32_t *reloc = fds.getRelocPtr();
772     for (codeview::FrameData fd : fds) {
773       fd.RvaStart += *reloc;
774       fd.FrameFunc =
775           translateStringTableIndex(fd.FrameFunc, cvStrTab, linker.pdbStrTab);
776       dbiBuilder.addNewFpoData(fd);
777     }
778   }
779 
780   for (ulittle32_t *ref : stringTableReferences)
781     *ref = translateStringTableIndex(*ref, cvStrTab, linker.pdbStrTab);
782 
783   // Make a new file checksum table that refers to offsets in the PDB-wide
784   // string table. Generally the string table subsection appears after the
785   // checksum table, so we have to do this after looping over all the
786   // subsections. The new checksum table must have the exact same layout and
787   // size as the original. Otherwise, the file references in the line and
788   // inlinee line tables will be incorrect.
789   auto newChecksums = std::make_unique<DebugChecksumsSubsection>(linker.pdbStrTab);
790   for (FileChecksumEntry &fc : checksums) {
791     SmallString<128> filename =
792         exitOnErr(cvStrTab.getString(fc.FileNameOffset));
793     pdbMakeAbsolute(filename);
794     exitOnErr(dbiBuilder.addModuleSourceFile(*file.moduleDBI, filename));
795     newChecksums->addChecksum(filename, fc.Kind, fc.Checksum);
796   }
797   assert(checksums.getArray().getUnderlyingStream().getLength() ==
798              newChecksums->calculateSerializedSize() &&
799          "file checksum table must have same layout");
800 
801   file.moduleDBI->addDebugSubsection(std::move(newChecksums));
802 }
803 
804 static void warnUnusable(InputFile *f, Error e) {
805   if (!config->warnDebugInfoUnusable) {
806     consumeError(std::move(e));
807     return;
808   }
809   auto msg = "Cannot use debug info for '" + toString(f) + "' [LNK4099]";
810   if (e)
811     warn(msg + "\n>>> failed to load reference " + toString(std::move(e)));
812   else
813     warn(msg);
814 }
815 
816 // Allocate memory for a .debug$S / .debug$F section and relocate it.
817 static ArrayRef<uint8_t> relocateDebugChunk(SectionChunk &debugChunk) {
818   uint8_t *buffer = bAlloc.Allocate<uint8_t>(debugChunk.getSize());
819   assert(debugChunk.getOutputSectionIdx() == 0 &&
820          "debug sections should not be in output sections");
821   debugChunk.writeTo(buffer);
822   return makeArrayRef(buffer, debugChunk.getSize());
823 }
824 
825 void PDBLinker::addDebugSymbols(TpiSource *source) {
826   // If this TpiSource doesn't have an object file, it must be from a type
827   // server PDB. Type server PDBs do not contain symbols, so stop here.
828   if (!source->file)
829     return;
830 
831   ScopedTimer t(symbolMergingTimer);
832   pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
833   DebugSHandler dsh(*this, *source->file, source);
834   // Now do all live .debug$S and .debug$F sections.
835   for (SectionChunk *debugChunk : source->file->getDebugChunks()) {
836     if (!debugChunk->live || debugChunk->getSize() == 0)
837       continue;
838 
839     bool isDebugS = debugChunk->getSectionName() == ".debug$S";
840     bool isDebugF = debugChunk->getSectionName() == ".debug$F";
841     if (!isDebugS && !isDebugF)
842       continue;
843 
844     ArrayRef<uint8_t> relocatedDebugContents = relocateDebugChunk(*debugChunk);
845 
846     if (isDebugS) {
847       dsh.handleDebugS(relocatedDebugContents);
848     } else if (isDebugF) {
849       FixedStreamArray<object::FpoData> fpoRecords;
850       BinaryStreamReader reader(relocatedDebugContents, support::little);
851       uint32_t count = relocatedDebugContents.size() / sizeof(object::FpoData);
852       exitOnErr(reader.readArray(fpoRecords, count));
853 
854       // These are already relocated and don't refer to the string table, so we
855       // can just copy it.
856       for (const object::FpoData &fd : fpoRecords)
857         dbiBuilder.addOldFpoData(fd);
858     }
859   }
860 
861   // Do any post-processing now that all .debug$S sections have been processed.
862   dsh.finish();
863 }
864 
865 // Add a module descriptor for every object file. We need to put an absolute
866 // path to the object into the PDB. If this is a plain object, we make its
867 // path absolute. If it's an object in an archive, we make the archive path
868 // absolute.
869 static void createModuleDBI(pdb::PDBFileBuilder &builder, ObjFile *file) {
870   pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
871   SmallString<128> objName;
872 
873   bool inArchive = !file->parentName.empty();
874   objName = inArchive ? file->parentName : file->getName();
875   pdbMakeAbsolute(objName);
876   StringRef modName = inArchive ? file->getName() : StringRef(objName);
877 
878   file->moduleDBI = &exitOnErr(dbiBuilder.addModuleInfo(modName));
879   file->moduleDBI->setObjFileName(objName);
880 
881   ArrayRef<Chunk *> chunks = file->getChunks();
882   uint32_t modi = file->moduleDBI->getModuleIndex();
883 
884   for (Chunk *c : chunks) {
885     auto *secChunk = dyn_cast<SectionChunk>(c);
886     if (!secChunk || !secChunk->live)
887       continue;
888     pdb::SectionContrib sc = createSectionContrib(secChunk, modi);
889     file->moduleDBI->setFirstSectionContrib(sc);
890     break;
891   }
892 }
893 
894 void PDBLinker::addDebug(TpiSource *source) {
895   // Before we can process symbol substreams from .debug$S, we need to process
896   // type information, file checksums, and the string table. Add type info to
897   // the PDB first, so that we can get the map from object file type and item
898   // indices to PDB type and item indices.  If we are using ghashes, types have
899   // already been merged.
900   if (!config->debugGHashes) {
901     ScopedTimer t(typeMergingTimer);
902     if (Error e = source->mergeDebugT(&tMerger)) {
903       // If type merging failed, ignore the symbols.
904       warnUnusable(source->file, std::move(e));
905       return;
906     }
907   }
908 
909   // If type merging failed, ignore the symbols.
910   Error typeError = std::move(source->typeMergingError);
911   if (typeError) {
912     warnUnusable(source->file, std::move(typeError));
913     return;
914   }
915 
916   addDebugSymbols(source);
917 }
918 
919 static pdb::BulkPublic createPublic(Defined *def) {
920   pdb::BulkPublic pub;
921   pub.Name = def->getName().data();
922   pub.NameLen = def->getName().size();
923 
924   PublicSymFlags flags = PublicSymFlags::None;
925   if (auto *d = dyn_cast<DefinedCOFF>(def)) {
926     if (d->getCOFFSymbol().isFunctionDefinition())
927       flags = PublicSymFlags::Function;
928   } else if (isa<DefinedImportThunk>(def)) {
929     flags = PublicSymFlags::Function;
930   }
931   pub.setFlags(flags);
932 
933   OutputSection *os = def->getChunk()->getOutputSection();
934   assert(os && "all publics should be in final image");
935   pub.Offset = def->getRVA() - os->getRVA();
936   pub.Segment = os->sectionIndex;
937   return pub;
938 }
939 
940 // Add all object files to the PDB. Merge .debug$T sections into IpiData and
941 // TpiData.
942 void PDBLinker::addObjectsToPDB() {
943   ScopedTimer t1(addObjectsTimer);
944 
945   // Create module descriptors
946   for_each(ObjFile::instances,
947            [&](ObjFile *obj) { createModuleDBI(builder, obj); });
948 
949   // Reorder dependency type sources to come first.
950   TpiSource::sortDependencies();
951 
952   // Merge type information from input files using global type hashing.
953   if (config->debugGHashes)
954     tMerger.mergeTypesWithGHash();
955 
956   // Merge dependencies and then regular objects.
957   for_each(TpiSource::dependencySources,
958            [&](TpiSource *source) { addDebug(source); });
959   for_each(TpiSource::objectSources,
960            [&](TpiSource *source) { addDebug(source); });
961 
962   builder.getStringTableBuilder().setStrings(pdbStrTab);
963   t1.stop();
964 
965   // Construct TPI and IPI stream contents.
966   ScopedTimer t2(tpiStreamLayoutTimer);
967   // Collect all the merged types.
968   if (config->debugGHashes) {
969     addGHashTypeInfo(builder);
970   } else {
971     addTypeInfo(builder.getTpiBuilder(), tMerger.getTypeTable());
972     addTypeInfo(builder.getIpiBuilder(), tMerger.getIDTable());
973   }
974   t2.stop();
975 
976   if (config->showSummary) {
977     for_each(TpiSource::instances, [&](TpiSource *source) {
978       nbTypeRecords += source->nbTypeRecords;
979       nbTypeRecordsBytes += source->nbTypeRecordsBytes;
980     });
981   }
982 }
983 
984 void PDBLinker::addPublicsToPDB() {
985   ScopedTimer t3(publicsLayoutTimer);
986   // Compute the public symbols.
987   auto &gsiBuilder = builder.getGsiBuilder();
988   std::vector<pdb::BulkPublic> publics;
989   symtab->forEachSymbol([&publics](Symbol *s) {
990     // Only emit external, defined, live symbols that have a chunk. Static,
991     // non-external symbols do not appear in the symbol table.
992     auto *def = dyn_cast<Defined>(s);
993     if (def && def->isLive() && def->getChunk())
994       publics.push_back(createPublic(def));
995   });
996 
997   if (!publics.empty()) {
998     publicSymbols = publics.size();
999     gsiBuilder.addPublicSymbols(std::move(publics));
1000   }
1001 }
1002 
1003 void PDBLinker::printStats() {
1004   if (!config->showSummary)
1005     return;
1006 
1007   SmallString<256> buffer;
1008   raw_svector_ostream stream(buffer);
1009 
1010   stream << center_justify("Summary", 80) << '\n'
1011          << std::string(80, '-') << '\n';
1012 
1013   auto print = [&](uint64_t v, StringRef s) {
1014     stream << format_decimal(v, 15) << " " << s << '\n';
1015   };
1016 
1017   print(ObjFile::instances.size(),
1018         "Input OBJ files (expanded from all cmd-line inputs)");
1019   print(TpiSource::countTypeServerPDBs(), "PDB type server dependencies");
1020   print(TpiSource::countPrecompObjs(), "Precomp OBJ dependencies");
1021   print(nbTypeRecords, "Input type records");
1022   print(nbTypeRecordsBytes, "Input type records bytes");
1023   print(builder.getTpiBuilder().getRecordCount(), "Merged TPI records");
1024   print(builder.getIpiBuilder().getRecordCount(), "Merged IPI records");
1025   print(pdbStrTab.size(), "Output PDB strings");
1026   print(globalSymbols, "Global symbol records");
1027   print(moduleSymbols, "Module symbol records");
1028   print(publicSymbols, "Public symbol records");
1029 
1030   auto printLargeInputTypeRecs = [&](StringRef name,
1031                                      ArrayRef<uint32_t> recCounts,
1032                                      TypeCollection &records) {
1033     // Figure out which type indices were responsible for the most duplicate
1034     // bytes in the input files. These should be frequently emitted LF_CLASS and
1035     // LF_FIELDLIST records.
1036     struct TypeSizeInfo {
1037       uint32_t typeSize;
1038       uint32_t dupCount;
1039       TypeIndex typeIndex;
1040       uint64_t totalInputSize() const { return uint64_t(dupCount) * typeSize; }
1041       bool operator<(const TypeSizeInfo &rhs) const {
1042         if (totalInputSize() == rhs.totalInputSize())
1043           return typeIndex < rhs.typeIndex;
1044         return totalInputSize() < rhs.totalInputSize();
1045       }
1046     };
1047     SmallVector<TypeSizeInfo, 0> tsis;
1048     for (auto e : enumerate(recCounts)) {
1049       TypeIndex typeIndex = TypeIndex::fromArrayIndex(e.index());
1050       uint32_t typeSize = records.getType(typeIndex).length();
1051       uint32_t dupCount = e.value();
1052       tsis.push_back({typeSize, dupCount, typeIndex});
1053     }
1054 
1055     if (!tsis.empty()) {
1056       stream << "\nTop 10 types responsible for the most " << name
1057              << " input:\n";
1058       stream << "       index     total bytes   count     size\n";
1059       llvm::sort(tsis);
1060       unsigned i = 0;
1061       for (const auto &tsi : reverse(tsis)) {
1062         stream << formatv("  {0,10:X}: {1,14:N} = {2,5:N} * {3,6:N}\n",
1063                           tsi.typeIndex.getIndex(), tsi.totalInputSize(),
1064                           tsi.dupCount, tsi.typeSize);
1065         if (++i >= 10)
1066           break;
1067       }
1068       stream
1069           << "Run llvm-pdbutil to print details about a particular record:\n";
1070       stream << formatv("llvm-pdbutil dump -{0}s -{0}-index {1:X} {2}\n",
1071                         (name == "TPI" ? "type" : "id"),
1072                         tsis.back().typeIndex.getIndex(), config->pdbPath);
1073     }
1074   };
1075 
1076   if (!config->debugGHashes) {
1077     // FIXME: Reimplement for ghash.
1078     printLargeInputTypeRecs("TPI", tMerger.tpiCounts, tMerger.getTypeTable());
1079     printLargeInputTypeRecs("IPI", tMerger.ipiCounts, tMerger.getIDTable());
1080   }
1081 
1082   message(buffer);
1083 }
1084 
1085 void PDBLinker::addNatvisFiles() {
1086   for (StringRef file : config->natvisFiles) {
1087     ErrorOr<std::unique_ptr<MemoryBuffer>> dataOrErr =
1088         MemoryBuffer::getFile(file);
1089     if (!dataOrErr) {
1090       warn("Cannot open input file: " + file);
1091       continue;
1092     }
1093     builder.addInjectedSource(file, std::move(*dataOrErr));
1094   }
1095 }
1096 
1097 void PDBLinker::addNamedStreams() {
1098   for (const auto &streamFile : config->namedStreams) {
1099     const StringRef stream = streamFile.getKey(), file = streamFile.getValue();
1100     ErrorOr<std::unique_ptr<MemoryBuffer>> dataOrErr =
1101         MemoryBuffer::getFile(file);
1102     if (!dataOrErr) {
1103       warn("Cannot open input file: " + file);
1104       continue;
1105     }
1106     exitOnErr(builder.addNamedStream(stream, (*dataOrErr)->getBuffer()));
1107   }
1108 }
1109 
1110 static codeview::CPUType toCodeViewMachine(COFF::MachineTypes machine) {
1111   switch (machine) {
1112   case COFF::IMAGE_FILE_MACHINE_AMD64:
1113     return codeview::CPUType::X64;
1114   case COFF::IMAGE_FILE_MACHINE_ARM:
1115     return codeview::CPUType::ARM7;
1116   case COFF::IMAGE_FILE_MACHINE_ARM64:
1117     return codeview::CPUType::ARM64;
1118   case COFF::IMAGE_FILE_MACHINE_ARMNT:
1119     return codeview::CPUType::ARMNT;
1120   case COFF::IMAGE_FILE_MACHINE_I386:
1121     return codeview::CPUType::Intel80386;
1122   default:
1123     llvm_unreachable("Unsupported CPU Type");
1124   }
1125 }
1126 
1127 // Mimic MSVC which surrounds arguments containing whitespace with quotes.
1128 // Double double-quotes are handled, so that the resulting string can be
1129 // executed again on the cmd-line.
1130 static std::string quote(ArrayRef<StringRef> args) {
1131   std::string r;
1132   r.reserve(256);
1133   for (StringRef a : args) {
1134     if (!r.empty())
1135       r.push_back(' ');
1136     bool hasWS = a.find(' ') != StringRef::npos;
1137     bool hasQ = a.find('"') != StringRef::npos;
1138     if (hasWS || hasQ)
1139       r.push_back('"');
1140     if (hasQ) {
1141       SmallVector<StringRef, 4> s;
1142       a.split(s, '"');
1143       r.append(join(s, "\"\""));
1144     } else {
1145       r.append(std::string(a));
1146     }
1147     if (hasWS || hasQ)
1148       r.push_back('"');
1149   }
1150   return r;
1151 }
1152 
1153 static void fillLinkerVerRecord(Compile3Sym &cs) {
1154   cs.Machine = toCodeViewMachine(config->machine);
1155   // Interestingly, if we set the string to 0.0.0.0, then when trying to view
1156   // local variables WinDbg emits an error that private symbols are not present.
1157   // By setting this to a valid MSVC linker version string, local variables are
1158   // displayed properly.   As such, even though it is not representative of
1159   // LLVM's version information, we need this for compatibility.
1160   cs.Flags = CompileSym3Flags::None;
1161   cs.VersionBackendBuild = 25019;
1162   cs.VersionBackendMajor = 14;
1163   cs.VersionBackendMinor = 10;
1164   cs.VersionBackendQFE = 0;
1165 
1166   // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
1167   // linker module (which is by definition a backend), so we don't need to do
1168   // anything here.  Also, it seems we can use "LLVM Linker" for the linker name
1169   // without any problems.  Only the backend version has to be hardcoded to a
1170   // magic number.
1171   cs.VersionFrontendBuild = 0;
1172   cs.VersionFrontendMajor = 0;
1173   cs.VersionFrontendMinor = 0;
1174   cs.VersionFrontendQFE = 0;
1175   cs.Version = "LLVM Linker";
1176   cs.setLanguage(SourceLanguage::Link);
1177 }
1178 
1179 static void addCommonLinkerModuleSymbols(StringRef path,
1180                                          pdb::DbiModuleDescriptorBuilder &mod) {
1181   ObjNameSym ons(SymbolRecordKind::ObjNameSym);
1182   EnvBlockSym ebs(SymbolRecordKind::EnvBlockSym);
1183   Compile3Sym cs(SymbolRecordKind::Compile3Sym);
1184   fillLinkerVerRecord(cs);
1185 
1186   ons.Name = "* Linker *";
1187   ons.Signature = 0;
1188 
1189   ArrayRef<StringRef> args = makeArrayRef(config->argv).drop_front();
1190   std::string argStr = quote(args);
1191   ebs.Fields.push_back("cwd");
1192   SmallString<64> cwd;
1193   if (config->pdbSourcePath.empty())
1194     sys::fs::current_path(cwd);
1195   else
1196     cwd = config->pdbSourcePath;
1197   ebs.Fields.push_back(cwd);
1198   ebs.Fields.push_back("exe");
1199   SmallString<64> exe = config->argv[0];
1200   pdbMakeAbsolute(exe);
1201   ebs.Fields.push_back(exe);
1202   ebs.Fields.push_back("pdb");
1203   ebs.Fields.push_back(path);
1204   ebs.Fields.push_back("cmd");
1205   ebs.Fields.push_back(argStr);
1206   mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1207       ons, bAlloc, CodeViewContainer::Pdb));
1208   mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1209       cs, bAlloc, CodeViewContainer::Pdb));
1210   mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1211       ebs, bAlloc, CodeViewContainer::Pdb));
1212 }
1213 
1214 static void addLinkerModuleCoffGroup(PartialSection *sec,
1215                                      pdb::DbiModuleDescriptorBuilder &mod,
1216                                      OutputSection &os) {
1217   // If there's a section, there's at least one chunk
1218   assert(!sec->chunks.empty());
1219   const Chunk *firstChunk = *sec->chunks.begin();
1220   const Chunk *lastChunk = *sec->chunks.rbegin();
1221 
1222   // Emit COFF group
1223   CoffGroupSym cgs(SymbolRecordKind::CoffGroupSym);
1224   cgs.Name = sec->name;
1225   cgs.Segment = os.sectionIndex;
1226   cgs.Offset = firstChunk->getRVA() - os.getRVA();
1227   cgs.Size = lastChunk->getRVA() + lastChunk->getSize() - firstChunk->getRVA();
1228   cgs.Characteristics = sec->characteristics;
1229 
1230   // Somehow .idata sections & sections groups in the debug symbol stream have
1231   // the "write" flag set. However the section header for the corresponding
1232   // .idata section doesn't have it.
1233   if (cgs.Name.startswith(".idata"))
1234     cgs.Characteristics |= llvm::COFF::IMAGE_SCN_MEM_WRITE;
1235 
1236   mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1237       cgs, bAlloc, CodeViewContainer::Pdb));
1238 }
1239 
1240 static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &mod,
1241                                          OutputSection &os) {
1242   SectionSym sym(SymbolRecordKind::SectionSym);
1243   sym.Alignment = 12; // 2^12 = 4KB
1244   sym.Characteristics = os.header.Characteristics;
1245   sym.Length = os.getVirtualSize();
1246   sym.Name = os.name;
1247   sym.Rva = os.getRVA();
1248   sym.SectionNumber = os.sectionIndex;
1249   mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1250       sym, bAlloc, CodeViewContainer::Pdb));
1251 
1252   // Skip COFF groups in MinGW because it adds a significant footprint to the
1253   // PDB, due to each function being in its own section
1254   if (config->mingw)
1255     return;
1256 
1257   // Output COFF groups for individual chunks of this section.
1258   for (PartialSection *sec : os.contribSections) {
1259     addLinkerModuleCoffGroup(sec, mod, os);
1260   }
1261 }
1262 
1263 // Add all import files as modules to the PDB.
1264 void PDBLinker::addImportFilesToPDB(ArrayRef<OutputSection *> outputSections) {
1265   if (ImportFile::instances.empty())
1266     return;
1267 
1268   std::map<std::string, llvm::pdb::DbiModuleDescriptorBuilder *> dllToModuleDbi;
1269 
1270   for (ImportFile *file : ImportFile::instances) {
1271     if (!file->live)
1272       continue;
1273 
1274     if (!file->thunkSym)
1275       continue;
1276 
1277     if (!file->thunkLive)
1278         continue;
1279 
1280     std::string dll = StringRef(file->dllName).lower();
1281     llvm::pdb::DbiModuleDescriptorBuilder *&mod = dllToModuleDbi[dll];
1282     if (!mod) {
1283       pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1284       SmallString<128> libPath = file->parentName;
1285       pdbMakeAbsolute(libPath);
1286       sys::path::native(libPath);
1287 
1288       // Name modules similar to MSVC's link.exe.
1289       // The first module is the simple dll filename
1290       llvm::pdb::DbiModuleDescriptorBuilder &firstMod =
1291           exitOnErr(dbiBuilder.addModuleInfo(file->dllName));
1292       firstMod.setObjFileName(libPath);
1293       pdb::SectionContrib sc =
1294           createSectionContrib(nullptr, llvm::pdb::kInvalidStreamIndex);
1295       firstMod.setFirstSectionContrib(sc);
1296 
1297       // The second module is where the import stream goes.
1298       mod = &exitOnErr(dbiBuilder.addModuleInfo("Import:" + file->dllName));
1299       mod->setObjFileName(libPath);
1300     }
1301 
1302     DefinedImportThunk *thunk = cast<DefinedImportThunk>(file->thunkSym);
1303     Chunk *thunkChunk = thunk->getChunk();
1304     OutputSection *thunkOS = thunkChunk->getOutputSection();
1305 
1306     ObjNameSym ons(SymbolRecordKind::ObjNameSym);
1307     Compile3Sym cs(SymbolRecordKind::Compile3Sym);
1308     Thunk32Sym ts(SymbolRecordKind::Thunk32Sym);
1309     ScopeEndSym es(SymbolRecordKind::ScopeEndSym);
1310 
1311     ons.Name = file->dllName;
1312     ons.Signature = 0;
1313 
1314     fillLinkerVerRecord(cs);
1315 
1316     ts.Name = thunk->getName();
1317     ts.Parent = 0;
1318     ts.End = 0;
1319     ts.Next = 0;
1320     ts.Thunk = ThunkOrdinal::Standard;
1321     ts.Length = thunkChunk->getSize();
1322     ts.Segment = thunkOS->sectionIndex;
1323     ts.Offset = thunkChunk->getRVA() - thunkOS->getRVA();
1324 
1325     mod->addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1326         ons, bAlloc, CodeViewContainer::Pdb));
1327     mod->addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1328         cs, bAlloc, CodeViewContainer::Pdb));
1329 
1330     SmallVector<SymbolScope, 4> scopes;
1331     CVSymbol newSym = codeview::SymbolSerializer::writeOneSymbol(
1332         ts, bAlloc, CodeViewContainer::Pdb);
1333     scopeStackOpen(scopes, mod->getNextSymbolOffset(), newSym);
1334 
1335     mod->addSymbol(newSym);
1336 
1337     newSym = codeview::SymbolSerializer::writeOneSymbol(es, bAlloc,
1338                                                         CodeViewContainer::Pdb);
1339     scopeStackClose(scopes, mod->getNextSymbolOffset(), file);
1340 
1341     mod->addSymbol(newSym);
1342 
1343     pdb::SectionContrib sc =
1344         createSectionContrib(thunk->getChunk(), mod->getModuleIndex());
1345     mod->setFirstSectionContrib(sc);
1346   }
1347 }
1348 
1349 // Creates a PDB file.
1350 void lld::coff::createPDB(SymbolTable *symtab,
1351                           ArrayRef<OutputSection *> outputSections,
1352                           ArrayRef<uint8_t> sectionTable,
1353                           llvm::codeview::DebugInfo *buildId) {
1354   ScopedTimer t1(totalPdbLinkTimer);
1355   PDBLinker pdb(symtab);
1356 
1357   pdb.initialize(buildId);
1358   pdb.addObjectsToPDB();
1359   pdb.addImportFilesToPDB(outputSections);
1360   pdb.addSections(outputSections, sectionTable);
1361   pdb.addNatvisFiles();
1362   pdb.addNamedStreams();
1363   pdb.addPublicsToPDB();
1364 
1365   ScopedTimer t2(diskCommitTimer);
1366   codeview::GUID guid;
1367   pdb.commit(&guid);
1368   memcpy(&buildId->PDB70.Signature, &guid, 16);
1369 
1370   t2.stop();
1371   t1.stop();
1372   pdb.printStats();
1373 }
1374 
1375 void PDBLinker::initialize(llvm::codeview::DebugInfo *buildId) {
1376   exitOnErr(builder.initialize(4096)); // 4096 is blocksize
1377 
1378   buildId->Signature.CVSignature = OMF::Signature::PDB70;
1379   // Signature is set to a hash of the PDB contents when the PDB is done.
1380   memset(buildId->PDB70.Signature, 0, 16);
1381   buildId->PDB70.Age = 1;
1382 
1383   // Create streams in MSF for predefined streams, namely
1384   // PDB, TPI, DBI and IPI.
1385   for (int i = 0; i < (int)pdb::kSpecialStreamCount; ++i)
1386     exitOnErr(builder.getMsfBuilder().addStream(0));
1387 
1388   // Add an Info stream.
1389   auto &infoBuilder = builder.getInfoBuilder();
1390   infoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
1391   infoBuilder.setHashPDBContentsToGUID(true);
1392 
1393   // Add an empty DBI stream.
1394   pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1395   dbiBuilder.setAge(buildId->PDB70.Age);
1396   dbiBuilder.setVersionHeader(pdb::PdbDbiV70);
1397   dbiBuilder.setMachineType(config->machine);
1398   // Technically we are not link.exe 14.11, but there are known cases where
1399   // debugging tools on Windows expect Microsoft-specific version numbers or
1400   // they fail to work at all.  Since we know we produce PDBs that are
1401   // compatible with LINK 14.11, we set that version number here.
1402   dbiBuilder.setBuildNumber(14, 11);
1403 }
1404 
1405 void PDBLinker::addSections(ArrayRef<OutputSection *> outputSections,
1406                             ArrayRef<uint8_t> sectionTable) {
1407   // It's not entirely clear what this is, but the * Linker * module uses it.
1408   pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1409   nativePath = config->pdbPath;
1410   pdbMakeAbsolute(nativePath);
1411   uint32_t pdbFilePathNI = dbiBuilder.addECName(nativePath);
1412   auto &linkerModule = exitOnErr(dbiBuilder.addModuleInfo("* Linker *"));
1413   linkerModule.setPdbFilePathNI(pdbFilePathNI);
1414   addCommonLinkerModuleSymbols(nativePath, linkerModule);
1415 
1416   // Add section contributions. They must be ordered by ascending RVA.
1417   for (OutputSection *os : outputSections) {
1418     addLinkerModuleSectionSymbol(linkerModule, *os);
1419     for (Chunk *c : os->chunks) {
1420       pdb::SectionContrib sc =
1421           createSectionContrib(c, linkerModule.getModuleIndex());
1422       builder.getDbiBuilder().addSectionContrib(sc);
1423     }
1424   }
1425 
1426   // The * Linker * first section contrib is only used along with /INCREMENTAL,
1427   // to provide trampolines thunks for incremental function patching. Set this
1428   // as "unused" because LLD doesn't support /INCREMENTAL link.
1429   pdb::SectionContrib sc =
1430       createSectionContrib(nullptr, llvm::pdb::kInvalidStreamIndex);
1431   linkerModule.setFirstSectionContrib(sc);
1432 
1433   // Add Section Map stream.
1434   ArrayRef<object::coff_section> sections = {
1435       (const object::coff_section *)sectionTable.data(),
1436       sectionTable.size() / sizeof(object::coff_section)};
1437   dbiBuilder.createSectionMap(sections);
1438 
1439   // Add COFF section header stream.
1440   exitOnErr(
1441       dbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, sectionTable));
1442 }
1443 
1444 void PDBLinker::commit(codeview::GUID *guid) {
1445   ExitOnError exitOnErr((config->pdbPath + ": ").str());
1446   // Write to a file.
1447   exitOnErr(builder.commit(config->pdbPath, guid));
1448 }
1449 
1450 static uint32_t getSecrelReloc() {
1451   switch (config->machine) {
1452   case AMD64:
1453     return COFF::IMAGE_REL_AMD64_SECREL;
1454   case I386:
1455     return COFF::IMAGE_REL_I386_SECREL;
1456   case ARMNT:
1457     return COFF::IMAGE_REL_ARM_SECREL;
1458   case ARM64:
1459     return COFF::IMAGE_REL_ARM64_SECREL;
1460   default:
1461     llvm_unreachable("unknown machine type");
1462   }
1463 }
1464 
1465 // Try to find a line table for the given offset Addr into the given chunk C.
1466 // If a line table was found, the line table, the string and checksum tables
1467 // that are used to interpret the line table, and the offset of Addr in the line
1468 // table are stored in the output arguments. Returns whether a line table was
1469 // found.
1470 static bool findLineTable(const SectionChunk *c, uint32_t addr,
1471                           DebugStringTableSubsectionRef &cvStrTab,
1472                           DebugChecksumsSubsectionRef &checksums,
1473                           DebugLinesSubsectionRef &lines,
1474                           uint32_t &offsetInLinetable) {
1475   ExitOnError exitOnErr;
1476   uint32_t secrelReloc = getSecrelReloc();
1477 
1478   for (SectionChunk *dbgC : c->file->getDebugChunks()) {
1479     if (dbgC->getSectionName() != ".debug$S")
1480       continue;
1481 
1482     // Build a mapping of SECREL relocations in dbgC that refer to `c`.
1483     DenseMap<uint32_t, uint32_t> secrels;
1484     for (const coff_relocation &r : dbgC->getRelocs()) {
1485       if (r.Type != secrelReloc)
1486         continue;
1487 
1488       if (auto *s = dyn_cast_or_null<DefinedRegular>(
1489               c->file->getSymbols()[r.SymbolTableIndex]))
1490         if (s->getChunk() == c)
1491           secrels[r.VirtualAddress] = s->getValue();
1492     }
1493 
1494     ArrayRef<uint8_t> contents =
1495         SectionChunk::consumeDebugMagic(dbgC->getContents(), ".debug$S");
1496     DebugSubsectionArray subsections;
1497     BinaryStreamReader reader(contents, support::little);
1498     exitOnErr(reader.readArray(subsections, contents.size()));
1499 
1500     for (const DebugSubsectionRecord &ss : subsections) {
1501       switch (ss.kind()) {
1502       case DebugSubsectionKind::StringTable: {
1503         assert(!cvStrTab.valid() &&
1504                "Encountered multiple string table subsections!");
1505         exitOnErr(cvStrTab.initialize(ss.getRecordData()));
1506         break;
1507       }
1508       case DebugSubsectionKind::FileChecksums:
1509         assert(!checksums.valid() &&
1510                "Encountered multiple checksum subsections!");
1511         exitOnErr(checksums.initialize(ss.getRecordData()));
1512         break;
1513       case DebugSubsectionKind::Lines: {
1514         ArrayRef<uint8_t> bytes;
1515         auto ref = ss.getRecordData();
1516         exitOnErr(ref.readLongestContiguousChunk(0, bytes));
1517         size_t offsetInDbgC = bytes.data() - dbgC->getContents().data();
1518 
1519         // Check whether this line table refers to C.
1520         auto i = secrels.find(offsetInDbgC);
1521         if (i == secrels.end())
1522           break;
1523 
1524         // Check whether this line table covers Addr in C.
1525         DebugLinesSubsectionRef linesTmp;
1526         exitOnErr(linesTmp.initialize(BinaryStreamReader(ref)));
1527         uint32_t offsetInC = i->second + linesTmp.header()->RelocOffset;
1528         if (addr < offsetInC || addr >= offsetInC + linesTmp.header()->CodeSize)
1529           break;
1530 
1531         assert(!lines.header() &&
1532                "Encountered multiple line tables for function!");
1533         exitOnErr(lines.initialize(BinaryStreamReader(ref)));
1534         offsetInLinetable = addr - offsetInC;
1535         break;
1536       }
1537       default:
1538         break;
1539       }
1540 
1541       if (cvStrTab.valid() && checksums.valid() && lines.header())
1542         return true;
1543     }
1544   }
1545 
1546   return false;
1547 }
1548 
1549 // Use CodeView line tables to resolve a file and line number for the given
1550 // offset into the given chunk and return them, or None if a line table was
1551 // not found.
1552 Optional<std::pair<StringRef, uint32_t>>
1553 lld::coff::getFileLineCodeView(const SectionChunk *c, uint32_t addr) {
1554   ExitOnError exitOnErr;
1555 
1556   DebugStringTableSubsectionRef cvStrTab;
1557   DebugChecksumsSubsectionRef checksums;
1558   DebugLinesSubsectionRef lines;
1559   uint32_t offsetInLinetable;
1560 
1561   if (!findLineTable(c, addr, cvStrTab, checksums, lines, offsetInLinetable))
1562     return None;
1563 
1564   Optional<uint32_t> nameIndex;
1565   Optional<uint32_t> lineNumber;
1566   for (LineColumnEntry &entry : lines) {
1567     for (const LineNumberEntry &ln : entry.LineNumbers) {
1568       LineInfo li(ln.Flags);
1569       if (ln.Offset > offsetInLinetable) {
1570         if (!nameIndex) {
1571           nameIndex = entry.NameIndex;
1572           lineNumber = li.getStartLine();
1573         }
1574         StringRef filename =
1575             exitOnErr(getFileName(cvStrTab, checksums, *nameIndex));
1576         return std::make_pair(filename, *lineNumber);
1577       }
1578       nameIndex = entry.NameIndex;
1579       lineNumber = li.getStartLine();
1580     }
1581   }
1582   if (!nameIndex)
1583     return None;
1584   StringRef filename = exitOnErr(getFileName(cvStrTab, checksums, *nameIndex));
1585   return std::make_pair(filename, *lineNumber);
1586 }
1587