blob: b73bc08ce3b2c975738e8157f44715d0845ba927 [file] [log] [blame]
Rui Ueyamae7378242015-12-04 23:11:05 +00001//===- 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
Rui Ueyama1d99ab32016-09-15 22:24:51 +000010#include "PDB.h"
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000011#include "Chunks.h"
Rui Ueyamabe939b32016-11-21 17:22:35 +000012#include "Config.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000013#include "Error.h"
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000014#include "SymbolTable.h"
15#include "Symbols.h"
Saleem Abdulrasooldf8a13b2017-01-04 17:56:54 +000016#include "llvm/DebugInfo/CodeView/CVDebugRecord.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000017#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
Reid Kleckner44cdb102017-06-19 17:21:45 +000018#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
19#include "llvm/DebugInfo/CodeView/DebugSubsectionVisitor.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000020#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
Zachary Turner6708e0b2017-07-10 21:01:37 +000021#include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000022#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerd0e6e242017-06-21 17:25:56 +000023#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
Rui Ueyama52896622017-01-12 03:09:25 +000024#include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
25#include "llvm/DebugInfo/CodeView/TypeTableBuilder.h"
Rui Ueyamab28c6d42016-09-16 04:32:33 +000026#include "llvm/DebugInfo/MSF/MSFBuilder.h"
Rui Ueyama7f382992016-09-15 18:55:18 +000027#include "llvm/DebugInfo/MSF/MSFCommon.h"
Zachary Turner6708e0b2017-07-10 21:01:37 +000028#include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000029#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/PDBFile.h"
34#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
Rafael Espindolaa0f30da2017-05-02 20:19:42 +000035#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
Zachary Turner7b327d02017-02-16 23:35:45 +000036#include "llvm/DebugInfo/PDB/Native/PDBTypeServerHandler.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000037#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
38#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
Rui Ueyama20df4ec2016-10-31 21:09:21 +000039#include "llvm/Object/COFF.h"
Zachary Turnerd9dc2822017-03-02 20:52:51 +000040#include "llvm/Support/BinaryByteStream.h"
Rui Ueyama1763c0d2015-12-08 18:39:55 +000041#include "llvm/Support/Endian.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000042#include "llvm/Support/FileOutputBuffer.h"
Zachary Turner7b327d02017-02-16 23:35:45 +000043#include "llvm/Support/Path.h"
Rui Ueyamabe939b32016-11-21 17:22:35 +000044#include "llvm/Support/ScopedPrinter.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000045#include <memory>
46
Rui Ueyama1d99ab32016-09-15 22:24:51 +000047using namespace lld;
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000048using namespace lld::coff;
Rui Ueyamae7378242015-12-04 23:11:05 +000049using namespace llvm;
Rui Ueyamabe939b32016-11-21 17:22:35 +000050using namespace llvm::codeview;
Rui Ueyamae7378242015-12-04 23:11:05 +000051
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000052using llvm::object::coff_section;
53
Rui Ueyamab28c6d42016-09-16 04:32:33 +000054static ExitOnError ExitOnErr;
55
Reid Kleckner0faf6d72017-07-14 00:14:58 +000056namespace {
57class PDBLinker {
58public:
59 PDBLinker(SymbolTable *Symtab)
60 : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
61 IDTable(Alloc) {}
62
63 /// Emit the basic PDB structure: initial streams, headers, etc.
64 void initialize(const llvm::codeview::DebugInfo *DI);
65
66 /// Link CodeView from each object file in the symbol table into the PDB.
67 void addObjectsToPDB();
68
69 /// Link CodeView from a single object file into the PDB.
70 void addObjectFile(ObjectFile *File);
71
72 /// Merge the type information from the .debug$T section in the given object
73 /// file. Produce a mapping from object file type indices to type or
74 /// item indices in the final PDB.
75 void mergeDebugT(ObjectFile *File, SmallVectorImpl<TypeIndex> &TypeIndexMap);
76
77 /// Add the section map and section contributions to the PDB.
78 void addSections(ArrayRef<uint8_t> SectionTable);
79
80 /// Write the PDB to disk.
81 void commit();
82
83private:
84 BumpPtrAllocator Alloc;
85
86 SymbolTable *Symtab;
87
88 pdb::PDBFileBuilder Builder;
89
90 /// Type records that will go into the PDB TPI stream.
91 TypeTableBuilder TypeTable;
92
93 /// Item records that will go into the PDB IPI stream.
94 TypeTableBuilder IDTable;
95
96 /// PDBs use a single global string table for filenames in the file checksum
97 /// table.
98 DebugStringTableSubsection PDBStrTab;
99
100 // Follow type servers. If the same type server is encountered more than once
101 // for this instance of `PDBTypeServerHandler` (for example if many object
102 // files reference the same TypeServer), the types from the TypeServer will
103 // only be visited once.
104 pdb::PDBTypeServerHandler TSHandler;
105
106 llvm::SmallString<128> NativePath;
107
108 std::vector<pdb::SecMapEntry> SectionMap;
109};
110}
111
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000112// Returns a list of all SectionChunks.
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000113static void addSectionContribs(SymbolTable *Symtab,
114 pdb::DbiStreamBuilder &DbiBuilder) {
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000115 for (Chunk *C : Symtab->getChunks())
116 if (auto *SC = dyn_cast<SectionChunk>(C))
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000117 DbiBuilder.addSectionContrib(SC->File->ModuleDBI, SC->Header);
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000118}
119
Rui Ueyamabe939b32016-11-21 17:22:35 +0000120static SectionChunk *findByName(std::vector<SectionChunk *> &Sections,
121 StringRef Name) {
122 for (SectionChunk *C : Sections)
123 if (C->getSectionName() == Name)
124 return C;
125 return nullptr;
126}
127
Reid Kleckner44cdb102017-06-19 17:21:45 +0000128static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
129 StringRef SecName) {
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000130 // First 4 bytes are section magic.
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000131 if (Data.size() < 4)
Rui Ueyama52896622017-01-12 03:09:25 +0000132 fatal(SecName + " too short");
Reid Kleckner44cdb102017-06-19 17:21:45 +0000133 if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
Rui Ueyama52896622017-01-12 03:09:25 +0000134 fatal(SecName + " has an invalid magic");
Rui Ueyama26186c72016-12-09 04:46:54 +0000135 return Data.slice(4);
136}
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000137
Reid Kleckner44cdb102017-06-19 17:21:45 +0000138static ArrayRef<uint8_t> getDebugSection(ObjectFile *File, StringRef SecName) {
139 if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
140 return consumeDebugMagic(Sec->getContents(), SecName);
141 return {};
142}
143
Reid Kleckner5d577522017-03-24 17:26:38 +0000144static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
Reid Kleckner44cdb102017-06-19 17:21:45 +0000145 TypeTableBuilder &TypeTable) {
Reid Kleckner5d577522017-03-24 17:26:38 +0000146 // Start the TPI or IPI stream header.
147 TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
Rui Ueyama52896622017-01-12 03:09:25 +0000148
Reid Kleckner5d577522017-03-24 17:26:38 +0000149 // Flatten the in memory type table.
Reid Kleckner5d577522017-03-24 17:26:38 +0000150 TypeTable.ForEachRecord([&](TypeIndex TI, ArrayRef<uint8_t> Rec) {
Reid Kleckner13fc4112017-04-04 00:56:34 +0000151 // FIXME: Hash types.
152 TpiBuilder.addTypeRecord(Rec, None);
Reid Kleckner5d577522017-03-24 17:26:38 +0000153 });
Reid Kleckner5d577522017-03-24 17:26:38 +0000154}
155
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000156void PDBLinker::mergeDebugT(ObjectFile *File,
157 SmallVectorImpl<TypeIndex> &TypeIndexMap) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000158 ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
159 if (Data.empty())
160 return;
161
Reid Kleckner6597c282017-07-13 20:12:23 +0000162 // Look for type server PDBs next to the input file. If this file has a parent
163 // archive, look next to the archive path.
164 StringRef LocalPath =
165 !File->ParentName.empty() ? File->ParentName : File->getName();
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000166 TSHandler.addSearchPath(sys::path::parent_path(LocalPath));
Reid Kleckner6597c282017-07-13 20:12:23 +0000167
Reid Kleckner44cdb102017-06-19 17:21:45 +0000168 BinaryByteStream Stream(Data, support::little);
169 CVTypeArray Types;
170 BinaryStreamReader Reader(Stream);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000171 if (auto EC = Reader.readArray(Types, Reader.getLength()))
172 fatal(EC, "Reader::readArray failed");
Reid Kleckner6597c282017-07-13 20:12:23 +0000173 if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable, TypeIndexMap,
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000174 &TSHandler, Types))
Reid Kleckner44cdb102017-06-19 17:21:45 +0000175 fatal(Err, "codeview::mergeTypeStreams failed");
176}
177
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000178static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
179 if (TI.isSimple())
180 return true;
181 if (TI.toArrayIndex() >= TypeIndexMap.size())
182 return false;
183 TI = TypeIndexMap[TI.toArrayIndex()];
184 return true;
185}
186
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000187static void remapTypesInSymbolRecord(ObjectFile *File,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000188 MutableArrayRef<uint8_t> Contents,
189 ArrayRef<TypeIndex> TypeIndexMap,
190 ArrayRef<TiReference> TypeRefs) {
191 for (const TiReference &Ref : TypeRefs) {
192 unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000193 if (Contents.size() < Ref.Offset + ByteSize)
194 fatal("symbol record too short");
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000195 MutableArrayRef<TypeIndex> TIs(
196 reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000197 for (TypeIndex &TI : TIs) {
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000198 if (!remapTypeIndex(TI, TypeIndexMap)) {
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000199 TI = TypeIndex(SimpleTypeKind::NotTranslated);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000200 log("ignoring symbol record in " + File->getName() +
201 " with bad type index 0x" + utohexstr(TI.getIndex()));
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000202 continue;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000203 }
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000204 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000205 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000206}
207
208/// MSVC translates S_PROC_ID_END to S_END.
209uint16_t canonicalizeSymbolKind(SymbolKind Kind) {
210 if (Kind == SymbolKind::S_PROC_ID_END)
211 return SymbolKind::S_END;
212 return Kind;
213}
214
215/// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
216/// The object file may not be aligned.
217static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
218 BumpPtrAllocator &Alloc) {
219 size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
220 assert(Size >= 4 && "record too short");
221 assert(Size <= MaxRecordLength && "record too long");
222 void *Mem = Alloc.Allocate(Size, 4);
223
224 // Copy the symbol record and zero out any padding bytes.
225 MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
226 memcpy(NewData.data(), Sym.data().data(), Sym.length());
227 memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
228
229 // Update the record prefix length. It should point to the beginning of the
230 // next record. MSVC does some canonicalization of the record kind, so we do
231 // that as well.
232 auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
233 Prefix->RecordKind = canonicalizeSymbolKind(Sym.kind());
234 Prefix->RecordLen = Size - 2;
235 return NewData;
236}
237
Reid Kleckner3f851922017-07-06 16:39:32 +0000238/// Return true if this symbol opens a scope. This implies that the symbol has
239/// "parent" and "end" fields, which contain the offset of the S_END or
240/// S_INLINESITE_END record.
241static bool symbolOpensScope(SymbolKind Kind) {
242 switch (Kind) {
243 case SymbolKind::S_GPROC32:
244 case SymbolKind::S_LPROC32:
245 case SymbolKind::S_LPROC32_ID:
246 case SymbolKind::S_GPROC32_ID:
247 case SymbolKind::S_BLOCK32:
248 case SymbolKind::S_SEPCODE:
249 case SymbolKind::S_THUNK32:
250 case SymbolKind::S_INLINESITE:
251 case SymbolKind::S_INLINESITE2:
252 return true;
253 default:
254 break;
255 }
256 return false;
257}
258
259static bool symbolEndsScope(SymbolKind Kind) {
260 switch (Kind) {
261 case SymbolKind::S_END:
262 case SymbolKind::S_PROC_ID_END:
263 case SymbolKind::S_INLINESITE_END:
264 return true;
265 default:
266 break;
267 }
268 return false;
269}
270
271struct ScopeRecord {
272 ulittle32_t PtrParent;
273 ulittle32_t PtrEnd;
274};
275
276struct SymbolScope {
277 ScopeRecord *OpeningRecord;
278 uint32_t ScopeOffset;
279};
280
281static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
282 uint32_t CurOffset, CVSymbol &Sym) {
283 assert(symbolOpensScope(Sym.kind()));
284 SymbolScope S;
285 S.ScopeOffset = CurOffset;
286 S.OpeningRecord = const_cast<ScopeRecord *>(
287 reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
288 S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
289 Stack.push_back(S);
290}
291
292static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
293 uint32_t CurOffset, ObjectFile *File) {
294 if (Stack.empty()) {
295 warn("symbol scopes are not balanced in " + File->getName());
296 return;
297 }
298 SymbolScope S = Stack.pop_back_val();
299 S.OpeningRecord->PtrEnd = CurOffset;
300}
301
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000302static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjectFile *File,
303 ArrayRef<TypeIndex> TypeIndexMap,
304 BinaryStreamRef SymData) {
305 // FIXME: Improve error recovery by warning and skipping records when
306 // possible.
307 CVSymbolArray Syms;
308 BinaryStreamReader Reader(SymData);
309 ExitOnErr(Reader.readArray(Syms, Reader.getLength()));
Reid Kleckner3f851922017-07-06 16:39:32 +0000310 SmallVector<SymbolScope, 4> Scopes;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000311 for (const CVSymbol &Sym : Syms) {
312 // Discover type index references in the record. Skip it if we don't know
313 // where they are.
314 SmallVector<TiReference, 32> TypeRefs;
315 if (!discoverTypeIndices(Sym, TypeRefs)) {
316 log("ignoring unknown symbol record with kind 0x" + utohexstr(Sym.kind()));
317 continue;
318 }
319
320 // Copy the symbol record so we can mutate it.
321 MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
322
323 // Re-map all the type index references.
324 MutableArrayRef<uint8_t> Contents =
325 NewData.drop_front(sizeof(RecordPrefix));
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000326 remapTypesInSymbolRecord(File, Contents, TypeIndexMap, TypeRefs);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000327
Reid Kleckner3f851922017-07-06 16:39:32 +0000328 // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
329 CVSymbol NewSym(Sym.kind(), NewData);
330 if (symbolOpensScope(Sym.kind()))
331 scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(), NewSym);
332 else if (symbolEndsScope(Sym.kind()))
333 scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000334
335 // Add the symbol to the module.
Reid Kleckner3f851922017-07-06 16:39:32 +0000336 File->ModuleDBI->addSymbol(NewSym);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000337 }
338}
339
Reid Kleckner44cdb102017-06-19 17:21:45 +0000340// Allocate memory for a .debug$S section and relocate it.
341static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
342 SectionChunk *DebugChunk) {
343 uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk->getSize());
344 assert(DebugChunk->OutputSectionOff == 0 &&
345 "debug sections should not be in output sections");
346 DebugChunk->writeTo(Buffer);
347 return consumeDebugMagic(makeArrayRef(Buffer, DebugChunk->getSize()),
348 ".debug$S");
349}
350
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000351void PDBLinker::addObjectFile(ObjectFile *File) {
352 // Add a module descriptor for every object file. We need to put an absolute
353 // path to the object into the PDB. If this is a plain object, we make its
354 // path absolute. If it's an object in an archive, we make the archive path
355 // absolute.
356 bool InArchive = !File->ParentName.empty();
357 SmallString<128> Path = InArchive ? File->ParentName : File->getName();
358 sys::fs::make_absolute(Path);
359 sys::path::native(Path, sys::path::Style::windows);
360 StringRef Name = InArchive ? File->getName() : StringRef(Path);
Zachary Turner2897e032017-05-25 21:16:03 +0000361
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000362 File->ModuleDBI = &ExitOnErr(Builder.getDbiBuilder().addModuleInfo(Name));
363 File->ModuleDBI->setObjFileName(Path);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000364
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000365 // Before we can process symbol substreams from .debug$S, we need to process
366 // type information, file checksums, and the string table. Add type info to
367 // the PDB first, so that we can get the map from object file type and item
368 // indices to PDB type and item indices.
369 SmallVector<TypeIndex, 128> TypeIndexMap;
370 mergeDebugT(File, TypeIndexMap);
Zachary Turner448dea42017-07-07 18:46:14 +0000371
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000372 // Now do all live .debug$S sections.
373 for (SectionChunk *DebugChunk : File->getDebugChunks()) {
374 if (!DebugChunk->isLive() || DebugChunk->getSectionName() != ".debug$S")
375 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000376
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000377 ArrayRef<uint8_t> RelocatedDebugContents =
378 relocateDebugChunk(Alloc, DebugChunk);
379 if (RelocatedDebugContents.empty())
380 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000381
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000382 DebugSubsectionArray Subsections;
383 BinaryStreamReader Reader(RelocatedDebugContents, support::little);
384 ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
Rui Ueyama52896622017-01-12 03:09:25 +0000385
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000386 DebugStringTableSubsectionRef CVStrTab;
387 DebugChecksumsSubsectionRef Checksums;
388 for (const DebugSubsectionRecord &SS : Subsections) {
389 switch (SS.kind()) {
390 case DebugSubsectionKind::StringTable:
391 ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
392 break;
393 case DebugSubsectionKind::FileChecksums:
394 ExitOnErr(Checksums.initialize(SS.getRecordData()));
395 break;
396 case DebugSubsectionKind::Lines:
397 // We can add the relocated line table directly to the PDB without
398 // modification because the file checksum offsets will stay the same.
399 File->ModuleDBI->addDebugSubsection(SS);
400 break;
401 case DebugSubsectionKind::Symbols:
402 mergeSymbolRecords(Alloc, File, TypeIndexMap, SS.getRecordData());
403 break;
404 default:
405 // FIXME: Process the rest of the subsections.
406 break;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000407 }
408 }
Rui Ueyama52896622017-01-12 03:09:25 +0000409
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000410 if (Checksums.valid()) {
411 // Make a new file checksum table that refers to offsets in the PDB-wide
412 // string table. Generally the string table subsection appears after the
413 // checksum table, so we have to do this after looping over all the
414 // subsections.
415 if (!CVStrTab.valid())
416 fatal(".debug$S sections must have both a string table subsection "
417 "and a checksum subsection table or neither");
418 auto NewChecksums = make_unique<DebugChecksumsSubsection>(PDBStrTab);
419 for (FileChecksumEntry &FC : Checksums) {
420 StringRef FileName = ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
421 ExitOnErr(Builder.getDbiBuilder().addModuleSourceFile(*File->ModuleDBI,
422 FileName));
423 NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
424 }
425 File->ModuleDBI->addDebugSubsection(std::move(NewChecksums));
426 }
427 }
428}
429
430// Add all object files to the PDB. Merge .debug$T sections into IpiData and
431// TpiData.
432void PDBLinker::addObjectsToPDB() {
433 for (ObjectFile *File : Symtab->ObjectFiles)
434 addObjectFile(File);
435
436 Builder.getStringTableBuilder().setStrings(PDBStrTab);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000437
Reid Kleckner5d577522017-03-24 17:26:38 +0000438 // Construct TPI stream contents.
Reid Kleckner13fc4112017-04-04 00:56:34 +0000439 addTypeInfo(Builder.getTpiBuilder(), TypeTable);
Reid Kleckner5d577522017-03-24 17:26:38 +0000440
441 // Construct IPI stream contents.
Reid Kleckner13fc4112017-04-04 00:56:34 +0000442 addTypeInfo(Builder.getIpiBuilder(), IDTable);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000443
444 // Add public and symbol records stream.
445
446 // For now we don't actually write any thing useful to the publics stream, but
447 // the act of "getting" it also creates it lazily so that we write an empty
448 // stream.
449 (void)Builder.getPublicsBuilder();
Rui Ueyama52896622017-01-12 03:09:25 +0000450}
451
Zachary Turner6708e0b2017-07-10 21:01:37 +0000452static void addLinkerModuleSymbols(StringRef Path,
453 pdb::DbiModuleDescriptorBuilder &Mod,
454 BumpPtrAllocator &Allocator) {
455 codeview::SymbolSerializer Serializer(Allocator, CodeViewContainer::Pdb);
456 codeview::ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
457 codeview::Compile3Sym CS(SymbolRecordKind::Compile3Sym);
458 codeview::EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
459
460 ONS.Name = "* Linker *";
461 ONS.Signature = 0;
462
463 CS.Machine = Config->is64() ? CPUType::X64 : CPUType::Intel80386;
464 CS.Flags = CompileSym3Flags::None;
465 CS.VersionBackendBuild = 0;
466 CS.VersionBackendMajor = 0;
467 CS.VersionBackendMinor = 0;
468 CS.VersionBackendQFE = 0;
469 CS.VersionFrontendBuild = 0;
470 CS.VersionFrontendMajor = 0;
471 CS.VersionFrontendMinor = 0;
472 CS.VersionFrontendQFE = 0;
473 CS.Version = "LLVM Linker";
474 CS.setLanguage(SourceLanguage::Link);
475
476 ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
477 std::string ArgStr = llvm::join(Args, " ");
478 EBS.Fields.push_back("cwd");
479 SmallString<64> cwd;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000480 sys::fs::current_path(cwd);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000481 EBS.Fields.push_back(cwd);
482 EBS.Fields.push_back("exe");
Zachary Turner77f23b92017-07-10 21:09:11 +0000483 EBS.Fields.push_back(Config->Argv[0]);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000484 EBS.Fields.push_back("pdb");
485 EBS.Fields.push_back(Path);
486 EBS.Fields.push_back("cmd");
487 EBS.Fields.push_back(ArgStr);
488 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
489 ONS, Allocator, CodeViewContainer::Pdb));
490 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
491 CS, Allocator, CodeViewContainer::Pdb));
492 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
493 EBS, Allocator, CodeViewContainer::Pdb));
494}
495
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000496// Creates a PDB file.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000497void coff::createPDB(SymbolTable *Symtab, ArrayRef<uint8_t> SectionTable,
Saleem Abdulrasooldf8a13b2017-01-04 17:56:54 +0000498 const llvm::codeview::DebugInfo *DI) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000499 PDBLinker PDB(Symtab);
500 PDB.initialize(DI);
501 PDB.addObjectsToPDB();
502 PDB.addSections(SectionTable);
503 PDB.commit();
504}
505
506void PDBLinker::initialize(const llvm::codeview::DebugInfo *DI) {
Rui Ueyama12979542016-09-30 20:53:45 +0000507 ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
Rui Ueyama7f382992016-09-15 18:55:18 +0000508
Rui Ueyama8d3fb5d2016-10-05 22:08:58 +0000509 // Create streams in MSF for predefined streams, namely
510 // PDB, TPI, DBI and IPI.
511 for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
512 ExitOnErr(Builder.getMsfBuilder().addStream(0));
Rui Ueyama7f382992016-09-15 18:55:18 +0000513
Rui Ueyamabb542b32016-09-16 22:51:17 +0000514 // Add an Info stream.
515 auto &InfoBuilder = Builder.getInfoBuilder();
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000516 InfoBuilder.setAge(DI ? DI->PDB70.Age : 0);
517
518 pdb::PDB_UniqueId uuid{};
519 if (DI)
520 memcpy(&uuid, &DI->PDB70.Signature, sizeof(uuid));
521 InfoBuilder.setGuid(uuid);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000522 InfoBuilder.setSignature(time(nullptr));
Rui Ueyamabb542b32016-09-16 22:51:17 +0000523 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
Rui Ueyama7f382992016-09-15 18:55:18 +0000524
Zachary Turner6c4bfba2017-07-07 05:04:36 +0000525 // Add an empty DBI stream.
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000526 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Zachary Turnerc1e93e52017-07-07 18:45:56 +0000527 DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000528 ExitOnErr(DbiBuilder.addDbgStream(pdb::DbgHeaderType::NewFPO, {}));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000529}
Rui Ueyama1343fac2016-10-06 22:52:01 +0000530
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000531void PDBLinker::addSections(ArrayRef<uint8_t> SectionTable) {
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000532 // Add Section Contributions.
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000533 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000534 addSectionContribs(Symtab, DbiBuilder);
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000535
Rui Ueyama20df4ec2016-10-31 21:09:21 +0000536 // Add Section Map stream.
537 ArrayRef<object::coff_section> Sections = {
Rui Ueyama6294a242016-11-04 17:41:29 +0000538 (const object::coff_section *)SectionTable.data(),
Rui Ueyama20df4ec2016-10-31 21:09:21 +0000539 SectionTable.size() / sizeof(object::coff_section)};
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000540 SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
Rui Ueyama20df4ec2016-10-31 21:09:21 +0000541 DbiBuilder.setSectionMap(SectionMap);
542
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000543 // It's not entirely clear what this is, but the * Linker * module uses it.
544 NativePath = Config->PDBPath;
545 sys::fs::make_absolute(NativePath);
546 sys::path::native(NativePath, sys::path::Style::windows);
547 uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
Zachary Turner6c4bfba2017-07-07 05:04:36 +0000548 auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
549 LinkerModule.setPdbFilePathNI(PdbFilePathNI);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000550 addLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
Rui Ueyamac91f7162016-11-16 01:10:46 +0000551
Rui Ueyama9f66f822016-10-11 19:45:07 +0000552 // Add COFF section header stream.
553 ExitOnErr(
554 DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000555}
Rui Ueyama9f66f822016-10-11 19:45:07 +0000556
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000557void PDBLinker::commit() {
Rui Ueyama3e9d6bb2016-09-26 23:53:55 +0000558 // Write to a file.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000559 ExitOnErr(Builder.commit(Config->PDBPath));
Rui Ueyamae7378242015-12-04 23:11:05 +0000560}