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