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