blob: 54dc1faefe273c102224160d7f1efb9d3cb367c5 [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"
Reid Kleckner44cdb102017-06-19 17:21:45 +000017#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000018#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
Zachary Turner6708e0b2017-07-10 21:01:37 +000019#include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
Reid Kleckner651db912017-07-18 00:21:25 +000020#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000021#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerd0e6e242017-06-21 17:25:56 +000022#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
Rui Ueyama52896622017-01-12 03:09:25 +000023#include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
24#include "llvm/DebugInfo/CodeView/TypeTableBuilder.h"
Rui Ueyamab28c6d42016-09-16 04:32:33 +000025#include "llvm/DebugInfo/MSF/MSFBuilder.h"
Rui Ueyama7f382992016-09-15 18:55:18 +000026#include "llvm/DebugInfo/MSF/MSFCommon.h"
Reid Kleckner651db912017-07-18 00:21:25 +000027#include "llvm/DebugInfo/PDB/GenericError.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"
Reid Kleckner651db912017-07-18 00:21:25 +000033#include "llvm/DebugInfo/PDB/Native/NativeSession.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000034#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
35#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
Rafael Espindolaa0f30da2017-05-02 20:19:42 +000036#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000037#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
38#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
Reid Kleckner651db912017-07-18 00:21:25 +000039#include "llvm/DebugInfo/PDB/PDB.h"
Rui Ueyama20df4ec2016-10-31 21:09:21 +000040#include "llvm/Object/COFF.h"
Zachary Turnerd9dc2822017-03-02 20:52:51 +000041#include "llvm/Support/BinaryByteStream.h"
Rui Ueyama1763c0d2015-12-08 18:39:55 +000042#include "llvm/Support/Endian.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000043#include "llvm/Support/FileOutputBuffer.h"
Zachary Turner7b327d02017-02-16 23:35:45 +000044#include "llvm/Support/Path.h"
Rui Ueyamabe939b32016-11-21 17:22:35 +000045#include "llvm/Support/ScopedPrinter.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000046#include <memory>
47
Rui Ueyama1d99ab32016-09-15 22:24:51 +000048using namespace lld;
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000049using namespace lld::coff;
Rui Ueyamae7378242015-12-04 23:11:05 +000050using namespace llvm;
Rui Ueyamabe939b32016-11-21 17:22:35 +000051using namespace llvm::codeview;
Rui Ueyamae7378242015-12-04 23:11:05 +000052
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000053using llvm::object::coff_section;
54
Rui Ueyamab28c6d42016-09-16 04:32:33 +000055static ExitOnError ExitOnErr;
56
Reid Kleckner0faf6d72017-07-14 00:14:58 +000057namespace {
Reid Kleckner651db912017-07-18 00:21:25 +000058/// Map from type index and item index in a type server PDB to the
59/// corresponding index in the destination PDB.
60struct CVIndexMap {
61 SmallVector<TypeIndex, 0> TPIMap;
62 SmallVector<TypeIndex, 0> IPIMap;
63 bool IsTypeServerMap = false;
64};
65
Reid Kleckner0faf6d72017-07-14 00:14:58 +000066class PDBLinker {
67public:
68 PDBLinker(SymbolTable *Symtab)
69 : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
70 IDTable(Alloc) {}
71
72 /// Emit the basic PDB structure: initial streams, headers, etc.
73 void initialize(const llvm::codeview::DebugInfo *DI);
74
75 /// Link CodeView from each object file in the symbol table into the PDB.
76 void addObjectsToPDB();
77
78 /// Link CodeView from a single object file into the PDB.
79 void addObjectFile(ObjectFile *File);
80
Reid Kleckner651db912017-07-18 00:21:25 +000081 /// Produce a mapping from the type and item indices used in the object
82 /// file to those in the destination PDB.
83 ///
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
87 /// mapping.
88 ///
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);
93
94 const CVIndexMap &maybeMergeTypeServerPDB(ObjectFile *File,
95 TypeServer2Record &TS);
Reid Kleckner0faf6d72017-07-14 00:14:58 +000096
97 /// Add the section map and section contributions to the PDB.
98 void addSections(ArrayRef<uint8_t> SectionTable);
99
100 /// Write the PDB to disk.
101 void commit();
102
103private:
104 BumpPtrAllocator Alloc;
105
106 SymbolTable *Symtab;
107
108 pdb::PDBFileBuilder Builder;
109
110 /// Type records that will go into the PDB TPI stream.
111 TypeTableBuilder TypeTable;
112
113 /// Item records that will go into the PDB IPI stream.
114 TypeTableBuilder IDTable;
115
116 /// PDBs use a single global string table for filenames in the file checksum
117 /// table.
118 DebugStringTableSubsection PDBStrTab;
119
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000120 llvm::SmallString<128> NativePath;
121
122 std::vector<pdb::SecMapEntry> SectionMap;
Reid Kleckner651db912017-07-18 00:21:25 +0000123
124 /// Type index mappings of type server PDBs that we've loaded so far.
125 std::map<GUID, CVIndexMap> TypeServerIndexMappings;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000126};
127}
128
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000129// Returns a list of all SectionChunks.
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000130static void addSectionContribs(SymbolTable *Symtab,
131 pdb::DbiStreamBuilder &DbiBuilder) {
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000132 for (Chunk *C : Symtab->getChunks())
133 if (auto *SC = dyn_cast<SectionChunk>(C))
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000134 DbiBuilder.addSectionContrib(SC->File->ModuleDBI, SC->Header);
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000135}
136
Rui Ueyamabe939b32016-11-21 17:22:35 +0000137static SectionChunk *findByName(std::vector<SectionChunk *> &Sections,
138 StringRef Name) {
139 for (SectionChunk *C : Sections)
140 if (C->getSectionName() == Name)
141 return C;
142 return nullptr;
143}
144
Reid Kleckner44cdb102017-06-19 17:21:45 +0000145static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
146 StringRef SecName) {
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000147 // First 4 bytes are section magic.
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000148 if (Data.size() < 4)
Rui Ueyama52896622017-01-12 03:09:25 +0000149 fatal(SecName + " too short");
Reid Kleckner44cdb102017-06-19 17:21:45 +0000150 if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
Rui Ueyama52896622017-01-12 03:09:25 +0000151 fatal(SecName + " has an invalid magic");
Rui Ueyama26186c72016-12-09 04:46:54 +0000152 return Data.slice(4);
153}
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000154
Reid Kleckner44cdb102017-06-19 17:21:45 +0000155static ArrayRef<uint8_t> getDebugSection(ObjectFile *File, StringRef SecName) {
156 if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
157 return consumeDebugMagic(Sec->getContents(), SecName);
158 return {};
159}
160
Reid Kleckner5d577522017-03-24 17:26:38 +0000161static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
Reid Kleckner44cdb102017-06-19 17:21:45 +0000162 TypeTableBuilder &TypeTable) {
Reid Kleckner5d577522017-03-24 17:26:38 +0000163 // Start the TPI or IPI stream header.
164 TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
Rui Ueyama52896622017-01-12 03:09:25 +0000165
Reid Kleckner5d577522017-03-24 17:26:38 +0000166 // Flatten the in memory type table.
Reid Kleckner5d577522017-03-24 17:26:38 +0000167 TypeTable.ForEachRecord([&](TypeIndex TI, ArrayRef<uint8_t> Rec) {
Reid Kleckner13fc4112017-04-04 00:56:34 +0000168 // FIXME: Hash types.
169 TpiBuilder.addTypeRecord(Rec, None);
Reid Kleckner5d577522017-03-24 17:26:38 +0000170 });
Reid Kleckner5d577522017-03-24 17:26:38 +0000171}
172
Reid Kleckner651db912017-07-18 00:21:25 +0000173static Optional<TypeServer2Record>
174maybeReadTypeServerRecord(CVTypeArray &Types) {
175 auto I = Types.begin();
176 if (I == Types.end())
177 return None;
178 const CVType &Type = *I;
179 if (Type.kind() != LF_TYPESERVER2)
180 return None;
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);
185}
186
187const CVIndexMap &PDBLinker::mergeDebugT(ObjectFile *File,
188 CVIndexMap &ObjectIndexMap) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000189 ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
190 if (Data.empty())
Reid Kleckner651db912017-07-18 00:21:25 +0000191 return ObjectIndexMap;
Reid Kleckner6597c282017-07-13 20:12:23 +0000192
Reid Kleckner44cdb102017-06-19 17:21:45 +0000193 BinaryByteStream Stream(Data, support::little);
194 CVTypeArray Types;
195 BinaryStreamReader Reader(Stream);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000196 if (auto EC = Reader.readArray(Types, Reader.getLength()))
197 fatal(EC, "Reader::readArray failed");
Reid Kleckner651db912017-07-18 00:21:25 +0000198
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);
203
204 // This is a /Z7 object. Fill in the temporary, caller-provided
205 // ObjectIndexMap.
206 if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable,
207 ObjectIndexMap.TPIMap, Types))
208 fatal(Err, "codeview::mergeTypeAndIdRecords failed");
209 return ObjectIndexMap;
210}
211
212static Expected<std::unique_ptr<pdb::NativeSession>>
213tryToLoadPDB(const GUID &GuidFromObj, StringRef TSPath) {
214 std::unique_ptr<pdb::IPDBSession> ThisSession;
215 if (auto EC =
216 pdb::loadDataForPDB(pdb::PDB_ReaderType::Native, TSPath, ThisSession))
217 return std::move(EC);
218
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.
224 if (!ExpectedInfo)
225 return ExpectedInfo.takeError();
226
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);
233
234 return std::move(NS);
235}
236
237const 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)
244 return IndexMap;
245
246 // Mark this map as a type server map.
247 IndexMap.IsTypeServerMap = true;
248
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);
258 sys::path::append(Path, sys::path::filename(TS.getName()));
259 ExpectedSession = tryToLoadPDB(TS.getGuid(), Path);
260 }
261 if (auto E = ExpectedSession.takeError())
262 fatal(E, "Type server PDB was not found");
263
264 // Merge TPI first, because the IPI stream will reference type indices.
265 auto ExpectedTpi = (*ExpectedSession)->getPDBFile().getPDBTpiStream();
266 if (auto E = ExpectedTpi.takeError())
267 fatal(E, "Type server does not have TPI stream");
268 if (auto Err = mergeTypeRecords(TypeTable, IndexMap.TPIMap,
269 ExpectedTpi->typeArray()))
270 fatal(Err, "codeview::mergeTypeRecords failed");
271
272 // Merge IPI.
273 auto ExpectedIpi = (*ExpectedSession)->getPDBFile().getPDBIpiStream();
274 if (auto E = ExpectedIpi.takeError())
275 fatal(E, "Type server does not have TPI stream");
276 if (auto Err = mergeIdRecords(IDTable, IndexMap.TPIMap, IndexMap.IPIMap,
277 ExpectedIpi->typeArray()))
278 fatal(Err, "codeview::mergeIdRecords failed");
279
280 return IndexMap;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000281}
282
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000283static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
284 if (TI.isSimple())
285 return true;
286 if (TI.toArrayIndex() >= TypeIndexMap.size())
287 return false;
288 TI = TypeIndexMap[TI.toArrayIndex()];
289 return true;
290}
291
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000292static void remapTypesInSymbolRecord(ObjectFile *File,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000293 MutableArrayRef<uint8_t> Contents,
Reid Kleckner651db912017-07-18 00:21:25 +0000294 const CVIndexMap &IndexMap,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000295 ArrayRef<TiReference> TypeRefs) {
296 for (const TiReference &Ref : TypeRefs) {
297 unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000298 if (Contents.size() < Ref.Offset + ByteSize)
299 fatal("symbol record too short");
Reid Kleckner651db912017-07-18 00:21:25 +0000300
301 // This can be an item index or a type index. Choose the appropriate map.
302 ArrayRef<TypeIndex> TypeOrItemMap = IndexMap.TPIMap;
303 if (Ref.Kind == TiRefKind::IndexRef && IndexMap.IsTypeServerMap)
304 TypeOrItemMap = IndexMap.IPIMap;
305
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000306 MutableArrayRef<TypeIndex> TIs(
307 reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000308 for (TypeIndex &TI : TIs) {
Reid Kleckner651db912017-07-18 00:21:25 +0000309 if (!remapTypeIndex(TI, TypeOrItemMap)) {
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000310 TI = TypeIndex(SimpleTypeKind::NotTranslated);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000311 log("ignoring symbol record in " + File->getName() +
312 " with bad type index 0x" + utohexstr(TI.getIndex()));
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000313 continue;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000314 }
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000315 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000316 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000317}
318
319/// MSVC translates S_PROC_ID_END to S_END.
320uint16_t canonicalizeSymbolKind(SymbolKind Kind) {
321 if (Kind == SymbolKind::S_PROC_ID_END)
322 return SymbolKind::S_END;
323 return Kind;
324}
325
326/// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
327/// The object file may not be aligned.
328static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
329 BumpPtrAllocator &Alloc) {
330 size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
331 assert(Size >= 4 && "record too short");
332 assert(Size <= MaxRecordLength && "record too long");
333 void *Mem = Alloc.Allocate(Size, 4);
334
335 // Copy the symbol record and zero out any padding bytes.
336 MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
337 memcpy(NewData.data(), Sym.data().data(), Sym.length());
338 memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
339
340 // Update the record prefix length. It should point to the beginning of the
341 // next record. MSVC does some canonicalization of the record kind, so we do
342 // that as well.
343 auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
344 Prefix->RecordKind = canonicalizeSymbolKind(Sym.kind());
345 Prefix->RecordLen = Size - 2;
346 return NewData;
347}
348
Reid Kleckner3f851922017-07-06 16:39:32 +0000349/// Return true if this symbol opens a scope. This implies that the symbol has
350/// "parent" and "end" fields, which contain the offset of the S_END or
351/// S_INLINESITE_END record.
352static bool symbolOpensScope(SymbolKind Kind) {
353 switch (Kind) {
354 case SymbolKind::S_GPROC32:
355 case SymbolKind::S_LPROC32:
356 case SymbolKind::S_LPROC32_ID:
357 case SymbolKind::S_GPROC32_ID:
358 case SymbolKind::S_BLOCK32:
359 case SymbolKind::S_SEPCODE:
360 case SymbolKind::S_THUNK32:
361 case SymbolKind::S_INLINESITE:
362 case SymbolKind::S_INLINESITE2:
363 return true;
364 default:
365 break;
366 }
367 return false;
368}
369
370static bool symbolEndsScope(SymbolKind Kind) {
371 switch (Kind) {
372 case SymbolKind::S_END:
373 case SymbolKind::S_PROC_ID_END:
374 case SymbolKind::S_INLINESITE_END:
375 return true;
376 default:
377 break;
378 }
379 return false;
380}
381
382struct ScopeRecord {
383 ulittle32_t PtrParent;
384 ulittle32_t PtrEnd;
385};
386
387struct SymbolScope {
388 ScopeRecord *OpeningRecord;
389 uint32_t ScopeOffset;
390};
391
392static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
393 uint32_t CurOffset, CVSymbol &Sym) {
394 assert(symbolOpensScope(Sym.kind()));
395 SymbolScope S;
396 S.ScopeOffset = CurOffset;
397 S.OpeningRecord = const_cast<ScopeRecord *>(
398 reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
399 S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
400 Stack.push_back(S);
401}
402
403static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
404 uint32_t CurOffset, ObjectFile *File) {
405 if (Stack.empty()) {
406 warn("symbol scopes are not balanced in " + File->getName());
407 return;
408 }
409 SymbolScope S = Stack.pop_back_val();
410 S.OpeningRecord->PtrEnd = CurOffset;
411}
412
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000413static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjectFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000414 const CVIndexMap &IndexMap,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000415 BinaryStreamRef SymData) {
416 // FIXME: Improve error recovery by warning and skipping records when
417 // possible.
418 CVSymbolArray Syms;
419 BinaryStreamReader Reader(SymData);
420 ExitOnErr(Reader.readArray(Syms, Reader.getLength()));
Reid Kleckner3f851922017-07-06 16:39:32 +0000421 SmallVector<SymbolScope, 4> Scopes;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000422 for (const CVSymbol &Sym : Syms) {
423 // Discover type index references in the record. Skip it if we don't know
424 // where they are.
425 SmallVector<TiReference, 32> TypeRefs;
426 if (!discoverTypeIndices(Sym, TypeRefs)) {
427 log("ignoring unknown symbol record with kind 0x" + utohexstr(Sym.kind()));
428 continue;
429 }
430
431 // Copy the symbol record so we can mutate it.
432 MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
433
434 // Re-map all the type index references.
435 MutableArrayRef<uint8_t> Contents =
436 NewData.drop_front(sizeof(RecordPrefix));
Reid Kleckner651db912017-07-18 00:21:25 +0000437 remapTypesInSymbolRecord(File, Contents, IndexMap, TypeRefs);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000438
Reid Kleckner3f851922017-07-06 16:39:32 +0000439 // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
440 CVSymbol NewSym(Sym.kind(), NewData);
441 if (symbolOpensScope(Sym.kind()))
442 scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(), NewSym);
443 else if (symbolEndsScope(Sym.kind()))
444 scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000445
446 // Add the symbol to the module.
Reid Kleckner3f851922017-07-06 16:39:32 +0000447 File->ModuleDBI->addSymbol(NewSym);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000448 }
449}
450
Reid Kleckner44cdb102017-06-19 17:21:45 +0000451// Allocate memory for a .debug$S section and relocate it.
452static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
453 SectionChunk *DebugChunk) {
454 uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk->getSize());
455 assert(DebugChunk->OutputSectionOff == 0 &&
456 "debug sections should not be in output sections");
457 DebugChunk->writeTo(Buffer);
458 return consumeDebugMagic(makeArrayRef(Buffer, DebugChunk->getSize()),
459 ".debug$S");
460}
461
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000462void PDBLinker::addObjectFile(ObjectFile *File) {
463 // Add a module descriptor for every object file. We need to put an absolute
464 // path to the object into the PDB. If this is a plain object, we make its
465 // path absolute. If it's an object in an archive, we make the archive path
466 // absolute.
467 bool InArchive = !File->ParentName.empty();
468 SmallString<128> Path = InArchive ? File->ParentName : File->getName();
469 sys::fs::make_absolute(Path);
470 sys::path::native(Path, sys::path::Style::windows);
471 StringRef Name = InArchive ? File->getName() : StringRef(Path);
Zachary Turner2897e032017-05-25 21:16:03 +0000472
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000473 File->ModuleDBI = &ExitOnErr(Builder.getDbiBuilder().addModuleInfo(Name));
474 File->ModuleDBI->setObjFileName(Path);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000475
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000476 // Before we can process symbol substreams from .debug$S, we need to process
477 // type information, file checksums, and the string table. Add type info to
478 // the PDB first, so that we can get the map from object file type and item
479 // indices to PDB type and item indices.
Reid Kleckner651db912017-07-18 00:21:25 +0000480 CVIndexMap ObjectIndexMap;
481 const CVIndexMap &IndexMap = mergeDebugT(File, ObjectIndexMap);
Zachary Turner448dea42017-07-07 18:46:14 +0000482
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000483 // Now do all live .debug$S sections.
484 for (SectionChunk *DebugChunk : File->getDebugChunks()) {
485 if (!DebugChunk->isLive() || DebugChunk->getSectionName() != ".debug$S")
486 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000487
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000488 ArrayRef<uint8_t> RelocatedDebugContents =
489 relocateDebugChunk(Alloc, DebugChunk);
490 if (RelocatedDebugContents.empty())
491 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000492
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000493 DebugSubsectionArray Subsections;
494 BinaryStreamReader Reader(RelocatedDebugContents, support::little);
495 ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
Rui Ueyama52896622017-01-12 03:09:25 +0000496
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000497 DebugStringTableSubsectionRef CVStrTab;
498 DebugChecksumsSubsectionRef Checksums;
499 for (const DebugSubsectionRecord &SS : Subsections) {
500 switch (SS.kind()) {
501 case DebugSubsectionKind::StringTable:
502 ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
503 break;
504 case DebugSubsectionKind::FileChecksums:
505 ExitOnErr(Checksums.initialize(SS.getRecordData()));
506 break;
507 case DebugSubsectionKind::Lines:
508 // We can add the relocated line table directly to the PDB without
509 // modification because the file checksum offsets will stay the same.
510 File->ModuleDBI->addDebugSubsection(SS);
511 break;
512 case DebugSubsectionKind::Symbols:
Reid Kleckner651db912017-07-18 00:21:25 +0000513 mergeSymbolRecords(Alloc, File, IndexMap, SS.getRecordData());
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000514 break;
515 default:
516 // FIXME: Process the rest of the subsections.
517 break;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000518 }
519 }
Rui Ueyama52896622017-01-12 03:09:25 +0000520
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000521 if (Checksums.valid()) {
522 // Make a new file checksum table that refers to offsets in the PDB-wide
523 // string table. Generally the string table subsection appears after the
524 // checksum table, so we have to do this after looping over all the
525 // subsections.
526 if (!CVStrTab.valid())
527 fatal(".debug$S sections must have both a string table subsection "
528 "and a checksum subsection table or neither");
529 auto NewChecksums = make_unique<DebugChecksumsSubsection>(PDBStrTab);
530 for (FileChecksumEntry &FC : Checksums) {
531 StringRef FileName = ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
532 ExitOnErr(Builder.getDbiBuilder().addModuleSourceFile(*File->ModuleDBI,
533 FileName));
534 NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
535 }
536 File->ModuleDBI->addDebugSubsection(std::move(NewChecksums));
537 }
538 }
539}
540
541// Add all object files to the PDB. Merge .debug$T sections into IpiData and
542// TpiData.
543void PDBLinker::addObjectsToPDB() {
544 for (ObjectFile *File : Symtab->ObjectFiles)
545 addObjectFile(File);
546
547 Builder.getStringTableBuilder().setStrings(PDBStrTab);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000548
Reid Kleckner5d577522017-03-24 17:26:38 +0000549 // Construct TPI stream contents.
Reid Kleckner13fc4112017-04-04 00:56:34 +0000550 addTypeInfo(Builder.getTpiBuilder(), TypeTable);
Reid Kleckner5d577522017-03-24 17:26:38 +0000551
552 // Construct IPI stream contents.
Reid Kleckner13fc4112017-04-04 00:56:34 +0000553 addTypeInfo(Builder.getIpiBuilder(), IDTable);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000554
555 // Add public and symbol records stream.
556
557 // For now we don't actually write any thing useful to the publics stream, but
558 // the act of "getting" it also creates it lazily so that we write an empty
559 // stream.
560 (void)Builder.getPublicsBuilder();
Rui Ueyama52896622017-01-12 03:09:25 +0000561}
562
Zachary Turner6708e0b2017-07-10 21:01:37 +0000563static void addLinkerModuleSymbols(StringRef Path,
564 pdb::DbiModuleDescriptorBuilder &Mod,
565 BumpPtrAllocator &Allocator) {
566 codeview::SymbolSerializer Serializer(Allocator, CodeViewContainer::Pdb);
567 codeview::ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
568 codeview::Compile3Sym CS(SymbolRecordKind::Compile3Sym);
569 codeview::EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
570
571 ONS.Name = "* Linker *";
572 ONS.Signature = 0;
573
574 CS.Machine = Config->is64() ? CPUType::X64 : CPUType::Intel80386;
575 CS.Flags = CompileSym3Flags::None;
576 CS.VersionBackendBuild = 0;
577 CS.VersionBackendMajor = 0;
578 CS.VersionBackendMinor = 0;
579 CS.VersionBackendQFE = 0;
580 CS.VersionFrontendBuild = 0;
581 CS.VersionFrontendMajor = 0;
582 CS.VersionFrontendMinor = 0;
583 CS.VersionFrontendQFE = 0;
584 CS.Version = "LLVM Linker";
585 CS.setLanguage(SourceLanguage::Link);
586
587 ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
588 std::string ArgStr = llvm::join(Args, " ");
589 EBS.Fields.push_back("cwd");
590 SmallString<64> cwd;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000591 sys::fs::current_path(cwd);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000592 EBS.Fields.push_back(cwd);
593 EBS.Fields.push_back("exe");
Zachary Turner77f23b92017-07-10 21:09:11 +0000594 EBS.Fields.push_back(Config->Argv[0]);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000595 EBS.Fields.push_back("pdb");
596 EBS.Fields.push_back(Path);
597 EBS.Fields.push_back("cmd");
598 EBS.Fields.push_back(ArgStr);
599 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
600 ONS, Allocator, CodeViewContainer::Pdb));
601 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
602 CS, Allocator, CodeViewContainer::Pdb));
603 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
604 EBS, Allocator, CodeViewContainer::Pdb));
605}
606
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000607// Creates a PDB file.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000608void coff::createPDB(SymbolTable *Symtab, ArrayRef<uint8_t> SectionTable,
Saleem Abdulrasooldf8a13b2017-01-04 17:56:54 +0000609 const llvm::codeview::DebugInfo *DI) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000610 PDBLinker PDB(Symtab);
611 PDB.initialize(DI);
612 PDB.addObjectsToPDB();
613 PDB.addSections(SectionTable);
614 PDB.commit();
615}
616
617void PDBLinker::initialize(const llvm::codeview::DebugInfo *DI) {
Rui Ueyama12979542016-09-30 20:53:45 +0000618 ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
Rui Ueyama7f382992016-09-15 18:55:18 +0000619
Rui Ueyama8d3fb5d2016-10-05 22:08:58 +0000620 // Create streams in MSF for predefined streams, namely
621 // PDB, TPI, DBI and IPI.
622 for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
623 ExitOnErr(Builder.getMsfBuilder().addStream(0));
Rui Ueyama7f382992016-09-15 18:55:18 +0000624
Rui Ueyamabb542b32016-09-16 22:51:17 +0000625 // Add an Info stream.
626 auto &InfoBuilder = Builder.getInfoBuilder();
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000627 InfoBuilder.setAge(DI ? DI->PDB70.Age : 0);
628
Reid Kleckner67653ee2017-07-17 23:59:44 +0000629 GUID uuid{};
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000630 if (DI)
631 memcpy(&uuid, &DI->PDB70.Signature, sizeof(uuid));
632 InfoBuilder.setGuid(uuid);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000633 InfoBuilder.setSignature(time(nullptr));
Rui Ueyamabb542b32016-09-16 22:51:17 +0000634 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
Rui Ueyama7f382992016-09-15 18:55:18 +0000635
Zachary Turner6c4bfba2017-07-07 05:04:36 +0000636 // Add an empty DBI stream.
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000637 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Zachary Turnerc1e93e52017-07-07 18:45:56 +0000638 DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000639 ExitOnErr(DbiBuilder.addDbgStream(pdb::DbgHeaderType::NewFPO, {}));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000640}
Rui Ueyama1343fac2016-10-06 22:52:01 +0000641
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000642void PDBLinker::addSections(ArrayRef<uint8_t> SectionTable) {
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000643 // Add Section Contributions.
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000644 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000645 addSectionContribs(Symtab, DbiBuilder);
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000646
Rui Ueyama20df4ec2016-10-31 21:09:21 +0000647 // Add Section Map stream.
648 ArrayRef<object::coff_section> Sections = {
Rui Ueyama6294a242016-11-04 17:41:29 +0000649 (const object::coff_section *)SectionTable.data(),
Rui Ueyama20df4ec2016-10-31 21:09:21 +0000650 SectionTable.size() / sizeof(object::coff_section)};
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000651 SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
Rui Ueyama20df4ec2016-10-31 21:09:21 +0000652 DbiBuilder.setSectionMap(SectionMap);
653
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000654 // It's not entirely clear what this is, but the * Linker * module uses it.
655 NativePath = Config->PDBPath;
656 sys::fs::make_absolute(NativePath);
657 sys::path::native(NativePath, sys::path::Style::windows);
658 uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
Zachary Turner6c4bfba2017-07-07 05:04:36 +0000659 auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
660 LinkerModule.setPdbFilePathNI(PdbFilePathNI);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000661 addLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
Rui Ueyamac91f7162016-11-16 01:10:46 +0000662
Rui Ueyama9f66f822016-10-11 19:45:07 +0000663 // Add COFF section header stream.
664 ExitOnErr(
665 DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000666}
Rui Ueyama9f66f822016-10-11 19:45:07 +0000667
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000668void PDBLinker::commit() {
Rui Ueyama3e9d6bb2016-09-26 23:53:55 +0000669 // Write to a file.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000670 ExitOnErr(Builder.commit(Config->PDBPath));
Rui Ueyamae7378242015-12-04 23:11:05 +0000671}