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