xref: /llvm-project-15.0.7/lld/COFF/PDB.cpp (revision e00799ea)
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/DebugSubsectionRecord.h"
20 #include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"
21 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
22 #include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
23 #include "llvm/DebugInfo/CodeView/RecordName.h"
24 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
25 #include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
26 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
27 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
28 #include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
29 #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
30 #include "llvm/DebugInfo/MSF/MSFBuilder.h"
31 #include "llvm/DebugInfo/MSF/MSFCommon.h"
32 #include "llvm/DebugInfo/PDB/GenericError.h"
33 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
34 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
35 #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
36 #include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h"
37 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
38 #include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
39 #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
40 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
41 #include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
42 #include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
43 #include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
44 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
45 #include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
46 #include "llvm/DebugInfo/PDB/PDB.h"
47 #include "llvm/Object/COFF.h"
48 #include "llvm/Object/CVDebugRecord.h"
49 #include "llvm/Support/BinaryByteStream.h"
50 #include "llvm/Support/Endian.h"
51 #include "llvm/Support/FormatVariadic.h"
52 #include "llvm/Support/JamCRC.h"
53 #include "llvm/Support/Path.h"
54 #include "llvm/Support/ScopedPrinter.h"
55 #include <memory>
56 
57 using namespace lld;
58 using namespace lld::coff;
59 using namespace llvm;
60 using namespace llvm::codeview;
61 
62 using llvm::object::coff_section;
63 
64 static ExitOnError ExitOnErr;
65 
66 static Timer TotalPdbLinkTimer("PDB Emission (Cumulative)", Timer::root());
67 
68 static Timer AddObjectsTimer("Add Objects", TotalPdbLinkTimer);
69 static Timer TypeMergingTimer("Type Merging", AddObjectsTimer);
70 static Timer SymbolMergingTimer("Symbol Merging", AddObjectsTimer);
71 static Timer GlobalsLayoutTimer("Globals Stream Layout", TotalPdbLinkTimer);
72 static Timer TpiStreamLayoutTimer("TPI Stream Layout", TotalPdbLinkTimer);
73 static Timer DiskCommitTimer("Commit to Disk", TotalPdbLinkTimer);
74 
75 namespace {
76 /// Map from type index and item index in a type server PDB to the
77 /// corresponding index in the destination PDB.
78 struct CVIndexMap {
79   SmallVector<TypeIndex, 0> TPIMap;
80   SmallVector<TypeIndex, 0> IPIMap;
81   bool IsTypeServerMap = false;
82 };
83 
84 class PDBLinker {
85 public:
86   PDBLinker(SymbolTable *Symtab)
87       : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
88         IDTable(Alloc), GlobalTypeTable(Alloc), GlobalIDTable(Alloc) {
89     // This isn't strictly necessary, but link.exe usually puts an empty string
90     // as the first "valid" string in the string table, so we do the same in
91     // order to maintain as much byte-for-byte compatibility as possible.
92     PDBStrTab.insert("");
93   }
94 
95   /// Emit the basic PDB structure: initial streams, headers, etc.
96   void initialize(const llvm::codeview::DebugInfo &BuildId);
97 
98   /// Add natvis files specified on the command line.
99   void addNatvisFiles();
100 
101   /// Link CodeView from each object file in the symbol table into the PDB.
102   void addObjectsToPDB();
103 
104   /// Link CodeView from a single object file into the PDB.
105   void addObjFile(ObjFile *File);
106 
107   /// Produce a mapping from the type and item indices used in the object
108   /// file to those in the destination PDB.
109   ///
110   /// If the object file uses a type server PDB (compiled with /Zi), merge TPI
111   /// and IPI from the type server PDB and return a map for it. Each unique type
112   /// server PDB is merged at most once, so this may return an existing index
113   /// mapping.
114   ///
115   /// If the object does not use a type server PDB (compiled with /Z7), we merge
116   /// all the type and item records from the .debug$S stream and fill in the
117   /// caller-provided ObjectIndexMap.
118   Expected<const CVIndexMap&> mergeDebugT(ObjFile *File,
119                                           CVIndexMap &ObjectIndexMap);
120 
121   Expected<const CVIndexMap&> maybeMergeTypeServerPDB(ObjFile *File,
122                                                       TypeServer2Record &TS);
123 
124   /// Add the section map and section contributions to the PDB.
125   void addSections(ArrayRef<OutputSection *> OutputSections,
126                    ArrayRef<uint8_t> SectionTable);
127 
128   void addSectionContrib(pdb::DbiModuleDescriptorBuilder &LinkerModule,
129                          OutputSection *OS, Chunk *C);
130 
131   /// Write the PDB to disk.
132   void commit();
133 
134 private:
135   BumpPtrAllocator Alloc;
136 
137   SymbolTable *Symtab;
138 
139   pdb::PDBFileBuilder Builder;
140 
141   /// Type records that will go into the PDB TPI stream.
142   MergingTypeTableBuilder TypeTable;
143 
144   /// Item records that will go into the PDB IPI stream.
145   MergingTypeTableBuilder IDTable;
146 
147   /// Type records that will go into the PDB TPI stream (for /DEBUG:GHASH)
148   GlobalTypeTableBuilder GlobalTypeTable;
149 
150   /// Item records that will go into the PDB IPI stream (for /DEBUG:GHASH)
151   GlobalTypeTableBuilder GlobalIDTable;
152 
153   /// PDBs use a single global string table for filenames in the file checksum
154   /// table.
155   DebugStringTableSubsection PDBStrTab;
156 
157   llvm::SmallString<128> NativePath;
158 
159   /// A list of other PDBs which are loaded during the linking process and which
160   /// we need to keep around since the linking operation may reference pointers
161   /// inside of these PDBs.
162   llvm::SmallVector<std::unique_ptr<pdb::NativeSession>, 2> LoadedPDBs;
163 
164   std::vector<pdb::SecMapEntry> SectionMap;
165 
166   /// Type index mappings of type server PDBs that we've loaded so far.
167   std::map<GUID, CVIndexMap> TypeServerIndexMappings;
168 
169   /// List of TypeServer PDBs which cannot be loaded.
170   /// Cached to prevent repeated load attempts.
171   std::set<GUID> MissingTypeServerPDBs;
172 };
173 }
174 
175 static SectionChunk *findByName(ArrayRef<SectionChunk *> Sections,
176                                 StringRef Name) {
177   for (SectionChunk *C : Sections)
178     if (C->getSectionName() == Name)
179       return C;
180   return nullptr;
181 }
182 
183 static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
184                                            StringRef SecName) {
185   // First 4 bytes are section magic.
186   if (Data.size() < 4)
187     fatal(SecName + " too short");
188   if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
189     fatal(SecName + " has an invalid magic");
190   return Data.slice(4);
191 }
192 
193 static ArrayRef<uint8_t> getDebugSection(ObjFile *File, StringRef SecName) {
194   if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
195     return consumeDebugMagic(Sec->getContents(), SecName);
196   return {};
197 }
198 
199 // A COFF .debug$H section is currently a clang extension.  This function checks
200 // if a .debug$H section is in a format that we expect / understand, so that we
201 // can ignore any sections which are coincidentally also named .debug$H but do
202 // not contain a format we recognize.
203 static bool canUseDebugH(ArrayRef<uint8_t> DebugH) {
204   if (DebugH.size() < sizeof(object::debug_h_header))
205     return false;
206   auto *Header =
207       reinterpret_cast<const object::debug_h_header *>(DebugH.data());
208   DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
209   return Header->Magic == COFF::DEBUG_HASHES_SECTION_MAGIC &&
210          Header->Version == 0 &&
211          Header->HashAlgorithm == uint16_t(GlobalTypeHashAlg::SHA1) &&
212          (DebugH.size() % 20 == 0);
213 }
214 
215 static Optional<ArrayRef<uint8_t>> getDebugH(ObjFile *File) {
216   SectionChunk *Sec = findByName(File->getDebugChunks(), ".debug$H");
217   if (!Sec)
218     return llvm::None;
219   ArrayRef<uint8_t> Contents = Sec->getContents();
220   if (!canUseDebugH(Contents))
221     return None;
222   return Contents;
223 }
224 
225 static ArrayRef<GloballyHashedType>
226 getHashesFromDebugH(ArrayRef<uint8_t> DebugH) {
227   assert(canUseDebugH(DebugH));
228 
229   DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
230   uint32_t Count = DebugH.size() / sizeof(GloballyHashedType);
231   return {reinterpret_cast<const GloballyHashedType *>(DebugH.data()), Count};
232 }
233 
234 static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
235                         TypeCollection &TypeTable) {
236   // Start the TPI or IPI stream header.
237   TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
238 
239   // Flatten the in memory type table and hash each type.
240   TypeTable.ForEachRecord([&](TypeIndex TI, const CVType &Type) {
241     auto Hash = pdb::hashTypeRecord(Type);
242     if (auto E = Hash.takeError())
243       fatal("type hashing error");
244     TpiBuilder.addTypeRecord(Type.RecordData, *Hash);
245   });
246 }
247 
248 static Optional<TypeServer2Record>
249 maybeReadTypeServerRecord(CVTypeArray &Types) {
250   auto I = Types.begin();
251   if (I == Types.end())
252     return None;
253   const CVType &Type = *I;
254   if (Type.kind() != LF_TYPESERVER2)
255     return None;
256   TypeServer2Record TS;
257   if (auto EC = TypeDeserializer::deserializeAs(const_cast<CVType &>(Type), TS))
258     fatal("error reading type server record: " + toString(std::move(EC)));
259   return std::move(TS);
260 }
261 
262 Expected<const CVIndexMap&> PDBLinker::mergeDebugT(ObjFile *File,
263                                                    CVIndexMap &ObjectIndexMap) {
264   ScopedTimer T(TypeMergingTimer);
265 
266   ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
267   if (Data.empty())
268     return ObjectIndexMap;
269 
270   BinaryByteStream Stream(Data, support::little);
271   CVTypeArray Types;
272   BinaryStreamReader Reader(Stream);
273   if (auto EC = Reader.readArray(Types, Reader.getLength()))
274     fatal("Reader::readArray failed: " + toString(std::move(EC)));
275 
276   // Look through type servers. If we've already seen this type server, don't
277   // merge any type information.
278   if (Optional<TypeServer2Record> TS = maybeReadTypeServerRecord(Types))
279     return maybeMergeTypeServerPDB(File, *TS);
280 
281   // This is a /Z7 object. Fill in the temporary, caller-provided
282   // ObjectIndexMap.
283   if (Config->DebugGHashes) {
284     ArrayRef<GloballyHashedType> Hashes;
285     std::vector<GloballyHashedType> OwnedHashes;
286     if (Optional<ArrayRef<uint8_t>> DebugH = getDebugH(File))
287       Hashes = getHashesFromDebugH(*DebugH);
288     else {
289       OwnedHashes = GloballyHashedType::hashTypes(Types);
290       Hashes = OwnedHashes;
291     }
292 
293     if (auto Err = mergeTypeAndIdRecords(GlobalIDTable, GlobalTypeTable,
294                                          ObjectIndexMap.TPIMap, Types, Hashes))
295       fatal("codeview::mergeTypeAndIdRecords failed: " +
296             toString(std::move(Err)));
297   } else {
298     if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable,
299                                          ObjectIndexMap.TPIMap, Types))
300       fatal("codeview::mergeTypeAndIdRecords failed: " +
301             toString(std::move(Err)));
302   }
303   return ObjectIndexMap;
304 }
305 
306 static Expected<std::unique_ptr<pdb::NativeSession>>
307 tryToLoadPDB(const GUID &GuidFromObj, StringRef TSPath) {
308   ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(
309       TSPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
310   if (!MBOrErr)
311     return errorCodeToError(MBOrErr.getError());
312 
313   std::unique_ptr<pdb::IPDBSession> ThisSession;
314   if (auto EC = pdb::NativeSession::createFromPdb(
315           MemoryBuffer::getMemBuffer(Driver->takeBuffer(std::move(*MBOrErr)),
316                                      /*RequiresNullTerminator=*/false),
317           ThisSession))
318     return std::move(EC);
319 
320   std::unique_ptr<pdb::NativeSession> NS(
321       static_cast<pdb::NativeSession *>(ThisSession.release()));
322   pdb::PDBFile &File = NS->getPDBFile();
323   auto ExpectedInfo = File.getPDBInfoStream();
324   // All PDB Files should have an Info stream.
325   if (!ExpectedInfo)
326     return ExpectedInfo.takeError();
327 
328   // Just because a file with a matching name was found and it was an actual
329   // PDB file doesn't mean it matches.  For it to match the InfoStream's GUID
330   // must match the GUID specified in the TypeServer2 record.
331   if (ExpectedInfo->getGuid() != GuidFromObj)
332     return make_error<pdb::GenericError>(
333         pdb::generic_error_code::type_server_not_found, TSPath);
334 
335   return std::move(NS);
336 }
337 
338 Expected<const CVIndexMap&> PDBLinker::maybeMergeTypeServerPDB(ObjFile *File,
339                                                                TypeServer2Record &TS) {
340   const GUID& TSId = TS.getGuid();
341   StringRef TSPath = TS.getName();
342 
343   // First, check if the PDB has previously failed to load.
344   if (MissingTypeServerPDBs.count(TSId))
345     return make_error<pdb::GenericError>(
346       pdb::generic_error_code::type_server_not_found, TSPath);
347 
348   // Second, check if we already loaded a PDB with this GUID. Return the type
349   // index mapping if we have it.
350   auto Insertion = TypeServerIndexMappings.insert({TSId, CVIndexMap()});
351   CVIndexMap &IndexMap = Insertion.first->second;
352   if (!Insertion.second)
353     return IndexMap;
354 
355   // Mark this map as a type server map.
356   IndexMap.IsTypeServerMap = true;
357 
358   // Check for a PDB at:
359   // 1. The given file path
360   // 2. Next to the object file or archive file
361   auto ExpectedSession = tryToLoadPDB(TSId, TSPath);
362   if (!ExpectedSession) {
363     consumeError(ExpectedSession.takeError());
364     StringRef LocalPath =
365         !File->ParentName.empty() ? File->ParentName : File->getName();
366     SmallString<128> Path = sys::path::parent_path(LocalPath);
367     sys::path::append(
368         Path, sys::path::filename(TSPath, sys::path::Style::windows));
369     ExpectedSession = tryToLoadPDB(TSId, Path);
370   }
371   if (auto E = ExpectedSession.takeError()) {
372     TypeServerIndexMappings.erase(TSId);
373     MissingTypeServerPDBs.emplace(TSId);
374     return std::move(E);
375   }
376 
377   pdb::NativeSession *Session = ExpectedSession->get();
378 
379   // Keep a strong reference to this PDB, so that it's safe to hold pointers
380   // into the file.
381   LoadedPDBs.push_back(std::move(*ExpectedSession));
382 
383   auto ExpectedTpi = Session->getPDBFile().getPDBTpiStream();
384   if (auto E = ExpectedTpi.takeError())
385     fatal("Type server does not have TPI stream: " + toString(std::move(E)));
386   auto ExpectedIpi = Session->getPDBFile().getPDBIpiStream();
387   if (auto E = ExpectedIpi.takeError())
388     fatal("Type server does not have TPI stream: " + toString(std::move(E)));
389 
390   if (Config->DebugGHashes) {
391     // PDBs do not actually store global hashes, so when merging a type server
392     // PDB we have to synthesize global hashes.  To do this, we first synthesize
393     // global hashes for the TPI stream, since it is independent, then we
394     // synthesize hashes for the IPI stream, using the hashes for the TPI stream
395     // as inputs.
396     auto TpiHashes = GloballyHashedType::hashTypes(ExpectedTpi->typeArray());
397     auto IpiHashes =
398         GloballyHashedType::hashIds(ExpectedIpi->typeArray(), TpiHashes);
399 
400     // Merge TPI first, because the IPI stream will reference type indices.
401     if (auto Err = mergeTypeRecords(GlobalTypeTable, IndexMap.TPIMap,
402                                     ExpectedTpi->typeArray(), TpiHashes))
403       fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
404 
405     // Merge IPI.
406     if (auto Err =
407             mergeIdRecords(GlobalIDTable, IndexMap.TPIMap, IndexMap.IPIMap,
408                            ExpectedIpi->typeArray(), IpiHashes))
409       fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
410   } else {
411     // Merge TPI first, because the IPI stream will reference type indices.
412     if (auto Err = mergeTypeRecords(TypeTable, IndexMap.TPIMap,
413                                     ExpectedTpi->typeArray()))
414       fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
415 
416     // Merge IPI.
417     if (auto Err = mergeIdRecords(IDTable, IndexMap.TPIMap, IndexMap.IPIMap,
418                                   ExpectedIpi->typeArray()))
419       fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
420   }
421 
422   return IndexMap;
423 }
424 
425 static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
426   if (TI.isSimple())
427     return true;
428   if (TI.toArrayIndex() >= TypeIndexMap.size())
429     return false;
430   TI = TypeIndexMap[TI.toArrayIndex()];
431   return true;
432 }
433 
434 static void remapTypesInSymbolRecord(ObjFile *File, SymbolKind SymKind,
435                                      MutableArrayRef<uint8_t> Contents,
436                                      const CVIndexMap &IndexMap,
437                                      ArrayRef<TiReference> TypeRefs) {
438   for (const TiReference &Ref : TypeRefs) {
439     unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
440     if (Contents.size() < Ref.Offset + ByteSize)
441       fatal("symbol record too short");
442 
443     // This can be an item index or a type index. Choose the appropriate map.
444     ArrayRef<TypeIndex> TypeOrItemMap = IndexMap.TPIMap;
445     bool IsItemIndex = Ref.Kind == TiRefKind::IndexRef;
446     if (IsItemIndex && IndexMap.IsTypeServerMap)
447       TypeOrItemMap = IndexMap.IPIMap;
448 
449     MutableArrayRef<TypeIndex> TIs(
450         reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
451     for (TypeIndex &TI : TIs) {
452       if (!remapTypeIndex(TI, TypeOrItemMap)) {
453         log("ignoring symbol record of kind 0x" + utohexstr(SymKind) + " in " +
454             File->getName() + " with bad " + (IsItemIndex ? "item" : "type") +
455             " index 0x" + utohexstr(TI.getIndex()));
456         TI = TypeIndex(SimpleTypeKind::NotTranslated);
457         continue;
458       }
459     }
460   }
461 }
462 
463 static void
464 recordStringTableReferenceAtOffset(MutableArrayRef<uint8_t> Contents,
465                                    uint32_t Offset,
466                                    std::vector<ulittle32_t *> &StrTableRefs) {
467   Contents =
468       Contents.drop_front(Offset).take_front(sizeof(support::ulittle32_t));
469   ulittle32_t *Index = reinterpret_cast<ulittle32_t *>(Contents.data());
470   StrTableRefs.push_back(Index);
471 }
472 
473 static void
474 recordStringTableReferences(SymbolKind Kind, MutableArrayRef<uint8_t> Contents,
475                             std::vector<ulittle32_t *> &StrTableRefs) {
476   // For now we only handle S_FILESTATIC, but we may need the same logic for
477   // S_DEFRANGE and S_DEFRANGE_SUBFIELD.  However, I cannot seem to generate any
478   // PDBs that contain these types of records, so because of the uncertainty
479   // they are omitted here until we can prove that it's necessary.
480   switch (Kind) {
481   case SymbolKind::S_FILESTATIC:
482     // FileStaticSym::ModFileOffset
483     recordStringTableReferenceAtOffset(Contents, 4, StrTableRefs);
484     break;
485   case SymbolKind::S_DEFRANGE:
486   case SymbolKind::S_DEFRANGE_SUBFIELD:
487     log("Not fixing up string table reference in S_DEFRANGE / "
488         "S_DEFRANGE_SUBFIELD record");
489     break;
490   default:
491     break;
492   }
493 }
494 
495 static SymbolKind symbolKind(ArrayRef<uint8_t> RecordData) {
496   const RecordPrefix *Prefix =
497       reinterpret_cast<const RecordPrefix *>(RecordData.data());
498   return static_cast<SymbolKind>(uint16_t(Prefix->RecordKind));
499 }
500 
501 /// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
502 static void translateIdSymbols(MutableArrayRef<uint8_t> &RecordData,
503                                TypeCollection &IDTable) {
504   RecordPrefix *Prefix = reinterpret_cast<RecordPrefix *>(RecordData.data());
505 
506   SymbolKind Kind = symbolKind(RecordData);
507 
508   if (Kind == SymbolKind::S_PROC_ID_END) {
509     Prefix->RecordKind = SymbolKind::S_END;
510     return;
511   }
512 
513   // In an object file, GPROC32_ID has an embedded reference which refers to the
514   // single object file type index namespace.  This has already been translated
515   // to the PDB file's ID stream index space, but we need to convert this to a
516   // symbol that refers to the type stream index space.  So we remap again from
517   // ID index space to type index space.
518   if (Kind == SymbolKind::S_GPROC32_ID || Kind == SymbolKind::S_LPROC32_ID) {
519     SmallVector<TiReference, 1> Refs;
520     auto Content = RecordData.drop_front(sizeof(RecordPrefix));
521     CVSymbol Sym(Kind, RecordData);
522     discoverTypeIndicesInSymbol(Sym, Refs);
523     assert(Refs.size() == 1);
524     assert(Refs.front().Count == 1);
525 
526     TypeIndex *TI =
527         reinterpret_cast<TypeIndex *>(Content.data() + Refs[0].Offset);
528     // `TI` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
529     // the IPI stream, whose `FunctionType` member refers to the TPI stream.
530     // Note that LF_FUNC_ID and LF_MEMFUNC_ID have the same record layout, and
531     // in both cases we just need the second type index.
532     if (!TI->isSimple() && !TI->isNoneType()) {
533       CVType FuncIdData = IDTable.getType(*TI);
534       SmallVector<TypeIndex, 2> Indices;
535       discoverTypeIndices(FuncIdData, Indices);
536       assert(Indices.size() == 2);
537       *TI = Indices[1];
538     }
539 
540     Kind = (Kind == SymbolKind::S_GPROC32_ID) ? SymbolKind::S_GPROC32
541                                               : SymbolKind::S_LPROC32;
542     Prefix->RecordKind = uint16_t(Kind);
543   }
544 }
545 
546 /// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
547 /// The object file may not be aligned.
548 static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
549                                                  BumpPtrAllocator &Alloc) {
550   size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
551   assert(Size >= 4 && "record too short");
552   assert(Size <= MaxRecordLength && "record too long");
553   void *Mem = Alloc.Allocate(Size, 4);
554 
555   // Copy the symbol record and zero out any padding bytes.
556   MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
557   memcpy(NewData.data(), Sym.data().data(), Sym.length());
558   memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
559 
560   // Update the record prefix length. It should point to the beginning of the
561   // next record.
562   auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
563   Prefix->RecordLen = Size - 2;
564   return NewData;
565 }
566 
567 /// Return true if this symbol opens a scope. This implies that the symbol has
568 /// "parent" and "end" fields, which contain the offset of the S_END or
569 /// S_INLINESITE_END record.
570 static bool symbolOpensScope(SymbolKind Kind) {
571   switch (Kind) {
572   case SymbolKind::S_GPROC32:
573   case SymbolKind::S_LPROC32:
574   case SymbolKind::S_LPROC32_ID:
575   case SymbolKind::S_GPROC32_ID:
576   case SymbolKind::S_BLOCK32:
577   case SymbolKind::S_SEPCODE:
578   case SymbolKind::S_THUNK32:
579   case SymbolKind::S_INLINESITE:
580   case SymbolKind::S_INLINESITE2:
581     return true;
582   default:
583     break;
584   }
585   return false;
586 }
587 
588 static bool symbolEndsScope(SymbolKind Kind) {
589   switch (Kind) {
590   case SymbolKind::S_END:
591   case SymbolKind::S_PROC_ID_END:
592   case SymbolKind::S_INLINESITE_END:
593     return true;
594   default:
595     break;
596   }
597   return false;
598 }
599 
600 struct ScopeRecord {
601   ulittle32_t PtrParent;
602   ulittle32_t PtrEnd;
603 };
604 
605 struct SymbolScope {
606   ScopeRecord *OpeningRecord;
607   uint32_t ScopeOffset;
608 };
609 
610 static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
611                            uint32_t CurOffset, CVSymbol &Sym) {
612   assert(symbolOpensScope(Sym.kind()));
613   SymbolScope S;
614   S.ScopeOffset = CurOffset;
615   S.OpeningRecord = const_cast<ScopeRecord *>(
616       reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
617   S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
618   Stack.push_back(S);
619 }
620 
621 static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
622                             uint32_t CurOffset, ObjFile *File) {
623   if (Stack.empty()) {
624     warn("symbol scopes are not balanced in " + File->getName());
625     return;
626   }
627   SymbolScope S = Stack.pop_back_val();
628   S.OpeningRecord->PtrEnd = CurOffset;
629 }
630 
631 static bool symbolGoesInModuleStream(const CVSymbol &Sym) {
632   switch (Sym.kind()) {
633   case SymbolKind::S_GDATA32:
634   case SymbolKind::S_CONSTANT:
635   case SymbolKind::S_UDT:
636   // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
637   // since they are synthesized by the linker in response to S_GPROC32 and
638   // S_LPROC32, but if we do see them, don't put them in the module stream I
639   // guess.
640   case SymbolKind::S_PROCREF:
641   case SymbolKind::S_LPROCREF:
642     return false;
643   // S_GDATA32 does not go in the module stream, but S_LDATA32 does.
644   case SymbolKind::S_LDATA32:
645   default:
646     return true;
647   }
648 }
649 
650 static bool symbolGoesInGlobalsStream(const CVSymbol &Sym) {
651   switch (Sym.kind()) {
652   case SymbolKind::S_CONSTANT:
653   case SymbolKind::S_GDATA32:
654   // S_LDATA32 goes in both the module stream and the globals stream.
655   case SymbolKind::S_LDATA32:
656   case SymbolKind::S_GPROC32:
657   case SymbolKind::S_LPROC32:
658   // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
659   // since they are synthesized by the linker in response to S_GPROC32 and
660   // S_LPROC32, but if we do see them, copy them straight through.
661   case SymbolKind::S_PROCREF:
662   case SymbolKind::S_LPROCREF:
663     return true;
664   // FIXME: For now, we drop all S_UDT symbols (i.e. they don't go in the
665   // globals stream or the modules stream).  These have special handling which
666   // needs more investigation before we can get right, but by putting them all
667   // into the globals stream WinDbg fails to display local variables of class
668   // types saying that it cannot find the type Foo *.  So as a stopgap just to
669   // keep things working, we drop them.
670   case SymbolKind::S_UDT:
671   default:
672     return false;
673   }
674 }
675 
676 static void addGlobalSymbol(pdb::GSIStreamBuilder &Builder, ObjFile &File,
677                             const CVSymbol &Sym) {
678   switch (Sym.kind()) {
679   case SymbolKind::S_CONSTANT:
680   case SymbolKind::S_UDT:
681   case SymbolKind::S_GDATA32:
682   case SymbolKind::S_LDATA32:
683   case SymbolKind::S_PROCREF:
684   case SymbolKind::S_LPROCREF:
685     Builder.addGlobalSymbol(Sym);
686     break;
687   case SymbolKind::S_GPROC32:
688   case SymbolKind::S_LPROC32: {
689     SymbolRecordKind K = SymbolRecordKind::ProcRefSym;
690     if (Sym.kind() == SymbolKind::S_LPROC32)
691       K = SymbolRecordKind::LocalProcRef;
692     ProcRefSym PS(K);
693     PS.Module = static_cast<uint16_t>(File.ModuleDBI->getModuleIndex());
694     // For some reason, MSVC seems to add one to this value.
695     ++PS.Module;
696     PS.Name = getSymbolName(Sym);
697     PS.SumName = 0;
698     PS.SymOffset = File.ModuleDBI->getNextSymbolOffset();
699     Builder.addGlobalSymbol(PS);
700     break;
701   }
702   default:
703     llvm_unreachable("Invalid symbol kind!");
704   }
705 }
706 
707 static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjFile *File,
708                                pdb::GSIStreamBuilder &GsiBuilder,
709                                const CVIndexMap &IndexMap,
710                                TypeCollection &IDTable,
711                                std::vector<ulittle32_t *> &StringTableRefs,
712                                BinaryStreamRef SymData) {
713   // FIXME: Improve error recovery by warning and skipping records when
714   // possible.
715   ArrayRef<uint8_t> SymsBuffer;
716   cantFail(SymData.readBytes(0, SymData.getLength(), SymsBuffer));
717   SmallVector<SymbolScope, 4> Scopes;
718 
719   auto EC = forEachCodeViewRecord<CVSymbol>(
720       SymsBuffer, [&](const CVSymbol &Sym) -> llvm::Error {
721         // Discover type index references in the record. Skip it if we don't
722         // know where they are.
723         SmallVector<TiReference, 32> TypeRefs;
724         if (!discoverTypeIndicesInSymbol(Sym, TypeRefs)) {
725           log("ignoring unknown symbol record with kind 0x" +
726               utohexstr(Sym.kind()));
727           return Error::success();
728         }
729 
730         // Copy the symbol record so we can mutate it.
731         MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
732 
733         // Re-map all the type index references.
734         MutableArrayRef<uint8_t> Contents =
735             NewData.drop_front(sizeof(RecordPrefix));
736         remapTypesInSymbolRecord(File, Sym.kind(), Contents, IndexMap,
737                                  TypeRefs);
738 
739         // An object file may have S_xxx_ID symbols, but these get converted to
740         // "real" symbols in a PDB.
741         translateIdSymbols(NewData, IDTable);
742 
743         // If this record refers to an offset in the object file's string table,
744         // add that item to the global PDB string table and re-write the index.
745         recordStringTableReferences(Sym.kind(), Contents, StringTableRefs);
746 
747         SymbolKind NewKind = symbolKind(NewData);
748 
749         // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
750         CVSymbol NewSym(NewKind, NewData);
751         if (symbolOpensScope(NewKind))
752           scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(),
753                          NewSym);
754         else if (symbolEndsScope(NewKind))
755           scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
756 
757         // Add the symbol to the globals stream if necessary.  Do this before
758         // adding the symbol to the module since we may need to get the next
759         // symbol offset, and writing to the module's symbol stream will update
760         // that offset.
761         if (symbolGoesInGlobalsStream(NewSym))
762           addGlobalSymbol(GsiBuilder, *File, NewSym);
763 
764         // Add the symbol to the module.
765         if (symbolGoesInModuleStream(NewSym))
766           File->ModuleDBI->addSymbol(NewSym);
767         return Error::success();
768       });
769   cantFail(std::move(EC));
770 }
771 
772 // Allocate memory for a .debug$S section and relocate it.
773 static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
774                                             SectionChunk *DebugChunk) {
775   uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk->getSize());
776   assert(DebugChunk->OutputSectionOff == 0 &&
777          "debug sections should not be in output sections");
778   DebugChunk->writeTo(Buffer);
779   return consumeDebugMagic(makeArrayRef(Buffer, DebugChunk->getSize()),
780                            ".debug$S");
781 }
782 
783 void PDBLinker::addObjFile(ObjFile *File) {
784   // Add a module descriptor for every object file. We need to put an absolute
785   // path to the object into the PDB. If this is a plain object, we make its
786   // path absolute. If it's an object in an archive, we make the archive path
787   // absolute.
788   bool InArchive = !File->ParentName.empty();
789   SmallString<128> Path = InArchive ? File->ParentName : File->getName();
790   sys::fs::make_absolute(Path);
791   sys::path::native(Path, sys::path::Style::windows);
792   StringRef Name = InArchive ? File->getName() : StringRef(Path);
793 
794   File->ModuleDBI = &ExitOnErr(Builder.getDbiBuilder().addModuleInfo(Name));
795   File->ModuleDBI->setObjFileName(Path);
796 
797   // Before we can process symbol substreams from .debug$S, we need to process
798   // type information, file checksums, and the string table.  Add type info to
799   // the PDB first, so that we can get the map from object file type and item
800   // indices to PDB type and item indices.
801   CVIndexMap ObjectIndexMap;
802   auto IndexMapResult = mergeDebugT(File, ObjectIndexMap);
803 
804   // If the .debug$T sections fail to merge, assume there is no debug info.
805   if (!IndexMapResult) {
806     warn("Type server PDB for " + Name + " is invalid, ignoring debug info. " +
807          toString(IndexMapResult.takeError()));
808     return;
809   }
810 
811   const CVIndexMap &IndexMap = *IndexMapResult;
812 
813   ScopedTimer T(SymbolMergingTimer);
814 
815   // Now do all live .debug$S sections.
816   DebugStringTableSubsectionRef CVStrTab;
817   DebugChecksumsSubsectionRef Checksums;
818   std::vector<ulittle32_t *> StringTableReferences;
819   for (SectionChunk *DebugChunk : File->getDebugChunks()) {
820     if (!DebugChunk->isLive() || DebugChunk->getSectionName() != ".debug$S")
821       continue;
822 
823     ArrayRef<uint8_t> RelocatedDebugContents =
824         relocateDebugChunk(Alloc, DebugChunk);
825     if (RelocatedDebugContents.empty())
826       continue;
827 
828     DebugSubsectionArray Subsections;
829     BinaryStreamReader Reader(RelocatedDebugContents, support::little);
830     ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
831 
832     for (const DebugSubsectionRecord &SS : Subsections) {
833       switch (SS.kind()) {
834       case DebugSubsectionKind::StringTable: {
835         auto Data = SS.getRecordData();
836         ArrayRef<uint8_t> Buffer;
837         cantFail(Data.readLongestContiguousChunk(0, Buffer));
838         assert(!CVStrTab.valid() &&
839                "Encountered multiple string table subsections!");
840         ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
841         break;
842       }
843       case DebugSubsectionKind::FileChecksums:
844         assert(!Checksums.valid() &&
845                "Encountered multiple checksum subsections!");
846         ExitOnErr(Checksums.initialize(SS.getRecordData()));
847         break;
848       case DebugSubsectionKind::Lines:
849         // We can add the relocated line table directly to the PDB without
850         // modification because the file checksum offsets will stay the same.
851         File->ModuleDBI->addDebugSubsection(SS);
852         break;
853       case DebugSubsectionKind::Symbols:
854         if (Config->DebugGHashes) {
855           mergeSymbolRecords(Alloc, File, Builder.getGsiBuilder(), IndexMap,
856                              GlobalIDTable, StringTableReferences,
857                              SS.getRecordData());
858         } else {
859           mergeSymbolRecords(Alloc, File, Builder.getGsiBuilder(), IndexMap,
860                              IDTable, StringTableReferences,
861                              SS.getRecordData());
862         }
863         break;
864       default:
865         // FIXME: Process the rest of the subsections.
866         break;
867       }
868     }
869   }
870 
871   // We should have seen all debug subsections across the entire object file now
872   // which means that if a StringTable subsection and Checksums subsection were
873   // present, now is the time to handle them.
874   if (!CVStrTab.valid()) {
875     if (Checksums.valid())
876       fatal(".debug$S sections with a checksums subsection must also contain a "
877             "string table subsection");
878 
879     if (!StringTableReferences.empty())
880       warn("No StringTable subsection was encountered, but there are string "
881            "table references");
882     return;
883   }
884 
885   // Rewrite each string table reference based on the value that the string
886   // assumes in the final PDB.
887   for (ulittle32_t *Ref : StringTableReferences) {
888     auto ExpectedString = CVStrTab.getString(*Ref);
889     if (!ExpectedString) {
890       warn("Invalid string table reference");
891       consumeError(ExpectedString.takeError());
892       continue;
893     }
894 
895     *Ref = PDBStrTab.insert(*ExpectedString);
896   }
897 
898   // Make a new file checksum table that refers to offsets in the PDB-wide
899   // string table. Generally the string table subsection appears after the
900   // checksum table, so we have to do this after looping over all the
901   // subsections.
902   auto NewChecksums = make_unique<DebugChecksumsSubsection>(PDBStrTab);
903   for (FileChecksumEntry &FC : Checksums) {
904     StringRef FileName = ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
905     ExitOnErr(Builder.getDbiBuilder().addModuleSourceFile(*File->ModuleDBI,
906                                                           FileName));
907     NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
908   }
909   File->ModuleDBI->addDebugSubsection(std::move(NewChecksums));
910 }
911 
912 static PublicSym32 createPublic(Defined *Def) {
913   PublicSym32 Pub(SymbolKind::S_PUB32);
914   Pub.Name = Def->getName();
915   if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
916     if (D->getCOFFSymbol().isFunctionDefinition())
917       Pub.Flags = PublicSymFlags::Function;
918   } else if (isa<DefinedImportThunk>(Def)) {
919     Pub.Flags = PublicSymFlags::Function;
920   }
921 
922   OutputSection *OS = Def->getChunk()->getOutputSection();
923   assert(OS && "all publics should be in final image");
924   Pub.Offset = Def->getRVA() - OS->getRVA();
925   Pub.Segment = OS->SectionIndex;
926   return Pub;
927 }
928 
929 // Add all object files to the PDB. Merge .debug$T sections into IpiData and
930 // TpiData.
931 void PDBLinker::addObjectsToPDB() {
932   ScopedTimer T1(AddObjectsTimer);
933   for (ObjFile *File : ObjFile::Instances)
934     addObjFile(File);
935 
936   Builder.getStringTableBuilder().setStrings(PDBStrTab);
937   T1.stop();
938 
939   // Construct TPI and IPI stream contents.
940   ScopedTimer T2(TpiStreamLayoutTimer);
941   if (Config->DebugGHashes) {
942     addTypeInfo(Builder.getTpiBuilder(), GlobalTypeTable);
943     addTypeInfo(Builder.getIpiBuilder(), GlobalIDTable);
944   } else {
945     addTypeInfo(Builder.getTpiBuilder(), TypeTable);
946     addTypeInfo(Builder.getIpiBuilder(), IDTable);
947   }
948   T2.stop();
949 
950   ScopedTimer T3(GlobalsLayoutTimer);
951   // Compute the public and global symbols.
952   auto &GsiBuilder = Builder.getGsiBuilder();
953   std::vector<PublicSym32> Publics;
954   Symtab->forEachSymbol([&Publics](Symbol *S) {
955     // Only emit defined, live symbols that have a chunk.
956     auto *Def = dyn_cast<Defined>(S);
957     if (Def && Def->isLive() && Def->getChunk())
958       Publics.push_back(createPublic(Def));
959   });
960 
961   if (!Publics.empty()) {
962     // Sort the public symbols and add them to the stream.
963     std::sort(Publics.begin(), Publics.end(),
964               [](const PublicSym32 &L, const PublicSym32 &R) {
965                 return L.Name < R.Name;
966               });
967     for (const PublicSym32 &Pub : Publics)
968       GsiBuilder.addPublicSymbol(Pub);
969   }
970 }
971 
972 void PDBLinker::addNatvisFiles() {
973   for (StringRef File : Config->NatvisFiles) {
974     ErrorOr<std::unique_ptr<MemoryBuffer>> DataOrErr =
975         MemoryBuffer::getFile(File);
976     if (!DataOrErr) {
977       warn("Cannot open input file: " + File);
978       continue;
979     }
980     Builder.addInjectedSource(File, std::move(*DataOrErr));
981   }
982 }
983 
984 static void addCommonLinkerModuleSymbols(StringRef Path,
985                                          pdb::DbiModuleDescriptorBuilder &Mod,
986                                          BumpPtrAllocator &Allocator) {
987   ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
988   Compile3Sym CS(SymbolRecordKind::Compile3Sym);
989   EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
990 
991   ONS.Name = "* Linker *";
992   ONS.Signature = 0;
993 
994   CS.Machine = Config->is64() ? CPUType::X64 : CPUType::Intel80386;
995   // Interestingly, if we set the string to 0.0.0.0, then when trying to view
996   // local variables WinDbg emits an error that private symbols are not present.
997   // By setting this to a valid MSVC linker version string, local variables are
998   // displayed properly.   As such, even though it is not representative of
999   // LLVM's version information, we need this for compatibility.
1000   CS.Flags = CompileSym3Flags::None;
1001   CS.VersionBackendBuild = 25019;
1002   CS.VersionBackendMajor = 14;
1003   CS.VersionBackendMinor = 10;
1004   CS.VersionBackendQFE = 0;
1005 
1006   // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
1007   // linker module (which is by definition a backend), so we don't need to do
1008   // anything here.  Also, it seems we can use "LLVM Linker" for the linker name
1009   // without any problems.  Only the backend version has to be hardcoded to a
1010   // magic number.
1011   CS.VersionFrontendBuild = 0;
1012   CS.VersionFrontendMajor = 0;
1013   CS.VersionFrontendMinor = 0;
1014   CS.VersionFrontendQFE = 0;
1015   CS.Version = "LLVM Linker";
1016   CS.setLanguage(SourceLanguage::Link);
1017 
1018   ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
1019   std::string ArgStr = llvm::join(Args, " ");
1020   EBS.Fields.push_back("cwd");
1021   SmallString<64> cwd;
1022   sys::fs::current_path(cwd);
1023   EBS.Fields.push_back(cwd);
1024   EBS.Fields.push_back("exe");
1025   SmallString<64> exe = Config->Argv[0];
1026   llvm::sys::fs::make_absolute(exe);
1027   EBS.Fields.push_back(exe);
1028   EBS.Fields.push_back("pdb");
1029   EBS.Fields.push_back(Path);
1030   EBS.Fields.push_back("cmd");
1031   EBS.Fields.push_back(ArgStr);
1032   Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1033       ONS, Allocator, CodeViewContainer::Pdb));
1034   Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1035       CS, Allocator, CodeViewContainer::Pdb));
1036   Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1037       EBS, Allocator, CodeViewContainer::Pdb));
1038 }
1039 
1040 static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &Mod,
1041                                          OutputSection &OS,
1042                                          BumpPtrAllocator &Allocator) {
1043   SectionSym Sym(SymbolRecordKind::SectionSym);
1044   Sym.Alignment = 12; // 2^12 = 4KB
1045   Sym.Characteristics = OS.getCharacteristics();
1046   Sym.Length = OS.getVirtualSize();
1047   Sym.Name = OS.Name;
1048   Sym.Rva = OS.getRVA();
1049   Sym.SectionNumber = OS.SectionIndex;
1050   Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1051       Sym, Allocator, CodeViewContainer::Pdb));
1052 }
1053 
1054 // Creates a PDB file.
1055 void coff::createPDB(SymbolTable *Symtab,
1056                      ArrayRef<OutputSection *> OutputSections,
1057                      ArrayRef<uint8_t> SectionTable,
1058                      const llvm::codeview::DebugInfo &BuildId) {
1059   ScopedTimer T1(TotalPdbLinkTimer);
1060   PDBLinker PDB(Symtab);
1061 
1062   PDB.initialize(BuildId);
1063   PDB.addObjectsToPDB();
1064   PDB.addSections(OutputSections, SectionTable);
1065   PDB.addNatvisFiles();
1066 
1067   ScopedTimer T2(DiskCommitTimer);
1068   PDB.commit();
1069 }
1070 
1071 void PDBLinker::initialize(const llvm::codeview::DebugInfo &BuildId) {
1072   ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
1073 
1074   // Create streams in MSF for predefined streams, namely
1075   // PDB, TPI, DBI and IPI.
1076   for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
1077     ExitOnErr(Builder.getMsfBuilder().addStream(0));
1078 
1079   // Add an Info stream.
1080   auto &InfoBuilder = Builder.getInfoBuilder();
1081   GUID uuid;
1082   memcpy(&uuid, &BuildId.PDB70.Signature, sizeof(uuid));
1083   InfoBuilder.setAge(BuildId.PDB70.Age);
1084   InfoBuilder.setGuid(uuid);
1085   InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
1086 
1087   // Add an empty DBI stream.
1088   pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
1089   DbiBuilder.setAge(BuildId.PDB70.Age);
1090   DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
1091 }
1092 
1093 void PDBLinker::addSectionContrib(pdb::DbiModuleDescriptorBuilder &LinkerModule,
1094                                   OutputSection *OS, Chunk *C) {
1095   pdb::SectionContrib SC;
1096   memset(&SC, 0, sizeof(SC));
1097   SC.ISect = OS->SectionIndex;
1098   SC.Off = C->getRVA() - OS->getRVA();
1099   SC.Size = C->getSize();
1100   if (auto *SecChunk = dyn_cast<SectionChunk>(C)) {
1101     SC.Characteristics = SecChunk->Header->Characteristics;
1102     SC.Imod = SecChunk->File->ModuleDBI->getModuleIndex();
1103     ArrayRef<uint8_t> Contents = SecChunk->getContents();
1104     JamCRC CRC(0);
1105     ArrayRef<char> CharContents = makeArrayRef(
1106         reinterpret_cast<const char *>(Contents.data()), Contents.size());
1107     CRC.update(CharContents);
1108     SC.DataCrc = CRC.getCRC();
1109   } else {
1110     SC.Characteristics = OS->getCharacteristics();
1111     // FIXME: When we start creating DBI for import libraries, use those here.
1112     SC.Imod = LinkerModule.getModuleIndex();
1113   }
1114   SC.RelocCrc = 0; // FIXME
1115   Builder.getDbiBuilder().addSectionContrib(SC);
1116 }
1117 
1118 void PDBLinker::addSections(ArrayRef<OutputSection *> OutputSections,
1119                             ArrayRef<uint8_t> SectionTable) {
1120   // It's not entirely clear what this is, but the * Linker * module uses it.
1121   pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
1122   NativePath = Config->PDBPath;
1123   sys::fs::make_absolute(NativePath);
1124   sys::path::native(NativePath, sys::path::Style::windows);
1125   uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
1126   auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
1127   LinkerModule.setPdbFilePathNI(PdbFilePathNI);
1128   addCommonLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
1129 
1130   // Add section contributions. They must be ordered by ascending RVA.
1131   for (OutputSection *OS : OutputSections) {
1132     addLinkerModuleSectionSymbol(LinkerModule, *OS, Alloc);
1133     for (Chunk *C : OS->getChunks())
1134       addSectionContrib(LinkerModule, OS, C);
1135   }
1136 
1137   // Add Section Map stream.
1138   ArrayRef<object::coff_section> Sections = {
1139       (const object::coff_section *)SectionTable.data(),
1140       SectionTable.size() / sizeof(object::coff_section)};
1141   SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
1142   DbiBuilder.setSectionMap(SectionMap);
1143 
1144   // Add COFF section header stream.
1145   ExitOnErr(
1146       DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
1147 }
1148 
1149 void PDBLinker::commit() {
1150   // Write to a file.
1151   ExitOnErr(Builder.commit(Config->PDBPath));
1152 }
1153