blob: a1e8f49eafdb56e6e63e7b4f003ac6b7802bfe90 [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"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000036#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
37#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
Rui Ueyama20df4ec2016-10-31 21:09:21 +000038#include "llvm/Object/COFF.h"
Zachary Turnerd9dc2822017-03-02 20:52:51 +000039#include "llvm/Support/BinaryByteStream.h"
Rui Ueyama1763c0d2015-12-08 18:39:55 +000040#include "llvm/Support/Endian.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000041#include "llvm/Support/FileOutputBuffer.h"
Zachary Turner7b327d02017-02-16 23:35:45 +000042#include "llvm/Support/Path.h"
Rui Ueyamabe939b32016-11-21 17:22:35 +000043#include "llvm/Support/ScopedPrinter.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000044#include <memory>
45
Rui Ueyama1d99ab32016-09-15 22:24:51 +000046using namespace lld;
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000047using namespace lld::coff;
Rui Ueyamae7378242015-12-04 23:11:05 +000048using namespace llvm;
Rui Ueyamabe939b32016-11-21 17:22:35 +000049using namespace llvm::codeview;
Rui Ueyamae7378242015-12-04 23:11:05 +000050
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000051using llvm::object::coff_section;
52
Rui Ueyamab28c6d42016-09-16 04:32:33 +000053static ExitOnError ExitOnErr;
54
Reid Kleckner0faf6d72017-07-14 00:14:58 +000055namespace {
56class PDBLinker {
57public:
58 PDBLinker(SymbolTable *Symtab)
59 : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
60 IDTable(Alloc) {}
61
62 /// Emit the basic PDB structure: initial streams, headers, etc.
63 void initialize(const llvm::codeview::DebugInfo *DI);
64
65 /// Link CodeView from each object file in the symbol table into the PDB.
66 void addObjectsToPDB();
67
68 /// Link CodeView from a single object file into the PDB.
69 void addObjectFile(ObjectFile *File);
70
71 /// Merge the type information from the .debug$T section in the given object
72 /// file. Produce a mapping from object file type indices to type or
73 /// item indices in the final PDB.
74 void mergeDebugT(ObjectFile *File, SmallVectorImpl<TypeIndex> &TypeIndexMap);
75
76 /// Add the section map and section contributions to the PDB.
77 void addSections(ArrayRef<uint8_t> SectionTable);
78
79 /// Write the PDB to disk.
80 void commit();
81
82private:
83 BumpPtrAllocator Alloc;
84
85 SymbolTable *Symtab;
86
87 pdb::PDBFileBuilder Builder;
88
89 /// Type records that will go into the PDB TPI stream.
90 TypeTableBuilder TypeTable;
91
92 /// Item records that will go into the PDB IPI stream.
93 TypeTableBuilder IDTable;
94
95 /// PDBs use a single global string table for filenames in the file checksum
96 /// table.
97 DebugStringTableSubsection PDBStrTab;
98
Reid Kleckner0faf6d72017-07-14 00:14:58 +000099 llvm::SmallString<128> NativePath;
100
101 std::vector<pdb::SecMapEntry> SectionMap;
102};
103}
104
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000105// Returns a list of all SectionChunks.
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000106static void addSectionContribs(SymbolTable *Symtab,
107 pdb::DbiStreamBuilder &DbiBuilder) {
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000108 for (Chunk *C : Symtab->getChunks())
109 if (auto *SC = dyn_cast<SectionChunk>(C))
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000110 DbiBuilder.addSectionContrib(SC->File->ModuleDBI, SC->Header);
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000111}
112
Rui Ueyamabe939b32016-11-21 17:22:35 +0000113static SectionChunk *findByName(std::vector<SectionChunk *> &Sections,
114 StringRef Name) {
115 for (SectionChunk *C : Sections)
116 if (C->getSectionName() == Name)
117 return C;
118 return nullptr;
119}
120
Reid Kleckner44cdb102017-06-19 17:21:45 +0000121static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
122 StringRef SecName) {
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000123 // First 4 bytes are section magic.
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000124 if (Data.size() < 4)
Rui Ueyama52896622017-01-12 03:09:25 +0000125 fatal(SecName + " too short");
Reid Kleckner44cdb102017-06-19 17:21:45 +0000126 if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
Rui Ueyama52896622017-01-12 03:09:25 +0000127 fatal(SecName + " has an invalid magic");
Rui Ueyama26186c72016-12-09 04:46:54 +0000128 return Data.slice(4);
129}
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000130
Reid Kleckner44cdb102017-06-19 17:21:45 +0000131static ArrayRef<uint8_t> getDebugSection(ObjectFile *File, StringRef SecName) {
132 if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
133 return consumeDebugMagic(Sec->getContents(), SecName);
134 return {};
135}
136
Reid Kleckner5d577522017-03-24 17:26:38 +0000137static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
Reid Kleckner44cdb102017-06-19 17:21:45 +0000138 TypeTableBuilder &TypeTable) {
Reid Kleckner5d577522017-03-24 17:26:38 +0000139 // Start the TPI or IPI stream header.
140 TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
Rui Ueyama52896622017-01-12 03:09:25 +0000141
Reid Kleckner5d577522017-03-24 17:26:38 +0000142 // Flatten the in memory type table.
Reid Kleckner5d577522017-03-24 17:26:38 +0000143 TypeTable.ForEachRecord([&](TypeIndex TI, ArrayRef<uint8_t> Rec) {
Reid Kleckner13fc4112017-04-04 00:56:34 +0000144 // FIXME: Hash types.
145 TpiBuilder.addTypeRecord(Rec, None);
Reid Kleckner5d577522017-03-24 17:26:38 +0000146 });
Reid Kleckner5d577522017-03-24 17:26:38 +0000147}
148
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000149void PDBLinker::mergeDebugT(ObjectFile *File,
150 SmallVectorImpl<TypeIndex> &TypeIndexMap) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000151 ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
152 if (Data.empty())
153 return;
154
Reid Kleckner6597c282017-07-13 20:12:23 +0000155 // Look for type server PDBs next to the input file. If this file has a parent
156 // archive, look next to the archive path.
157 StringRef LocalPath =
158 !File->ParentName.empty() ? File->ParentName : File->getName();
Reid Klecknera842cd72017-07-17 20:28:06 +0000159 (void)LocalPath; // FIXME: Implement type server handling here.
Reid Kleckner6597c282017-07-13 20:12:23 +0000160
Reid Kleckner44cdb102017-06-19 17:21:45 +0000161 BinaryByteStream Stream(Data, support::little);
162 CVTypeArray Types;
163 BinaryStreamReader Reader(Stream);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000164 if (auto EC = Reader.readArray(Types, Reader.getLength()))
165 fatal(EC, "Reader::readArray failed");
Reid Klecknera842cd72017-07-17 20:28:06 +0000166 if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable, TypeIndexMap, Types))
Reid Kleckner44cdb102017-06-19 17:21:45 +0000167 fatal(Err, "codeview::mergeTypeStreams failed");
168}
169
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000170static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
171 if (TI.isSimple())
172 return true;
173 if (TI.toArrayIndex() >= TypeIndexMap.size())
174 return false;
175 TI = TypeIndexMap[TI.toArrayIndex()];
176 return true;
177}
178
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000179static void remapTypesInSymbolRecord(ObjectFile *File,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000180 MutableArrayRef<uint8_t> Contents,
181 ArrayRef<TypeIndex> TypeIndexMap,
182 ArrayRef<TiReference> TypeRefs) {
183 for (const TiReference &Ref : TypeRefs) {
184 unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000185 if (Contents.size() < Ref.Offset + ByteSize)
186 fatal("symbol record too short");
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000187 MutableArrayRef<TypeIndex> TIs(
188 reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000189 for (TypeIndex &TI : TIs) {
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000190 if (!remapTypeIndex(TI, TypeIndexMap)) {
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000191 TI = TypeIndex(SimpleTypeKind::NotTranslated);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000192 log("ignoring symbol record in " + File->getName() +
193 " with bad type index 0x" + utohexstr(TI.getIndex()));
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000194 continue;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000195 }
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000196 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000197 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000198}
199
200/// MSVC translates S_PROC_ID_END to S_END.
201uint16_t canonicalizeSymbolKind(SymbolKind Kind) {
202 if (Kind == SymbolKind::S_PROC_ID_END)
203 return SymbolKind::S_END;
204 return Kind;
205}
206
207/// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
208/// The object file may not be aligned.
209static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
210 BumpPtrAllocator &Alloc) {
211 size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
212 assert(Size >= 4 && "record too short");
213 assert(Size <= MaxRecordLength && "record too long");
214 void *Mem = Alloc.Allocate(Size, 4);
215
216 // Copy the symbol record and zero out any padding bytes.
217 MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
218 memcpy(NewData.data(), Sym.data().data(), Sym.length());
219 memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
220
221 // Update the record prefix length. It should point to the beginning of the
222 // next record. MSVC does some canonicalization of the record kind, so we do
223 // that as well.
224 auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
225 Prefix->RecordKind = canonicalizeSymbolKind(Sym.kind());
226 Prefix->RecordLen = Size - 2;
227 return NewData;
228}
229
Reid Kleckner3f851922017-07-06 16:39:32 +0000230/// Return true if this symbol opens a scope. This implies that the symbol has
231/// "parent" and "end" fields, which contain the offset of the S_END or
232/// S_INLINESITE_END record.
233static bool symbolOpensScope(SymbolKind Kind) {
234 switch (Kind) {
235 case SymbolKind::S_GPROC32:
236 case SymbolKind::S_LPROC32:
237 case SymbolKind::S_LPROC32_ID:
238 case SymbolKind::S_GPROC32_ID:
239 case SymbolKind::S_BLOCK32:
240 case SymbolKind::S_SEPCODE:
241 case SymbolKind::S_THUNK32:
242 case SymbolKind::S_INLINESITE:
243 case SymbolKind::S_INLINESITE2:
244 return true;
245 default:
246 break;
247 }
248 return false;
249}
250
251static bool symbolEndsScope(SymbolKind Kind) {
252 switch (Kind) {
253 case SymbolKind::S_END:
254 case SymbolKind::S_PROC_ID_END:
255 case SymbolKind::S_INLINESITE_END:
256 return true;
257 default:
258 break;
259 }
260 return false;
261}
262
263struct ScopeRecord {
264 ulittle32_t PtrParent;
265 ulittle32_t PtrEnd;
266};
267
268struct SymbolScope {
269 ScopeRecord *OpeningRecord;
270 uint32_t ScopeOffset;
271};
272
273static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
274 uint32_t CurOffset, CVSymbol &Sym) {
275 assert(symbolOpensScope(Sym.kind()));
276 SymbolScope S;
277 S.ScopeOffset = CurOffset;
278 S.OpeningRecord = const_cast<ScopeRecord *>(
279 reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
280 S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
281 Stack.push_back(S);
282}
283
284static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
285 uint32_t CurOffset, ObjectFile *File) {
286 if (Stack.empty()) {
287 warn("symbol scopes are not balanced in " + File->getName());
288 return;
289 }
290 SymbolScope S = Stack.pop_back_val();
291 S.OpeningRecord->PtrEnd = CurOffset;
292}
293
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000294static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjectFile *File,
295 ArrayRef<TypeIndex> TypeIndexMap,
296 BinaryStreamRef SymData) {
297 // FIXME: Improve error recovery by warning and skipping records when
298 // possible.
299 CVSymbolArray Syms;
300 BinaryStreamReader Reader(SymData);
301 ExitOnErr(Reader.readArray(Syms, Reader.getLength()));
Reid Kleckner3f851922017-07-06 16:39:32 +0000302 SmallVector<SymbolScope, 4> Scopes;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000303 for (const CVSymbol &Sym : Syms) {
304 // Discover type index references in the record. Skip it if we don't know
305 // where they are.
306 SmallVector<TiReference, 32> TypeRefs;
307 if (!discoverTypeIndices(Sym, TypeRefs)) {
308 log("ignoring unknown symbol record with kind 0x" + utohexstr(Sym.kind()));
309 continue;
310 }
311
312 // Copy the symbol record so we can mutate it.
313 MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
314
315 // Re-map all the type index references.
316 MutableArrayRef<uint8_t> Contents =
317 NewData.drop_front(sizeof(RecordPrefix));
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000318 remapTypesInSymbolRecord(File, Contents, TypeIndexMap, TypeRefs);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000319
Reid Kleckner3f851922017-07-06 16:39:32 +0000320 // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
321 CVSymbol NewSym(Sym.kind(), NewData);
322 if (symbolOpensScope(Sym.kind()))
323 scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(), NewSym);
324 else if (symbolEndsScope(Sym.kind()))
325 scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000326
327 // Add the symbol to the module.
Reid Kleckner3f851922017-07-06 16:39:32 +0000328 File->ModuleDBI->addSymbol(NewSym);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000329 }
330}
331
Reid Kleckner44cdb102017-06-19 17:21:45 +0000332// Allocate memory for a .debug$S section and relocate it.
333static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
334 SectionChunk *DebugChunk) {
335 uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk->getSize());
336 assert(DebugChunk->OutputSectionOff == 0 &&
337 "debug sections should not be in output sections");
338 DebugChunk->writeTo(Buffer);
339 return consumeDebugMagic(makeArrayRef(Buffer, DebugChunk->getSize()),
340 ".debug$S");
341}
342
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000343void PDBLinker::addObjectFile(ObjectFile *File) {
344 // Add a module descriptor for every object file. We need to put an absolute
345 // path to the object into the PDB. If this is a plain object, we make its
346 // path absolute. If it's an object in an archive, we make the archive path
347 // absolute.
348 bool InArchive = !File->ParentName.empty();
349 SmallString<128> Path = InArchive ? File->ParentName : File->getName();
350 sys::fs::make_absolute(Path);
351 sys::path::native(Path, sys::path::Style::windows);
352 StringRef Name = InArchive ? File->getName() : StringRef(Path);
Zachary Turner2897e032017-05-25 21:16:03 +0000353
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000354 File->ModuleDBI = &ExitOnErr(Builder.getDbiBuilder().addModuleInfo(Name));
355 File->ModuleDBI->setObjFileName(Path);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000356
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000357 // Before we can process symbol substreams from .debug$S, we need to process
358 // type information, file checksums, and the string table. Add type info to
359 // the PDB first, so that we can get the map from object file type and item
360 // indices to PDB type and item indices.
361 SmallVector<TypeIndex, 128> TypeIndexMap;
362 mergeDebugT(File, TypeIndexMap);
Zachary Turner448dea42017-07-07 18:46:14 +0000363
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000364 // Now do all live .debug$S sections.
365 for (SectionChunk *DebugChunk : File->getDebugChunks()) {
366 if (!DebugChunk->isLive() || DebugChunk->getSectionName() != ".debug$S")
367 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000368
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000369 ArrayRef<uint8_t> RelocatedDebugContents =
370 relocateDebugChunk(Alloc, DebugChunk);
371 if (RelocatedDebugContents.empty())
372 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000373
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000374 DebugSubsectionArray Subsections;
375 BinaryStreamReader Reader(RelocatedDebugContents, support::little);
376 ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
Rui Ueyama52896622017-01-12 03:09:25 +0000377
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000378 DebugStringTableSubsectionRef CVStrTab;
379 DebugChecksumsSubsectionRef Checksums;
380 for (const DebugSubsectionRecord &SS : Subsections) {
381 switch (SS.kind()) {
382 case DebugSubsectionKind::StringTable:
383 ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
384 break;
385 case DebugSubsectionKind::FileChecksums:
386 ExitOnErr(Checksums.initialize(SS.getRecordData()));
387 break;
388 case DebugSubsectionKind::Lines:
389 // We can add the relocated line table directly to the PDB without
390 // modification because the file checksum offsets will stay the same.
391 File->ModuleDBI->addDebugSubsection(SS);
392 break;
393 case DebugSubsectionKind::Symbols:
394 mergeSymbolRecords(Alloc, File, TypeIndexMap, SS.getRecordData());
395 break;
396 default:
397 // FIXME: Process the rest of the subsections.
398 break;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000399 }
400 }
Rui Ueyama52896622017-01-12 03:09:25 +0000401
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000402 if (Checksums.valid()) {
403 // Make a new file checksum table that refers to offsets in the PDB-wide
404 // string table. Generally the string table subsection appears after the
405 // checksum table, so we have to do this after looping over all the
406 // subsections.
407 if (!CVStrTab.valid())
408 fatal(".debug$S sections must have both a string table subsection "
409 "and a checksum subsection table or neither");
410 auto NewChecksums = make_unique<DebugChecksumsSubsection>(PDBStrTab);
411 for (FileChecksumEntry &FC : Checksums) {
412 StringRef FileName = ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
413 ExitOnErr(Builder.getDbiBuilder().addModuleSourceFile(*File->ModuleDBI,
414 FileName));
415 NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
416 }
417 File->ModuleDBI->addDebugSubsection(std::move(NewChecksums));
418 }
419 }
420}
421
422// Add all object files to the PDB. Merge .debug$T sections into IpiData and
423// TpiData.
424void PDBLinker::addObjectsToPDB() {
425 for (ObjectFile *File : Symtab->ObjectFiles)
426 addObjectFile(File);
427
428 Builder.getStringTableBuilder().setStrings(PDBStrTab);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000429
Reid Kleckner5d577522017-03-24 17:26:38 +0000430 // Construct TPI stream contents.
Reid Kleckner13fc4112017-04-04 00:56:34 +0000431 addTypeInfo(Builder.getTpiBuilder(), TypeTable);
Reid Kleckner5d577522017-03-24 17:26:38 +0000432
433 // Construct IPI stream contents.
Reid Kleckner13fc4112017-04-04 00:56:34 +0000434 addTypeInfo(Builder.getIpiBuilder(), IDTable);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000435
436 // Add public and symbol records stream.
437
438 // For now we don't actually write any thing useful to the publics stream, but
439 // the act of "getting" it also creates it lazily so that we write an empty
440 // stream.
441 (void)Builder.getPublicsBuilder();
Rui Ueyama52896622017-01-12 03:09:25 +0000442}
443
Zachary Turner6708e0b2017-07-10 21:01:37 +0000444static void addLinkerModuleSymbols(StringRef Path,
445 pdb::DbiModuleDescriptorBuilder &Mod,
446 BumpPtrAllocator &Allocator) {
447 codeview::SymbolSerializer Serializer(Allocator, CodeViewContainer::Pdb);
448 codeview::ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
449 codeview::Compile3Sym CS(SymbolRecordKind::Compile3Sym);
450 codeview::EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
451
452 ONS.Name = "* Linker *";
453 ONS.Signature = 0;
454
455 CS.Machine = Config->is64() ? CPUType::X64 : CPUType::Intel80386;
456 CS.Flags = CompileSym3Flags::None;
457 CS.VersionBackendBuild = 0;
458 CS.VersionBackendMajor = 0;
459 CS.VersionBackendMinor = 0;
460 CS.VersionBackendQFE = 0;
461 CS.VersionFrontendBuild = 0;
462 CS.VersionFrontendMajor = 0;
463 CS.VersionFrontendMinor = 0;
464 CS.VersionFrontendQFE = 0;
465 CS.Version = "LLVM Linker";
466 CS.setLanguage(SourceLanguage::Link);
467
468 ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
469 std::string ArgStr = llvm::join(Args, " ");
470 EBS.Fields.push_back("cwd");
471 SmallString<64> cwd;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000472 sys::fs::current_path(cwd);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000473 EBS.Fields.push_back(cwd);
474 EBS.Fields.push_back("exe");
Zachary Turner77f23b92017-07-10 21:09:11 +0000475 EBS.Fields.push_back(Config->Argv[0]);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000476 EBS.Fields.push_back("pdb");
477 EBS.Fields.push_back(Path);
478 EBS.Fields.push_back("cmd");
479 EBS.Fields.push_back(ArgStr);
480 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
481 ONS, Allocator, CodeViewContainer::Pdb));
482 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
483 CS, Allocator, CodeViewContainer::Pdb));
484 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
485 EBS, Allocator, CodeViewContainer::Pdb));
486}
487
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000488// Creates a PDB file.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000489void coff::createPDB(SymbolTable *Symtab, ArrayRef<uint8_t> SectionTable,
Saleem Abdulrasooldf8a13b2017-01-04 17:56:54 +0000490 const llvm::codeview::DebugInfo *DI) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000491 PDBLinker PDB(Symtab);
492 PDB.initialize(DI);
493 PDB.addObjectsToPDB();
494 PDB.addSections(SectionTable);
495 PDB.commit();
496}
497
498void PDBLinker::initialize(const llvm::codeview::DebugInfo *DI) {
Rui Ueyama12979542016-09-30 20:53:45 +0000499 ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
Rui Ueyama7f382992016-09-15 18:55:18 +0000500
Rui Ueyama8d3fb5d2016-10-05 22:08:58 +0000501 // Create streams in MSF for predefined streams, namely
502 // PDB, TPI, DBI and IPI.
503 for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
504 ExitOnErr(Builder.getMsfBuilder().addStream(0));
Rui Ueyama7f382992016-09-15 18:55:18 +0000505
Rui Ueyamabb542b32016-09-16 22:51:17 +0000506 // Add an Info stream.
507 auto &InfoBuilder = Builder.getInfoBuilder();
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000508 InfoBuilder.setAge(DI ? DI->PDB70.Age : 0);
509
Reid Kleckner67653ee2017-07-17 23:59:44 +0000510 GUID uuid{};
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000511 if (DI)
512 memcpy(&uuid, &DI->PDB70.Signature, sizeof(uuid));
513 InfoBuilder.setGuid(uuid);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000514 InfoBuilder.setSignature(time(nullptr));
Rui Ueyamabb542b32016-09-16 22:51:17 +0000515 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
Rui Ueyama7f382992016-09-15 18:55:18 +0000516
Zachary Turner6c4bfba2017-07-07 05:04:36 +0000517 // Add an empty DBI stream.
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000518 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Zachary Turnerc1e93e52017-07-07 18:45:56 +0000519 DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000520 ExitOnErr(DbiBuilder.addDbgStream(pdb::DbgHeaderType::NewFPO, {}));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000521}
Rui Ueyama1343fac2016-10-06 22:52:01 +0000522
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000523void PDBLinker::addSections(ArrayRef<uint8_t> SectionTable) {
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000524 // Add Section Contributions.
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000525 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000526 addSectionContribs(Symtab, DbiBuilder);
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000527
Rui Ueyama20df4ec2016-10-31 21:09:21 +0000528 // Add Section Map stream.
529 ArrayRef<object::coff_section> Sections = {
Rui Ueyama6294a242016-11-04 17:41:29 +0000530 (const object::coff_section *)SectionTable.data(),
Rui Ueyama20df4ec2016-10-31 21:09:21 +0000531 SectionTable.size() / sizeof(object::coff_section)};
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000532 SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
Rui Ueyama20df4ec2016-10-31 21:09:21 +0000533 DbiBuilder.setSectionMap(SectionMap);
534
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000535 // It's not entirely clear what this is, but the * Linker * module uses it.
536 NativePath = Config->PDBPath;
537 sys::fs::make_absolute(NativePath);
538 sys::path::native(NativePath, sys::path::Style::windows);
539 uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
Zachary Turner6c4bfba2017-07-07 05:04:36 +0000540 auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
541 LinkerModule.setPdbFilePathNI(PdbFilePathNI);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000542 addLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
Rui Ueyamac91f7162016-11-16 01:10:46 +0000543
Rui Ueyama9f66f822016-10-11 19:45:07 +0000544 // Add COFF section header stream.
545 ExitOnErr(
546 DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000547}
Rui Ueyama9f66f822016-10-11 19:45:07 +0000548
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000549void PDBLinker::commit() {
Rui Ueyama3e9d6bb2016-09-26 23:53:55 +0000550 // Write to a file.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000551 ExitOnErr(Builder.commit(Config->PDBPath));
Rui Ueyamae7378242015-12-04 23:11:05 +0000552}