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