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