blob: 674a3925b37f8db56748f0f1b89f5619c594aedc [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"
Reid Klecknereacdf042017-07-27 18:25:59 +000016#include "Writer.h"
Saleem Abdulrasooldf8a13b2017-01-04 17:56:54 +000017#include "llvm/DebugInfo/CodeView/CVDebugRecord.h"
Reid Kleckner44cdb102017-06-19 17:21:45 +000018#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000019#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
Zachary Turner6708e0b2017-07-10 21:01:37 +000020#include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
Reid Kleckner651db912017-07-18 00:21:25 +000021#include "llvm/DebugInfo/CodeView/TypeDeserializer.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"
Reid Kleckner651db912017-07-18 00:21:25 +000028#include "llvm/DebugInfo/PDB/GenericError.h"
Zachary Turner6708e0b2017-07-10 21:01:37 +000029#include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000030#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
31#include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
32#include "llvm/DebugInfo/PDB/Native/InfoStream.h"
33#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
Reid Kleckner651db912017-07-18 00:21:25 +000034#include "llvm/DebugInfo/PDB/Native/NativeSession.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000035#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
36#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
Rafael Espindolaa0f30da2017-05-02 20:19:42 +000037#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
Reid Klecknereacdf042017-07-27 18:25:59 +000038#include "llvm/DebugInfo/PDB/Native/PublicsStreamBuilder.h"
Reid Klecknerd91ca762017-07-19 17:26:07 +000039#include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000040#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
41#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
Reid Kleckner651db912017-07-18 00:21:25 +000042#include "llvm/DebugInfo/PDB/PDB.h"
Rui Ueyama20df4ec2016-10-31 21:09:21 +000043#include "llvm/Object/COFF.h"
Zachary Turnerd9dc2822017-03-02 20:52:51 +000044#include "llvm/Support/BinaryByteStream.h"
Rui Ueyama1763c0d2015-12-08 18:39:55 +000045#include "llvm/Support/Endian.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000046#include "llvm/Support/FileOutputBuffer.h"
Zachary Turner7b327d02017-02-16 23:35:45 +000047#include "llvm/Support/Path.h"
Rui Ueyamabe939b32016-11-21 17:22:35 +000048#include "llvm/Support/ScopedPrinter.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000049#include <memory>
50
Rui Ueyama1d99ab32016-09-15 22:24:51 +000051using namespace lld;
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000052using namespace lld::coff;
Rui Ueyamae7378242015-12-04 23:11:05 +000053using namespace llvm;
Rui Ueyamabe939b32016-11-21 17:22:35 +000054using namespace llvm::codeview;
Rui Ueyamae7378242015-12-04 23:11:05 +000055
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000056using llvm::object::coff_section;
57
Rui Ueyamab28c6d42016-09-16 04:32:33 +000058static ExitOnError ExitOnErr;
59
Reid Kleckner0faf6d72017-07-14 00:14:58 +000060namespace {
Reid Kleckner651db912017-07-18 00:21:25 +000061/// Map from type index and item index in a type server PDB to the
62/// corresponding index in the destination PDB.
63struct CVIndexMap {
64 SmallVector<TypeIndex, 0> TPIMap;
65 SmallVector<TypeIndex, 0> IPIMap;
66 bool IsTypeServerMap = false;
67};
68
Reid Kleckner0faf6d72017-07-14 00:14:58 +000069class PDBLinker {
70public:
71 PDBLinker(SymbolTable *Symtab)
72 : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
73 IDTable(Alloc) {}
74
75 /// Emit the basic PDB structure: initial streams, headers, etc.
76 void initialize(const llvm::codeview::DebugInfo *DI);
77
78 /// Link CodeView from each object file in the symbol table into the PDB.
79 void addObjectsToPDB();
80
81 /// Link CodeView from a single object file into the PDB.
Rui Ueyamae1b48e02017-07-26 23:05:24 +000082 void addObjFile(ObjFile *File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +000083
Reid Kleckner651db912017-07-18 00:21:25 +000084 /// Produce a mapping from the type and item indices used in the object
85 /// file to those in the destination PDB.
86 ///
87 /// If the object file uses a type server PDB (compiled with /Zi), merge TPI
88 /// and IPI from the type server PDB and return a map for it. Each unique type
89 /// server PDB is merged at most once, so this may return an existing index
90 /// mapping.
91 ///
92 /// If the object does not use a type server PDB (compiled with /Z7), we merge
93 /// all the type and item records from the .debug$S stream and fill in the
94 /// caller-provided ObjectIndexMap.
Rui Ueyamae1b48e02017-07-26 23:05:24 +000095 const CVIndexMap &mergeDebugT(ObjFile *File, CVIndexMap &ObjectIndexMap);
Reid Kleckner651db912017-07-18 00:21:25 +000096
Rui Ueyamae1b48e02017-07-26 23:05:24 +000097 const CVIndexMap &maybeMergeTypeServerPDB(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +000098 TypeServer2Record &TS);
Reid Kleckner0faf6d72017-07-14 00:14:58 +000099
100 /// Add the section map and section contributions to the PDB.
101 void addSections(ArrayRef<uint8_t> SectionTable);
102
103 /// Write the PDB to disk.
104 void commit();
105
106private:
107 BumpPtrAllocator Alloc;
108
109 SymbolTable *Symtab;
110
111 pdb::PDBFileBuilder Builder;
112
113 /// Type records that will go into the PDB TPI stream.
114 TypeTableBuilder TypeTable;
115
116 /// Item records that will go into the PDB IPI stream.
117 TypeTableBuilder IDTable;
118
119 /// PDBs use a single global string table for filenames in the file checksum
120 /// table.
121 DebugStringTableSubsection PDBStrTab;
122
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000123 llvm::SmallString<128> NativePath;
124
125 std::vector<pdb::SecMapEntry> SectionMap;
Reid Kleckner651db912017-07-18 00:21:25 +0000126
127 /// Type index mappings of type server PDBs that we've loaded so far.
128 std::map<GUID, CVIndexMap> TypeServerIndexMappings;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000129};
130}
131
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000132// Returns a list of all SectionChunks.
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000133static void addSectionContribs(SymbolTable *Symtab,
134 pdb::DbiStreamBuilder &DbiBuilder) {
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000135 for (Chunk *C : Symtab->getChunks())
136 if (auto *SC = dyn_cast<SectionChunk>(C))
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000137 DbiBuilder.addSectionContrib(SC->File->ModuleDBI, SC->Header);
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000138}
139
Rui Ueyamabe939b32016-11-21 17:22:35 +0000140static SectionChunk *findByName(std::vector<SectionChunk *> &Sections,
141 StringRef Name) {
142 for (SectionChunk *C : Sections)
143 if (C->getSectionName() == Name)
144 return C;
145 return nullptr;
146}
147
Reid Kleckner44cdb102017-06-19 17:21:45 +0000148static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
149 StringRef SecName) {
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000150 // First 4 bytes are section magic.
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000151 if (Data.size() < 4)
Rui Ueyama52896622017-01-12 03:09:25 +0000152 fatal(SecName + " too short");
Reid Kleckner44cdb102017-06-19 17:21:45 +0000153 if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
Rui Ueyama52896622017-01-12 03:09:25 +0000154 fatal(SecName + " has an invalid magic");
Rui Ueyama26186c72016-12-09 04:46:54 +0000155 return Data.slice(4);
156}
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000157
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000158static ArrayRef<uint8_t> getDebugSection(ObjFile *File, StringRef SecName) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000159 if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
160 return consumeDebugMagic(Sec->getContents(), SecName);
161 return {};
162}
163
Reid Kleckner5d577522017-03-24 17:26:38 +0000164static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
Reid Kleckner44cdb102017-06-19 17:21:45 +0000165 TypeTableBuilder &TypeTable) {
Reid Kleckner5d577522017-03-24 17:26:38 +0000166 // Start the TPI or IPI stream header.
167 TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
Rui Ueyama52896622017-01-12 03:09:25 +0000168
Reid Klecknerd91ca762017-07-19 17:26:07 +0000169 // Flatten the in memory type table and hash each type.
Reid Kleckner5d577522017-03-24 17:26:38 +0000170 TypeTable.ForEachRecord([&](TypeIndex TI, ArrayRef<uint8_t> Rec) {
Reid Klecknerd91ca762017-07-19 17:26:07 +0000171 assert(Rec.size() >= sizeof(RecordPrefix));
172 const RecordPrefix *P = reinterpret_cast<const RecordPrefix *>(Rec.data());
173 CVType Type(static_cast<TypeLeafKind>(unsigned(P->RecordKind)), Rec);
174 auto Hash = pdb::hashTypeRecord(Type);
175 if (auto E = Hash.takeError())
176 fatal("type hashing error");
177 TpiBuilder.addTypeRecord(Rec, *Hash);
Reid Kleckner5d577522017-03-24 17:26:38 +0000178 });
Reid Kleckner5d577522017-03-24 17:26:38 +0000179}
180
Reid Kleckner651db912017-07-18 00:21:25 +0000181static Optional<TypeServer2Record>
182maybeReadTypeServerRecord(CVTypeArray &Types) {
183 auto I = Types.begin();
184 if (I == Types.end())
185 return None;
186 const CVType &Type = *I;
187 if (Type.kind() != LF_TYPESERVER2)
188 return None;
189 TypeServer2Record TS;
190 if (auto EC = TypeDeserializer::deserializeAs(const_cast<CVType &>(Type), TS))
191 fatal(EC, "error reading type server record");
192 return std::move(TS);
193}
194
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000195const CVIndexMap &PDBLinker::mergeDebugT(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000196 CVIndexMap &ObjectIndexMap) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000197 ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
198 if (Data.empty())
Reid Kleckner651db912017-07-18 00:21:25 +0000199 return ObjectIndexMap;
Reid Kleckner6597c282017-07-13 20:12:23 +0000200
Reid Kleckner44cdb102017-06-19 17:21:45 +0000201 BinaryByteStream Stream(Data, support::little);
202 CVTypeArray Types;
203 BinaryStreamReader Reader(Stream);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000204 if (auto EC = Reader.readArray(Types, Reader.getLength()))
205 fatal(EC, "Reader::readArray failed");
Reid Kleckner651db912017-07-18 00:21:25 +0000206
207 // Look through type servers. If we've already seen this type server, don't
208 // merge any type information.
209 if (Optional<TypeServer2Record> TS = maybeReadTypeServerRecord(Types))
210 return maybeMergeTypeServerPDB(File, *TS);
211
212 // This is a /Z7 object. Fill in the temporary, caller-provided
213 // ObjectIndexMap.
214 if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable,
215 ObjectIndexMap.TPIMap, Types))
216 fatal(Err, "codeview::mergeTypeAndIdRecords failed");
217 return ObjectIndexMap;
218}
219
220static Expected<std::unique_ptr<pdb::NativeSession>>
221tryToLoadPDB(const GUID &GuidFromObj, StringRef TSPath) {
222 std::unique_ptr<pdb::IPDBSession> ThisSession;
223 if (auto EC =
224 pdb::loadDataForPDB(pdb::PDB_ReaderType::Native, TSPath, ThisSession))
225 return std::move(EC);
226
227 std::unique_ptr<pdb::NativeSession> NS(
228 static_cast<pdb::NativeSession *>(ThisSession.release()));
229 pdb::PDBFile &File = NS->getPDBFile();
230 auto ExpectedInfo = File.getPDBInfoStream();
231 // All PDB Files should have an Info stream.
232 if (!ExpectedInfo)
233 return ExpectedInfo.takeError();
234
235 // Just because a file with a matching name was found and it was an actual
236 // PDB file doesn't mean it matches. For it to match the InfoStream's GUID
237 // must match the GUID specified in the TypeServer2 record.
238 if (ExpectedInfo->getGuid() != GuidFromObj)
239 return make_error<pdb::GenericError>(
240 pdb::generic_error_code::type_server_not_found, TSPath);
241
242 return std::move(NS);
243}
244
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000245const CVIndexMap &PDBLinker::maybeMergeTypeServerPDB(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000246 TypeServer2Record &TS) {
247 // First, check if we already loaded a PDB with this GUID. Return the type
248 // index mapping if we have it.
249 auto Insertion = TypeServerIndexMappings.insert({TS.getGuid(), CVIndexMap()});
250 CVIndexMap &IndexMap = Insertion.first->second;
251 if (!Insertion.second)
252 return IndexMap;
253
254 // Mark this map as a type server map.
255 IndexMap.IsTypeServerMap = true;
256
257 // Check for a PDB at:
258 // 1. The given file path
259 // 2. Next to the object file or archive file
260 auto ExpectedSession = tryToLoadPDB(TS.getGuid(), TS.getName());
261 if (!ExpectedSession) {
262 consumeError(ExpectedSession.takeError());
263 StringRef LocalPath =
264 !File->ParentName.empty() ? File->ParentName : File->getName();
265 SmallString<128> Path = sys::path::parent_path(LocalPath);
Reid Klecknerf8522d82017-07-18 00:33:53 +0000266 sys::path::append(
267 Path, sys::path::filename(TS.getName(), sys::path::Style::windows));
Reid Kleckner651db912017-07-18 00:21:25 +0000268 ExpectedSession = tryToLoadPDB(TS.getGuid(), Path);
269 }
270 if (auto E = ExpectedSession.takeError())
271 fatal(E, "Type server PDB was not found");
272
273 // Merge TPI first, because the IPI stream will reference type indices.
274 auto ExpectedTpi = (*ExpectedSession)->getPDBFile().getPDBTpiStream();
275 if (auto E = ExpectedTpi.takeError())
276 fatal(E, "Type server does not have TPI stream");
277 if (auto Err = mergeTypeRecords(TypeTable, IndexMap.TPIMap,
278 ExpectedTpi->typeArray()))
279 fatal(Err, "codeview::mergeTypeRecords failed");
280
281 // Merge IPI.
282 auto ExpectedIpi = (*ExpectedSession)->getPDBFile().getPDBIpiStream();
283 if (auto E = ExpectedIpi.takeError())
284 fatal(E, "Type server does not have TPI stream");
285 if (auto Err = mergeIdRecords(IDTable, IndexMap.TPIMap, IndexMap.IPIMap,
286 ExpectedIpi->typeArray()))
287 fatal(Err, "codeview::mergeIdRecords failed");
288
289 return IndexMap;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000290}
291
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000292static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
293 if (TI.isSimple())
294 return true;
295 if (TI.toArrayIndex() >= TypeIndexMap.size())
296 return false;
297 TI = TypeIndexMap[TI.toArrayIndex()];
298 return true;
299}
300
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000301static void remapTypesInSymbolRecord(ObjFile *File,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000302 MutableArrayRef<uint8_t> Contents,
Reid Kleckner651db912017-07-18 00:21:25 +0000303 const CVIndexMap &IndexMap,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000304 ArrayRef<TiReference> TypeRefs) {
305 for (const TiReference &Ref : TypeRefs) {
306 unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000307 if (Contents.size() < Ref.Offset + ByteSize)
308 fatal("symbol record too short");
Reid Kleckner651db912017-07-18 00:21:25 +0000309
310 // This can be an item index or a type index. Choose the appropriate map.
311 ArrayRef<TypeIndex> TypeOrItemMap = IndexMap.TPIMap;
312 if (Ref.Kind == TiRefKind::IndexRef && IndexMap.IsTypeServerMap)
313 TypeOrItemMap = IndexMap.IPIMap;
314
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000315 MutableArrayRef<TypeIndex> TIs(
316 reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000317 for (TypeIndex &TI : TIs) {
Reid Kleckner651db912017-07-18 00:21:25 +0000318 if (!remapTypeIndex(TI, TypeOrItemMap)) {
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000319 TI = TypeIndex(SimpleTypeKind::NotTranslated);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000320 log("ignoring symbol record in " + File->getName() +
321 " with bad type index 0x" + utohexstr(TI.getIndex()));
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000322 continue;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000323 }
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000324 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000325 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000326}
327
328/// MSVC translates S_PROC_ID_END to S_END.
329uint16_t canonicalizeSymbolKind(SymbolKind Kind) {
330 if (Kind == SymbolKind::S_PROC_ID_END)
331 return SymbolKind::S_END;
332 return Kind;
333}
334
335/// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
336/// The object file may not be aligned.
337static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
338 BumpPtrAllocator &Alloc) {
339 size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
340 assert(Size >= 4 && "record too short");
341 assert(Size <= MaxRecordLength && "record too long");
342 void *Mem = Alloc.Allocate(Size, 4);
343
344 // Copy the symbol record and zero out any padding bytes.
345 MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
346 memcpy(NewData.data(), Sym.data().data(), Sym.length());
347 memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
348
349 // Update the record prefix length. It should point to the beginning of the
350 // next record. MSVC does some canonicalization of the record kind, so we do
351 // that as well.
352 auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
353 Prefix->RecordKind = canonicalizeSymbolKind(Sym.kind());
354 Prefix->RecordLen = Size - 2;
355 return NewData;
356}
357
Reid Kleckner3f851922017-07-06 16:39:32 +0000358/// Return true if this symbol opens a scope. This implies that the symbol has
359/// "parent" and "end" fields, which contain the offset of the S_END or
360/// S_INLINESITE_END record.
361static bool symbolOpensScope(SymbolKind Kind) {
362 switch (Kind) {
363 case SymbolKind::S_GPROC32:
364 case SymbolKind::S_LPROC32:
365 case SymbolKind::S_LPROC32_ID:
366 case SymbolKind::S_GPROC32_ID:
367 case SymbolKind::S_BLOCK32:
368 case SymbolKind::S_SEPCODE:
369 case SymbolKind::S_THUNK32:
370 case SymbolKind::S_INLINESITE:
371 case SymbolKind::S_INLINESITE2:
372 return true;
373 default:
374 break;
375 }
376 return false;
377}
378
379static bool symbolEndsScope(SymbolKind Kind) {
380 switch (Kind) {
381 case SymbolKind::S_END:
382 case SymbolKind::S_PROC_ID_END:
383 case SymbolKind::S_INLINESITE_END:
384 return true;
385 default:
386 break;
387 }
388 return false;
389}
390
391struct ScopeRecord {
392 ulittle32_t PtrParent;
393 ulittle32_t PtrEnd;
394};
395
396struct SymbolScope {
397 ScopeRecord *OpeningRecord;
398 uint32_t ScopeOffset;
399};
400
401static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
402 uint32_t CurOffset, CVSymbol &Sym) {
403 assert(symbolOpensScope(Sym.kind()));
404 SymbolScope S;
405 S.ScopeOffset = CurOffset;
406 S.OpeningRecord = const_cast<ScopeRecord *>(
407 reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
408 S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
409 Stack.push_back(S);
410}
411
412static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000413 uint32_t CurOffset, ObjFile *File) {
Reid Kleckner3f851922017-07-06 16:39:32 +0000414 if (Stack.empty()) {
415 warn("symbol scopes are not balanced in " + File->getName());
416 return;
417 }
418 SymbolScope S = Stack.pop_back_val();
419 S.OpeningRecord->PtrEnd = CurOffset;
420}
421
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000422static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000423 const CVIndexMap &IndexMap,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000424 BinaryStreamRef SymData) {
425 // FIXME: Improve error recovery by warning and skipping records when
426 // possible.
427 CVSymbolArray Syms;
428 BinaryStreamReader Reader(SymData);
429 ExitOnErr(Reader.readArray(Syms, Reader.getLength()));
Reid Kleckner3f851922017-07-06 16:39:32 +0000430 SmallVector<SymbolScope, 4> Scopes;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000431 for (const CVSymbol &Sym : Syms) {
432 // Discover type index references in the record. Skip it if we don't know
433 // where they are.
434 SmallVector<TiReference, 32> TypeRefs;
435 if (!discoverTypeIndices(Sym, TypeRefs)) {
436 log("ignoring unknown symbol record with kind 0x" + utohexstr(Sym.kind()));
437 continue;
438 }
439
440 // Copy the symbol record so we can mutate it.
441 MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
442
443 // Re-map all the type index references.
444 MutableArrayRef<uint8_t> Contents =
445 NewData.drop_front(sizeof(RecordPrefix));
Reid Kleckner651db912017-07-18 00:21:25 +0000446 remapTypesInSymbolRecord(File, Contents, IndexMap, TypeRefs);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000447
Reid Kleckner3f851922017-07-06 16:39:32 +0000448 // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
449 CVSymbol NewSym(Sym.kind(), NewData);
450 if (symbolOpensScope(Sym.kind()))
451 scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(), NewSym);
452 else if (symbolEndsScope(Sym.kind()))
453 scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000454
455 // Add the symbol to the module.
Reid Kleckner3f851922017-07-06 16:39:32 +0000456 File->ModuleDBI->addSymbol(NewSym);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000457 }
458}
459
Reid Kleckner44cdb102017-06-19 17:21:45 +0000460// Allocate memory for a .debug$S section and relocate it.
461static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
462 SectionChunk *DebugChunk) {
463 uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk->getSize());
464 assert(DebugChunk->OutputSectionOff == 0 &&
465 "debug sections should not be in output sections");
466 DebugChunk->writeTo(Buffer);
467 return consumeDebugMagic(makeArrayRef(Buffer, DebugChunk->getSize()),
468 ".debug$S");
469}
470
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000471void PDBLinker::addObjFile(ObjFile *File) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000472 // Add a module descriptor for every object file. We need to put an absolute
473 // path to the object into the PDB. If this is a plain object, we make its
474 // path absolute. If it's an object in an archive, we make the archive path
475 // absolute.
476 bool InArchive = !File->ParentName.empty();
477 SmallString<128> Path = InArchive ? File->ParentName : File->getName();
478 sys::fs::make_absolute(Path);
479 sys::path::native(Path, sys::path::Style::windows);
480 StringRef Name = InArchive ? File->getName() : StringRef(Path);
Zachary Turner2897e032017-05-25 21:16:03 +0000481
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000482 File->ModuleDBI = &ExitOnErr(Builder.getDbiBuilder().addModuleInfo(Name));
483 File->ModuleDBI->setObjFileName(Path);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000484
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000485 // Before we can process symbol substreams from .debug$S, we need to process
486 // type information, file checksums, and the string table. Add type info to
487 // the PDB first, so that we can get the map from object file type and item
488 // indices to PDB type and item indices.
Reid Kleckner651db912017-07-18 00:21:25 +0000489 CVIndexMap ObjectIndexMap;
490 const CVIndexMap &IndexMap = mergeDebugT(File, ObjectIndexMap);
Zachary Turner448dea42017-07-07 18:46:14 +0000491
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000492 // Now do all live .debug$S sections.
493 for (SectionChunk *DebugChunk : File->getDebugChunks()) {
494 if (!DebugChunk->isLive() || DebugChunk->getSectionName() != ".debug$S")
495 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000496
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000497 ArrayRef<uint8_t> RelocatedDebugContents =
498 relocateDebugChunk(Alloc, DebugChunk);
499 if (RelocatedDebugContents.empty())
500 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000501
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000502 DebugSubsectionArray Subsections;
503 BinaryStreamReader Reader(RelocatedDebugContents, support::little);
504 ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
Rui Ueyama52896622017-01-12 03:09:25 +0000505
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000506 DebugStringTableSubsectionRef CVStrTab;
507 DebugChecksumsSubsectionRef Checksums;
508 for (const DebugSubsectionRecord &SS : Subsections) {
509 switch (SS.kind()) {
510 case DebugSubsectionKind::StringTable:
511 ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
512 break;
513 case DebugSubsectionKind::FileChecksums:
514 ExitOnErr(Checksums.initialize(SS.getRecordData()));
515 break;
516 case DebugSubsectionKind::Lines:
517 // We can add the relocated line table directly to the PDB without
518 // modification because the file checksum offsets will stay the same.
519 File->ModuleDBI->addDebugSubsection(SS);
520 break;
521 case DebugSubsectionKind::Symbols:
Reid Kleckner651db912017-07-18 00:21:25 +0000522 mergeSymbolRecords(Alloc, File, IndexMap, SS.getRecordData());
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000523 break;
524 default:
525 // FIXME: Process the rest of the subsections.
526 break;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000527 }
528 }
Rui Ueyama52896622017-01-12 03:09:25 +0000529
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000530 if (Checksums.valid()) {
531 // Make a new file checksum table that refers to offsets in the PDB-wide
532 // string table. Generally the string table subsection appears after the
533 // checksum table, so we have to do this after looping over all the
534 // subsections.
535 if (!CVStrTab.valid())
536 fatal(".debug$S sections must have both a string table subsection "
537 "and a checksum subsection table or neither");
538 auto NewChecksums = make_unique<DebugChecksumsSubsection>(PDBStrTab);
539 for (FileChecksumEntry &FC : Checksums) {
540 StringRef FileName = ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
541 ExitOnErr(Builder.getDbiBuilder().addModuleSourceFile(*File->ModuleDBI,
542 FileName));
543 NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
544 }
545 File->ModuleDBI->addDebugSubsection(std::move(NewChecksums));
546 }
547 }
548}
549
Reid Klecknereacdf042017-07-27 18:25:59 +0000550static PublicSym32 createPublic(Defined *Def) {
551 PublicSym32 Pub(SymbolKind::S_PUB32);
552 Pub.Name = Def->getName();
553 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
554 if (D->getCOFFSymbol().isFunctionDefinition())
555 Pub.Flags = PublicSymFlags::Function;
556 } else if (isa<DefinedImportThunk>(Def)) {
557 Pub.Flags = PublicSymFlags::Function;
558 }
559
560 OutputSection *OS = Def->getChunk()->getOutputSection();
561 assert(OS && "all publics should be in final image");
562 Pub.Offset = Def->getRVA() - OS->getRVA();
563 Pub.Segment = OS->SectionIndex;
564 return Pub;
565}
566
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000567// Add all object files to the PDB. Merge .debug$T sections into IpiData and
568// TpiData.
569void PDBLinker::addObjectsToPDB() {
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000570 for (ObjFile *File : ObjFile::Instances)
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000571 addObjFile(File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000572
573 Builder.getStringTableBuilder().setStrings(PDBStrTab);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000574
Reid Kleckner5d577522017-03-24 17:26:38 +0000575 // Construct TPI stream contents.
Reid Kleckner13fc4112017-04-04 00:56:34 +0000576 addTypeInfo(Builder.getTpiBuilder(), TypeTable);
Reid Kleckner5d577522017-03-24 17:26:38 +0000577
578 // Construct IPI stream contents.
Reid Kleckner13fc4112017-04-04 00:56:34 +0000579 addTypeInfo(Builder.getIpiBuilder(), IDTable);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000580
Reid Klecknereacdf042017-07-27 18:25:59 +0000581 // Compute the public symbols.
582 std::vector<PublicSym32> Publics;
583 Symtab->forEachSymbol([&Publics](Symbol *S) {
584 // Only emit defined, live symbols that have a chunk.
585 auto *Def = dyn_cast<Defined>(S->body());
586 if (Def && Def->isLive() && Def->getChunk())
587 Publics.push_back(createPublic(Def));
588 });
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000589
Reid Klecknereacdf042017-07-27 18:25:59 +0000590 if (!Publics.empty()) {
591 // Sort the public symbols and add them to the stream.
592 std::sort(Publics.begin(), Publics.end(),
593 [](const PublicSym32 &L, const PublicSym32 &R) {
594 return L.Name < R.Name;
595 });
596 auto &PublicsBuilder = Builder.getPublicsBuilder();
597 for (const PublicSym32 &Pub : Publics)
598 PublicsBuilder.addPublicSymbol(Pub);
599 }
Rui Ueyama52896622017-01-12 03:09:25 +0000600}
601
Zachary Turner6708e0b2017-07-10 21:01:37 +0000602static void addLinkerModuleSymbols(StringRef Path,
603 pdb::DbiModuleDescriptorBuilder &Mod,
604 BumpPtrAllocator &Allocator) {
605 codeview::SymbolSerializer Serializer(Allocator, CodeViewContainer::Pdb);
606 codeview::ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
607 codeview::Compile3Sym CS(SymbolRecordKind::Compile3Sym);
608 codeview::EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
609
610 ONS.Name = "* Linker *";
611 ONS.Signature = 0;
612
613 CS.Machine = Config->is64() ? CPUType::X64 : CPUType::Intel80386;
614 CS.Flags = CompileSym3Flags::None;
615 CS.VersionBackendBuild = 0;
616 CS.VersionBackendMajor = 0;
617 CS.VersionBackendMinor = 0;
618 CS.VersionBackendQFE = 0;
619 CS.VersionFrontendBuild = 0;
620 CS.VersionFrontendMajor = 0;
621 CS.VersionFrontendMinor = 0;
622 CS.VersionFrontendQFE = 0;
623 CS.Version = "LLVM Linker";
624 CS.setLanguage(SourceLanguage::Link);
625
626 ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
627 std::string ArgStr = llvm::join(Args, " ");
628 EBS.Fields.push_back("cwd");
629 SmallString<64> cwd;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000630 sys::fs::current_path(cwd);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000631 EBS.Fields.push_back(cwd);
632 EBS.Fields.push_back("exe");
Zachary Turner77f23b92017-07-10 21:09:11 +0000633 EBS.Fields.push_back(Config->Argv[0]);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000634 EBS.Fields.push_back("pdb");
635 EBS.Fields.push_back(Path);
636 EBS.Fields.push_back("cmd");
637 EBS.Fields.push_back(ArgStr);
638 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
639 ONS, Allocator, CodeViewContainer::Pdb));
640 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
641 CS, Allocator, CodeViewContainer::Pdb));
642 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
643 EBS, Allocator, CodeViewContainer::Pdb));
644}
645
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000646// Creates a PDB file.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000647void coff::createPDB(SymbolTable *Symtab, ArrayRef<uint8_t> SectionTable,
Saleem Abdulrasooldf8a13b2017-01-04 17:56:54 +0000648 const llvm::codeview::DebugInfo *DI) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000649 PDBLinker PDB(Symtab);
650 PDB.initialize(DI);
651 PDB.addObjectsToPDB();
652 PDB.addSections(SectionTable);
653 PDB.commit();
654}
655
656void PDBLinker::initialize(const llvm::codeview::DebugInfo *DI) {
Rui Ueyama12979542016-09-30 20:53:45 +0000657 ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
Rui Ueyama7f382992016-09-15 18:55:18 +0000658
Rui Ueyama8d3fb5d2016-10-05 22:08:58 +0000659 // Create streams in MSF for predefined streams, namely
660 // PDB, TPI, DBI and IPI.
661 for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
662 ExitOnErr(Builder.getMsfBuilder().addStream(0));
Rui Ueyama7f382992016-09-15 18:55:18 +0000663
Rui Ueyamabb542b32016-09-16 22:51:17 +0000664 // Add an Info stream.
665 auto &InfoBuilder = Builder.getInfoBuilder();
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000666 InfoBuilder.setAge(DI ? DI->PDB70.Age : 0);
667
Reid Kleckner67653ee2017-07-17 23:59:44 +0000668 GUID uuid{};
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000669 if (DI)
670 memcpy(&uuid, &DI->PDB70.Signature, sizeof(uuid));
671 InfoBuilder.setGuid(uuid);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000672 InfoBuilder.setSignature(time(nullptr));
Rui Ueyamabb542b32016-09-16 22:51:17 +0000673 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
Rui Ueyama7f382992016-09-15 18:55:18 +0000674
Zachary Turner6c4bfba2017-07-07 05:04:36 +0000675 // Add an empty DBI stream.
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000676 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Zachary Turnerc1e93e52017-07-07 18:45:56 +0000677 DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000678 ExitOnErr(DbiBuilder.addDbgStream(pdb::DbgHeaderType::NewFPO, {}));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000679}
Rui Ueyama1343fac2016-10-06 22:52:01 +0000680
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000681void PDBLinker::addSections(ArrayRef<uint8_t> SectionTable) {
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000682 // Add Section Contributions.
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000683 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000684 addSectionContribs(Symtab, DbiBuilder);
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000685
Rui Ueyama20df4ec2016-10-31 21:09:21 +0000686 // Add Section Map stream.
687 ArrayRef<object::coff_section> Sections = {
Rui Ueyama6294a242016-11-04 17:41:29 +0000688 (const object::coff_section *)SectionTable.data(),
Rui Ueyama20df4ec2016-10-31 21:09:21 +0000689 SectionTable.size() / sizeof(object::coff_section)};
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000690 SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
Rui Ueyama20df4ec2016-10-31 21:09:21 +0000691 DbiBuilder.setSectionMap(SectionMap);
692
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000693 // It's not entirely clear what this is, but the * Linker * module uses it.
694 NativePath = Config->PDBPath;
695 sys::fs::make_absolute(NativePath);
696 sys::path::native(NativePath, sys::path::Style::windows);
697 uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
Zachary Turner6c4bfba2017-07-07 05:04:36 +0000698 auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
699 LinkerModule.setPdbFilePathNI(PdbFilePathNI);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000700 addLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
Rui Ueyamac91f7162016-11-16 01:10:46 +0000701
Rui Ueyama9f66f822016-10-11 19:45:07 +0000702 // Add COFF section header stream.
703 ExitOnErr(
704 DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000705}
Rui Ueyama9f66f822016-10-11 19:45:07 +0000706
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000707void PDBLinker::commit() {
Rui Ueyama3e9d6bb2016-09-26 23:53:55 +0000708 // Write to a file.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000709 ExitOnErr(Builder.commit(Config->PDBPath));
Rui Ueyamae7378242015-12-04 23:11:05 +0000710}