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