blob: 1b5662beed6ea1e6deeb586ecfc88e491cf381c8 [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"
Reid Klecknerd91ca762017-07-19 17:26:07 +000037#include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000038#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
39#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
Reid Kleckner651db912017-07-18 00:21:25 +000040#include "llvm/DebugInfo/PDB/PDB.h"
Rui Ueyama20df4ec2016-10-31 21:09:21 +000041#include "llvm/Object/COFF.h"
Zachary Turnerd9dc2822017-03-02 20:52:51 +000042#include "llvm/Support/BinaryByteStream.h"
Rui Ueyama1763c0d2015-12-08 18:39:55 +000043#include "llvm/Support/Endian.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000044#include "llvm/Support/FileOutputBuffer.h"
Zachary Turner7b327d02017-02-16 23:35:45 +000045#include "llvm/Support/Path.h"
Rui Ueyamabe939b32016-11-21 17:22:35 +000046#include "llvm/Support/ScopedPrinter.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000047#include <memory>
48
Rui Ueyama1d99ab32016-09-15 22:24:51 +000049using namespace lld;
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000050using namespace lld::coff;
Rui Ueyamae7378242015-12-04 23:11:05 +000051using namespace llvm;
Rui Ueyamabe939b32016-11-21 17:22:35 +000052using namespace llvm::codeview;
Rui Ueyamae7378242015-12-04 23:11:05 +000053
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000054using llvm::object::coff_section;
55
Rui Ueyamab28c6d42016-09-16 04:32:33 +000056static ExitOnError ExitOnErr;
57
Reid Kleckner0faf6d72017-07-14 00:14:58 +000058namespace {
Reid Kleckner651db912017-07-18 00:21:25 +000059/// Map from type index and item index in a type server PDB to the
60/// corresponding index in the destination PDB.
61struct CVIndexMap {
62 SmallVector<TypeIndex, 0> TPIMap;
63 SmallVector<TypeIndex, 0> IPIMap;
64 bool IsTypeServerMap = false;
65};
66
Reid Kleckner0faf6d72017-07-14 00:14:58 +000067class PDBLinker {
68public:
69 PDBLinker(SymbolTable *Symtab)
70 : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
71 IDTable(Alloc) {}
72
73 /// Emit the basic PDB structure: initial streams, headers, etc.
74 void initialize(const llvm::codeview::DebugInfo *DI);
75
76 /// Link CodeView from each object file in the symbol table into the PDB.
77 void addObjectsToPDB();
78
79 /// Link CodeView from a single object file into the PDB.
Rui Ueyamae1b48e02017-07-26 23:05:24 +000080 void addObjFile(ObjFile *File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +000081
Reid Kleckner651db912017-07-18 00:21:25 +000082 /// Produce a mapping from the type and item indices used in the object
83 /// file to those in the destination PDB.
84 ///
85 /// If the object file uses a type server PDB (compiled with /Zi), merge TPI
86 /// and IPI from the type server PDB and return a map for it. Each unique type
87 /// server PDB is merged at most once, so this may return an existing index
88 /// mapping.
89 ///
90 /// If the object does not use a type server PDB (compiled with /Z7), we merge
91 /// all the type and item records from the .debug$S stream and fill in the
92 /// caller-provided ObjectIndexMap.
Rui Ueyamae1b48e02017-07-26 23:05:24 +000093 const CVIndexMap &mergeDebugT(ObjFile *File, CVIndexMap &ObjectIndexMap);
Reid Kleckner651db912017-07-18 00:21:25 +000094
Rui Ueyamae1b48e02017-07-26 23:05:24 +000095 const CVIndexMap &maybeMergeTypeServerPDB(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +000096 TypeServer2Record &TS);
Reid Kleckner0faf6d72017-07-14 00:14:58 +000097
98 /// Add the section map and section contributions to the PDB.
99 void addSections(ArrayRef<uint8_t> SectionTable);
100
101 /// Write the PDB to disk.
102 void commit();
103
104private:
105 BumpPtrAllocator Alloc;
106
107 SymbolTable *Symtab;
108
109 pdb::PDBFileBuilder Builder;
110
111 /// Type records that will go into the PDB TPI stream.
112 TypeTableBuilder TypeTable;
113
114 /// Item records that will go into the PDB IPI stream.
115 TypeTableBuilder IDTable;
116
117 /// PDBs use a single global string table for filenames in the file checksum
118 /// table.
119 DebugStringTableSubsection PDBStrTab;
120
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000121 llvm::SmallString<128> NativePath;
122
123 std::vector<pdb::SecMapEntry> SectionMap;
Reid Kleckner651db912017-07-18 00:21:25 +0000124
125 /// Type index mappings of type server PDBs that we've loaded so far.
126 std::map<GUID, CVIndexMap> TypeServerIndexMappings;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000127};
128}
129
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000130// Returns a list of all SectionChunks.
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000131static void addSectionContribs(SymbolTable *Symtab,
132 pdb::DbiStreamBuilder &DbiBuilder) {
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000133 for (Chunk *C : Symtab->getChunks())
134 if (auto *SC = dyn_cast<SectionChunk>(C))
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000135 DbiBuilder.addSectionContrib(SC->File->ModuleDBI, SC->Header);
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000136}
137
Rui Ueyamabe939b32016-11-21 17:22:35 +0000138static SectionChunk *findByName(std::vector<SectionChunk *> &Sections,
139 StringRef Name) {
140 for (SectionChunk *C : Sections)
141 if (C->getSectionName() == Name)
142 return C;
143 return nullptr;
144}
145
Reid Kleckner44cdb102017-06-19 17:21:45 +0000146static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
147 StringRef SecName) {
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000148 // First 4 bytes are section magic.
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000149 if (Data.size() < 4)
Rui Ueyama52896622017-01-12 03:09:25 +0000150 fatal(SecName + " too short");
Reid Kleckner44cdb102017-06-19 17:21:45 +0000151 if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
Rui Ueyama52896622017-01-12 03:09:25 +0000152 fatal(SecName + " has an invalid magic");
Rui Ueyama26186c72016-12-09 04:46:54 +0000153 return Data.slice(4);
154}
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000155
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000156static ArrayRef<uint8_t> getDebugSection(ObjFile *File, StringRef SecName) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000157 if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
158 return consumeDebugMagic(Sec->getContents(), SecName);
159 return {};
160}
161
Reid Kleckner5d577522017-03-24 17:26:38 +0000162static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
Reid Kleckner44cdb102017-06-19 17:21:45 +0000163 TypeTableBuilder &TypeTable) {
Reid Kleckner5d577522017-03-24 17:26:38 +0000164 // Start the TPI or IPI stream header.
165 TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
Rui Ueyama52896622017-01-12 03:09:25 +0000166
Reid Klecknerd91ca762017-07-19 17:26:07 +0000167 // Flatten the in memory type table and hash each type.
Reid Kleckner5d577522017-03-24 17:26:38 +0000168 TypeTable.ForEachRecord([&](TypeIndex TI, ArrayRef<uint8_t> Rec) {
Reid Klecknerd91ca762017-07-19 17:26:07 +0000169 assert(Rec.size() >= sizeof(RecordPrefix));
170 const RecordPrefix *P = reinterpret_cast<const RecordPrefix *>(Rec.data());
171 CVType Type(static_cast<TypeLeafKind>(unsigned(P->RecordKind)), Rec);
172 auto Hash = pdb::hashTypeRecord(Type);
173 if (auto E = Hash.takeError())
174 fatal("type hashing error");
175 TpiBuilder.addTypeRecord(Rec, *Hash);
Reid Kleckner5d577522017-03-24 17:26:38 +0000176 });
Reid Kleckner5d577522017-03-24 17:26:38 +0000177}
178
Reid Kleckner651db912017-07-18 00:21:25 +0000179static Optional<TypeServer2Record>
180maybeReadTypeServerRecord(CVTypeArray &Types) {
181 auto I = Types.begin();
182 if (I == Types.end())
183 return None;
184 const CVType &Type = *I;
185 if (Type.kind() != LF_TYPESERVER2)
186 return None;
187 TypeServer2Record TS;
188 if (auto EC = TypeDeserializer::deserializeAs(const_cast<CVType &>(Type), TS))
189 fatal(EC, "error reading type server record");
190 return std::move(TS);
191}
192
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000193const CVIndexMap &PDBLinker::mergeDebugT(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000194 CVIndexMap &ObjectIndexMap) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000195 ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
196 if (Data.empty())
Reid Kleckner651db912017-07-18 00:21:25 +0000197 return ObjectIndexMap;
Reid Kleckner6597c282017-07-13 20:12:23 +0000198
Reid Kleckner44cdb102017-06-19 17:21:45 +0000199 BinaryByteStream Stream(Data, support::little);
200 CVTypeArray Types;
201 BinaryStreamReader Reader(Stream);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000202 if (auto EC = Reader.readArray(Types, Reader.getLength()))
203 fatal(EC, "Reader::readArray failed");
Reid Kleckner651db912017-07-18 00:21:25 +0000204
205 // Look through type servers. If we've already seen this type server, don't
206 // merge any type information.
207 if (Optional<TypeServer2Record> TS = maybeReadTypeServerRecord(Types))
208 return maybeMergeTypeServerPDB(File, *TS);
209
210 // This is a /Z7 object. Fill in the temporary, caller-provided
211 // ObjectIndexMap.
212 if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable,
213 ObjectIndexMap.TPIMap, Types))
214 fatal(Err, "codeview::mergeTypeAndIdRecords failed");
215 return ObjectIndexMap;
216}
217
218static Expected<std::unique_ptr<pdb::NativeSession>>
219tryToLoadPDB(const GUID &GuidFromObj, StringRef TSPath) {
220 std::unique_ptr<pdb::IPDBSession> ThisSession;
221 if (auto EC =
222 pdb::loadDataForPDB(pdb::PDB_ReaderType::Native, TSPath, ThisSession))
223 return std::move(EC);
224
225 std::unique_ptr<pdb::NativeSession> NS(
226 static_cast<pdb::NativeSession *>(ThisSession.release()));
227 pdb::PDBFile &File = NS->getPDBFile();
228 auto ExpectedInfo = File.getPDBInfoStream();
229 // All PDB Files should have an Info stream.
230 if (!ExpectedInfo)
231 return ExpectedInfo.takeError();
232
233 // Just because a file with a matching name was found and it was an actual
234 // PDB file doesn't mean it matches. For it to match the InfoStream's GUID
235 // must match the GUID specified in the TypeServer2 record.
236 if (ExpectedInfo->getGuid() != GuidFromObj)
237 return make_error<pdb::GenericError>(
238 pdb::generic_error_code::type_server_not_found, TSPath);
239
240 return std::move(NS);
241}
242
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000243const CVIndexMap &PDBLinker::maybeMergeTypeServerPDB(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000244 TypeServer2Record &TS) {
245 // First, check if we already loaded a PDB with this GUID. Return the type
246 // index mapping if we have it.
247 auto Insertion = TypeServerIndexMappings.insert({TS.getGuid(), CVIndexMap()});
248 CVIndexMap &IndexMap = Insertion.first->second;
249 if (!Insertion.second)
250 return IndexMap;
251
252 // Mark this map as a type server map.
253 IndexMap.IsTypeServerMap = true;
254
255 // Check for a PDB at:
256 // 1. The given file path
257 // 2. Next to the object file or archive file
258 auto ExpectedSession = tryToLoadPDB(TS.getGuid(), TS.getName());
259 if (!ExpectedSession) {
260 consumeError(ExpectedSession.takeError());
261 StringRef LocalPath =
262 !File->ParentName.empty() ? File->ParentName : File->getName();
263 SmallString<128> Path = sys::path::parent_path(LocalPath);
Reid Klecknerf8522d82017-07-18 00:33:53 +0000264 sys::path::append(
265 Path, sys::path::filename(TS.getName(), sys::path::Style::windows));
Reid Kleckner651db912017-07-18 00:21:25 +0000266 ExpectedSession = tryToLoadPDB(TS.getGuid(), Path);
267 }
268 if (auto E = ExpectedSession.takeError())
269 fatal(E, "Type server PDB was not found");
270
271 // Merge TPI first, because the IPI stream will reference type indices.
272 auto ExpectedTpi = (*ExpectedSession)->getPDBFile().getPDBTpiStream();
273 if (auto E = ExpectedTpi.takeError())
274 fatal(E, "Type server does not have TPI stream");
275 if (auto Err = mergeTypeRecords(TypeTable, IndexMap.TPIMap,
276 ExpectedTpi->typeArray()))
277 fatal(Err, "codeview::mergeTypeRecords failed");
278
279 // Merge IPI.
280 auto ExpectedIpi = (*ExpectedSession)->getPDBFile().getPDBIpiStream();
281 if (auto E = ExpectedIpi.takeError())
282 fatal(E, "Type server does not have TPI stream");
283 if (auto Err = mergeIdRecords(IDTable, IndexMap.TPIMap, IndexMap.IPIMap,
284 ExpectedIpi->typeArray()))
285 fatal(Err, "codeview::mergeIdRecords failed");
286
287 return IndexMap;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000288}
289
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000290static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
291 if (TI.isSimple())
292 return true;
293 if (TI.toArrayIndex() >= TypeIndexMap.size())
294 return false;
295 TI = TypeIndexMap[TI.toArrayIndex()];
296 return true;
297}
298
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000299static void remapTypesInSymbolRecord(ObjFile *File,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000300 MutableArrayRef<uint8_t> Contents,
Reid Kleckner651db912017-07-18 00:21:25 +0000301 const CVIndexMap &IndexMap,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000302 ArrayRef<TiReference> TypeRefs) {
303 for (const TiReference &Ref : TypeRefs) {
304 unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000305 if (Contents.size() < Ref.Offset + ByteSize)
306 fatal("symbol record too short");
Reid Kleckner651db912017-07-18 00:21:25 +0000307
308 // This can be an item index or a type index. Choose the appropriate map.
309 ArrayRef<TypeIndex> TypeOrItemMap = IndexMap.TPIMap;
310 if (Ref.Kind == TiRefKind::IndexRef && IndexMap.IsTypeServerMap)
311 TypeOrItemMap = IndexMap.IPIMap;
312
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000313 MutableArrayRef<TypeIndex> TIs(
314 reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000315 for (TypeIndex &TI : TIs) {
Reid Kleckner651db912017-07-18 00:21:25 +0000316 if (!remapTypeIndex(TI, TypeOrItemMap)) {
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000317 TI = TypeIndex(SimpleTypeKind::NotTranslated);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000318 log("ignoring symbol record in " + File->getName() +
319 " with bad type index 0x" + utohexstr(TI.getIndex()));
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000320 continue;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000321 }
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000322 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000323 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000324}
325
326/// MSVC translates S_PROC_ID_END to S_END.
327uint16_t canonicalizeSymbolKind(SymbolKind Kind) {
328 if (Kind == SymbolKind::S_PROC_ID_END)
329 return SymbolKind::S_END;
330 return Kind;
331}
332
333/// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
334/// The object file may not be aligned.
335static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
336 BumpPtrAllocator &Alloc) {
337 size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
338 assert(Size >= 4 && "record too short");
339 assert(Size <= MaxRecordLength && "record too long");
340 void *Mem = Alloc.Allocate(Size, 4);
341
342 // Copy the symbol record and zero out any padding bytes.
343 MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
344 memcpy(NewData.data(), Sym.data().data(), Sym.length());
345 memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
346
347 // Update the record prefix length. It should point to the beginning of the
348 // next record. MSVC does some canonicalization of the record kind, so we do
349 // that as well.
350 auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
351 Prefix->RecordKind = canonicalizeSymbolKind(Sym.kind());
352 Prefix->RecordLen = Size - 2;
353 return NewData;
354}
355
Reid Kleckner3f851922017-07-06 16:39:32 +0000356/// Return true if this symbol opens a scope. This implies that the symbol has
357/// "parent" and "end" fields, which contain the offset of the S_END or
358/// S_INLINESITE_END record.
359static bool symbolOpensScope(SymbolKind Kind) {
360 switch (Kind) {
361 case SymbolKind::S_GPROC32:
362 case SymbolKind::S_LPROC32:
363 case SymbolKind::S_LPROC32_ID:
364 case SymbolKind::S_GPROC32_ID:
365 case SymbolKind::S_BLOCK32:
366 case SymbolKind::S_SEPCODE:
367 case SymbolKind::S_THUNK32:
368 case SymbolKind::S_INLINESITE:
369 case SymbolKind::S_INLINESITE2:
370 return true;
371 default:
372 break;
373 }
374 return false;
375}
376
377static bool symbolEndsScope(SymbolKind Kind) {
378 switch (Kind) {
379 case SymbolKind::S_END:
380 case SymbolKind::S_PROC_ID_END:
381 case SymbolKind::S_INLINESITE_END:
382 return true;
383 default:
384 break;
385 }
386 return false;
387}
388
389struct ScopeRecord {
390 ulittle32_t PtrParent;
391 ulittle32_t PtrEnd;
392};
393
394struct SymbolScope {
395 ScopeRecord *OpeningRecord;
396 uint32_t ScopeOffset;
397};
398
399static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
400 uint32_t CurOffset, CVSymbol &Sym) {
401 assert(symbolOpensScope(Sym.kind()));
402 SymbolScope S;
403 S.ScopeOffset = CurOffset;
404 S.OpeningRecord = const_cast<ScopeRecord *>(
405 reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
406 S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
407 Stack.push_back(S);
408}
409
410static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000411 uint32_t CurOffset, ObjFile *File) {
Reid Kleckner3f851922017-07-06 16:39:32 +0000412 if (Stack.empty()) {
413 warn("symbol scopes are not balanced in " + File->getName());
414 return;
415 }
416 SymbolScope S = Stack.pop_back_val();
417 S.OpeningRecord->PtrEnd = CurOffset;
418}
419
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000420static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000421 const CVIndexMap &IndexMap,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000422 BinaryStreamRef SymData) {
423 // FIXME: Improve error recovery by warning and skipping records when
424 // possible.
425 CVSymbolArray Syms;
426 BinaryStreamReader Reader(SymData);
427 ExitOnErr(Reader.readArray(Syms, Reader.getLength()));
Reid Kleckner3f851922017-07-06 16:39:32 +0000428 SmallVector<SymbolScope, 4> Scopes;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000429 for (const CVSymbol &Sym : Syms) {
430 // Discover type index references in the record. Skip it if we don't know
431 // where they are.
432 SmallVector<TiReference, 32> TypeRefs;
433 if (!discoverTypeIndices(Sym, TypeRefs)) {
434 log("ignoring unknown symbol record with kind 0x" + utohexstr(Sym.kind()));
435 continue;
436 }
437
438 // Copy the symbol record so we can mutate it.
439 MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
440
441 // Re-map all the type index references.
442 MutableArrayRef<uint8_t> Contents =
443 NewData.drop_front(sizeof(RecordPrefix));
Reid Kleckner651db912017-07-18 00:21:25 +0000444 remapTypesInSymbolRecord(File, Contents, IndexMap, TypeRefs);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000445
Reid Kleckner3f851922017-07-06 16:39:32 +0000446 // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
447 CVSymbol NewSym(Sym.kind(), NewData);
448 if (symbolOpensScope(Sym.kind()))
449 scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(), NewSym);
450 else if (symbolEndsScope(Sym.kind()))
451 scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000452
453 // Add the symbol to the module.
Reid Kleckner3f851922017-07-06 16:39:32 +0000454 File->ModuleDBI->addSymbol(NewSym);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000455 }
456}
457
Reid Kleckner44cdb102017-06-19 17:21:45 +0000458// Allocate memory for a .debug$S section and relocate it.
459static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
460 SectionChunk *DebugChunk) {
461 uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk->getSize());
462 assert(DebugChunk->OutputSectionOff == 0 &&
463 "debug sections should not be in output sections");
464 DebugChunk->writeTo(Buffer);
465 return consumeDebugMagic(makeArrayRef(Buffer, DebugChunk->getSize()),
466 ".debug$S");
467}
468
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000469void PDBLinker::addObjFile(ObjFile *File) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000470 // Add a module descriptor for every object file. We need to put an absolute
471 // path to the object into the PDB. If this is a plain object, we make its
472 // path absolute. If it's an object in an archive, we make the archive path
473 // absolute.
474 bool InArchive = !File->ParentName.empty();
475 SmallString<128> Path = InArchive ? File->ParentName : File->getName();
476 sys::fs::make_absolute(Path);
477 sys::path::native(Path, sys::path::Style::windows);
478 StringRef Name = InArchive ? File->getName() : StringRef(Path);
Zachary Turner2897e032017-05-25 21:16:03 +0000479
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000480 File->ModuleDBI = &ExitOnErr(Builder.getDbiBuilder().addModuleInfo(Name));
481 File->ModuleDBI->setObjFileName(Path);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000482
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000483 // Before we can process symbol substreams from .debug$S, we need to process
484 // type information, file checksums, and the string table. Add type info to
485 // the PDB first, so that we can get the map from object file type and item
486 // indices to PDB type and item indices.
Reid Kleckner651db912017-07-18 00:21:25 +0000487 CVIndexMap ObjectIndexMap;
488 const CVIndexMap &IndexMap = mergeDebugT(File, ObjectIndexMap);
Zachary Turner448dea42017-07-07 18:46:14 +0000489
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000490 // Now do all live .debug$S sections.
491 for (SectionChunk *DebugChunk : File->getDebugChunks()) {
492 if (!DebugChunk->isLive() || DebugChunk->getSectionName() != ".debug$S")
493 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000494
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000495 ArrayRef<uint8_t> RelocatedDebugContents =
496 relocateDebugChunk(Alloc, DebugChunk);
497 if (RelocatedDebugContents.empty())
498 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000499
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000500 DebugSubsectionArray Subsections;
501 BinaryStreamReader Reader(RelocatedDebugContents, support::little);
502 ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
Rui Ueyama52896622017-01-12 03:09:25 +0000503
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000504 DebugStringTableSubsectionRef CVStrTab;
505 DebugChecksumsSubsectionRef Checksums;
506 for (const DebugSubsectionRecord &SS : Subsections) {
507 switch (SS.kind()) {
508 case DebugSubsectionKind::StringTable:
509 ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
510 break;
511 case DebugSubsectionKind::FileChecksums:
512 ExitOnErr(Checksums.initialize(SS.getRecordData()));
513 break;
514 case DebugSubsectionKind::Lines:
515 // We can add the relocated line table directly to the PDB without
516 // modification because the file checksum offsets will stay the same.
517 File->ModuleDBI->addDebugSubsection(SS);
518 break;
519 case DebugSubsectionKind::Symbols:
Reid Kleckner651db912017-07-18 00:21:25 +0000520 mergeSymbolRecords(Alloc, File, IndexMap, SS.getRecordData());
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000521 break;
522 default:
523 // FIXME: Process the rest of the subsections.
524 break;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000525 }
526 }
Rui Ueyama52896622017-01-12 03:09:25 +0000527
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000528 if (Checksums.valid()) {
529 // Make a new file checksum table that refers to offsets in the PDB-wide
530 // string table. Generally the string table subsection appears after the
531 // checksum table, so we have to do this after looping over all the
532 // subsections.
533 if (!CVStrTab.valid())
534 fatal(".debug$S sections must have both a string table subsection "
535 "and a checksum subsection table or neither");
536 auto NewChecksums = make_unique<DebugChecksumsSubsection>(PDBStrTab);
537 for (FileChecksumEntry &FC : Checksums) {
538 StringRef FileName = ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
539 ExitOnErr(Builder.getDbiBuilder().addModuleSourceFile(*File->ModuleDBI,
540 FileName));
541 NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
542 }
543 File->ModuleDBI->addDebugSubsection(std::move(NewChecksums));
544 }
545 }
546}
547
548// Add all object files to the PDB. Merge .debug$T sections into IpiData and
549// TpiData.
550void PDBLinker::addObjectsToPDB() {
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000551 for (ObjFile *File : Symtab->ObjFiles)
552 addObjFile(File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000553
554 Builder.getStringTableBuilder().setStrings(PDBStrTab);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000555
Reid Kleckner5d577522017-03-24 17:26:38 +0000556 // Construct TPI stream contents.
Reid Kleckner13fc4112017-04-04 00:56:34 +0000557 addTypeInfo(Builder.getTpiBuilder(), TypeTable);
Reid Kleckner5d577522017-03-24 17:26:38 +0000558
559 // Construct IPI stream contents.
Reid Kleckner13fc4112017-04-04 00:56:34 +0000560 addTypeInfo(Builder.getIpiBuilder(), IDTable);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000561
562 // Add public and symbol records stream.
563
564 // For now we don't actually write any thing useful to the publics stream, but
565 // the act of "getting" it also creates it lazily so that we write an empty
566 // stream.
567 (void)Builder.getPublicsBuilder();
Rui Ueyama52896622017-01-12 03:09:25 +0000568}
569
Zachary Turner6708e0b2017-07-10 21:01:37 +0000570static void addLinkerModuleSymbols(StringRef Path,
571 pdb::DbiModuleDescriptorBuilder &Mod,
572 BumpPtrAllocator &Allocator) {
573 codeview::SymbolSerializer Serializer(Allocator, CodeViewContainer::Pdb);
574 codeview::ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
575 codeview::Compile3Sym CS(SymbolRecordKind::Compile3Sym);
576 codeview::EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
577
578 ONS.Name = "* Linker *";
579 ONS.Signature = 0;
580
581 CS.Machine = Config->is64() ? CPUType::X64 : CPUType::Intel80386;
582 CS.Flags = CompileSym3Flags::None;
583 CS.VersionBackendBuild = 0;
584 CS.VersionBackendMajor = 0;
585 CS.VersionBackendMinor = 0;
586 CS.VersionBackendQFE = 0;
587 CS.VersionFrontendBuild = 0;
588 CS.VersionFrontendMajor = 0;
589 CS.VersionFrontendMinor = 0;
590 CS.VersionFrontendQFE = 0;
591 CS.Version = "LLVM Linker";
592 CS.setLanguage(SourceLanguage::Link);
593
594 ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
595 std::string ArgStr = llvm::join(Args, " ");
596 EBS.Fields.push_back("cwd");
597 SmallString<64> cwd;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000598 sys::fs::current_path(cwd);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000599 EBS.Fields.push_back(cwd);
600 EBS.Fields.push_back("exe");
Zachary Turner77f23b92017-07-10 21:09:11 +0000601 EBS.Fields.push_back(Config->Argv[0]);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000602 EBS.Fields.push_back("pdb");
603 EBS.Fields.push_back(Path);
604 EBS.Fields.push_back("cmd");
605 EBS.Fields.push_back(ArgStr);
606 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
607 ONS, Allocator, CodeViewContainer::Pdb));
608 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
609 CS, Allocator, CodeViewContainer::Pdb));
610 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
611 EBS, Allocator, CodeViewContainer::Pdb));
612}
613
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000614// Creates a PDB file.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000615void coff::createPDB(SymbolTable *Symtab, ArrayRef<uint8_t> SectionTable,
Saleem Abdulrasooldf8a13b2017-01-04 17:56:54 +0000616 const llvm::codeview::DebugInfo *DI) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000617 PDBLinker PDB(Symtab);
618 PDB.initialize(DI);
619 PDB.addObjectsToPDB();
620 PDB.addSections(SectionTable);
621 PDB.commit();
622}
623
624void PDBLinker::initialize(const llvm::codeview::DebugInfo *DI) {
Rui Ueyama12979542016-09-30 20:53:45 +0000625 ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
Rui Ueyama7f382992016-09-15 18:55:18 +0000626
Rui Ueyama8d3fb5d2016-10-05 22:08:58 +0000627 // Create streams in MSF for predefined streams, namely
628 // PDB, TPI, DBI and IPI.
629 for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
630 ExitOnErr(Builder.getMsfBuilder().addStream(0));
Rui Ueyama7f382992016-09-15 18:55:18 +0000631
Rui Ueyamabb542b32016-09-16 22:51:17 +0000632 // Add an Info stream.
633 auto &InfoBuilder = Builder.getInfoBuilder();
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000634 InfoBuilder.setAge(DI ? DI->PDB70.Age : 0);
635
Reid Kleckner67653ee2017-07-17 23:59:44 +0000636 GUID uuid{};
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000637 if (DI)
638 memcpy(&uuid, &DI->PDB70.Signature, sizeof(uuid));
639 InfoBuilder.setGuid(uuid);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000640 InfoBuilder.setSignature(time(nullptr));
Rui Ueyamabb542b32016-09-16 22:51:17 +0000641 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
Rui Ueyama7f382992016-09-15 18:55:18 +0000642
Zachary Turner6c4bfba2017-07-07 05:04:36 +0000643 // Add an empty DBI stream.
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000644 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Zachary Turnerc1e93e52017-07-07 18:45:56 +0000645 DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000646 ExitOnErr(DbiBuilder.addDbgStream(pdb::DbgHeaderType::NewFPO, {}));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000647}
Rui Ueyama1343fac2016-10-06 22:52:01 +0000648
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000649void PDBLinker::addSections(ArrayRef<uint8_t> SectionTable) {
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000650 // Add Section Contributions.
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000651 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000652 addSectionContribs(Symtab, DbiBuilder);
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000653
Rui Ueyama20df4ec2016-10-31 21:09:21 +0000654 // Add Section Map stream.
655 ArrayRef<object::coff_section> Sections = {
Rui Ueyama6294a242016-11-04 17:41:29 +0000656 (const object::coff_section *)SectionTable.data(),
Rui Ueyama20df4ec2016-10-31 21:09:21 +0000657 SectionTable.size() / sizeof(object::coff_section)};
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000658 SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
Rui Ueyama20df4ec2016-10-31 21:09:21 +0000659 DbiBuilder.setSectionMap(SectionMap);
660
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000661 // It's not entirely clear what this is, but the * Linker * module uses it.
662 NativePath = Config->PDBPath;
663 sys::fs::make_absolute(NativePath);
664 sys::path::native(NativePath, sys::path::Style::windows);
665 uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
Zachary Turner6c4bfba2017-07-07 05:04:36 +0000666 auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
667 LinkerModule.setPdbFilePathNI(PdbFilePathNI);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000668 addLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
Rui Ueyamac91f7162016-11-16 01:10:46 +0000669
Rui Ueyama9f66f822016-10-11 19:45:07 +0000670 // Add COFF section header stream.
671 ExitOnErr(
672 DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000673}
Rui Ueyama9f66f822016-10-11 19:45:07 +0000674
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000675void PDBLinker::commit() {
Rui Ueyama3e9d6bb2016-09-26 23:53:55 +0000676 // Write to a file.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000677 ExitOnErr(Builder.commit(Config->PDBPath));
Rui Ueyamae7378242015-12-04 23:11:05 +0000678}