PDB.cpp revision 329410
1124208Sdes//===- PDB.cpp ------------------------------------------------------------===//
298937Sdes//
398937Sdes//                             The LLVM Linker
498937Sdes//
598937Sdes// This file is distributed under the University of Illinois Open Source
698937Sdes// License. See LICENSE.TXT for details.
798937Sdes//
898937Sdes//===----------------------------------------------------------------------===//
998937Sdes
1098937Sdes#include "PDB.h"
1198937Sdes#include "Chunks.h"
1298937Sdes#include "Config.h"
1398937Sdes#include "Driver.h"
1498937Sdes#include "SymbolTable.h"
1598937Sdes#include "Symbols.h"
1698937Sdes#include "Writer.h"
1798937Sdes#include "lld/Common/ErrorHandler.h"
1898937Sdes#include "llvm/DebugInfo/CodeView/CVDebugRecord.h"
1998937Sdes#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
2098937Sdes#include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"
2198937Sdes#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
2298937Sdes#include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
2398937Sdes#include "llvm/DebugInfo/CodeView/RecordName.h"
2498937Sdes#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
2598937Sdes#include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
2698937Sdes#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
2798937Sdes#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
2898937Sdes#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
2999060Sdes#include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
30113908Sdes#include "llvm/DebugInfo/MSF/MSFBuilder.h"
3198937Sdes#include "llvm/DebugInfo/MSF/MSFCommon.h"
3298937Sdes#include "llvm/DebugInfo/PDB/GenericError.h"
3398937Sdes#include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
3498937Sdes#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
3598937Sdes#include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
3698937Sdes#include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h"
3798937Sdes#include "llvm/DebugInfo/PDB/Native/InfoStream.h"
3898937Sdes#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
3998937Sdes#include "llvm/DebugInfo/PDB/Native/NativeSession.h"
4098937Sdes#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
4198937Sdes#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
4298937Sdes#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
4398937Sdes#include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
4498937Sdes#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
4598937Sdes#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
4698937Sdes#include "llvm/DebugInfo/PDB/PDB.h"
4798937Sdes#include "llvm/Object/COFF.h"
4898937Sdes#include "llvm/Support/BinaryByteStream.h"
49124208Sdes#include "llvm/Support/Endian.h"
5098937Sdes#include "llvm/Support/JamCRC.h"
5198937Sdes#include "llvm/Support/Path.h"
5298937Sdes#include "llvm/Support/ScopedPrinter.h"
53113908Sdes#include <memory>
5498937Sdes
5598937Sdesusing namespace lld;
5698937Sdesusing namespace lld::coff;
5798937Sdesusing namespace llvm;
5898937Sdesusing namespace llvm::codeview;
5998937Sdes
6098937Sdesusing llvm::object::coff_section;
6198937Sdes
62113908Sdesstatic ExitOnError ExitOnErr;
6398937Sdes
64113908Sdesnamespace {
65124208Sdes/// Map from type index and item index in a type server PDB to the
66124208Sdes/// corresponding index in the destination PDB.
67124208Sdesstruct CVIndexMap {
68124208Sdes  SmallVector<TypeIndex, 0> TPIMap;
69113908Sdes  SmallVector<TypeIndex, 0> IPIMap;
70113908Sdes  bool IsTypeServerMap = false;
71124208Sdes};
72124208Sdes
7398937Sdesclass PDBLinker {
74113908Sdespublic:
75113908Sdes  PDBLinker(SymbolTable *Symtab)
7698937Sdes      : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
77113908Sdes        IDTable(Alloc), GlobalTypeTable(Alloc), GlobalIDTable(Alloc) {}
78113908Sdes
79113908Sdes  /// Emit the basic PDB structure: initial streams, headers, etc.
80113908Sdes  void initialize(const llvm::codeview::DebugInfo &BuildId);
81113908Sdes
82113908Sdes  /// Link CodeView from each object file in the symbol table into the PDB.
83113908Sdes  void addObjectsToPDB();
84113908Sdes
85124208Sdes  /// Link CodeView from a single object file into the PDB.
86124208Sdes  void addObjFile(ObjFile *File);
87124208Sdes
8898937Sdes  /// Produce a mapping from the type and item indices used in the object
8998937Sdes  /// file to those in the destination PDB.
9098937Sdes  ///
9198937Sdes  /// If the object file uses a type server PDB (compiled with /Zi), merge TPI
9298937Sdes  /// and IPI from the type server PDB and return a map for it. Each unique type
9398937Sdes  /// server PDB is merged at most once, so this may return an existing index
9498937Sdes  /// mapping.
9598937Sdes  ///
9698937Sdes  /// If the object does not use a type server PDB (compiled with /Z7), we merge
97113908Sdes  /// all the type and item records from the .debug$S stream and fill in the
98113908Sdes  /// caller-provided ObjectIndexMap.
99113908Sdes  Expected<const CVIndexMap&> mergeDebugT(ObjFile *File,
100113908Sdes                                          CVIndexMap &ObjectIndexMap);
101113908Sdes
102113908Sdes  Expected<const CVIndexMap&> maybeMergeTypeServerPDB(ObjFile *File,
103113908Sdes                                                      TypeServer2Record &TS);
104113908Sdes
105113908Sdes  /// Add the section map and section contributions to the PDB.
106113908Sdes  void addSections(ArrayRef<OutputSection *> OutputSections,
107113908Sdes                   ArrayRef<uint8_t> SectionTable);
108113908Sdes
109113908Sdes  void addSectionContrib(pdb::DbiModuleDescriptorBuilder &LinkerModule,
110113908Sdes                         OutputSection *OS, Chunk *C);
111113908Sdes
11298937Sdes  /// Write the PDB to disk.
113113908Sdes  void commit();
11498937Sdes
115124208Sdesprivate:
11698937Sdes  BumpPtrAllocator Alloc;
117124208Sdes
118124208Sdes  SymbolTable *Symtab;
119124208Sdes
12098937Sdes  pdb::PDBFileBuilder Builder;
12198937Sdes
12298937Sdes  /// Type records that will go into the PDB TPI stream.
12398937Sdes  MergingTypeTableBuilder TypeTable;
12498937Sdes
12598937Sdes  /// Item records that will go into the PDB IPI stream.
12698937Sdes  MergingTypeTableBuilder IDTable;
12798937Sdes
12898937Sdes  /// Type records that will go into the PDB TPI stream (for /DEBUG:GHASH)
12998937Sdes  GlobalTypeTableBuilder GlobalTypeTable;
13098937Sdes
13198937Sdes  /// Item records that will go into the PDB IPI stream (for /DEBUG:GHASH)
13298937Sdes  GlobalTypeTableBuilder GlobalIDTable;
13398937Sdes
13498937Sdes  /// PDBs use a single global string table for filenames in the file checksum
13598937Sdes  /// table.
13698937Sdes  DebugStringTableSubsection PDBStrTab;
13798937Sdes
13898937Sdes  llvm::SmallString<128> NativePath;
139113908Sdes
140113908Sdes  std::vector<pdb::SecMapEntry> SectionMap;
14198937Sdes
14298937Sdes  /// Type index mappings of type server PDBs that we've loaded so far.
14398937Sdes  std::map<GUID, CVIndexMap> TypeServerIndexMappings;
14498937Sdes
14598937Sdes  /// List of TypeServer PDBs which cannot be loaded.
14698937Sdes  /// Cached to prevent repeated load attempts.
14798937Sdes  std::set<GUID> MissingTypeServerPDBs;
14898937Sdes};
14998937Sdes}
15098937Sdes
15198937Sdesstatic SectionChunk *findByName(ArrayRef<SectionChunk *> Sections,
152106121Sdes                                StringRef Name) {
15398937Sdes  for (SectionChunk *C : Sections)
15498937Sdes    if (C->getSectionName() == Name)
15598937Sdes      return C;
15698937Sdes  return nullptr;
15798937Sdes}
15898937Sdes
15998937Sdesstatic ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
160113908Sdes                                           StringRef SecName) {
161113908Sdes  // First 4 bytes are section magic.
16298937Sdes  if (Data.size() < 4)
16398937Sdes    fatal(SecName + " too short");
16498937Sdes  if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
16598937Sdes    fatal(SecName + " has an invalid magic");
16698937Sdes  return Data.slice(4);
16798937Sdes}
16898937Sdes
16998937Sdesstatic ArrayRef<uint8_t> getDebugSection(ObjFile *File, StringRef SecName) {
17098937Sdes  if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
17198937Sdes    return consumeDebugMagic(Sec->getContents(), SecName);
17298937Sdes  return {};
17398937Sdes}
17498937Sdes
17598937Sdes// A COFF .debug$H section is currently a clang extension.  This function checks
17698937Sdes// if a .debug$H section is in a format that we expect / understand, so that we
177124208Sdes// can ignore any sections which are coincidentally also named .debug$H but do
17898937Sdes// not contain a format we recognize.
17998937Sdesstatic bool canUseDebugH(ArrayRef<uint8_t> DebugH) {
18098937Sdes  if (DebugH.size() < sizeof(object::debug_h_header))
18198937Sdes    return false;
18298937Sdes  auto *Header =
18398937Sdes      reinterpret_cast<const object::debug_h_header *>(DebugH.data());
18498937Sdes  DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
18598937Sdes  return Header->Magic == COFF::DEBUG_HASHES_SECTION_MAGIC &&
186124208Sdes         Header->Version == 0 &&
187124208Sdes         Header->HashAlgorithm == uint16_t(GlobalTypeHashAlg::SHA1) &&
188124208Sdes         (DebugH.size() % 20 == 0);
189124208Sdes}
190124208Sdes
191124208Sdesstatic Optional<ArrayRef<uint8_t>> getDebugH(ObjFile *File) {
192124208Sdes  SectionChunk *Sec = findByName(File->getDebugChunks(), ".debug$H");
193124208Sdes  if (!Sec)
194124208Sdes    return llvm::None;
195124208Sdes  ArrayRef<uint8_t> Contents = Sec->getContents();
19698937Sdes  if (!canUseDebugH(Contents))
19798937Sdes    return None;
19898937Sdes  return Contents;
19998937Sdes}
200124208Sdes
20198937Sdesstatic ArrayRef<GloballyHashedType>
20298937SdesgetHashesFromDebugH(ArrayRef<uint8_t> DebugH) {
20398937Sdes  assert(canUseDebugH(DebugH));
20498937Sdes
20598937Sdes  DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
20698937Sdes  uint32_t Count = DebugH.size() / sizeof(GloballyHashedType);
20798937Sdes  return {reinterpret_cast<const GloballyHashedType *>(DebugH.data()), Count};
208124208Sdes}
20998937Sdes
21098937Sdesstatic void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
211124208Sdes                        TypeCollection &TypeTable) {
21298937Sdes  // Start the TPI or IPI stream header.
213124208Sdes  TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
214124208Sdes
21598937Sdes  // Flatten the in memory type table and hash each type.
21698937Sdes  TypeTable.ForEachRecord([&](TypeIndex TI, const CVType &Type) {
21798937Sdes    auto Hash = pdb::hashTypeRecord(Type);
21898937Sdes    if (auto E = Hash.takeError())
21998937Sdes      fatal("type hashing error");
22098937Sdes    TpiBuilder.addTypeRecord(Type.RecordData, *Hash);
22198937Sdes  });
22298937Sdes}
22398937Sdes
22498937Sdesstatic Optional<TypeServer2Record>
22598937SdesmaybeReadTypeServerRecord(CVTypeArray &Types) {
22698937Sdes  auto I = Types.begin();
227124208Sdes  if (I == Types.end())
228124208Sdes    return None;
22998937Sdes  const CVType &Type = *I;
230106121Sdes  if (Type.kind() != LF_TYPESERVER2)
231106121Sdes    return None;
23299060Sdes  TypeServer2Record TS;
23398937Sdes  if (auto EC = TypeDeserializer::deserializeAs(const_cast<CVType &>(Type), TS))
23498937Sdes    fatal("error reading type server record: " + toString(std::move(EC)));
23598937Sdes  return std::move(TS);
23698937Sdes}
23798937Sdes
23898937SdesExpected<const CVIndexMap&> PDBLinker::mergeDebugT(ObjFile *File,
23998937Sdes                                                   CVIndexMap &ObjectIndexMap) {
24098937Sdes  ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
24198937Sdes  if (Data.empty())
24298937Sdes    return ObjectIndexMap;
24398937Sdes
24498937Sdes  BinaryByteStream Stream(Data, support::little);
245106121Sdes  CVTypeArray Types;
246113908Sdes  BinaryStreamReader Reader(Stream);
247113908Sdes  if (auto EC = Reader.readArray(Types, Reader.getLength()))
248113908Sdes    fatal("Reader::readArray failed: " + toString(std::move(EC)));
249113908Sdes
250113908Sdes  // Look through type servers. If we've already seen this type server, don't
251113908Sdes  // merge any type information.
252113908Sdes  if (Optional<TypeServer2Record> TS = maybeReadTypeServerRecord(Types))
25398937Sdes    return maybeMergeTypeServerPDB(File, *TS);
254113908Sdes
25598937Sdes  // This is a /Z7 object. Fill in the temporary, caller-provided
256113908Sdes  // ObjectIndexMap.
257113908Sdes  if (Config->DebugGHashes) {
258113908Sdes    ArrayRef<GloballyHashedType> Hashes;
25998937Sdes    std::vector<GloballyHashedType> OwnedHashes;
26098937Sdes    if (Optional<ArrayRef<uint8_t>> DebugH = getDebugH(File))
26198937Sdes      Hashes = getHashesFromDebugH(*DebugH);
26298937Sdes    else {
26398937Sdes      OwnedHashes = GloballyHashedType::hashTypes(Types);
26498937Sdes      Hashes = OwnedHashes;
26598937Sdes    }
26698937Sdes
26798937Sdes    if (auto Err = mergeTypeAndIdRecords(GlobalIDTable, GlobalTypeTable,
26899060Sdes                                         ObjectIndexMap.TPIMap, Types, Hashes))
26998937Sdes      fatal("codeview::mergeTypeAndIdRecords failed: " +
27098937Sdes            toString(std::move(Err)));
271113908Sdes  } else {
272113908Sdes    if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable,
27398937Sdes                                         ObjectIndexMap.TPIMap, Types))
27498937Sdes      fatal("codeview::mergeTypeAndIdRecords failed: " +
275106121Sdes            toString(std::move(Err)));
27698937Sdes  }
277106121Sdes  return ObjectIndexMap;
27898937Sdes}
27998937Sdes
28098937Sdesstatic Expected<std::unique_ptr<pdb::NativeSession>>
281106121SdestryToLoadPDB(const GUID &GuidFromObj, StringRef TSPath) {
28298937Sdes  ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(
28398937Sdes      TSPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
28498937Sdes  if (!MBOrErr)
28598937Sdes    return errorCodeToError(MBOrErr.getError());
286106121Sdes
28798937Sdes  std::unique_ptr<pdb::IPDBSession> ThisSession;
28898937Sdes  if (auto EC = pdb::NativeSession::createFromPdb(
28998937Sdes          MemoryBuffer::getMemBuffer(Driver->takeBuffer(std::move(*MBOrErr)),
29098937Sdes                                     /*RequiresNullTerminator=*/false),
291106121Sdes          ThisSession))
29298937Sdes    return std::move(EC);
29398937Sdes
29498937Sdes  std::unique_ptr<pdb::NativeSession> NS(
29598937Sdes      static_cast<pdb::NativeSession *>(ThisSession.release()));
29698937Sdes  pdb::PDBFile &File = NS->getPDBFile();
29798937Sdes  auto ExpectedInfo = File.getPDBInfoStream();
298106121Sdes  // All PDB Files should have an Info stream.
29998937Sdes  if (!ExpectedInfo)
30098937Sdes    return ExpectedInfo.takeError();
30198937Sdes
30298937Sdes  // Just because a file with a matching name was found and it was an actual
30398937Sdes  // PDB file doesn't mean it matches.  For it to match the InfoStream's GUID
30498937Sdes  // must match the GUID specified in the TypeServer2 record.
30598937Sdes  if (ExpectedInfo->getGuid() != GuidFromObj)
30698937Sdes    return make_error<pdb::GenericError>(
30798937Sdes        pdb::generic_error_code::type_server_not_found, TSPath);
30898937Sdes
30998937Sdes  return std::move(NS);
310106121Sdes}
31198937Sdes
31298937SdesExpected<const CVIndexMap&> PDBLinker::maybeMergeTypeServerPDB(ObjFile *File,
31398937Sdes                                                               TypeServer2Record &TS) {
31498937Sdes  const GUID& TSId = TS.getGuid();
31598937Sdes  StringRef TSPath = TS.getName();
31698937Sdes
31798937Sdes  // First, check if the PDB has previously failed to load.
31898937Sdes  if (MissingTypeServerPDBs.count(TSId))
31998937Sdes    return make_error<pdb::GenericError>(
32098937Sdes      pdb::generic_error_code::type_server_not_found, TSPath);
32198937Sdes
32298937Sdes  // Second, check if we already loaded a PDB with this GUID. Return the type
32398937Sdes  // index mapping if we have it.
32498937Sdes  auto Insertion = TypeServerIndexMappings.insert({TSId, CVIndexMap()});
32598937Sdes  CVIndexMap &IndexMap = Insertion.first->second;
32698937Sdes  if (!Insertion.second)
32798937Sdes    return IndexMap;
32898937Sdes
32998937Sdes  // Mark this map as a type server map.
33098937Sdes  IndexMap.IsTypeServerMap = true;
33198937Sdes
33298937Sdes  // Check for a PDB at:
33398937Sdes  // 1. The given file path
33498937Sdes  // 2. Next to the object file or archive file
33598937Sdes  auto ExpectedSession = tryToLoadPDB(TSId, TSPath);
33698937Sdes  if (!ExpectedSession) {
33798937Sdes    consumeError(ExpectedSession.takeError());
33898937Sdes    StringRef LocalPath =
33998937Sdes        !File->ParentName.empty() ? File->ParentName : File->getName();
34098937Sdes    SmallString<128> Path = sys::path::parent_path(LocalPath);
34198937Sdes    sys::path::append(
34298937Sdes        Path, sys::path::filename(TSPath, sys::path::Style::windows));
34398937Sdes    ExpectedSession = tryToLoadPDB(TSId, Path);
34498937Sdes  }
34598937Sdes  if (auto E = ExpectedSession.takeError()) {
34698937Sdes    TypeServerIndexMappings.erase(TSId);
34798937Sdes    MissingTypeServerPDBs.emplace(TSId);
34898937Sdes    return std::move(E);
34998937Sdes  }
35098937Sdes
35198937Sdes  auto ExpectedTpi = (*ExpectedSession)->getPDBFile().getPDBTpiStream();
35298937Sdes  if (auto E = ExpectedTpi.takeError())
35398937Sdes    fatal("Type server does not have TPI stream: " + toString(std::move(E)));
35498937Sdes  auto ExpectedIpi = (*ExpectedSession)->getPDBFile().getPDBIpiStream();
35598937Sdes  if (auto E = ExpectedIpi.takeError())
35698937Sdes    fatal("Type server does not have TPI stream: " + toString(std::move(E)));
35798937Sdes
35898937Sdes  if (Config->DebugGHashes) {
35998937Sdes    // PDBs do not actually store global hashes, so when merging a type server
36098937Sdes    // PDB we have to synthesize global hashes.  To do this, we first synthesize
36198937Sdes    // global hashes for the TPI stream, since it is independent, then we
36298937Sdes    // synthesize hashes for the IPI stream, using the hashes for the TPI stream
36398937Sdes    // as inputs.
36498937Sdes    auto TpiHashes = GloballyHashedType::hashTypes(ExpectedTpi->typeArray());
36598937Sdes    auto IpiHashes =
36698937Sdes        GloballyHashedType::hashIds(ExpectedIpi->typeArray(), TpiHashes);
36798937Sdes
36898937Sdes    // Merge TPI first, because the IPI stream will reference type indices.
36998937Sdes    if (auto Err = mergeTypeRecords(GlobalTypeTable, IndexMap.TPIMap,
370124208Sdes                                    ExpectedTpi->typeArray(), TpiHashes))
371124208Sdes      fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
372124208Sdes
373124208Sdes    // Merge IPI.
374124208Sdes    if (auto Err =
375124208Sdes            mergeIdRecords(GlobalIDTable, IndexMap.TPIMap, IndexMap.IPIMap,
376124208Sdes                           ExpectedIpi->typeArray(), IpiHashes))
377124208Sdes      fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
378124208Sdes  } else {
379124208Sdes    // Merge TPI first, because the IPI stream will reference type indices.
380124208Sdes    if (auto Err = mergeTypeRecords(TypeTable, IndexMap.TPIMap,
381124208Sdes                                    ExpectedTpi->typeArray()))
382124208Sdes      fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
383124208Sdes
384124208Sdes    // Merge IPI.
385124208Sdes    if (auto Err = mergeIdRecords(IDTable, IndexMap.TPIMap, IndexMap.IPIMap,
386124208Sdes                                  ExpectedIpi->typeArray()))
387124208Sdes      fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
388124208Sdes  }
389124208Sdes
390124208Sdes  return IndexMap;
391124208Sdes}
392124208Sdes
393124208Sdesstatic bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
394124208Sdes  if (TI.isSimple())
395124208Sdes    return true;
396124208Sdes  if (TI.toArrayIndex() >= TypeIndexMap.size())
397124208Sdes    return false;
398124208Sdes  TI = TypeIndexMap[TI.toArrayIndex()];
399124208Sdes  return true;
400124208Sdes}
401124208Sdes
402124208Sdesstatic void remapTypesInSymbolRecord(ObjFile *File, SymbolKind SymKind,
403124208Sdes                                     MutableArrayRef<uint8_t> Contents,
404124208Sdes                                     const CVIndexMap &IndexMap,
405124208Sdes                                     ArrayRef<TiReference> TypeRefs) {
406  for (const TiReference &Ref : TypeRefs) {
407    unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
408    if (Contents.size() < Ref.Offset + ByteSize)
409      fatal("symbol record too short");
410
411    // This can be an item index or a type index. Choose the appropriate map.
412    ArrayRef<TypeIndex> TypeOrItemMap = IndexMap.TPIMap;
413    bool IsItemIndex = Ref.Kind == TiRefKind::IndexRef;
414    if (IsItemIndex && IndexMap.IsTypeServerMap)
415      TypeOrItemMap = IndexMap.IPIMap;
416
417    MutableArrayRef<TypeIndex> TIs(
418        reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
419    for (TypeIndex &TI : TIs) {
420      if (!remapTypeIndex(TI, TypeOrItemMap)) {
421        log("ignoring symbol record of kind 0x" + utohexstr(SymKind) + " in " +
422            File->getName() + " with bad " + (IsItemIndex ? "item" : "type") +
423            " index 0x" + utohexstr(TI.getIndex()));
424        TI = TypeIndex(SimpleTypeKind::NotTranslated);
425        continue;
426      }
427    }
428  }
429}
430
431static SymbolKind symbolKind(ArrayRef<uint8_t> RecordData) {
432  const RecordPrefix *Prefix =
433      reinterpret_cast<const RecordPrefix *>(RecordData.data());
434  return static_cast<SymbolKind>(uint16_t(Prefix->RecordKind));
435}
436
437/// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
438static void translateIdSymbols(MutableArrayRef<uint8_t> &RecordData,
439                               TypeCollection &IDTable) {
440  RecordPrefix *Prefix = reinterpret_cast<RecordPrefix *>(RecordData.data());
441
442  SymbolKind Kind = symbolKind(RecordData);
443
444  if (Kind == SymbolKind::S_PROC_ID_END) {
445    Prefix->RecordKind = SymbolKind::S_END;
446    return;
447  }
448
449  // In an object file, GPROC32_ID has an embedded reference which refers to the
450  // single object file type index namespace.  This has already been translated
451  // to the PDB file's ID stream index space, but we need to convert this to a
452  // symbol that refers to the type stream index space.  So we remap again from
453  // ID index space to type index space.
454  if (Kind == SymbolKind::S_GPROC32_ID || Kind == SymbolKind::S_LPROC32_ID) {
455    SmallVector<TiReference, 1> Refs;
456    auto Content = RecordData.drop_front(sizeof(RecordPrefix));
457    CVSymbol Sym(Kind, RecordData);
458    discoverTypeIndicesInSymbol(Sym, Refs);
459    assert(Refs.size() == 1);
460    assert(Refs.front().Count == 1);
461
462    TypeIndex *TI =
463        reinterpret_cast<TypeIndex *>(Content.data() + Refs[0].Offset);
464    // `TI` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
465    // the IPI stream, whose `FunctionType` member refers to the TPI stream.
466    // Note that LF_FUNC_ID and LF_MEMFUNC_ID have the same record layout, and
467    // in both cases we just need the second type index.
468    if (!TI->isSimple() && !TI->isNoneType()) {
469      CVType FuncIdData = IDTable.getType(*TI);
470      SmallVector<TypeIndex, 2> Indices;
471      discoverTypeIndices(FuncIdData, Indices);
472      assert(Indices.size() == 2);
473      *TI = Indices[1];
474    }
475
476    Kind = (Kind == SymbolKind::S_GPROC32_ID) ? SymbolKind::S_GPROC32
477                                              : SymbolKind::S_LPROC32;
478    Prefix->RecordKind = uint16_t(Kind);
479  }
480}
481
482/// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
483/// The object file may not be aligned.
484static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
485                                                 BumpPtrAllocator &Alloc) {
486  size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
487  assert(Size >= 4 && "record too short");
488  assert(Size <= MaxRecordLength && "record too long");
489  void *Mem = Alloc.Allocate(Size, 4);
490
491  // Copy the symbol record and zero out any padding bytes.
492  MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
493  memcpy(NewData.data(), Sym.data().data(), Sym.length());
494  memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
495
496  // Update the record prefix length. It should point to the beginning of the
497  // next record.
498  auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
499  Prefix->RecordLen = Size - 2;
500  return NewData;
501}
502
503/// Return true if this symbol opens a scope. This implies that the symbol has
504/// "parent" and "end" fields, which contain the offset of the S_END or
505/// S_INLINESITE_END record.
506static bool symbolOpensScope(SymbolKind Kind) {
507  switch (Kind) {
508  case SymbolKind::S_GPROC32:
509  case SymbolKind::S_LPROC32:
510  case SymbolKind::S_LPROC32_ID:
511  case SymbolKind::S_GPROC32_ID:
512  case SymbolKind::S_BLOCK32:
513  case SymbolKind::S_SEPCODE:
514  case SymbolKind::S_THUNK32:
515  case SymbolKind::S_INLINESITE:
516  case SymbolKind::S_INLINESITE2:
517    return true;
518  default:
519    break;
520  }
521  return false;
522}
523
524static bool symbolEndsScope(SymbolKind Kind) {
525  switch (Kind) {
526  case SymbolKind::S_END:
527  case SymbolKind::S_PROC_ID_END:
528  case SymbolKind::S_INLINESITE_END:
529    return true;
530  default:
531    break;
532  }
533  return false;
534}
535
536struct ScopeRecord {
537  ulittle32_t PtrParent;
538  ulittle32_t PtrEnd;
539};
540
541struct SymbolScope {
542  ScopeRecord *OpeningRecord;
543  uint32_t ScopeOffset;
544};
545
546static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
547                           uint32_t CurOffset, CVSymbol &Sym) {
548  assert(symbolOpensScope(Sym.kind()));
549  SymbolScope S;
550  S.ScopeOffset = CurOffset;
551  S.OpeningRecord = const_cast<ScopeRecord *>(
552      reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
553  S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
554  Stack.push_back(S);
555}
556
557static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
558                            uint32_t CurOffset, ObjFile *File) {
559  if (Stack.empty()) {
560    warn("symbol scopes are not balanced in " + File->getName());
561    return;
562  }
563  SymbolScope S = Stack.pop_back_val();
564  S.OpeningRecord->PtrEnd = CurOffset;
565}
566
567static bool symbolGoesInModuleStream(const CVSymbol &Sym) {
568  switch (Sym.kind()) {
569  case SymbolKind::S_GDATA32:
570  case SymbolKind::S_CONSTANT:
571  case SymbolKind::S_UDT:
572  // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
573  // since they are synthesized by the linker in response to S_GPROC32 and
574  // S_LPROC32, but if we do see them, don't put them in the module stream I
575  // guess.
576  case SymbolKind::S_PROCREF:
577  case SymbolKind::S_LPROCREF:
578    return false;
579  // S_GDATA32 does not go in the module stream, but S_LDATA32 does.
580  case SymbolKind::S_LDATA32:
581  default:
582    return true;
583  }
584}
585
586static bool symbolGoesInGlobalsStream(const CVSymbol &Sym) {
587  switch (Sym.kind()) {
588  case SymbolKind::S_CONSTANT:
589  case SymbolKind::S_GDATA32:
590  // S_LDATA32 goes in both the module stream and the globals stream.
591  case SymbolKind::S_LDATA32:
592  case SymbolKind::S_GPROC32:
593  case SymbolKind::S_LPROC32:
594  // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
595  // since they are synthesized by the linker in response to S_GPROC32 and
596  // S_LPROC32, but if we do see them, copy them straight through.
597  case SymbolKind::S_PROCREF:
598  case SymbolKind::S_LPROCREF:
599    return true;
600  // FIXME: For now, we drop all S_UDT symbols (i.e. they don't go in the
601  // globals stream or the modules stream).  These have special handling which
602  // needs more investigation before we can get right, but by putting them all
603  // into the globals stream WinDbg fails to display local variables of class
604  // types saying that it cannot find the type Foo *.  So as a stopgap just to
605  // keep things working, we drop them.
606  case SymbolKind::S_UDT:
607  default:
608    return false;
609  }
610}
611
612static void addGlobalSymbol(pdb::GSIStreamBuilder &Builder, ObjFile &File,
613                            const CVSymbol &Sym) {
614  switch (Sym.kind()) {
615  case SymbolKind::S_CONSTANT:
616  case SymbolKind::S_UDT:
617  case SymbolKind::S_GDATA32:
618  case SymbolKind::S_LDATA32:
619  case SymbolKind::S_PROCREF:
620  case SymbolKind::S_LPROCREF:
621    Builder.addGlobalSymbol(Sym);
622    break;
623  case SymbolKind::S_GPROC32:
624  case SymbolKind::S_LPROC32: {
625    SymbolRecordKind K = SymbolRecordKind::ProcRefSym;
626    if (Sym.kind() == SymbolKind::S_LPROC32)
627      K = SymbolRecordKind::LocalProcRef;
628    ProcRefSym PS(K);
629    PS.Module = static_cast<uint16_t>(File.ModuleDBI->getModuleIndex());
630    // For some reason, MSVC seems to add one to this value.
631    ++PS.Module;
632    PS.Name = getSymbolName(Sym);
633    PS.SumName = 0;
634    PS.SymOffset = File.ModuleDBI->getNextSymbolOffset();
635    Builder.addGlobalSymbol(PS);
636    break;
637  }
638  default:
639    llvm_unreachable("Invalid symbol kind!");
640  }
641}
642
643static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjFile *File,
644                               pdb::GSIStreamBuilder &GsiBuilder,
645                               const CVIndexMap &IndexMap,
646                               TypeCollection &IDTable,
647                               BinaryStreamRef SymData) {
648  // FIXME: Improve error recovery by warning and skipping records when
649  // possible.
650  CVSymbolArray Syms;
651  BinaryStreamReader Reader(SymData);
652  ExitOnErr(Reader.readArray(Syms, Reader.getLength()));
653  SmallVector<SymbolScope, 4> Scopes;
654  for (CVSymbol Sym : Syms) {
655    // Discover type index references in the record. Skip it if we don't know
656    // where they are.
657    SmallVector<TiReference, 32> TypeRefs;
658    if (!discoverTypeIndicesInSymbol(Sym, TypeRefs)) {
659      log("ignoring unknown symbol record with kind 0x" + utohexstr(Sym.kind()));
660      continue;
661    }
662
663    // Copy the symbol record so we can mutate it.
664    MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
665
666    // Re-map all the type index references.
667    MutableArrayRef<uint8_t> Contents =
668        NewData.drop_front(sizeof(RecordPrefix));
669    remapTypesInSymbolRecord(File, Sym.kind(), Contents, IndexMap, TypeRefs);
670
671    // An object file may have S_xxx_ID symbols, but these get converted to
672    // "real" symbols in a PDB.
673    translateIdSymbols(NewData, IDTable);
674
675    SymbolKind NewKind = symbolKind(NewData);
676
677    // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
678    CVSymbol NewSym(NewKind, NewData);
679    if (symbolOpensScope(NewKind))
680      scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(), NewSym);
681    else if (symbolEndsScope(NewKind))
682      scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
683
684    // Add the symbol to the globals stream if necessary.  Do this before adding
685    // the symbol to the module since we may need to get the next symbol offset,
686    // and writing to the module's symbol stream will update that offset.
687    if (symbolGoesInGlobalsStream(NewSym))
688      addGlobalSymbol(GsiBuilder, *File, NewSym);
689
690    // Add the symbol to the module.
691    if (symbolGoesInModuleStream(NewSym))
692      File->ModuleDBI->addSymbol(NewSym);
693  }
694}
695
696// Allocate memory for a .debug$S section and relocate it.
697static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
698                                            SectionChunk *DebugChunk) {
699  uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk->getSize());
700  assert(DebugChunk->OutputSectionOff == 0 &&
701         "debug sections should not be in output sections");
702  DebugChunk->writeTo(Buffer);
703  return consumeDebugMagic(makeArrayRef(Buffer, DebugChunk->getSize()),
704                           ".debug$S");
705}
706
707void PDBLinker::addObjFile(ObjFile *File) {
708  // Add a module descriptor for every object file. We need to put an absolute
709  // path to the object into the PDB. If this is a plain object, we make its
710  // path absolute. If it's an object in an archive, we make the archive path
711  // absolute.
712  bool InArchive = !File->ParentName.empty();
713  SmallString<128> Path = InArchive ? File->ParentName : File->getName();
714  sys::fs::make_absolute(Path);
715  sys::path::native(Path, sys::path::Style::windows);
716  StringRef Name = InArchive ? File->getName() : StringRef(Path);
717
718  File->ModuleDBI = &ExitOnErr(Builder.getDbiBuilder().addModuleInfo(Name));
719  File->ModuleDBI->setObjFileName(Path);
720
721  // Before we can process symbol substreams from .debug$S, we need to process
722  // type information, file checksums, and the string table.  Add type info to
723  // the PDB first, so that we can get the map from object file type and item
724  // indices to PDB type and item indices.
725  CVIndexMap ObjectIndexMap;
726  auto IndexMapResult = mergeDebugT(File, ObjectIndexMap);
727
728  // If the .debug$T sections fail to merge, assume there is no debug info.
729  if (!IndexMapResult) {
730    warn("Type server PDB for " + Name + " is invalid, ignoring debug info. " +
731         toString(IndexMapResult.takeError()));
732    return;
733  }
734
735  const CVIndexMap &IndexMap = *IndexMapResult;
736
737  // Now do all live .debug$S sections.
738  for (SectionChunk *DebugChunk : File->getDebugChunks()) {
739    if (!DebugChunk->isLive() || DebugChunk->getSectionName() != ".debug$S")
740      continue;
741
742    ArrayRef<uint8_t> RelocatedDebugContents =
743        relocateDebugChunk(Alloc, DebugChunk);
744    if (RelocatedDebugContents.empty())
745      continue;
746
747    DebugSubsectionArray Subsections;
748    BinaryStreamReader Reader(RelocatedDebugContents, support::little);
749    ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
750
751    DebugStringTableSubsectionRef CVStrTab;
752    DebugChecksumsSubsectionRef Checksums;
753    for (const DebugSubsectionRecord &SS : Subsections) {
754      switch (SS.kind()) {
755      case DebugSubsectionKind::StringTable:
756        ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
757        break;
758      case DebugSubsectionKind::FileChecksums:
759        ExitOnErr(Checksums.initialize(SS.getRecordData()));
760        break;
761      case DebugSubsectionKind::Lines:
762        // We can add the relocated line table directly to the PDB without
763        // modification because the file checksum offsets will stay the same.
764        File->ModuleDBI->addDebugSubsection(SS);
765        break;
766      case DebugSubsectionKind::Symbols:
767        if (Config->DebugGHashes) {
768          mergeSymbolRecords(Alloc, File, Builder.getGsiBuilder(), IndexMap,
769                             GlobalIDTable, SS.getRecordData());
770        } else {
771          mergeSymbolRecords(Alloc, File, Builder.getGsiBuilder(), IndexMap,
772                             IDTable, SS.getRecordData());
773        }
774        break;
775      default:
776        // FIXME: Process the rest of the subsections.
777        break;
778      }
779    }
780
781    if (Checksums.valid()) {
782      // Make a new file checksum table that refers to offsets in the PDB-wide
783      // string table. Generally the string table subsection appears after the
784      // checksum table, so we have to do this after looping over all the
785      // subsections.
786      if (!CVStrTab.valid())
787        fatal(".debug$S sections must have both a string table subsection "
788              "and a checksum subsection table or neither");
789      auto NewChecksums = make_unique<DebugChecksumsSubsection>(PDBStrTab);
790      for (FileChecksumEntry &FC : Checksums) {
791        StringRef FileName = ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
792        ExitOnErr(Builder.getDbiBuilder().addModuleSourceFile(*File->ModuleDBI,
793                                                              FileName));
794        NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
795      }
796      File->ModuleDBI->addDebugSubsection(std::move(NewChecksums));
797    }
798  }
799}
800
801static PublicSym32 createPublic(Defined *Def) {
802  PublicSym32 Pub(SymbolKind::S_PUB32);
803  Pub.Name = Def->getName();
804  if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
805    if (D->getCOFFSymbol().isFunctionDefinition())
806      Pub.Flags = PublicSymFlags::Function;
807  } else if (isa<DefinedImportThunk>(Def)) {
808    Pub.Flags = PublicSymFlags::Function;
809  }
810
811  OutputSection *OS = Def->getChunk()->getOutputSection();
812  assert(OS && "all publics should be in final image");
813  Pub.Offset = Def->getRVA() - OS->getRVA();
814  Pub.Segment = OS->SectionIndex;
815  return Pub;
816}
817
818// Add all object files to the PDB. Merge .debug$T sections into IpiData and
819// TpiData.
820void PDBLinker::addObjectsToPDB() {
821  for (ObjFile *File : ObjFile::Instances)
822    addObjFile(File);
823
824  Builder.getStringTableBuilder().setStrings(PDBStrTab);
825
826  // Construct TPI and IPI stream contents.
827  if (Config->DebugGHashes) {
828    addTypeInfo(Builder.getTpiBuilder(), GlobalTypeTable);
829    addTypeInfo(Builder.getIpiBuilder(), GlobalIDTable);
830  } else {
831    addTypeInfo(Builder.getTpiBuilder(), TypeTable);
832    addTypeInfo(Builder.getIpiBuilder(), IDTable);
833  }
834
835  // Compute the public and global symbols.
836  auto &GsiBuilder = Builder.getGsiBuilder();
837  std::vector<PublicSym32> Publics;
838  Symtab->forEachSymbol([&Publics](Symbol *S) {
839    // Only emit defined, live symbols that have a chunk.
840    auto *Def = dyn_cast<Defined>(S);
841    if (Def && Def->isLive() && Def->getChunk())
842      Publics.push_back(createPublic(Def));
843  });
844
845  if (!Publics.empty()) {
846    // Sort the public symbols and add them to the stream.
847    std::sort(Publics.begin(), Publics.end(),
848              [](const PublicSym32 &L, const PublicSym32 &R) {
849                return L.Name < R.Name;
850              });
851    for (const PublicSym32 &Pub : Publics)
852      GsiBuilder.addPublicSymbol(Pub);
853  }
854}
855
856static void addCommonLinkerModuleSymbols(StringRef Path,
857                                         pdb::DbiModuleDescriptorBuilder &Mod,
858                                         BumpPtrAllocator &Allocator) {
859  ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
860  Compile3Sym CS(SymbolRecordKind::Compile3Sym);
861  EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
862
863  ONS.Name = "* Linker *";
864  ONS.Signature = 0;
865
866  CS.Machine = Config->is64() ? CPUType::X64 : CPUType::Intel80386;
867  // Interestingly, if we set the string to 0.0.0.0, then when trying to view
868  // local variables WinDbg emits an error that private symbols are not present.
869  // By setting this to a valid MSVC linker version string, local variables are
870  // displayed properly.   As such, even though it is not representative of
871  // LLVM's version information, we need this for compatibility.
872  CS.Flags = CompileSym3Flags::None;
873  CS.VersionBackendBuild = 25019;
874  CS.VersionBackendMajor = 14;
875  CS.VersionBackendMinor = 10;
876  CS.VersionBackendQFE = 0;
877
878  // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
879  // linker module (which is by definition a backend), so we don't need to do
880  // anything here.  Also, it seems we can use "LLVM Linker" for the linker name
881  // without any problems.  Only the backend version has to be hardcoded to a
882  // magic number.
883  CS.VersionFrontendBuild = 0;
884  CS.VersionFrontendMajor = 0;
885  CS.VersionFrontendMinor = 0;
886  CS.VersionFrontendQFE = 0;
887  CS.Version = "LLVM Linker";
888  CS.setLanguage(SourceLanguage::Link);
889
890  ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
891  std::string ArgStr = llvm::join(Args, " ");
892  EBS.Fields.push_back("cwd");
893  SmallString<64> cwd;
894  sys::fs::current_path(cwd);
895  EBS.Fields.push_back(cwd);
896  EBS.Fields.push_back("exe");
897  SmallString<64> exe = Config->Argv[0];
898  llvm::sys::fs::make_absolute(exe);
899  EBS.Fields.push_back(exe);
900  EBS.Fields.push_back("pdb");
901  EBS.Fields.push_back(Path);
902  EBS.Fields.push_back("cmd");
903  EBS.Fields.push_back(ArgStr);
904  Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
905      ONS, Allocator, CodeViewContainer::Pdb));
906  Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
907      CS, Allocator, CodeViewContainer::Pdb));
908  Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
909      EBS, Allocator, CodeViewContainer::Pdb));
910}
911
912static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &Mod,
913                                         OutputSection &OS,
914                                         BumpPtrAllocator &Allocator) {
915  SectionSym Sym(SymbolRecordKind::SectionSym);
916  Sym.Alignment = 12; // 2^12 = 4KB
917  Sym.Characteristics = OS.getCharacteristics();
918  Sym.Length = OS.getVirtualSize();
919  Sym.Name = OS.getName();
920  Sym.Rva = OS.getRVA();
921  Sym.SectionNumber = OS.SectionIndex;
922  Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
923      Sym, Allocator, CodeViewContainer::Pdb));
924}
925
926// Creates a PDB file.
927void coff::createPDB(SymbolTable *Symtab,
928                     ArrayRef<OutputSection *> OutputSections,
929                     ArrayRef<uint8_t> SectionTable,
930                     const llvm::codeview::DebugInfo &BuildId) {
931  PDBLinker PDB(Symtab);
932  PDB.initialize(BuildId);
933  PDB.addObjectsToPDB();
934  PDB.addSections(OutputSections, SectionTable);
935  PDB.commit();
936}
937
938void PDBLinker::initialize(const llvm::codeview::DebugInfo &BuildId) {
939  ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
940
941  // Create streams in MSF for predefined streams, namely
942  // PDB, TPI, DBI and IPI.
943  for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
944    ExitOnErr(Builder.getMsfBuilder().addStream(0));
945
946  // Add an Info stream.
947  auto &InfoBuilder = Builder.getInfoBuilder();
948  InfoBuilder.setAge(BuildId.PDB70.Age);
949
950  GUID uuid;
951  memcpy(&uuid, &BuildId.PDB70.Signature, sizeof(uuid));
952  InfoBuilder.setGuid(uuid);
953  InfoBuilder.setSignature(time(nullptr));
954  InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
955
956  // Add an empty DBI stream.
957  pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
958  DbiBuilder.setAge(BuildId.PDB70.Age);
959  DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
960  ExitOnErr(DbiBuilder.addDbgStream(pdb::DbgHeaderType::NewFPO, {}));
961}
962
963void PDBLinker::addSectionContrib(pdb::DbiModuleDescriptorBuilder &LinkerModule,
964                                  OutputSection *OS, Chunk *C) {
965  pdb::SectionContrib SC;
966  memset(&SC, 0, sizeof(SC));
967  SC.ISect = OS->SectionIndex;
968  SC.Off = C->getRVA() - OS->getRVA();
969  SC.Size = C->getSize();
970  if (auto *SecChunk = dyn_cast<SectionChunk>(C)) {
971    SC.Characteristics = SecChunk->Header->Characteristics;
972    SC.Imod = SecChunk->File->ModuleDBI->getModuleIndex();
973    ArrayRef<uint8_t> Contents = SecChunk->getContents();
974    JamCRC CRC(0);
975    ArrayRef<char> CharContents = makeArrayRef(
976        reinterpret_cast<const char *>(Contents.data()), Contents.size());
977    CRC.update(CharContents);
978    SC.DataCrc = CRC.getCRC();
979  } else {
980    SC.Characteristics = OS->getCharacteristics();
981    // FIXME: When we start creating DBI for import libraries, use those here.
982    SC.Imod = LinkerModule.getModuleIndex();
983  }
984  SC.RelocCrc = 0; // FIXME
985  Builder.getDbiBuilder().addSectionContrib(SC);
986}
987
988void PDBLinker::addSections(ArrayRef<OutputSection *> OutputSections,
989                            ArrayRef<uint8_t> SectionTable) {
990  // It's not entirely clear what this is, but the * Linker * module uses it.
991  pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
992  NativePath = Config->PDBPath;
993  sys::fs::make_absolute(NativePath);
994  sys::path::native(NativePath, sys::path::Style::windows);
995  uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
996  auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
997  LinkerModule.setPdbFilePathNI(PdbFilePathNI);
998  addCommonLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
999
1000  // Add section contributions. They must be ordered by ascending RVA.
1001  for (OutputSection *OS : OutputSections) {
1002    addLinkerModuleSectionSymbol(LinkerModule, *OS, Alloc);
1003    for (Chunk *C : OS->getChunks())
1004      addSectionContrib(LinkerModule, OS, C);
1005  }
1006
1007  // Add Section Map stream.
1008  ArrayRef<object::coff_section> Sections = {
1009      (const object::coff_section *)SectionTable.data(),
1010      SectionTable.size() / sizeof(object::coff_section)};
1011  SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
1012  DbiBuilder.setSectionMap(SectionMap);
1013
1014  // Add COFF section header stream.
1015  ExitOnErr(
1016      DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
1017}
1018
1019void PDBLinker::commit() {
1020  // Write to a file.
1021  ExitOnErr(Builder.commit(Config->PDBPath));
1022}
1023