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