xref: /llvm-project-15.0.7/lld/COFF/PDB.cpp (revision bacf751a)
1 //===- PDB.cpp ------------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "PDB.h"
11 #include "Chunks.h"
12 #include "Config.h"
13 #include "Driver.h"
14 #include "SymbolTable.h"
15 #include "Symbols.h"
16 #include "Writer.h"
17 #include "lld/Common/ErrorHandler.h"
18 #include "lld/Common/Timer.h"
19 #include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
20 #include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
21 #include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"
22 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
23 #include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
24 #include "llvm/DebugInfo/CodeView/RecordName.h"
25 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
26 #include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
27 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
28 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
29 #include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
30 #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
31 #include "llvm/DebugInfo/MSF/MSFBuilder.h"
32 #include "llvm/DebugInfo/MSF/MSFCommon.h"
33 #include "llvm/DebugInfo/PDB/GenericError.h"
34 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
35 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
36 #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
37 #include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h"
38 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
39 #include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
40 #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
41 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
42 #include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
43 #include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
44 #include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
45 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
46 #include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
47 #include "llvm/DebugInfo/PDB/PDB.h"
48 #include "llvm/Object/COFF.h"
49 #include "llvm/Object/CVDebugRecord.h"
50 #include "llvm/Support/BinaryByteStream.h"
51 #include "llvm/Support/Endian.h"
52 #include "llvm/Support/FormatVariadic.h"
53 #include "llvm/Support/JamCRC.h"
54 #include "llvm/Support/Path.h"
55 #include "llvm/Support/ScopedPrinter.h"
56 #include <memory>
57 
58 using namespace lld;
59 using namespace lld::coff;
60 using namespace llvm;
61 using namespace llvm::codeview;
62 
63 using llvm::object::coff_section;
64 
65 static ExitOnError ExitOnErr;
66 
67 static Timer TotalPdbLinkTimer("PDB Emission (Cumulative)", Timer::root());
68 
69 static Timer AddObjectsTimer("Add Objects", TotalPdbLinkTimer);
70 static Timer TypeMergingTimer("Type Merging", AddObjectsTimer);
71 static Timer SymbolMergingTimer("Symbol Merging", AddObjectsTimer);
72 static Timer GlobalsLayoutTimer("Globals Stream Layout", TotalPdbLinkTimer);
73 static Timer TpiStreamLayoutTimer("TPI Stream Layout", TotalPdbLinkTimer);
74 static Timer DiskCommitTimer("Commit to Disk", TotalPdbLinkTimer);
75 
76 namespace {
77 /// Map from type index and item index in a type server PDB to the
78 /// corresponding index in the destination PDB.
79 struct CVIndexMap {
80   SmallVector<TypeIndex, 0> TPIMap;
81   SmallVector<TypeIndex, 0> IPIMap;
82   bool IsTypeServerMap = false;
83 };
84 
85 class DebugSHandler;
86 
87 class PDBLinker {
88   friend DebugSHandler;
89 
90 public:
91   PDBLinker(SymbolTable *Symtab)
92       : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
93         IDTable(Alloc), GlobalTypeTable(Alloc), GlobalIDTable(Alloc) {
94     // This isn't strictly necessary, but link.exe usually puts an empty string
95     // as the first "valid" string in the string table, so we do the same in
96     // order to maintain as much byte-for-byte compatibility as possible.
97     PDBStrTab.insert("");
98   }
99 
100   /// Emit the basic PDB structure: initial streams, headers, etc.
101   void initialize(llvm::codeview::DebugInfo *BuildId);
102 
103   /// Add natvis files specified on the command line.
104   void addNatvisFiles();
105 
106   /// Link CodeView from each object file in the symbol table into the PDB.
107   void addObjectsToPDB();
108 
109   /// Link CodeView from a single object file into the PDB.
110   void addObjFile(ObjFile *File);
111 
112   /// Produce a mapping from the type and item indices used in the object
113   /// file to those in the destination PDB.
114   ///
115   /// If the object file uses a type server PDB (compiled with /Zi), merge TPI
116   /// and IPI from the type server PDB and return a map for it. Each unique type
117   /// server PDB is merged at most once, so this may return an existing index
118   /// mapping.
119   ///
120   /// If the object does not use a type server PDB (compiled with /Z7), we merge
121   /// all the type and item records from the .debug$S stream and fill in the
122   /// caller-provided ObjectIndexMap.
123   Expected<const CVIndexMap&> mergeDebugT(ObjFile *File,
124                                           CVIndexMap &ObjectIndexMap);
125 
126   Expected<const CVIndexMap&> maybeMergeTypeServerPDB(ObjFile *File,
127                                                       TypeServer2Record &TS);
128 
129   /// Add the section map and section contributions to the PDB.
130   void addSections(ArrayRef<OutputSection *> OutputSections,
131                    ArrayRef<uint8_t> SectionTable);
132 
133   /// Write the PDB to disk and store the Guid generated for it in *Guid.
134   void commit(codeview::GUID *Guid);
135 
136 private:
137   BumpPtrAllocator Alloc;
138 
139   SymbolTable *Symtab;
140 
141   pdb::PDBFileBuilder Builder;
142 
143   /// Type records that will go into the PDB TPI stream.
144   MergingTypeTableBuilder TypeTable;
145 
146   /// Item records that will go into the PDB IPI stream.
147   MergingTypeTableBuilder IDTable;
148 
149   /// Type records that will go into the PDB TPI stream (for /DEBUG:GHASH)
150   GlobalTypeTableBuilder GlobalTypeTable;
151 
152   /// Item records that will go into the PDB IPI stream (for /DEBUG:GHASH)
153   GlobalTypeTableBuilder GlobalIDTable;
154 
155   /// PDBs use a single global string table for filenames in the file checksum
156   /// table.
157   DebugStringTableSubsection PDBStrTab;
158 
159   llvm::SmallString<128> NativePath;
160 
161   /// A list of other PDBs which are loaded during the linking process and which
162   /// we need to keep around since the linking operation may reference pointers
163   /// inside of these PDBs.
164   llvm::SmallVector<std::unique_ptr<pdb::NativeSession>, 2> LoadedPDBs;
165 
166   std::vector<pdb::SecMapEntry> SectionMap;
167 
168   /// Type index mappings of type server PDBs that we've loaded so far.
169   std::map<GUID, CVIndexMap> TypeServerIndexMappings;
170 
171   /// List of TypeServer PDBs which cannot be loaded.
172   /// Cached to prevent repeated load attempts.
173   std::map<GUID, std::string> MissingTypeServerPDBs;
174 };
175 
176 class DebugSHandler {
177   PDBLinker &Linker;
178 
179   /// The object file whose .debug$S sections we're processing.
180   ObjFile &File;
181 
182   /// The result of merging type indices.
183   const CVIndexMap &IndexMap;
184 
185   /// The DEBUG_S_STRINGTABLE subsection.  These strings are referred to by
186   /// index from other records in the .debug$S section.  All of these strings
187   /// need to be added to the global PDB string table, and all references to
188   /// these strings need to have their indices re-written to refer to the
189   /// global PDB string table.
190   DebugStringTableSubsectionRef CVStrTab;
191 
192   /// The DEBUG_S_FILECHKSMS subsection.  As above, these are referred to
193   /// by other records in the .debug$S section and need to be merged into the
194   /// PDB.
195   DebugChecksumsSubsectionRef Checksums;
196 
197   /// The DEBUG_S_FRAMEDATA subsection(s).  There can be more than one of
198   /// these and they need not appear in any specific order.  However, they
199   /// contain string table references which need to be re-written, so we
200   /// collect them all here and re-write them after all subsections have been
201   /// discovered and processed.
202   std::vector<DebugFrameDataSubsectionRef> NewFpoFrames;
203 
204   /// Pointers to raw memory that we determine have string table references
205   /// that need to be re-written.  We first process all .debug$S subsections
206   /// to ensure that we can handle subsections written in any order, building
207   /// up this list as we go.  At the end, we use the string table (which must
208   /// have been discovered by now else it is an error) to re-write these
209   /// references.
210   std::vector<ulittle32_t *> StringTableReferences;
211 
212 public:
213   DebugSHandler(PDBLinker &Linker, ObjFile &File, const CVIndexMap &IndexMap)
214       : Linker(Linker), File(File), IndexMap(IndexMap) {}
215 
216   void handleDebugS(lld::coff::SectionChunk &DebugS);
217   void finish();
218 };
219 }
220 
221 // Visual Studio's debugger requires absolute paths in various places in the
222 // PDB to work without additional configuration:
223 // https://docs.microsoft.com/en-us/visualstudio/debugger/debug-source-files-common-properties-solution-property-pages-dialog-box
224 static void pdbMakeAbsolute(SmallVectorImpl<char> &FileName) {
225   // The default behavior is to produce paths that are valid within the context
226   // of the machine that you perform the link on.  If the linker is running on
227   // a POSIX system, we will output absolute POSIX paths.  If the linker is
228   // running on a Windows system, we will output absolute Windows paths.  If the
229   // user desires any other kind of behavior, they should explicitly pass
230   // /pdbsourcepath, in which case we will treat the exact string the user
231   // passed in as the gospel and not normalize, canonicalize it.
232   if (sys::path::is_absolute(FileName, sys::path::Style::windows) ||
233       sys::path::is_absolute(FileName, sys::path::Style::posix))
234     return;
235 
236   // It's not absolute in any path syntax.  Relative paths necessarily refer to
237   // the local file system, so we can make it native without ending up with a
238   // nonsensical path.
239   sys::path::native(FileName);
240   if (Config->PDBSourcePath.empty()) {
241     sys::fs::make_absolute(FileName);
242     return;
243   }
244   // Only apply native and dot removal to the relative file path.  We want to
245   // leave the path the user specified untouched since we assume they specified
246   // it for a reason.
247   sys::path::remove_dots(FileName, /*remove_dot_dots=*/true);
248 
249   SmallString<128> AbsoluteFileName = Config->PDBSourcePath;
250   sys::path::append(AbsoluteFileName, FileName);
251   FileName = std::move(AbsoluteFileName);
252 }
253 
254 static SectionChunk *findByName(ArrayRef<SectionChunk *> Sections,
255                                 StringRef Name) {
256   for (SectionChunk *C : Sections)
257     if (C->getSectionName() == Name)
258       return C;
259   return nullptr;
260 }
261 
262 static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
263                                            StringRef SecName) {
264   // First 4 bytes are section magic.
265   if (Data.size() < 4)
266     fatal(SecName + " too short");
267   if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
268     fatal(SecName + " has an invalid magic");
269   return Data.slice(4);
270 }
271 
272 static ArrayRef<uint8_t> getDebugSection(ObjFile *File, StringRef SecName) {
273   if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
274     return consumeDebugMagic(Sec->getContents(), SecName);
275   return {};
276 }
277 
278 // A COFF .debug$H section is currently a clang extension.  This function checks
279 // if a .debug$H section is in a format that we expect / understand, so that we
280 // can ignore any sections which are coincidentally also named .debug$H but do
281 // not contain a format we recognize.
282 static bool canUseDebugH(ArrayRef<uint8_t> DebugH) {
283   if (DebugH.size() < sizeof(object::debug_h_header))
284     return false;
285   auto *Header =
286       reinterpret_cast<const object::debug_h_header *>(DebugH.data());
287   DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
288   return Header->Magic == COFF::DEBUG_HASHES_SECTION_MAGIC &&
289          Header->Version == 0 &&
290          Header->HashAlgorithm == uint16_t(GlobalTypeHashAlg::SHA1_8) &&
291          (DebugH.size() % 8 == 0);
292 }
293 
294 static Optional<ArrayRef<uint8_t>> getDebugH(ObjFile *File) {
295   SectionChunk *Sec = findByName(File->getDebugChunks(), ".debug$H");
296   if (!Sec)
297     return llvm::None;
298   ArrayRef<uint8_t> Contents = Sec->getContents();
299   if (!canUseDebugH(Contents))
300     return None;
301   return Contents;
302 }
303 
304 static ArrayRef<GloballyHashedType>
305 getHashesFromDebugH(ArrayRef<uint8_t> DebugH) {
306   assert(canUseDebugH(DebugH));
307 
308   DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
309   uint32_t Count = DebugH.size() / sizeof(GloballyHashedType);
310   return {reinterpret_cast<const GloballyHashedType *>(DebugH.data()), Count};
311 }
312 
313 static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
314                         TypeCollection &TypeTable) {
315   // Start the TPI or IPI stream header.
316   TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
317 
318   // Flatten the in memory type table and hash each type.
319   TypeTable.ForEachRecord([&](TypeIndex TI, const CVType &Type) {
320     auto Hash = pdb::hashTypeRecord(Type);
321     if (auto E = Hash.takeError())
322       fatal("type hashing error");
323     TpiBuilder.addTypeRecord(Type.RecordData, *Hash);
324   });
325 }
326 
327 static Optional<TypeServer2Record>
328 maybeReadTypeServerRecord(CVTypeArray &Types) {
329   auto I = Types.begin();
330   if (I == Types.end())
331     return None;
332   const CVType &Type = *I;
333   if (Type.kind() != LF_TYPESERVER2)
334     return None;
335   TypeServer2Record TS;
336   if (auto EC = TypeDeserializer::deserializeAs(const_cast<CVType &>(Type), TS))
337     fatal("error reading type server record: " + toString(std::move(EC)));
338   return std::move(TS);
339 }
340 
341 Expected<const CVIndexMap&> PDBLinker::mergeDebugT(ObjFile *File,
342                                                    CVIndexMap &ObjectIndexMap) {
343   ScopedTimer T(TypeMergingTimer);
344 
345   ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
346   if (Data.empty())
347     return ObjectIndexMap;
348 
349   BinaryByteStream Stream(Data, support::little);
350   CVTypeArray Types;
351   BinaryStreamReader Reader(Stream);
352   if (auto EC = Reader.readArray(Types, Reader.getLength()))
353     fatal("Reader::readArray failed: " + toString(std::move(EC)));
354 
355   // Look through type servers. If we've already seen this type server, don't
356   // merge any type information.
357   if (Optional<TypeServer2Record> TS = maybeReadTypeServerRecord(Types))
358     return maybeMergeTypeServerPDB(File, *TS);
359 
360   // This is a /Z7 object. Fill in the temporary, caller-provided
361   // ObjectIndexMap.
362   if (Config->DebugGHashes) {
363     ArrayRef<GloballyHashedType> Hashes;
364     std::vector<GloballyHashedType> OwnedHashes;
365     if (Optional<ArrayRef<uint8_t>> DebugH = getDebugH(File))
366       Hashes = getHashesFromDebugH(*DebugH);
367     else {
368       OwnedHashes = GloballyHashedType::hashTypes(Types);
369       Hashes = OwnedHashes;
370     }
371 
372     if (auto Err = mergeTypeAndIdRecords(GlobalIDTable, GlobalTypeTable,
373                                          ObjectIndexMap.TPIMap, Types, Hashes))
374       fatal("codeview::mergeTypeAndIdRecords failed: " +
375             toString(std::move(Err)));
376   } else {
377     if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable,
378                                          ObjectIndexMap.TPIMap, Types))
379       fatal("codeview::mergeTypeAndIdRecords failed: " +
380             toString(std::move(Err)));
381   }
382   return ObjectIndexMap;
383 }
384 
385 static Expected<std::unique_ptr<pdb::NativeSession>>
386 tryToLoadPDB(const GUID &GuidFromObj, StringRef TSPath) {
387   // Ensure the file exists before anything else. We want to return ENOENT,
388   // "file not found", even if the path points to a removable device (in which
389   // case the return message would be EAGAIN, "resource unavailable try again")
390   if (!llvm::sys::fs::exists(TSPath))
391     return errorCodeToError(std::error_code(ENOENT, std::generic_category()));
392 
393   ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(
394       TSPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
395   if (!MBOrErr)
396     return errorCodeToError(MBOrErr.getError());
397 
398   std::unique_ptr<pdb::IPDBSession> ThisSession;
399   if (auto EC = pdb::NativeSession::createFromPdb(
400           MemoryBuffer::getMemBuffer(Driver->takeBuffer(std::move(*MBOrErr)),
401                                      /*RequiresNullTerminator=*/false),
402           ThisSession))
403     return std::move(EC);
404 
405   std::unique_ptr<pdb::NativeSession> NS(
406       static_cast<pdb::NativeSession *>(ThisSession.release()));
407   pdb::PDBFile &File = NS->getPDBFile();
408   auto ExpectedInfo = File.getPDBInfoStream();
409   // All PDB Files should have an Info stream.
410   if (!ExpectedInfo)
411     return ExpectedInfo.takeError();
412 
413   // Just because a file with a matching name was found and it was an actual
414   // PDB file doesn't mean it matches.  For it to match the InfoStream's GUID
415   // must match the GUID specified in the TypeServer2 record.
416   if (ExpectedInfo->getGuid() != GuidFromObj)
417     return make_error<pdb::PDBError>(pdb::pdb_error_code::signature_out_of_date);
418 
419   return std::move(NS);
420 }
421 
422 Expected<const CVIndexMap &>
423 PDBLinker::maybeMergeTypeServerPDB(ObjFile *File, TypeServer2Record &TS) {
424   const GUID &TSId = TS.getGuid();
425   StringRef TSPath = TS.getName();
426 
427   // First, check if the PDB has previously failed to load.
428   auto PrevErr = MissingTypeServerPDBs.find(TSId);
429   if (PrevErr != MissingTypeServerPDBs.end())
430     return createFileError(
431         TSPath,
432         make_error<StringError>(PrevErr->second, inconvertibleErrorCode()));
433 
434   // Second, check if we already loaded a PDB with this GUID. Return the type
435   // index mapping if we have it.
436   auto Insertion = TypeServerIndexMappings.insert({TSId, CVIndexMap()});
437   CVIndexMap &IndexMap = Insertion.first->second;
438   if (!Insertion.second)
439     return IndexMap;
440 
441   // Mark this map as a type server map.
442   IndexMap.IsTypeServerMap = true;
443 
444   // Check for a PDB at:
445   // 1. The given file path
446   // 2. Next to the object file or archive file
447   auto ExpectedSession = handleExpected(
448       tryToLoadPDB(TSId, TSPath),
449       [&]() {
450         StringRef LocalPath =
451             !File->ParentName.empty() ? File->ParentName : File->getName();
452         SmallString<128> Path = sys::path::parent_path(LocalPath);
453         // Currently, type server PDBs are only created by cl, which only runs
454         // on Windows, so we can assume type server paths are Windows style.
455         sys::path::append(
456             Path, sys::path::filename(TSPath, sys::path::Style::windows));
457         return tryToLoadPDB(TSId, Path);
458       },
459       [&](std::unique_ptr<ECError> EC) -> Error {
460         auto SysErr = EC->convertToErrorCode();
461         // Only re-try loading if the previous error was "No such file or
462         // directory"
463         if (SysErr.category() == std::generic_category() &&
464             SysErr.value() == ENOENT)
465           return Error::success();
466         return Error(std::move(EC));
467       });
468 
469   if (auto E = ExpectedSession.takeError()) {
470     TypeServerIndexMappings.erase(TSId);
471 
472     // Flatten the error to a string, for later display, if the error occurs
473     // again on the same PDB.
474     std::string ErrMsg;
475     raw_string_ostream S(ErrMsg);
476     S << E;
477     MissingTypeServerPDBs.emplace(TSId, S.str());
478 
479     return createFileError(TSPath, std::move(E));
480   }
481 
482   pdb::NativeSession *Session = ExpectedSession->get();
483 
484   // Keep a strong reference to this PDB, so that it's safe to hold pointers
485   // into the file.
486   LoadedPDBs.push_back(std::move(*ExpectedSession));
487 
488   auto ExpectedTpi = Session->getPDBFile().getPDBTpiStream();
489   if (auto E = ExpectedTpi.takeError())
490     fatal("Type server does not have TPI stream: " + toString(std::move(E)));
491   auto ExpectedIpi = Session->getPDBFile().getPDBIpiStream();
492   if (auto E = ExpectedIpi.takeError())
493     fatal("Type server does not have TPI stream: " + toString(std::move(E)));
494 
495   if (Config->DebugGHashes) {
496     // PDBs do not actually store global hashes, so when merging a type server
497     // PDB we have to synthesize global hashes.  To do this, we first synthesize
498     // global hashes for the TPI stream, since it is independent, then we
499     // synthesize hashes for the IPI stream, using the hashes for the TPI stream
500     // as inputs.
501     auto TpiHashes = GloballyHashedType::hashTypes(ExpectedTpi->typeArray());
502     auto IpiHashes =
503         GloballyHashedType::hashIds(ExpectedIpi->typeArray(), TpiHashes);
504 
505     // Merge TPI first, because the IPI stream will reference type indices.
506     if (auto Err = mergeTypeRecords(GlobalTypeTable, IndexMap.TPIMap,
507                                     ExpectedTpi->typeArray(), TpiHashes))
508       fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
509 
510     // Merge IPI.
511     if (auto Err =
512             mergeIdRecords(GlobalIDTable, IndexMap.TPIMap, IndexMap.IPIMap,
513                            ExpectedIpi->typeArray(), IpiHashes))
514       fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
515   } else {
516     // Merge TPI first, because the IPI stream will reference type indices.
517     if (auto Err = mergeTypeRecords(TypeTable, IndexMap.TPIMap,
518                                     ExpectedTpi->typeArray()))
519       fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
520 
521     // Merge IPI.
522     if (auto Err = mergeIdRecords(IDTable, IndexMap.TPIMap, IndexMap.IPIMap,
523                                   ExpectedIpi->typeArray()))
524       fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
525   }
526 
527   return IndexMap;
528 }
529 
530 static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
531   if (TI.isSimple())
532     return true;
533   if (TI.toArrayIndex() >= TypeIndexMap.size())
534     return false;
535   TI = TypeIndexMap[TI.toArrayIndex()];
536   return true;
537 }
538 
539 static void remapTypesInSymbolRecord(ObjFile *File, SymbolKind SymKind,
540                                      MutableArrayRef<uint8_t> Contents,
541                                      const CVIndexMap &IndexMap,
542                                      ArrayRef<TiReference> TypeRefs) {
543   for (const TiReference &Ref : TypeRefs) {
544     unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
545     if (Contents.size() < Ref.Offset + ByteSize)
546       fatal("symbol record too short");
547 
548     // This can be an item index or a type index. Choose the appropriate map.
549     ArrayRef<TypeIndex> TypeOrItemMap = IndexMap.TPIMap;
550     bool IsItemIndex = Ref.Kind == TiRefKind::IndexRef;
551     if (IsItemIndex && IndexMap.IsTypeServerMap)
552       TypeOrItemMap = IndexMap.IPIMap;
553 
554     MutableArrayRef<TypeIndex> TIs(
555         reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
556     for (TypeIndex &TI : TIs) {
557       if (!remapTypeIndex(TI, TypeOrItemMap)) {
558         log("ignoring symbol record of kind 0x" + utohexstr(SymKind) + " in " +
559             File->getName() + " with bad " + (IsItemIndex ? "item" : "type") +
560             " index 0x" + utohexstr(TI.getIndex()));
561         TI = TypeIndex(SimpleTypeKind::NotTranslated);
562         continue;
563       }
564     }
565   }
566 }
567 
568 static void
569 recordStringTableReferenceAtOffset(MutableArrayRef<uint8_t> Contents,
570                                    uint32_t Offset,
571                                    std::vector<ulittle32_t *> &StrTableRefs) {
572   Contents =
573       Contents.drop_front(Offset).take_front(sizeof(support::ulittle32_t));
574   ulittle32_t *Index = reinterpret_cast<ulittle32_t *>(Contents.data());
575   StrTableRefs.push_back(Index);
576 }
577 
578 static void
579 recordStringTableReferences(SymbolKind Kind, MutableArrayRef<uint8_t> Contents,
580                             std::vector<ulittle32_t *> &StrTableRefs) {
581   // For now we only handle S_FILESTATIC, but we may need the same logic for
582   // S_DEFRANGE and S_DEFRANGE_SUBFIELD.  However, I cannot seem to generate any
583   // PDBs that contain these types of records, so because of the uncertainty
584   // they are omitted here until we can prove that it's necessary.
585   switch (Kind) {
586   case SymbolKind::S_FILESTATIC:
587     // FileStaticSym::ModFileOffset
588     recordStringTableReferenceAtOffset(Contents, 4, StrTableRefs);
589     break;
590   case SymbolKind::S_DEFRANGE:
591   case SymbolKind::S_DEFRANGE_SUBFIELD:
592     log("Not fixing up string table reference in S_DEFRANGE / "
593         "S_DEFRANGE_SUBFIELD record");
594     break;
595   default:
596     break;
597   }
598 }
599 
600 static SymbolKind symbolKind(ArrayRef<uint8_t> RecordData) {
601   const RecordPrefix *Prefix =
602       reinterpret_cast<const RecordPrefix *>(RecordData.data());
603   return static_cast<SymbolKind>(uint16_t(Prefix->RecordKind));
604 }
605 
606 /// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
607 static void translateIdSymbols(MutableArrayRef<uint8_t> &RecordData,
608                                TypeCollection &IDTable) {
609   RecordPrefix *Prefix = reinterpret_cast<RecordPrefix *>(RecordData.data());
610 
611   SymbolKind Kind = symbolKind(RecordData);
612 
613   if (Kind == SymbolKind::S_PROC_ID_END) {
614     Prefix->RecordKind = SymbolKind::S_END;
615     return;
616   }
617 
618   // In an object file, GPROC32_ID has an embedded reference which refers to the
619   // single object file type index namespace.  This has already been translated
620   // to the PDB file's ID stream index space, but we need to convert this to a
621   // symbol that refers to the type stream index space.  So we remap again from
622   // ID index space to type index space.
623   if (Kind == SymbolKind::S_GPROC32_ID || Kind == SymbolKind::S_LPROC32_ID) {
624     SmallVector<TiReference, 1> Refs;
625     auto Content = RecordData.drop_front(sizeof(RecordPrefix));
626     CVSymbol Sym(Kind, RecordData);
627     discoverTypeIndicesInSymbol(Sym, Refs);
628     assert(Refs.size() == 1);
629     assert(Refs.front().Count == 1);
630 
631     TypeIndex *TI =
632         reinterpret_cast<TypeIndex *>(Content.data() + Refs[0].Offset);
633     // `TI` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
634     // the IPI stream, whose `FunctionType` member refers to the TPI stream.
635     // Note that LF_FUNC_ID and LF_MEMFUNC_ID have the same record layout, and
636     // in both cases we just need the second type index.
637     if (!TI->isSimple() && !TI->isNoneType()) {
638       CVType FuncIdData = IDTable.getType(*TI);
639       SmallVector<TypeIndex, 2> Indices;
640       discoverTypeIndices(FuncIdData, Indices);
641       assert(Indices.size() == 2);
642       *TI = Indices[1];
643     }
644 
645     Kind = (Kind == SymbolKind::S_GPROC32_ID) ? SymbolKind::S_GPROC32
646                                               : SymbolKind::S_LPROC32;
647     Prefix->RecordKind = uint16_t(Kind);
648   }
649 }
650 
651 /// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
652 /// The object file may not be aligned.
653 static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
654                                                  BumpPtrAllocator &Alloc) {
655   size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
656   assert(Size >= 4 && "record too short");
657   assert(Size <= MaxRecordLength && "record too long");
658   void *Mem = Alloc.Allocate(Size, 4);
659 
660   // Copy the symbol record and zero out any padding bytes.
661   MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
662   memcpy(NewData.data(), Sym.data().data(), Sym.length());
663   memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
664 
665   // Update the record prefix length. It should point to the beginning of the
666   // next record.
667   auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
668   Prefix->RecordLen = Size - 2;
669   return NewData;
670 }
671 
672 /// Return true if this symbol opens a scope. This implies that the symbol has
673 /// "parent" and "end" fields, which contain the offset of the S_END or
674 /// S_INLINESITE_END record.
675 static bool symbolOpensScope(SymbolKind Kind) {
676   switch (Kind) {
677   case SymbolKind::S_GPROC32:
678   case SymbolKind::S_LPROC32:
679   case SymbolKind::S_LPROC32_ID:
680   case SymbolKind::S_GPROC32_ID:
681   case SymbolKind::S_BLOCK32:
682   case SymbolKind::S_SEPCODE:
683   case SymbolKind::S_THUNK32:
684   case SymbolKind::S_INLINESITE:
685   case SymbolKind::S_INLINESITE2:
686     return true;
687   default:
688     break;
689   }
690   return false;
691 }
692 
693 static bool symbolEndsScope(SymbolKind Kind) {
694   switch (Kind) {
695   case SymbolKind::S_END:
696   case SymbolKind::S_PROC_ID_END:
697   case SymbolKind::S_INLINESITE_END:
698     return true;
699   default:
700     break;
701   }
702   return false;
703 }
704 
705 struct ScopeRecord {
706   ulittle32_t PtrParent;
707   ulittle32_t PtrEnd;
708 };
709 
710 struct SymbolScope {
711   ScopeRecord *OpeningRecord;
712   uint32_t ScopeOffset;
713 };
714 
715 static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
716                            uint32_t CurOffset, CVSymbol &Sym) {
717   assert(symbolOpensScope(Sym.kind()));
718   SymbolScope S;
719   S.ScopeOffset = CurOffset;
720   S.OpeningRecord = const_cast<ScopeRecord *>(
721       reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
722   S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
723   Stack.push_back(S);
724 }
725 
726 static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
727                             uint32_t CurOffset, ObjFile *File) {
728   if (Stack.empty()) {
729     warn("symbol scopes are not balanced in " + File->getName());
730     return;
731   }
732   SymbolScope S = Stack.pop_back_val();
733   S.OpeningRecord->PtrEnd = CurOffset;
734 }
735 
736 static bool symbolGoesInModuleStream(const CVSymbol &Sym) {
737   switch (Sym.kind()) {
738   case SymbolKind::S_GDATA32:
739   case SymbolKind::S_CONSTANT:
740   case SymbolKind::S_UDT:
741   // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
742   // since they are synthesized by the linker in response to S_GPROC32 and
743   // S_LPROC32, but if we do see them, don't put them in the module stream I
744   // guess.
745   case SymbolKind::S_PROCREF:
746   case SymbolKind::S_LPROCREF:
747     return false;
748   // S_GDATA32 does not go in the module stream, but S_LDATA32 does.
749   case SymbolKind::S_LDATA32:
750   default:
751     return true;
752   }
753 }
754 
755 static bool symbolGoesInGlobalsStream(const CVSymbol &Sym) {
756   switch (Sym.kind()) {
757   case SymbolKind::S_CONSTANT:
758   case SymbolKind::S_GDATA32:
759   // S_LDATA32 goes in both the module stream and the globals stream.
760   case SymbolKind::S_LDATA32:
761   case SymbolKind::S_GPROC32:
762   case SymbolKind::S_LPROC32:
763   // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
764   // since they are synthesized by the linker in response to S_GPROC32 and
765   // S_LPROC32, but if we do see them, copy them straight through.
766   case SymbolKind::S_PROCREF:
767   case SymbolKind::S_LPROCREF:
768     return true;
769   // FIXME: For now, we drop all S_UDT symbols (i.e. they don't go in the
770   // globals stream or the modules stream).  These have special handling which
771   // needs more investigation before we can get right, but by putting them all
772   // into the globals stream WinDbg fails to display local variables of class
773   // types saying that it cannot find the type Foo *.  So as a stopgap just to
774   // keep things working, we drop them.
775   case SymbolKind::S_UDT:
776   default:
777     return false;
778   }
779 }
780 
781 static void addGlobalSymbol(pdb::GSIStreamBuilder &Builder, ObjFile &File,
782                             const CVSymbol &Sym) {
783   switch (Sym.kind()) {
784   case SymbolKind::S_CONSTANT:
785   case SymbolKind::S_UDT:
786   case SymbolKind::S_GDATA32:
787   case SymbolKind::S_LDATA32:
788   case SymbolKind::S_PROCREF:
789   case SymbolKind::S_LPROCREF:
790     Builder.addGlobalSymbol(Sym);
791     break;
792   case SymbolKind::S_GPROC32:
793   case SymbolKind::S_LPROC32: {
794     SymbolRecordKind K = SymbolRecordKind::ProcRefSym;
795     if (Sym.kind() == SymbolKind::S_LPROC32)
796       K = SymbolRecordKind::LocalProcRef;
797     ProcRefSym PS(K);
798     PS.Module = static_cast<uint16_t>(File.ModuleDBI->getModuleIndex());
799     // For some reason, MSVC seems to add one to this value.
800     ++PS.Module;
801     PS.Name = getSymbolName(Sym);
802     PS.SumName = 0;
803     PS.SymOffset = File.ModuleDBI->getNextSymbolOffset();
804     Builder.addGlobalSymbol(PS);
805     break;
806   }
807   default:
808     llvm_unreachable("Invalid symbol kind!");
809   }
810 }
811 
812 static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjFile *File,
813                                pdb::GSIStreamBuilder &GsiBuilder,
814                                const CVIndexMap &IndexMap,
815                                TypeCollection &IDTable,
816                                std::vector<ulittle32_t *> &StringTableRefs,
817                                BinaryStreamRef SymData) {
818   // FIXME: Improve error recovery by warning and skipping records when
819   // possible.
820   ArrayRef<uint8_t> SymsBuffer;
821   cantFail(SymData.readBytes(0, SymData.getLength(), SymsBuffer));
822   SmallVector<SymbolScope, 4> Scopes;
823 
824   auto EC = forEachCodeViewRecord<CVSymbol>(
825       SymsBuffer, [&](const CVSymbol &Sym) -> llvm::Error {
826         // Discover type index references in the record. Skip it if we don't
827         // know where they are.
828         SmallVector<TiReference, 32> TypeRefs;
829         if (!discoverTypeIndicesInSymbol(Sym, TypeRefs)) {
830           log("ignoring unknown symbol record with kind 0x" +
831               utohexstr(Sym.kind()));
832           return Error::success();
833         }
834 
835         // Copy the symbol record so we can mutate it.
836         MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
837 
838         // Re-map all the type index references.
839         MutableArrayRef<uint8_t> Contents =
840             NewData.drop_front(sizeof(RecordPrefix));
841         remapTypesInSymbolRecord(File, Sym.kind(), Contents, IndexMap,
842                                  TypeRefs);
843 
844         // An object file may have S_xxx_ID symbols, but these get converted to
845         // "real" symbols in a PDB.
846         translateIdSymbols(NewData, IDTable);
847 
848         // If this record refers to an offset in the object file's string table,
849         // add that item to the global PDB string table and re-write the index.
850         recordStringTableReferences(Sym.kind(), Contents, StringTableRefs);
851 
852         SymbolKind NewKind = symbolKind(NewData);
853 
854         // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
855         CVSymbol NewSym(NewKind, NewData);
856         if (symbolOpensScope(NewKind))
857           scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(),
858                          NewSym);
859         else if (symbolEndsScope(NewKind))
860           scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
861 
862         // Add the symbol to the globals stream if necessary.  Do this before
863         // adding the symbol to the module since we may need to get the next
864         // symbol offset, and writing to the module's symbol stream will update
865         // that offset.
866         if (symbolGoesInGlobalsStream(NewSym))
867           addGlobalSymbol(GsiBuilder, *File, NewSym);
868 
869         // Add the symbol to the module.
870         if (symbolGoesInModuleStream(NewSym))
871           File->ModuleDBI->addSymbol(NewSym);
872         return Error::success();
873       });
874   cantFail(std::move(EC));
875 }
876 
877 // Allocate memory for a .debug$S / .debug$F section and relocate it.
878 static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
879                                             SectionChunk &DebugChunk) {
880   uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk.getSize());
881   assert(DebugChunk.OutputSectionOff == 0 &&
882          "debug sections should not be in output sections");
883   DebugChunk.readRelocTargets();
884   DebugChunk.writeTo(Buffer);
885   return makeArrayRef(Buffer, DebugChunk.getSize());
886 }
887 
888 static pdb::SectionContrib createSectionContrib(const Chunk *C, uint32_t Modi) {
889   OutputSection *OS = C->getOutputSection();
890   pdb::SectionContrib SC;
891   memset(&SC, 0, sizeof(SC));
892   SC.ISect = OS->SectionIndex;
893   SC.Off = C->getRVA() - OS->getRVA();
894   SC.Size = C->getSize();
895   if (auto *SecChunk = dyn_cast<SectionChunk>(C)) {
896     SC.Characteristics = SecChunk->Header->Characteristics;
897     SC.Imod = SecChunk->File->ModuleDBI->getModuleIndex();
898     ArrayRef<uint8_t> Contents = SecChunk->getContents();
899     JamCRC CRC(0);
900     ArrayRef<char> CharContents = makeArrayRef(
901         reinterpret_cast<const char *>(Contents.data()), Contents.size());
902     CRC.update(CharContents);
903     SC.DataCrc = CRC.getCRC();
904   } else {
905     SC.Characteristics = OS->Header.Characteristics;
906     // FIXME: When we start creating DBI for import libraries, use those here.
907     SC.Imod = Modi;
908   }
909   SC.RelocCrc = 0; // FIXME
910 
911   return SC;
912 }
913 
914 static uint32_t
915 translateStringTableIndex(uint32_t ObjIndex,
916                           const DebugStringTableSubsectionRef &ObjStrTable,
917                           DebugStringTableSubsection &PdbStrTable) {
918   auto ExpectedString = ObjStrTable.getString(ObjIndex);
919   if (!ExpectedString) {
920     warn("Invalid string table reference");
921     consumeError(ExpectedString.takeError());
922     return 0;
923   }
924 
925   return PdbStrTable.insert(*ExpectedString);
926 }
927 
928 void DebugSHandler::handleDebugS(lld::coff::SectionChunk &DebugS) {
929   DebugSubsectionArray Subsections;
930 
931   ArrayRef<uint8_t> RelocatedDebugContents = consumeDebugMagic(
932       relocateDebugChunk(Linker.Alloc, DebugS), DebugS.getSectionName());
933 
934   BinaryStreamReader Reader(RelocatedDebugContents, support::little);
935   ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
936 
937   for (const DebugSubsectionRecord &SS : Subsections) {
938     switch (SS.kind()) {
939     case DebugSubsectionKind::StringTable: {
940       assert(!CVStrTab.valid() &&
941              "Encountered multiple string table subsections!");
942       ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
943       break;
944     }
945     case DebugSubsectionKind::FileChecksums:
946       assert(!Checksums.valid() &&
947              "Encountered multiple checksum subsections!");
948       ExitOnErr(Checksums.initialize(SS.getRecordData()));
949       break;
950     case DebugSubsectionKind::Lines:
951       // We can add the relocated line table directly to the PDB without
952       // modification because the file checksum offsets will stay the same.
953       File.ModuleDBI->addDebugSubsection(SS);
954       break;
955     case DebugSubsectionKind::FrameData: {
956       // We need to re-write string table indices here, so save off all
957       // frame data subsections until we've processed the entire list of
958       // subsections so that we can be sure we have the string table.
959       DebugFrameDataSubsectionRef FDS;
960       ExitOnErr(FDS.initialize(SS.getRecordData()));
961       NewFpoFrames.push_back(std::move(FDS));
962       break;
963     }
964     case DebugSubsectionKind::Symbols:
965       if (Config->DebugGHashes) {
966         mergeSymbolRecords(Linker.Alloc, &File, Linker.Builder.getGsiBuilder(),
967                            IndexMap, Linker.GlobalIDTable,
968                            StringTableReferences, SS.getRecordData());
969       } else {
970         mergeSymbolRecords(Linker.Alloc, &File, Linker.Builder.getGsiBuilder(),
971                            IndexMap, Linker.IDTable, StringTableReferences,
972                            SS.getRecordData());
973       }
974       break;
975     default:
976       // FIXME: Process the rest of the subsections.
977       break;
978     }
979   }
980 }
981 
982 void DebugSHandler::finish() {
983   pdb::DbiStreamBuilder &DbiBuilder = Linker.Builder.getDbiBuilder();
984 
985   // We should have seen all debug subsections across the entire object file now
986   // which means that if a StringTable subsection and Checksums subsection were
987   // present, now is the time to handle them.
988   if (!CVStrTab.valid()) {
989     if (Checksums.valid())
990       fatal(".debug$S sections with a checksums subsection must also contain a "
991             "string table subsection");
992 
993     if (!StringTableReferences.empty())
994       warn("No StringTable subsection was encountered, but there are string "
995            "table references");
996     return;
997   }
998 
999   // Rewrite string table indices in the Fpo Data and symbol records to refer to
1000   // the global PDB string table instead of the object file string table.
1001   for (DebugFrameDataSubsectionRef &FDS : NewFpoFrames) {
1002     const uint32_t *Reloc = FDS.getRelocPtr();
1003     for (codeview::FrameData FD : FDS) {
1004       FD.RvaStart += *Reloc;
1005       FD.FrameFunc =
1006           translateStringTableIndex(FD.FrameFunc, CVStrTab, Linker.PDBStrTab);
1007       DbiBuilder.addNewFpoData(FD);
1008     }
1009   }
1010 
1011   for (ulittle32_t *Ref : StringTableReferences)
1012     *Ref = translateStringTableIndex(*Ref, CVStrTab, Linker.PDBStrTab);
1013 
1014   // Make a new file checksum table that refers to offsets in the PDB-wide
1015   // string table. Generally the string table subsection appears after the
1016   // checksum table, so we have to do this after looping over all the
1017   // subsections.
1018   auto NewChecksums = make_unique<DebugChecksumsSubsection>(Linker.PDBStrTab);
1019   for (FileChecksumEntry &FC : Checksums) {
1020     SmallString<128> FileName =
1021         ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
1022     pdbMakeAbsolute(FileName);
1023     ExitOnErr(Linker.Builder.getDbiBuilder().addModuleSourceFile(
1024         *File.ModuleDBI, FileName));
1025     NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
1026   }
1027   File.ModuleDBI->addDebugSubsection(std::move(NewChecksums));
1028 }
1029 
1030 void PDBLinker::addObjFile(ObjFile *File) {
1031   // Add a module descriptor for every object file. We need to put an absolute
1032   // path to the object into the PDB. If this is a plain object, we make its
1033   // path absolute. If it's an object in an archive, we make the archive path
1034   // absolute.
1035   bool InArchive = !File->ParentName.empty();
1036   SmallString<128> Path = InArchive ? File->ParentName : File->getName();
1037   pdbMakeAbsolute(Path);
1038   StringRef Name = InArchive ? File->getName() : StringRef(Path);
1039 
1040   pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
1041   File->ModuleDBI = &ExitOnErr(DbiBuilder.addModuleInfo(Name));
1042   File->ModuleDBI->setObjFileName(Path);
1043 
1044   auto Chunks = File->getChunks();
1045   uint32_t Modi = File->ModuleDBI->getModuleIndex();
1046   for (Chunk *C : Chunks) {
1047     auto *SecChunk = dyn_cast<SectionChunk>(C);
1048     if (!SecChunk || !SecChunk->Live)
1049       continue;
1050     pdb::SectionContrib SC = createSectionContrib(SecChunk, Modi);
1051     File->ModuleDBI->setFirstSectionContrib(SC);
1052     break;
1053   }
1054 
1055   // Before we can process symbol substreams from .debug$S, we need to process
1056   // type information, file checksums, and the string table.  Add type info to
1057   // the PDB first, so that we can get the map from object file type and item
1058   // indices to PDB type and item indices.
1059   CVIndexMap ObjectIndexMap;
1060   auto IndexMapResult = mergeDebugT(File, ObjectIndexMap);
1061 
1062   // If the .debug$T sections fail to merge, assume there is no debug info.
1063   if (!IndexMapResult) {
1064     auto FileName = sys::path::filename(Path);
1065     warn("Cannot use debug info for '" + FileName + "'\n" +
1066          ">>> failed to load reference " +
1067          StringRef(toString(IndexMapResult.takeError())));
1068     return;
1069   }
1070 
1071   ScopedTimer T(SymbolMergingTimer);
1072 
1073   DebugSHandler DSH(*this, *File, *IndexMapResult);
1074   // Now do all live .debug$S and .debug$F sections.
1075   for (SectionChunk *DebugChunk : File->getDebugChunks()) {
1076     if (!DebugChunk->Live || DebugChunk->getSize() == 0)
1077       continue;
1078 
1079     if (DebugChunk->getSectionName() == ".debug$S") {
1080       DSH.handleDebugS(*DebugChunk);
1081       continue;
1082     }
1083 
1084     if (DebugChunk->getSectionName() == ".debug$F") {
1085       ArrayRef<uint8_t> RelocatedDebugContents =
1086           relocateDebugChunk(Alloc, *DebugChunk);
1087 
1088       FixedStreamArray<object::FpoData> FpoRecords;
1089       BinaryStreamReader Reader(RelocatedDebugContents, support::little);
1090       uint32_t Count = RelocatedDebugContents.size() / sizeof(object::FpoData);
1091       ExitOnErr(Reader.readArray(FpoRecords, Count));
1092 
1093       // These are already relocated and don't refer to the string table, so we
1094       // can just copy it.
1095       for (const object::FpoData &FD : FpoRecords)
1096         DbiBuilder.addOldFpoData(FD);
1097       continue;
1098     }
1099   }
1100 
1101   // Do any post-processing now that all .debug$S sections have been processed.
1102   DSH.finish();
1103 }
1104 
1105 static PublicSym32 createPublic(Defined *Def) {
1106   PublicSym32 Pub(SymbolKind::S_PUB32);
1107   Pub.Name = Def->getName();
1108   if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
1109     if (D->getCOFFSymbol().isFunctionDefinition())
1110       Pub.Flags = PublicSymFlags::Function;
1111   } else if (isa<DefinedImportThunk>(Def)) {
1112     Pub.Flags = PublicSymFlags::Function;
1113   }
1114 
1115   OutputSection *OS = Def->getChunk()->getOutputSection();
1116   assert(OS && "all publics should be in final image");
1117   Pub.Offset = Def->getRVA() - OS->getRVA();
1118   Pub.Segment = OS->SectionIndex;
1119   return Pub;
1120 }
1121 
1122 // Add all object files to the PDB. Merge .debug$T sections into IpiData and
1123 // TpiData.
1124 void PDBLinker::addObjectsToPDB() {
1125   ScopedTimer T1(AddObjectsTimer);
1126   for (ObjFile *File : ObjFile::Instances)
1127     addObjFile(File);
1128 
1129   Builder.getStringTableBuilder().setStrings(PDBStrTab);
1130   T1.stop();
1131 
1132   // Construct TPI and IPI stream contents.
1133   ScopedTimer T2(TpiStreamLayoutTimer);
1134   if (Config->DebugGHashes) {
1135     addTypeInfo(Builder.getTpiBuilder(), GlobalTypeTable);
1136     addTypeInfo(Builder.getIpiBuilder(), GlobalIDTable);
1137   } else {
1138     addTypeInfo(Builder.getTpiBuilder(), TypeTable);
1139     addTypeInfo(Builder.getIpiBuilder(), IDTable);
1140   }
1141   T2.stop();
1142 
1143   ScopedTimer T3(GlobalsLayoutTimer);
1144   // Compute the public and global symbols.
1145   auto &GsiBuilder = Builder.getGsiBuilder();
1146   std::vector<PublicSym32> Publics;
1147   Symtab->forEachSymbol([&Publics](Symbol *S) {
1148     // Only emit defined, live symbols that have a chunk.
1149     auto *Def = dyn_cast<Defined>(S);
1150     if (Def && Def->isLive() && Def->getChunk())
1151       Publics.push_back(createPublic(Def));
1152   });
1153 
1154   if (!Publics.empty()) {
1155     // Sort the public symbols and add them to the stream.
1156     std::sort(Publics.begin(), Publics.end(),
1157               [](const PublicSym32 &L, const PublicSym32 &R) {
1158                 return L.Name < R.Name;
1159               });
1160     for (const PublicSym32 &Pub : Publics)
1161       GsiBuilder.addPublicSymbol(Pub);
1162   }
1163 }
1164 
1165 void PDBLinker::addNatvisFiles() {
1166   for (StringRef File : Config->NatvisFiles) {
1167     ErrorOr<std::unique_ptr<MemoryBuffer>> DataOrErr =
1168         MemoryBuffer::getFile(File);
1169     if (!DataOrErr) {
1170       warn("Cannot open input file: " + File);
1171       continue;
1172     }
1173     Builder.addInjectedSource(File, std::move(*DataOrErr));
1174   }
1175 }
1176 
1177 static codeview::CPUType toCodeViewMachine(COFF::MachineTypes Machine) {
1178   switch (Machine) {
1179   case COFF::IMAGE_FILE_MACHINE_AMD64:
1180     return codeview::CPUType::X64;
1181   case COFF::IMAGE_FILE_MACHINE_ARM:
1182     return codeview::CPUType::ARM7;
1183   case COFF::IMAGE_FILE_MACHINE_ARM64:
1184     return codeview::CPUType::ARM64;
1185   case COFF::IMAGE_FILE_MACHINE_ARMNT:
1186     return codeview::CPUType::ARMNT;
1187   case COFF::IMAGE_FILE_MACHINE_I386:
1188     return codeview::CPUType::Intel80386;
1189   default:
1190     llvm_unreachable("Unsupported CPU Type");
1191   }
1192 }
1193 
1194 static void addCommonLinkerModuleSymbols(StringRef Path,
1195                                          pdb::DbiModuleDescriptorBuilder &Mod,
1196                                          BumpPtrAllocator &Allocator) {
1197   ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
1198   Compile3Sym CS(SymbolRecordKind::Compile3Sym);
1199   EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
1200 
1201   ONS.Name = "* Linker *";
1202   ONS.Signature = 0;
1203 
1204   CS.Machine = toCodeViewMachine(Config->Machine);
1205   // Interestingly, if we set the string to 0.0.0.0, then when trying to view
1206   // local variables WinDbg emits an error that private symbols are not present.
1207   // By setting this to a valid MSVC linker version string, local variables are
1208   // displayed properly.   As such, even though it is not representative of
1209   // LLVM's version information, we need this for compatibility.
1210   CS.Flags = CompileSym3Flags::None;
1211   CS.VersionBackendBuild = 25019;
1212   CS.VersionBackendMajor = 14;
1213   CS.VersionBackendMinor = 10;
1214   CS.VersionBackendQFE = 0;
1215 
1216   // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
1217   // linker module (which is by definition a backend), so we don't need to do
1218   // anything here.  Also, it seems we can use "LLVM Linker" for the linker name
1219   // without any problems.  Only the backend version has to be hardcoded to a
1220   // magic number.
1221   CS.VersionFrontendBuild = 0;
1222   CS.VersionFrontendMajor = 0;
1223   CS.VersionFrontendMinor = 0;
1224   CS.VersionFrontendQFE = 0;
1225   CS.Version = "LLVM Linker";
1226   CS.setLanguage(SourceLanguage::Link);
1227 
1228   ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
1229   std::string ArgStr = llvm::join(Args, " ");
1230   EBS.Fields.push_back("cwd");
1231   SmallString<64> cwd;
1232   if (Config->PDBSourcePath.empty())
1233     sys::fs::current_path(cwd);
1234   else
1235     cwd = Config->PDBSourcePath;
1236   EBS.Fields.push_back(cwd);
1237   EBS.Fields.push_back("exe");
1238   SmallString<64> exe = Config->Argv[0];
1239   pdbMakeAbsolute(exe);
1240   EBS.Fields.push_back(exe);
1241   EBS.Fields.push_back("pdb");
1242   EBS.Fields.push_back(Path);
1243   EBS.Fields.push_back("cmd");
1244   EBS.Fields.push_back(ArgStr);
1245   Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1246       ONS, Allocator, CodeViewContainer::Pdb));
1247   Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1248       CS, Allocator, CodeViewContainer::Pdb));
1249   Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1250       EBS, Allocator, CodeViewContainer::Pdb));
1251 }
1252 
1253 static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &Mod,
1254                                          OutputSection &OS,
1255                                          BumpPtrAllocator &Allocator) {
1256   SectionSym Sym(SymbolRecordKind::SectionSym);
1257   Sym.Alignment = 12; // 2^12 = 4KB
1258   Sym.Characteristics = OS.Header.Characteristics;
1259   Sym.Length = OS.getVirtualSize();
1260   Sym.Name = OS.Name;
1261   Sym.Rva = OS.getRVA();
1262   Sym.SectionNumber = OS.SectionIndex;
1263   Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1264       Sym, Allocator, CodeViewContainer::Pdb));
1265 }
1266 
1267 // Creates a PDB file.
1268 void coff::createPDB(SymbolTable *Symtab,
1269                      ArrayRef<OutputSection *> OutputSections,
1270                      ArrayRef<uint8_t> SectionTable,
1271                      llvm::codeview::DebugInfo *BuildId) {
1272   ScopedTimer T1(TotalPdbLinkTimer);
1273   PDBLinker PDB(Symtab);
1274 
1275   PDB.initialize(BuildId);
1276   PDB.addObjectsToPDB();
1277   PDB.addSections(OutputSections, SectionTable);
1278   PDB.addNatvisFiles();
1279 
1280   ScopedTimer T2(DiskCommitTimer);
1281   codeview::GUID Guid;
1282   PDB.commit(&Guid);
1283   memcpy(&BuildId->PDB70.Signature, &Guid, 16);
1284 }
1285 
1286 void PDBLinker::initialize(llvm::codeview::DebugInfo *BuildId) {
1287   ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
1288 
1289   BuildId->Signature.CVSignature = OMF::Signature::PDB70;
1290   // Signature is set to a hash of the PDB contents when the PDB is done.
1291   memset(BuildId->PDB70.Signature, 0, 16);
1292   BuildId->PDB70.Age = 1;
1293 
1294   // Create streams in MSF for predefined streams, namely
1295   // PDB, TPI, DBI and IPI.
1296   for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
1297     ExitOnErr(Builder.getMsfBuilder().addStream(0));
1298 
1299   // Add an Info stream.
1300   auto &InfoBuilder = Builder.getInfoBuilder();
1301   InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
1302   InfoBuilder.setHashPDBContentsToGUID(true);
1303 
1304   // Add an empty DBI stream.
1305   pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
1306   DbiBuilder.setAge(BuildId->PDB70.Age);
1307   DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
1308   DbiBuilder.setMachineType(Config->Machine);
1309   // Technically we are not link.exe 14.11, but there are known cases where
1310   // debugging tools on Windows expect Microsoft-specific version numbers or
1311   // they fail to work at all.  Since we know we produce PDBs that are
1312   // compatible with LINK 14.11, we set that version number here.
1313   DbiBuilder.setBuildNumber(14, 11);
1314 }
1315 
1316 void PDBLinker::addSections(ArrayRef<OutputSection *> OutputSections,
1317                             ArrayRef<uint8_t> SectionTable) {
1318   // It's not entirely clear what this is, but the * Linker * module uses it.
1319   pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
1320   NativePath = Config->PDBPath;
1321   pdbMakeAbsolute(NativePath);
1322   uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
1323   auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
1324   LinkerModule.setPdbFilePathNI(PdbFilePathNI);
1325   addCommonLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
1326 
1327   // Add section contributions. They must be ordered by ascending RVA.
1328   for (OutputSection *OS : OutputSections) {
1329     addLinkerModuleSectionSymbol(LinkerModule, *OS, Alloc);
1330     for (Chunk *C : OS->Chunks) {
1331       pdb::SectionContrib SC =
1332           createSectionContrib(C, LinkerModule.getModuleIndex());
1333       Builder.getDbiBuilder().addSectionContrib(SC);
1334     }
1335   }
1336 
1337   // Add Section Map stream.
1338   ArrayRef<object::coff_section> Sections = {
1339       (const object::coff_section *)SectionTable.data(),
1340       SectionTable.size() / sizeof(object::coff_section)};
1341   SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
1342   DbiBuilder.setSectionMap(SectionMap);
1343 
1344   // Add COFF section header stream.
1345   ExitOnErr(
1346       DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
1347 }
1348 
1349 void PDBLinker::commit(codeview::GUID *Guid) {
1350   // Write to a file.
1351   ExitOnErr(Builder.commit(Config->PDBPath, Guid));
1352 }
1353 
1354 static Expected<StringRef>
1355 getFileName(const DebugStringTableSubsectionRef &Strings,
1356             const DebugChecksumsSubsectionRef &Checksums, uint32_t FileID) {
1357   auto Iter = Checksums.getArray().at(FileID);
1358   if (Iter == Checksums.getArray().end())
1359     return make_error<CodeViewError>(cv_error_code::no_records);
1360   uint32_t Offset = Iter->FileNameOffset;
1361   return Strings.getString(Offset);
1362 }
1363 
1364 static uint32_t getSecrelReloc() {
1365   switch (Config->Machine) {
1366   case AMD64:
1367     return COFF::IMAGE_REL_AMD64_SECREL;
1368   case I386:
1369     return COFF::IMAGE_REL_I386_SECREL;
1370   case ARMNT:
1371     return COFF::IMAGE_REL_ARM_SECREL;
1372   case ARM64:
1373     return COFF::IMAGE_REL_ARM64_SECREL;
1374   default:
1375     llvm_unreachable("unknown machine type");
1376   }
1377 }
1378 
1379 // Try to find a line table for the given offset Addr into the given chunk C.
1380 // If a line table was found, the line table, the string and checksum tables
1381 // that are used to interpret the line table, and the offset of Addr in the line
1382 // table are stored in the output arguments. Returns whether a line table was
1383 // found.
1384 static bool findLineTable(const SectionChunk *C, uint32_t Addr,
1385                           DebugStringTableSubsectionRef &CVStrTab,
1386                           DebugChecksumsSubsectionRef &Checksums,
1387                           DebugLinesSubsectionRef &Lines,
1388                           uint32_t &OffsetInLinetable) {
1389   ExitOnError ExitOnErr;
1390   uint32_t SecrelReloc = getSecrelReloc();
1391 
1392   for (SectionChunk *DbgC : C->File->getDebugChunks()) {
1393     if (DbgC->getSectionName() != ".debug$S")
1394       continue;
1395 
1396     // Build a mapping of SECREL relocations in DbgC that refer to C.
1397     DenseMap<uint32_t, uint32_t> Secrels;
1398     for (const coff_relocation &R : DbgC->Relocs) {
1399       if (R.Type != SecrelReloc)
1400         continue;
1401 
1402       if (auto *S = dyn_cast_or_null<DefinedRegular>(
1403               C->File->getSymbols()[R.SymbolTableIndex]))
1404         if (S->getChunk() == C)
1405           Secrels[R.VirtualAddress] = S->getValue();
1406     }
1407 
1408     ArrayRef<uint8_t> Contents =
1409         consumeDebugMagic(DbgC->getContents(), ".debug$S");
1410     DebugSubsectionArray Subsections;
1411     BinaryStreamReader Reader(Contents, support::little);
1412     ExitOnErr(Reader.readArray(Subsections, Contents.size()));
1413 
1414     for (const DebugSubsectionRecord &SS : Subsections) {
1415       switch (SS.kind()) {
1416       case DebugSubsectionKind::StringTable: {
1417         assert(!CVStrTab.valid() &&
1418                "Encountered multiple string table subsections!");
1419         ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
1420         break;
1421       }
1422       case DebugSubsectionKind::FileChecksums:
1423         assert(!Checksums.valid() &&
1424                "Encountered multiple checksum subsections!");
1425         ExitOnErr(Checksums.initialize(SS.getRecordData()));
1426         break;
1427       case DebugSubsectionKind::Lines: {
1428         ArrayRef<uint8_t> Bytes;
1429         auto Ref = SS.getRecordData();
1430         ExitOnErr(Ref.readLongestContiguousChunk(0, Bytes));
1431         size_t OffsetInDbgC = Bytes.data() - DbgC->getContents().data();
1432 
1433         // Check whether this line table refers to C.
1434         auto I = Secrels.find(OffsetInDbgC);
1435         if (I == Secrels.end())
1436           break;
1437 
1438         // Check whether this line table covers Addr in C.
1439         DebugLinesSubsectionRef LinesTmp;
1440         ExitOnErr(LinesTmp.initialize(BinaryStreamReader(Ref)));
1441         uint32_t OffsetInC = I->second + LinesTmp.header()->RelocOffset;
1442         if (Addr < OffsetInC || Addr >= OffsetInC + LinesTmp.header()->CodeSize)
1443           break;
1444 
1445         assert(!Lines.header() &&
1446                "Encountered multiple line tables for function!");
1447         ExitOnErr(Lines.initialize(BinaryStreamReader(Ref)));
1448         OffsetInLinetable = Addr - OffsetInC;
1449         break;
1450       }
1451       default:
1452         break;
1453       }
1454 
1455       if (CVStrTab.valid() && Checksums.valid() && Lines.header())
1456         return true;
1457     }
1458   }
1459 
1460   return false;
1461 }
1462 
1463 // Use CodeView line tables to resolve a file and line number for the given
1464 // offset into the given chunk and return them, or {"", 0} if a line table was
1465 // not found.
1466 std::pair<StringRef, uint32_t> coff::getFileLine(const SectionChunk *C,
1467                                                  uint32_t Addr) {
1468   ExitOnError ExitOnErr;
1469 
1470   DebugStringTableSubsectionRef CVStrTab;
1471   DebugChecksumsSubsectionRef Checksums;
1472   DebugLinesSubsectionRef Lines;
1473   uint32_t OffsetInLinetable;
1474 
1475   if (!findLineTable(C, Addr, CVStrTab, Checksums, Lines, OffsetInLinetable))
1476     return {"", 0};
1477 
1478   uint32_t NameIndex;
1479   uint32_t LineNumber;
1480   for (LineColumnEntry &Entry : Lines) {
1481     for (const LineNumberEntry &LN : Entry.LineNumbers) {
1482       if (LN.Offset > OffsetInLinetable) {
1483         StringRef Filename =
1484             ExitOnErr(getFileName(CVStrTab, Checksums, NameIndex));
1485         return {Filename, LineNumber};
1486       }
1487       LineInfo LI(LN.Flags);
1488       NameIndex = Entry.NameIndex;
1489       LineNumber = LI.getStartLine();
1490     }
1491   }
1492   StringRef Filename = ExitOnErr(getFileName(CVStrTab, Checksums, NameIndex));
1493   return {Filename, LineNumber};
1494 }
1495