1 //===- PDB.cpp ------------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
14 #include "SymbolTable.h"
16 #include "llvm/DebugInfo/CodeView/CVDebugRecord.h"
17 #include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
18 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
19 #include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
20 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
21 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
22 #include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
23 #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
24 #include "llvm/DebugInfo/CodeView/TypeTableBuilder.h"
25 #include "llvm/DebugInfo/MSF/MSFBuilder.h"
26 #include "llvm/DebugInfo/MSF/MSFCommon.h"
27 #include "llvm/DebugInfo/PDB/GenericError.h"
28 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
29 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
30 #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
31 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
32 #include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
33 #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
34 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
35 #include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
36 #include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
37 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
38 #include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
39 #include "llvm/DebugInfo/PDB/PDB.h"
40 #include "llvm/Object/COFF.h"
41 #include "llvm/Support/BinaryByteStream.h"
42 #include "llvm/Support/Endian.h"
43 #include "llvm/Support/FileOutputBuffer.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/ScopedPrinter.h"
49 using namespace lld::coff;
51 using namespace llvm::codeview;
53 using llvm::object::coff_section;
55 static ExitOnError ExitOnErr;
58 /// Map from type index and item index in a type server PDB to the
59 /// corresponding index in the destination PDB.
61 SmallVector<TypeIndex, 0> TPIMap;
62 SmallVector<TypeIndex, 0> IPIMap;
63 bool IsTypeServerMap = false;
68 PDBLinker(SymbolTable *Symtab)
69 : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
72 /// Emit the basic PDB structure: initial streams, headers, etc.
73 void initialize(const llvm::codeview::DebugInfo *DI);
75 /// Link CodeView from each object file in the symbol table into the PDB.
76 void addObjectsToPDB();
78 /// Link CodeView from a single object file into the PDB.
79 void addObjectFile(ObjectFile *File);
81 /// Produce a mapping from the type and item indices used in the object
82 /// file to those in the destination PDB.
84 /// If the object file uses a type server PDB (compiled with /Zi), merge TPI
85 /// and IPI from the type server PDB and return a map for it. Each unique type
86 /// server PDB is merged at most once, so this may return an existing index
89 /// If the object does not use a type server PDB (compiled with /Z7), we merge
90 /// all the type and item records from the .debug$S stream and fill in the
91 /// caller-provided ObjectIndexMap.
92 const CVIndexMap &mergeDebugT(ObjectFile *File, CVIndexMap &ObjectIndexMap);
94 const CVIndexMap &maybeMergeTypeServerPDB(ObjectFile *File,
95 TypeServer2Record &TS);
97 /// Add the section map and section contributions to the PDB.
98 void addSections(ArrayRef<uint8_t> SectionTable);
100 /// Write the PDB to disk.
104 BumpPtrAllocator Alloc;
108 pdb::PDBFileBuilder Builder;
110 /// Type records that will go into the PDB TPI stream.
111 TypeTableBuilder TypeTable;
113 /// Item records that will go into the PDB IPI stream.
114 TypeTableBuilder IDTable;
116 /// PDBs use a single global string table for filenames in the file checksum
118 DebugStringTableSubsection PDBStrTab;
120 llvm::SmallString<128> NativePath;
122 std::vector<pdb::SecMapEntry> SectionMap;
124 /// Type index mappings of type server PDBs that we've loaded so far.
125 std::map<GUID, CVIndexMap> TypeServerIndexMappings;
129 // Returns a list of all SectionChunks.
130 static void addSectionContribs(SymbolTable *Symtab,
131 pdb::DbiStreamBuilder &DbiBuilder) {
132 for (Chunk *C : Symtab->getChunks())
133 if (auto *SC = dyn_cast<SectionChunk>(C))
134 DbiBuilder.addSectionContrib(SC->File->ModuleDBI, SC->Header);
137 static SectionChunk *findByName(std::vector<SectionChunk *> &Sections,
139 for (SectionChunk *C : Sections)
140 if (C->getSectionName() == Name)
145 static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
147 // First 4 bytes are section magic.
149 fatal(SecName + " too short");
150 if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
151 fatal(SecName + " has an invalid magic");
152 return Data.slice(4);
155 static ArrayRef<uint8_t> getDebugSection(ObjectFile *File, StringRef SecName) {
156 if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
157 return consumeDebugMagic(Sec->getContents(), SecName);
161 static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
162 TypeTableBuilder &TypeTable) {
163 // Start the TPI or IPI stream header.
164 TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
166 // Flatten the in memory type table.
167 TypeTable.ForEachRecord([&](TypeIndex TI, ArrayRef<uint8_t> Rec) {
168 // FIXME: Hash types.
169 TpiBuilder.addTypeRecord(Rec, None);
173 static Optional<TypeServer2Record>
174 maybeReadTypeServerRecord(CVTypeArray &Types) {
175 auto I = Types.begin();
176 if (I == Types.end())
178 const CVType &Type = *I;
179 if (Type.kind() != LF_TYPESERVER2)
181 TypeServer2Record TS;
182 if (auto EC = TypeDeserializer::deserializeAs(const_cast<CVType &>(Type), TS))
183 fatal(EC, "error reading type server record");
184 return std::move(TS);
187 const CVIndexMap &PDBLinker::mergeDebugT(ObjectFile *File,
188 CVIndexMap &ObjectIndexMap) {
189 ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
191 return ObjectIndexMap;
193 BinaryByteStream Stream(Data, support::little);
195 BinaryStreamReader Reader(Stream);
196 if (auto EC = Reader.readArray(Types, Reader.getLength()))
197 fatal(EC, "Reader::readArray failed");
199 // Look through type servers. If we've already seen this type server, don't
200 // merge any type information.
201 if (Optional<TypeServer2Record> TS = maybeReadTypeServerRecord(Types))
202 return maybeMergeTypeServerPDB(File, *TS);
204 // This is a /Z7 object. Fill in the temporary, caller-provided
206 if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable,
207 ObjectIndexMap.TPIMap, Types))
208 fatal(Err, "codeview::mergeTypeAndIdRecords failed");
209 return ObjectIndexMap;
212 static Expected<std::unique_ptr<pdb::NativeSession>>
213 tryToLoadPDB(const GUID &GuidFromObj, StringRef TSPath) {
214 std::unique_ptr<pdb::IPDBSession> ThisSession;
216 pdb::loadDataForPDB(pdb::PDB_ReaderType::Native, TSPath, ThisSession))
217 return std::move(EC);
219 std::unique_ptr<pdb::NativeSession> NS(
220 static_cast<pdb::NativeSession *>(ThisSession.release()));
221 pdb::PDBFile &File = NS->getPDBFile();
222 auto ExpectedInfo = File.getPDBInfoStream();
223 // All PDB Files should have an Info stream.
225 return ExpectedInfo.takeError();
227 // Just because a file with a matching name was found and it was an actual
228 // PDB file doesn't mean it matches. For it to match the InfoStream's GUID
229 // must match the GUID specified in the TypeServer2 record.
230 if (ExpectedInfo->getGuid() != GuidFromObj)
231 return make_error<pdb::GenericError>(
232 pdb::generic_error_code::type_server_not_found, TSPath);
234 return std::move(NS);
237 const CVIndexMap &PDBLinker::maybeMergeTypeServerPDB(ObjectFile *File,
238 TypeServer2Record &TS) {
239 // First, check if we already loaded a PDB with this GUID. Return the type
240 // index mapping if we have it.
241 auto Insertion = TypeServerIndexMappings.insert({TS.getGuid(), CVIndexMap()});
242 CVIndexMap &IndexMap = Insertion.first->second;
243 if (!Insertion.second)
246 // Mark this map as a type server map.
247 IndexMap.IsTypeServerMap = true;
249 // Check for a PDB at:
250 // 1. The given file path
251 // 2. Next to the object file or archive file
252 auto ExpectedSession = tryToLoadPDB(TS.getGuid(), TS.getName());
253 if (!ExpectedSession) {
254 consumeError(ExpectedSession.takeError());
255 StringRef LocalPath =
256 !File->ParentName.empty() ? File->ParentName : File->getName();
257 SmallString<128> Path = sys::path::parent_path(LocalPath);
259 Path, sys::path::filename(TS.getName(), sys::path::Style::windows));
260 ExpectedSession = tryToLoadPDB(TS.getGuid(), Path);
262 if (auto E = ExpectedSession.takeError())
263 fatal(E, "Type server PDB was not found");
265 // Merge TPI first, because the IPI stream will reference type indices.
266 auto ExpectedTpi = (*ExpectedSession)->getPDBFile().getPDBTpiStream();
267 if (auto E = ExpectedTpi.takeError())
268 fatal(E, "Type server does not have TPI stream");
269 if (auto Err = mergeTypeRecords(TypeTable, IndexMap.TPIMap,
270 ExpectedTpi->typeArray()))
271 fatal(Err, "codeview::mergeTypeRecords failed");
274 auto ExpectedIpi = (*ExpectedSession)->getPDBFile().getPDBIpiStream();
275 if (auto E = ExpectedIpi.takeError())
276 fatal(E, "Type server does not have TPI stream");
277 if (auto Err = mergeIdRecords(IDTable, IndexMap.TPIMap, IndexMap.IPIMap,
278 ExpectedIpi->typeArray()))
279 fatal(Err, "codeview::mergeIdRecords failed");
284 static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
287 if (TI.toArrayIndex() >= TypeIndexMap.size())
289 TI = TypeIndexMap[TI.toArrayIndex()];
293 static void remapTypesInSymbolRecord(ObjectFile *File,
294 MutableArrayRef<uint8_t> Contents,
295 const CVIndexMap &IndexMap,
296 ArrayRef<TiReference> TypeRefs) {
297 for (const TiReference &Ref : TypeRefs) {
298 unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
299 if (Contents.size() < Ref.Offset + ByteSize)
300 fatal("symbol record too short");
302 // This can be an item index or a type index. Choose the appropriate map.
303 ArrayRef<TypeIndex> TypeOrItemMap = IndexMap.TPIMap;
304 if (Ref.Kind == TiRefKind::IndexRef && IndexMap.IsTypeServerMap)
305 TypeOrItemMap = IndexMap.IPIMap;
307 MutableArrayRef<TypeIndex> TIs(
308 reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
309 for (TypeIndex &TI : TIs) {
310 if (!remapTypeIndex(TI, TypeOrItemMap)) {
311 TI = TypeIndex(SimpleTypeKind::NotTranslated);
312 log("ignoring symbol record in " + File->getName() +
313 " with bad type index 0x" + utohexstr(TI.getIndex()));
320 /// MSVC translates S_PROC_ID_END to S_END.
321 uint16_t canonicalizeSymbolKind(SymbolKind Kind) {
322 if (Kind == SymbolKind::S_PROC_ID_END)
323 return SymbolKind::S_END;
327 /// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
328 /// The object file may not be aligned.
329 static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
330 BumpPtrAllocator &Alloc) {
331 size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
332 assert(Size >= 4 && "record too short");
333 assert(Size <= MaxRecordLength && "record too long");
334 void *Mem = Alloc.Allocate(Size, 4);
336 // Copy the symbol record and zero out any padding bytes.
337 MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
338 memcpy(NewData.data(), Sym.data().data(), Sym.length());
339 memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
341 // Update the record prefix length. It should point to the beginning of the
342 // next record. MSVC does some canonicalization of the record kind, so we do
344 auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
345 Prefix->RecordKind = canonicalizeSymbolKind(Sym.kind());
346 Prefix->RecordLen = Size - 2;
350 /// Return true if this symbol opens a scope. This implies that the symbol has
351 /// "parent" and "end" fields, which contain the offset of the S_END or
352 /// S_INLINESITE_END record.
353 static bool symbolOpensScope(SymbolKind Kind) {
355 case SymbolKind::S_GPROC32:
356 case SymbolKind::S_LPROC32:
357 case SymbolKind::S_LPROC32_ID:
358 case SymbolKind::S_GPROC32_ID:
359 case SymbolKind::S_BLOCK32:
360 case SymbolKind::S_SEPCODE:
361 case SymbolKind::S_THUNK32:
362 case SymbolKind::S_INLINESITE:
363 case SymbolKind::S_INLINESITE2:
371 static bool symbolEndsScope(SymbolKind Kind) {
373 case SymbolKind::S_END:
374 case SymbolKind::S_PROC_ID_END:
375 case SymbolKind::S_INLINESITE_END:
384 ulittle32_t PtrParent;
389 ScopeRecord *OpeningRecord;
390 uint32_t ScopeOffset;
393 static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
394 uint32_t CurOffset, CVSymbol &Sym) {
395 assert(symbolOpensScope(Sym.kind()));
397 S.ScopeOffset = CurOffset;
398 S.OpeningRecord = const_cast<ScopeRecord *>(
399 reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
400 S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
404 static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
405 uint32_t CurOffset, ObjectFile *File) {
407 warn("symbol scopes are not balanced in " + File->getName());
410 SymbolScope S = Stack.pop_back_val();
411 S.OpeningRecord->PtrEnd = CurOffset;
414 static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjectFile *File,
415 const CVIndexMap &IndexMap,
416 BinaryStreamRef SymData) {
417 // FIXME: Improve error recovery by warning and skipping records when
420 BinaryStreamReader Reader(SymData);
421 ExitOnErr(Reader.readArray(Syms, Reader.getLength()));
422 SmallVector<SymbolScope, 4> Scopes;
423 for (const CVSymbol &Sym : Syms) {
424 // Discover type index references in the record. Skip it if we don't know
426 SmallVector<TiReference, 32> TypeRefs;
427 if (!discoverTypeIndices(Sym, TypeRefs)) {
428 log("ignoring unknown symbol record with kind 0x" + utohexstr(Sym.kind()));
432 // Copy the symbol record so we can mutate it.
433 MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
435 // Re-map all the type index references.
436 MutableArrayRef<uint8_t> Contents =
437 NewData.drop_front(sizeof(RecordPrefix));
438 remapTypesInSymbolRecord(File, Contents, IndexMap, TypeRefs);
440 // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
441 CVSymbol NewSym(Sym.kind(), NewData);
442 if (symbolOpensScope(Sym.kind()))
443 scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(), NewSym);
444 else if (symbolEndsScope(Sym.kind()))
445 scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
447 // Add the symbol to the module.
448 File->ModuleDBI->addSymbol(NewSym);
452 // Allocate memory for a .debug$S section and relocate it.
453 static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
454 SectionChunk *DebugChunk) {
455 uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk->getSize());
456 assert(DebugChunk->OutputSectionOff == 0 &&
457 "debug sections should not be in output sections");
458 DebugChunk->writeTo(Buffer);
459 return consumeDebugMagic(makeArrayRef(Buffer, DebugChunk->getSize()),
463 void PDBLinker::addObjectFile(ObjectFile *File) {
464 // Add a module descriptor for every object file. We need to put an absolute
465 // path to the object into the PDB. If this is a plain object, we make its
466 // path absolute. If it's an object in an archive, we make the archive path
468 bool InArchive = !File->ParentName.empty();
469 SmallString<128> Path = InArchive ? File->ParentName : File->getName();
470 sys::fs::make_absolute(Path);
471 sys::path::native(Path, sys::path::Style::windows);
472 StringRef Name = InArchive ? File->getName() : StringRef(Path);
474 File->ModuleDBI = &ExitOnErr(Builder.getDbiBuilder().addModuleInfo(Name));
475 File->ModuleDBI->setObjFileName(Path);
477 // Before we can process symbol substreams from .debug$S, we need to process
478 // type information, file checksums, and the string table. Add type info to
479 // the PDB first, so that we can get the map from object file type and item
480 // indices to PDB type and item indices.
481 CVIndexMap ObjectIndexMap;
482 const CVIndexMap &IndexMap = mergeDebugT(File, ObjectIndexMap);
484 // Now do all live .debug$S sections.
485 for (SectionChunk *DebugChunk : File->getDebugChunks()) {
486 if (!DebugChunk->isLive() || DebugChunk->getSectionName() != ".debug$S")
489 ArrayRef<uint8_t> RelocatedDebugContents =
490 relocateDebugChunk(Alloc, DebugChunk);
491 if (RelocatedDebugContents.empty())
494 DebugSubsectionArray Subsections;
495 BinaryStreamReader Reader(RelocatedDebugContents, support::little);
496 ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
498 DebugStringTableSubsectionRef CVStrTab;
499 DebugChecksumsSubsectionRef Checksums;
500 for (const DebugSubsectionRecord &SS : Subsections) {
502 case DebugSubsectionKind::StringTable:
503 ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
505 case DebugSubsectionKind::FileChecksums:
506 ExitOnErr(Checksums.initialize(SS.getRecordData()));
508 case DebugSubsectionKind::Lines:
509 // We can add the relocated line table directly to the PDB without
510 // modification because the file checksum offsets will stay the same.
511 File->ModuleDBI->addDebugSubsection(SS);
513 case DebugSubsectionKind::Symbols:
514 mergeSymbolRecords(Alloc, File, IndexMap, SS.getRecordData());
517 // FIXME: Process the rest of the subsections.
522 if (Checksums.valid()) {
523 // Make a new file checksum table that refers to offsets in the PDB-wide
524 // string table. Generally the string table subsection appears after the
525 // checksum table, so we have to do this after looping over all the
527 if (!CVStrTab.valid())
528 fatal(".debug$S sections must have both a string table subsection "
529 "and a checksum subsection table or neither");
530 auto NewChecksums = make_unique<DebugChecksumsSubsection>(PDBStrTab);
531 for (FileChecksumEntry &FC : Checksums) {
532 StringRef FileName = ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
533 ExitOnErr(Builder.getDbiBuilder().addModuleSourceFile(*File->ModuleDBI,
535 NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
537 File->ModuleDBI->addDebugSubsection(std::move(NewChecksums));
542 // Add all object files to the PDB. Merge .debug$T sections into IpiData and
544 void PDBLinker::addObjectsToPDB() {
545 for (ObjectFile *File : Symtab->ObjectFiles)
548 Builder.getStringTableBuilder().setStrings(PDBStrTab);
550 // Construct TPI stream contents.
551 addTypeInfo(Builder.getTpiBuilder(), TypeTable);
553 // Construct IPI stream contents.
554 addTypeInfo(Builder.getIpiBuilder(), IDTable);
556 // Add public and symbol records stream.
558 // For now we don't actually write any thing useful to the publics stream, but
559 // the act of "getting" it also creates it lazily so that we write an empty
561 (void)Builder.getPublicsBuilder();
564 static void addLinkerModuleSymbols(StringRef Path,
565 pdb::DbiModuleDescriptorBuilder &Mod,
566 BumpPtrAllocator &Allocator) {
567 codeview::SymbolSerializer Serializer(Allocator, CodeViewContainer::Pdb);
568 codeview::ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
569 codeview::Compile3Sym CS(SymbolRecordKind::Compile3Sym);
570 codeview::EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
572 ONS.Name = "* Linker *";
575 CS.Machine = Config->is64() ? CPUType::X64 : CPUType::Intel80386;
576 CS.Flags = CompileSym3Flags::None;
577 CS.VersionBackendBuild = 0;
578 CS.VersionBackendMajor = 0;
579 CS.VersionBackendMinor = 0;
580 CS.VersionBackendQFE = 0;
581 CS.VersionFrontendBuild = 0;
582 CS.VersionFrontendMajor = 0;
583 CS.VersionFrontendMinor = 0;
584 CS.VersionFrontendQFE = 0;
585 CS.Version = "LLVM Linker";
586 CS.setLanguage(SourceLanguage::Link);
588 ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
589 std::string ArgStr = llvm::join(Args, " ");
590 EBS.Fields.push_back("cwd");
592 sys::fs::current_path(cwd);
593 EBS.Fields.push_back(cwd);
594 EBS.Fields.push_back("exe");
595 EBS.Fields.push_back(Config->Argv[0]);
596 EBS.Fields.push_back("pdb");
597 EBS.Fields.push_back(Path);
598 EBS.Fields.push_back("cmd");
599 EBS.Fields.push_back(ArgStr);
600 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
601 ONS, Allocator, CodeViewContainer::Pdb));
602 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
603 CS, Allocator, CodeViewContainer::Pdb));
604 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
605 EBS, Allocator, CodeViewContainer::Pdb));
608 // Creates a PDB file.
609 void coff::createPDB(SymbolTable *Symtab, ArrayRef<uint8_t> SectionTable,
610 const llvm::codeview::DebugInfo *DI) {
611 PDBLinker PDB(Symtab);
613 PDB.addObjectsToPDB();
614 PDB.addSections(SectionTable);
618 void PDBLinker::initialize(const llvm::codeview::DebugInfo *DI) {
619 ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
621 // Create streams in MSF for predefined streams, namely
622 // PDB, TPI, DBI and IPI.
623 for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
624 ExitOnErr(Builder.getMsfBuilder().addStream(0));
626 // Add an Info stream.
627 auto &InfoBuilder = Builder.getInfoBuilder();
628 InfoBuilder.setAge(DI ? DI->PDB70.Age : 0);
632 memcpy(&uuid, &DI->PDB70.Signature, sizeof(uuid));
633 InfoBuilder.setGuid(uuid);
634 InfoBuilder.setSignature(time(nullptr));
635 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
637 // Add an empty DBI stream.
638 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
639 DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
640 ExitOnErr(DbiBuilder.addDbgStream(pdb::DbgHeaderType::NewFPO, {}));
643 void PDBLinker::addSections(ArrayRef<uint8_t> SectionTable) {
644 // Add Section Contributions.
645 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
646 addSectionContribs(Symtab, DbiBuilder);
648 // Add Section Map stream.
649 ArrayRef<object::coff_section> Sections = {
650 (const object::coff_section *)SectionTable.data(),
651 SectionTable.size() / sizeof(object::coff_section)};
652 SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
653 DbiBuilder.setSectionMap(SectionMap);
655 // It's not entirely clear what this is, but the * Linker * module uses it.
656 NativePath = Config->PDBPath;
657 sys::fs::make_absolute(NativePath);
658 sys::path::native(NativePath, sys::path::Style::windows);
659 uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
660 auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
661 LinkerModule.setPdbFilePathNI(PdbFilePathNI);
662 addLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
664 // Add COFF section header stream.
666 DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
669 void PDBLinker::commit() {
671 ExitOnErr(Builder.commit(Config->PDBPath));