blob: f36e700495ac674d8067ccc405176eece679955d [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"
Peter Collingbourne75257bc2017-10-20 19:48:26 +000013#include "Driver.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"
Bob Haarmanb8a59c82017-10-25 22:28:38 +000017#include "lld/Common/ErrorHandler.h"
Saleem Abdulrasooldf8a13b2017-01-04 17:56:54 +000018#include "llvm/DebugInfo/CodeView/CVDebugRecord.h"
Reid Kleckner44cdb102017-06-19 17:21:45 +000019#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
Zachary Turner0d07a8e2017-12-14 18:07:04 +000020#include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000021#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
Zachary Turnerca6dbf12017-11-30 18:39:50 +000022#include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
Zachary Turneree9906d2017-08-11 19:00:03 +000023#include "llvm/DebugInfo/CodeView/RecordName.h"
Zachary Turner59e3ae82017-08-08 18:34:44 +000024#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
Zachary Turner6708e0b2017-07-10 21:01:37 +000025#include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
Reid Kleckner651db912017-07-18 00:21:25 +000026#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000027#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerd0e6e242017-06-21 17:25:56 +000028#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
Rui Ueyama52896622017-01-12 03:09:25 +000029#include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
Rui Ueyamab28c6d42016-09-16 04:32:33 +000030#include "llvm/DebugInfo/MSF/MSFBuilder.h"
Rui Ueyama7f382992016-09-15 18:55:18 +000031#include "llvm/DebugInfo/MSF/MSFCommon.h"
Reid Kleckner651db912017-07-18 00:21:25 +000032#include "llvm/DebugInfo/PDB/GenericError.h"
Zachary Turner6708e0b2017-07-10 21:01:37 +000033#include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000034#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
35#include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
Zachary Turner946204c2017-08-09 04:23:25 +000036#include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000037#include "llvm/DebugInfo/PDB/Native/InfoStream.h"
38#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
Reid Kleckner651db912017-07-18 00:21:25 +000039#include "llvm/DebugInfo/PDB/Native/NativeSession.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000040#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
41#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
Rafael Espindolaa0f30da2017-05-02 20:19:42 +000042#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
Reid Klecknerd91ca762017-07-19 17:26:07 +000043#include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000044#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
45#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
Reid Kleckner651db912017-07-18 00:21:25 +000046#include "llvm/DebugInfo/PDB/PDB.h"
Rui Ueyama20df4ec2016-10-31 21:09:21 +000047#include "llvm/Object/COFF.h"
Zachary Turnerd9dc2822017-03-02 20:52:51 +000048#include "llvm/Support/BinaryByteStream.h"
Rui Ueyama1763c0d2015-12-08 18:39:55 +000049#include "llvm/Support/Endian.h"
Zachary Turner60478582018-01-05 19:12:40 +000050#include "llvm/Support/FormatVariadic.h"
Zachary Turner676386ff2017-08-07 20:23:45 +000051#include "llvm/Support/JamCRC.h"
Zachary Turner7b327d02017-02-16 23:35:45 +000052#include "llvm/Support/Path.h"
Rui Ueyamabe939b32016-11-21 17:22:35 +000053#include "llvm/Support/ScopedPrinter.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000054#include <memory>
55
Rui Ueyama1d99ab32016-09-15 22:24:51 +000056using namespace lld;
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000057using namespace lld::coff;
Rui Ueyamae7378242015-12-04 23:11:05 +000058using namespace llvm;
Rui Ueyamabe939b32016-11-21 17:22:35 +000059using namespace llvm::codeview;
Rui Ueyamae7378242015-12-04 23:11:05 +000060
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000061using llvm::object::coff_section;
62
Rui Ueyamab28c6d42016-09-16 04:32:33 +000063static ExitOnError ExitOnErr;
64
Reid Kleckner0faf6d72017-07-14 00:14:58 +000065namespace {
Reid Kleckner651db912017-07-18 00:21:25 +000066/// Map from type index and item index in a type server PDB to the
67/// corresponding index in the destination PDB.
68struct CVIndexMap {
69 SmallVector<TypeIndex, 0> TPIMap;
70 SmallVector<TypeIndex, 0> IPIMap;
71 bool IsTypeServerMap = false;
72};
73
Reid Kleckner0faf6d72017-07-14 00:14:58 +000074class PDBLinker {
75public:
76 PDBLinker(SymbolTable *Symtab)
Sam Cleggea244bf2017-12-14 21:09:31 +000077 : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
78 IDTable(Alloc), GlobalTypeTable(Alloc), GlobalIDTable(Alloc) {}
Reid Kleckner0faf6d72017-07-14 00:14:58 +000079
80 /// Emit the basic PDB structure: initial streams, headers, etc.
Zachary Turner024323c2017-08-15 21:31:41 +000081 void initialize(const llvm::codeview::DebugInfo &BuildId);
Reid Kleckner0faf6d72017-07-14 00:14:58 +000082
83 /// Link CodeView from each object file in the symbol table into the PDB.
84 void addObjectsToPDB();
85
86 /// Link CodeView from a single object file into the PDB.
Rui Ueyamae1b48e02017-07-26 23:05:24 +000087 void addObjFile(ObjFile *File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +000088
Reid Kleckner651db912017-07-18 00:21:25 +000089 /// Produce a mapping from the type and item indices used in the object
90 /// file to those in the destination PDB.
91 ///
92 /// If the object file uses a type server PDB (compiled with /Zi), merge TPI
93 /// and IPI from the type server PDB and return a map for it. Each unique type
94 /// server PDB is merged at most once, so this may return an existing index
95 /// mapping.
96 ///
97 /// If the object does not use a type server PDB (compiled with /Z7), we merge
98 /// all the type and item records from the .debug$S stream and fill in the
99 /// caller-provided ObjectIndexMap.
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000100 const CVIndexMap &mergeDebugT(ObjFile *File, CVIndexMap &ObjectIndexMap);
Reid Kleckner651db912017-07-18 00:21:25 +0000101
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000102 const CVIndexMap &maybeMergeTypeServerPDB(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000103 TypeServer2Record &TS);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000104
105 /// Add the section map and section contributions to the PDB.
Reid Kleckner175af4b2017-08-03 21:15:09 +0000106 void addSections(ArrayRef<OutputSection *> OutputSections,
107 ArrayRef<uint8_t> SectionTable);
108
109 void addSectionContrib(pdb::DbiModuleDescriptorBuilder &LinkerModule,
110 OutputSection *OS, Chunk *C);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000111
112 /// Write the PDB to disk.
113 void commit();
114
115private:
116 BumpPtrAllocator Alloc;
117
118 SymbolTable *Symtab;
119
120 pdb::PDBFileBuilder Builder;
121
122 /// Type records that will go into the PDB TPI stream.
Zachary Turnerca6dbf12017-11-30 18:39:50 +0000123 MergingTypeTableBuilder TypeTable;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000124
125 /// Item records that will go into the PDB IPI stream.
Zachary Turnerca6dbf12017-11-30 18:39:50 +0000126 MergingTypeTableBuilder IDTable;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000127
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000128 /// Type records that will go into the PDB TPI stream (for /DEBUG:GHASH)
129 GlobalTypeTableBuilder GlobalTypeTable;
130
131 /// Item records that will go into the PDB IPI stream (for /DEBUG:GHASH)
132 GlobalTypeTableBuilder GlobalIDTable;
133
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000134 /// PDBs use a single global string table for filenames in the file checksum
135 /// table.
136 DebugStringTableSubsection PDBStrTab;
137
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000138 llvm::SmallString<128> NativePath;
139
140 std::vector<pdb::SecMapEntry> SectionMap;
Reid Kleckner651db912017-07-18 00:21:25 +0000141
142 /// Type index mappings of type server PDBs that we've loaded so far.
143 std::map<GUID, CVIndexMap> TypeServerIndexMappings;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000144};
145}
146
Sam Clegg0fb6faa2017-12-08 01:09:21 +0000147static SectionChunk *findByName(ArrayRef<SectionChunk *> Sections,
Rui Ueyamabe939b32016-11-21 17:22:35 +0000148 StringRef Name) {
149 for (SectionChunk *C : Sections)
150 if (C->getSectionName() == Name)
151 return C;
152 return nullptr;
153}
154
Reid Kleckner44cdb102017-06-19 17:21:45 +0000155static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
156 StringRef SecName) {
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000157 // First 4 bytes are section magic.
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000158 if (Data.size() < 4)
Rui Ueyama52896622017-01-12 03:09:25 +0000159 fatal(SecName + " too short");
Reid Kleckner44cdb102017-06-19 17:21:45 +0000160 if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
Rui Ueyama52896622017-01-12 03:09:25 +0000161 fatal(SecName + " has an invalid magic");
Rui Ueyama26186c72016-12-09 04:46:54 +0000162 return Data.slice(4);
163}
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000164
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000165static ArrayRef<uint8_t> getDebugSection(ObjFile *File, StringRef SecName) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000166 if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
167 return consumeDebugMagic(Sec->getContents(), SecName);
168 return {};
169}
170
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000171// A COFF .debug$H section is currently a clang extension. This function checks
172// if a .debug$H section is in a format that we expect / understand, so that we
173// can ignore any sections which are coincidentally also named .debug$H but do
174// not contain a format we recognize.
175static bool canUseDebugH(ArrayRef<uint8_t> DebugH) {
176 if (DebugH.size() < sizeof(object::debug_h_header))
177 return false;
178 auto *Header =
179 reinterpret_cast<const object::debug_h_header *>(DebugH.data());
180 DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
181 return Header->Magic == COFF::DEBUG_HASHES_SECTION_MAGIC &&
182 Header->Version == 0 &&
183 Header->HashAlgorithm == uint16_t(GlobalTypeHashAlg::SHA1) &&
184 (DebugH.size() % 20 == 0);
185}
186
187static Optional<ArrayRef<uint8_t>> getDebugH(ObjFile *File) {
188 SectionChunk *Sec = findByName(File->getDebugChunks(), ".debug$H");
189 if (!Sec)
190 return llvm::None;
191 ArrayRef<uint8_t> Contents = Sec->getContents();
192 if (!canUseDebugH(Contents))
193 return None;
194 return Contents;
195}
196
197static ArrayRef<GloballyHashedType>
198getHashesFromDebugH(ArrayRef<uint8_t> DebugH) {
199 assert(canUseDebugH(DebugH));
200
201 DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
202 uint32_t Count = DebugH.size() / sizeof(GloballyHashedType);
203 return {reinterpret_cast<const GloballyHashedType *>(DebugH.data()), Count};
204}
205
Reid Kleckner5d577522017-03-24 17:26:38 +0000206static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
Zachary Turner3e3936d2017-11-29 19:35:21 +0000207 TypeCollection &TypeTable) {
Reid Kleckner5d577522017-03-24 17:26:38 +0000208 // Start the TPI or IPI stream header.
209 TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
Rui Ueyama52896622017-01-12 03:09:25 +0000210
Reid Klecknerd91ca762017-07-19 17:26:07 +0000211 // Flatten the in memory type table and hash each type.
Zachary Turner3e3936d2017-11-29 19:35:21 +0000212 TypeTable.ForEachRecord([&](TypeIndex TI, const CVType &Type) {
Reid Klecknerd91ca762017-07-19 17:26:07 +0000213 auto Hash = pdb::hashTypeRecord(Type);
214 if (auto E = Hash.takeError())
215 fatal("type hashing error");
Zachary Turner3e3936d2017-11-29 19:35:21 +0000216 TpiBuilder.addTypeRecord(Type.RecordData, *Hash);
Reid Kleckner5d577522017-03-24 17:26:38 +0000217 });
Reid Kleckner5d577522017-03-24 17:26:38 +0000218}
219
Reid Kleckner651db912017-07-18 00:21:25 +0000220static Optional<TypeServer2Record>
221maybeReadTypeServerRecord(CVTypeArray &Types) {
222 auto I = Types.begin();
223 if (I == Types.end())
224 return None;
225 const CVType &Type = *I;
226 if (Type.kind() != LF_TYPESERVER2)
227 return None;
228 TypeServer2Record TS;
229 if (auto EC = TypeDeserializer::deserializeAs(const_cast<CVType &>(Type), TS))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000230 fatal("error reading type server record: " + toString(std::move(EC)));
Reid Kleckner651db912017-07-18 00:21:25 +0000231 return std::move(TS);
232}
233
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000234const CVIndexMap &PDBLinker::mergeDebugT(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000235 CVIndexMap &ObjectIndexMap) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000236 ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
237 if (Data.empty())
Reid Kleckner651db912017-07-18 00:21:25 +0000238 return ObjectIndexMap;
Reid Kleckner6597c282017-07-13 20:12:23 +0000239
Reid Kleckner44cdb102017-06-19 17:21:45 +0000240 BinaryByteStream Stream(Data, support::little);
241 CVTypeArray Types;
242 BinaryStreamReader Reader(Stream);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000243 if (auto EC = Reader.readArray(Types, Reader.getLength()))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000244 fatal("Reader::readArray failed: " + toString(std::move(EC)));
Reid Kleckner651db912017-07-18 00:21:25 +0000245
246 // Look through type servers. If we've already seen this type server, don't
247 // merge any type information.
248 if (Optional<TypeServer2Record> TS = maybeReadTypeServerRecord(Types))
249 return maybeMergeTypeServerPDB(File, *TS);
250
251 // This is a /Z7 object. Fill in the temporary, caller-provided
252 // ObjectIndexMap.
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000253 if (Config->DebugGHashes) {
254 ArrayRef<GloballyHashedType> Hashes;
255 std::vector<GloballyHashedType> OwnedHashes;
256 if (Optional<ArrayRef<uint8_t>> DebugH = getDebugH(File))
257 Hashes = getHashesFromDebugH(*DebugH);
258 else {
259 OwnedHashes = GloballyHashedType::hashTypes(Types);
260 Hashes = OwnedHashes;
261 }
262
263 if (auto Err = mergeTypeAndIdRecords(GlobalIDTable, GlobalTypeTable,
264 ObjectIndexMap.TPIMap, Types, Hashes))
265 fatal("codeview::mergeTypeAndIdRecords failed: " +
266 toString(std::move(Err)));
267 } else {
268 if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable,
269 ObjectIndexMap.TPIMap, Types))
270 fatal("codeview::mergeTypeAndIdRecords failed: " +
271 toString(std::move(Err)));
272 }
Reid Kleckner651db912017-07-18 00:21:25 +0000273 return ObjectIndexMap;
274}
275
276static Expected<std::unique_ptr<pdb::NativeSession>>
277tryToLoadPDB(const GUID &GuidFromObj, StringRef TSPath) {
Peter Collingbourne75257bc2017-10-20 19:48:26 +0000278 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(
279 TSPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
280 if (!MBOrErr)
281 return errorCodeToError(MBOrErr.getError());
282
Reid Kleckner651db912017-07-18 00:21:25 +0000283 std::unique_ptr<pdb::IPDBSession> ThisSession;
Peter Collingbourne75257bc2017-10-20 19:48:26 +0000284 if (auto EC = pdb::NativeSession::createFromPdb(
285 MemoryBuffer::getMemBuffer(Driver->takeBuffer(std::move(*MBOrErr)),
286 /*RequiresNullTerminator=*/false),
287 ThisSession))
Reid Kleckner651db912017-07-18 00:21:25 +0000288 return std::move(EC);
289
290 std::unique_ptr<pdb::NativeSession> NS(
291 static_cast<pdb::NativeSession *>(ThisSession.release()));
292 pdb::PDBFile &File = NS->getPDBFile();
293 auto ExpectedInfo = File.getPDBInfoStream();
294 // All PDB Files should have an Info stream.
295 if (!ExpectedInfo)
296 return ExpectedInfo.takeError();
297
298 // Just because a file with a matching name was found and it was an actual
299 // PDB file doesn't mean it matches. For it to match the InfoStream's GUID
300 // must match the GUID specified in the TypeServer2 record.
301 if (ExpectedInfo->getGuid() != GuidFromObj)
302 return make_error<pdb::GenericError>(
303 pdb::generic_error_code::type_server_not_found, TSPath);
304
305 return std::move(NS);
306}
307
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000308const CVIndexMap &PDBLinker::maybeMergeTypeServerPDB(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000309 TypeServer2Record &TS) {
310 // First, check if we already loaded a PDB with this GUID. Return the type
311 // index mapping if we have it.
312 auto Insertion = TypeServerIndexMappings.insert({TS.getGuid(), CVIndexMap()});
313 CVIndexMap &IndexMap = Insertion.first->second;
314 if (!Insertion.second)
315 return IndexMap;
316
317 // Mark this map as a type server map.
318 IndexMap.IsTypeServerMap = true;
319
320 // Check for a PDB at:
321 // 1. The given file path
322 // 2. Next to the object file or archive file
323 auto ExpectedSession = tryToLoadPDB(TS.getGuid(), TS.getName());
324 if (!ExpectedSession) {
325 consumeError(ExpectedSession.takeError());
326 StringRef LocalPath =
327 !File->ParentName.empty() ? File->ParentName : File->getName();
328 SmallString<128> Path = sys::path::parent_path(LocalPath);
Reid Klecknerf8522d82017-07-18 00:33:53 +0000329 sys::path::append(
330 Path, sys::path::filename(TS.getName(), sys::path::Style::windows));
Reid Kleckner651db912017-07-18 00:21:25 +0000331 ExpectedSession = tryToLoadPDB(TS.getGuid(), Path);
332 }
333 if (auto E = ExpectedSession.takeError())
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000334 fatal("Type server PDB was not found: " + toString(std::move(E)));
Reid Kleckner651db912017-07-18 00:21:25 +0000335
Reid Kleckner651db912017-07-18 00:21:25 +0000336 auto ExpectedTpi = (*ExpectedSession)->getPDBFile().getPDBTpiStream();
337 if (auto E = ExpectedTpi.takeError())
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000338 fatal("Type server does not have TPI stream: " + toString(std::move(E)));
Reid Kleckner651db912017-07-18 00:21:25 +0000339 auto ExpectedIpi = (*ExpectedSession)->getPDBFile().getPDBIpiStream();
340 if (auto E = ExpectedIpi.takeError())
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000341 fatal("Type server does not have TPI stream: " + toString(std::move(E)));
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000342
343 if (Config->DebugGHashes) {
344 // PDBs do not actually store global hashes, so when merging a type server
345 // PDB we have to synthesize global hashes. To do this, we first synthesize
346 // global hashes for the TPI stream, since it is independent, then we
347 // synthesize hashes for the IPI stream, using the hashes for the TPI stream
348 // as inputs.
349 auto TpiHashes = GloballyHashedType::hashTypes(ExpectedTpi->typeArray());
350 auto IpiHashes =
351 GloballyHashedType::hashIds(ExpectedIpi->typeArray(), TpiHashes);
352
353 // Merge TPI first, because the IPI stream will reference type indices.
354 if (auto Err = mergeTypeRecords(GlobalTypeTable, IndexMap.TPIMap,
355 ExpectedTpi->typeArray(), TpiHashes))
356 fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
357
358 // Merge IPI.
359 if (auto Err =
360 mergeIdRecords(GlobalIDTable, IndexMap.TPIMap, IndexMap.IPIMap,
361 ExpectedIpi->typeArray(), IpiHashes))
362 fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
363 } else {
364 // Merge TPI first, because the IPI stream will reference type indices.
365 if (auto Err = mergeTypeRecords(TypeTable, IndexMap.TPIMap,
366 ExpectedTpi->typeArray()))
367 fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
368
369 // Merge IPI.
370 if (auto Err = mergeIdRecords(IDTable, IndexMap.TPIMap, IndexMap.IPIMap,
371 ExpectedIpi->typeArray()))
372 fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
373 }
Reid Kleckner651db912017-07-18 00:21:25 +0000374
375 return IndexMap;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000376}
377
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000378static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
379 if (TI.isSimple())
380 return true;
381 if (TI.toArrayIndex() >= TypeIndexMap.size())
382 return false;
383 TI = TypeIndexMap[TI.toArrayIndex()];
384 return true;
385}
386
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000387static void remapTypesInSymbolRecord(ObjFile *File, SymbolKind SymKind,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000388 MutableArrayRef<uint8_t> Contents,
Reid Kleckner651db912017-07-18 00:21:25 +0000389 const CVIndexMap &IndexMap,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000390 ArrayRef<TiReference> TypeRefs) {
391 for (const TiReference &Ref : TypeRefs) {
392 unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000393 if (Contents.size() < Ref.Offset + ByteSize)
394 fatal("symbol record too short");
Reid Kleckner651db912017-07-18 00:21:25 +0000395
396 // This can be an item index or a type index. Choose the appropriate map.
397 ArrayRef<TypeIndex> TypeOrItemMap = IndexMap.TPIMap;
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000398 bool IsItemIndex = Ref.Kind == TiRefKind::IndexRef;
399 if (IsItemIndex && IndexMap.IsTypeServerMap)
Reid Kleckner651db912017-07-18 00:21:25 +0000400 TypeOrItemMap = IndexMap.IPIMap;
401
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000402 MutableArrayRef<TypeIndex> TIs(
403 reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000404 for (TypeIndex &TI : TIs) {
Reid Kleckner651db912017-07-18 00:21:25 +0000405 if (!remapTypeIndex(TI, TypeOrItemMap)) {
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000406 log("ignoring symbol record of kind 0x" + utohexstr(SymKind) + " in " +
407 File->getName() + " with bad " + (IsItemIndex ? "item" : "type") +
408 " index 0x" + utohexstr(TI.getIndex()));
Reid Kleckner5d82f682017-10-23 22:44:51 +0000409 TI = TypeIndex(SimpleTypeKind::NotTranslated);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000410 continue;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000411 }
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000412 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000413 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000414}
415
Zachary Turner60478582018-01-05 19:12:40 +0000416static void
417recordStringTableReferenceAtOffset(MutableArrayRef<uint8_t> Contents,
418 uint32_t Offset,
419 std::vector<ulittle32_t *> &StrTableRefs) {
420 Contents =
421 Contents.drop_front(Offset).take_front(sizeof(support::ulittle32_t));
422 ulittle32_t *Index = reinterpret_cast<ulittle32_t *>(Contents.data());
423 StrTableRefs.push_back(Index);
424}
425
426static void
427recordStringTableReferences(SymbolKind Kind, MutableArrayRef<uint8_t> Contents,
428 std::vector<ulittle32_t *> &StrTableRefs) {
429 // For now we only handle S_FILESTATIC, but we may need the same logic for
430 // S_DEFRANGE and S_DEFRANGE_SUBFIELD. However, I cannot seem to generate any
431 // PDBs that contain these types of records, so because of the uncertainty
432 // they are omitted here until we can prove that it's necessary.
433 switch (Kind) {
434 case SymbolKind::S_FILESTATIC:
435 // FileStaticSym::ModFileOffset
436 recordStringTableReferenceAtOffset(Contents, 4, StrTableRefs);
437 break;
438 case SymbolKind::S_DEFRANGE:
439 case SymbolKind::S_DEFRANGE_SUBFIELD:
440 log("Not fixing up string table reference in S_DEFRANGE / "
441 "S_DEFRANGE_SUBFIELD record");
442 break;
Zachary Turner9e52e502018-01-05 19:28:39 +0000443 default:
444 break;
Zachary Turner60478582018-01-05 19:12:40 +0000445 }
446}
447
Zachary Turner59e3ae82017-08-08 18:34:44 +0000448static SymbolKind symbolKind(ArrayRef<uint8_t> RecordData) {
449 const RecordPrefix *Prefix =
450 reinterpret_cast<const RecordPrefix *>(RecordData.data());
451 return static_cast<SymbolKind>(uint16_t(Prefix->RecordKind));
452}
453
454/// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
455static void translateIdSymbols(MutableArrayRef<uint8_t> &RecordData,
Zachary Turner3e3936d2017-11-29 19:35:21 +0000456 TypeCollection &IDTable) {
Zachary Turner59e3ae82017-08-08 18:34:44 +0000457 RecordPrefix *Prefix = reinterpret_cast<RecordPrefix *>(RecordData.data());
458
459 SymbolKind Kind = symbolKind(RecordData);
460
461 if (Kind == SymbolKind::S_PROC_ID_END) {
462 Prefix->RecordKind = SymbolKind::S_END;
463 return;
464 }
465
466 // In an object file, GPROC32_ID has an embedded reference which refers to the
467 // single object file type index namespace. This has already been translated
468 // to the PDB file's ID stream index space, but we need to convert this to a
469 // symbol that refers to the type stream index space. So we remap again from
470 // ID index space to type index space.
471 if (Kind == SymbolKind::S_GPROC32_ID || Kind == SymbolKind::S_LPROC32_ID) {
472 SmallVector<TiReference, 1> Refs;
473 auto Content = RecordData.drop_front(sizeof(RecordPrefix));
474 CVSymbol Sym(Kind, RecordData);
475 discoverTypeIndicesInSymbol(Sym, Refs);
476 assert(Refs.size() == 1);
477 assert(Refs.front().Count == 1);
478
479 TypeIndex *TI =
480 reinterpret_cast<TypeIndex *>(Content.data() + Refs[0].Offset);
481 // `TI` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
482 // the IPI stream, whose `FunctionType` member refers to the TPI stream.
483 // Note that LF_FUNC_ID and LF_MEMFUNC_ID have the same record layout, and
484 // in both cases we just need the second type index.
485 if (!TI->isSimple() && !TI->isNoneType()) {
Zachary Turner3e3936d2017-11-29 19:35:21 +0000486 CVType FuncIdData = IDTable.getType(*TI);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000487 SmallVector<TypeIndex, 2> Indices;
488 discoverTypeIndices(FuncIdData, Indices);
489 assert(Indices.size() == 2);
490 *TI = Indices[1];
491 }
492
493 Kind = (Kind == SymbolKind::S_GPROC32_ID) ? SymbolKind::S_GPROC32
494 : SymbolKind::S_LPROC32;
495 Prefix->RecordKind = uint16_t(Kind);
496 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000497}
498
499/// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
500/// The object file may not be aligned.
501static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
502 BumpPtrAllocator &Alloc) {
503 size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
504 assert(Size >= 4 && "record too short");
505 assert(Size <= MaxRecordLength && "record too long");
506 void *Mem = Alloc.Allocate(Size, 4);
507
508 // Copy the symbol record and zero out any padding bytes.
509 MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
510 memcpy(NewData.data(), Sym.data().data(), Sym.length());
511 memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
512
513 // Update the record prefix length. It should point to the beginning of the
Zachary Turner59e3ae82017-08-08 18:34:44 +0000514 // next record.
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000515 auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000516 Prefix->RecordLen = Size - 2;
517 return NewData;
518}
519
Reid Kleckner3f851922017-07-06 16:39:32 +0000520/// Return true if this symbol opens a scope. This implies that the symbol has
521/// "parent" and "end" fields, which contain the offset of the S_END or
522/// S_INLINESITE_END record.
523static bool symbolOpensScope(SymbolKind Kind) {
524 switch (Kind) {
525 case SymbolKind::S_GPROC32:
526 case SymbolKind::S_LPROC32:
527 case SymbolKind::S_LPROC32_ID:
528 case SymbolKind::S_GPROC32_ID:
529 case SymbolKind::S_BLOCK32:
530 case SymbolKind::S_SEPCODE:
531 case SymbolKind::S_THUNK32:
532 case SymbolKind::S_INLINESITE:
533 case SymbolKind::S_INLINESITE2:
534 return true;
535 default:
536 break;
537 }
538 return false;
539}
540
541static bool symbolEndsScope(SymbolKind Kind) {
542 switch (Kind) {
543 case SymbolKind::S_END:
544 case SymbolKind::S_PROC_ID_END:
545 case SymbolKind::S_INLINESITE_END:
546 return true;
547 default:
548 break;
549 }
550 return false;
551}
552
553struct ScopeRecord {
554 ulittle32_t PtrParent;
555 ulittle32_t PtrEnd;
556};
557
558struct SymbolScope {
559 ScopeRecord *OpeningRecord;
560 uint32_t ScopeOffset;
561};
562
563static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
564 uint32_t CurOffset, CVSymbol &Sym) {
565 assert(symbolOpensScope(Sym.kind()));
566 SymbolScope S;
567 S.ScopeOffset = CurOffset;
568 S.OpeningRecord = const_cast<ScopeRecord *>(
569 reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
570 S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
571 Stack.push_back(S);
572}
573
574static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000575 uint32_t CurOffset, ObjFile *File) {
Reid Kleckner3f851922017-07-06 16:39:32 +0000576 if (Stack.empty()) {
577 warn("symbol scopes are not balanced in " + File->getName());
578 return;
579 }
580 SymbolScope S = Stack.pop_back_val();
581 S.OpeningRecord->PtrEnd = CurOffset;
582}
583
Zachary Turneree9906d2017-08-11 19:00:03 +0000584static bool symbolGoesInModuleStream(const CVSymbol &Sym) {
585 switch (Sym.kind()) {
586 case SymbolKind::S_GDATA32:
587 case SymbolKind::S_CONSTANT:
588 case SymbolKind::S_UDT:
589 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
590 // since they are synthesized by the linker in response to S_GPROC32 and
591 // S_LPROC32, but if we do see them, don't put them in the module stream I
592 // guess.
593 case SymbolKind::S_PROCREF:
594 case SymbolKind::S_LPROCREF:
595 return false;
596 // S_GDATA32 does not go in the module stream, but S_LDATA32 does.
597 case SymbolKind::S_LDATA32:
598 default:
599 return true;
600 }
601}
602
603static bool symbolGoesInGlobalsStream(const CVSymbol &Sym) {
604 switch (Sym.kind()) {
605 case SymbolKind::S_CONSTANT:
Zachary Turneree9906d2017-08-11 19:00:03 +0000606 case SymbolKind::S_GDATA32:
607 // S_LDATA32 goes in both the module stream and the globals stream.
608 case SymbolKind::S_LDATA32:
609 case SymbolKind::S_GPROC32:
610 case SymbolKind::S_LPROC32:
611 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
612 // since they are synthesized by the linker in response to S_GPROC32 and
613 // S_LPROC32, but if we do see them, copy them straight through.
614 case SymbolKind::S_PROCREF:
615 case SymbolKind::S_LPROCREF:
616 return true;
Zachary Turner302dc8b2017-08-14 18:44:58 +0000617 // FIXME: For now, we drop all S_UDT symbols (i.e. they don't go in the
618 // globals stream or the modules stream). These have special handling which
619 // needs more investigation before we can get right, but by putting them all
620 // into the globals stream WinDbg fails to display local variables of class
621 // types saying that it cannot find the type Foo *. So as a stopgap just to
622 // keep things working, we drop them.
623 case SymbolKind::S_UDT:
Zachary Turneree9906d2017-08-11 19:00:03 +0000624 default:
625 return false;
626 }
627}
628
629static void addGlobalSymbol(pdb::GSIStreamBuilder &Builder, ObjFile &File,
630 const CVSymbol &Sym) {
631 switch (Sym.kind()) {
632 case SymbolKind::S_CONSTANT:
633 case SymbolKind::S_UDT:
634 case SymbolKind::S_GDATA32:
635 case SymbolKind::S_LDATA32:
636 case SymbolKind::S_PROCREF:
637 case SymbolKind::S_LPROCREF:
638 Builder.addGlobalSymbol(Sym);
639 break;
640 case SymbolKind::S_GPROC32:
641 case SymbolKind::S_LPROC32: {
642 SymbolRecordKind K = SymbolRecordKind::ProcRefSym;
643 if (Sym.kind() == SymbolKind::S_LPROC32)
644 K = SymbolRecordKind::LocalProcRef;
645 ProcRefSym PS(K);
646 PS.Module = static_cast<uint16_t>(File.ModuleDBI->getModuleIndex());
647 // For some reason, MSVC seems to add one to this value.
648 ++PS.Module;
649 PS.Name = getSymbolName(Sym);
650 PS.SumName = 0;
651 PS.SymOffset = File.ModuleDBI->getNextSymbolOffset();
652 Builder.addGlobalSymbol(PS);
653 break;
654 }
655 default:
656 llvm_unreachable("Invalid symbol kind!");
657 }
658}
659
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000660static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjFile *File,
Zachary Turneree9906d2017-08-11 19:00:03 +0000661 pdb::GSIStreamBuilder &GsiBuilder,
Reid Kleckner651db912017-07-18 00:21:25 +0000662 const CVIndexMap &IndexMap,
Zachary Turner3e3936d2017-11-29 19:35:21 +0000663 TypeCollection &IDTable,
Zachary Turner60478582018-01-05 19:12:40 +0000664 std::vector<ulittle32_t *> &StringTableRefs,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000665 BinaryStreamRef SymData) {
666 // FIXME: Improve error recovery by warning and skipping records when
667 // possible.
668 CVSymbolArray Syms;
669 BinaryStreamReader Reader(SymData);
670 ExitOnErr(Reader.readArray(Syms, Reader.getLength()));
Reid Kleckner3f851922017-07-06 16:39:32 +0000671 SmallVector<SymbolScope, 4> Scopes;
Zachary Turner59e3ae82017-08-08 18:34:44 +0000672 for (CVSymbol Sym : Syms) {
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000673 // Discover type index references in the record. Skip it if we don't know
674 // where they are.
675 SmallVector<TiReference, 32> TypeRefs;
Zachary Turner59e3ae82017-08-08 18:34:44 +0000676 if (!discoverTypeIndicesInSymbol(Sym, TypeRefs)) {
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000677 log("ignoring unknown symbol record with kind 0x" + utohexstr(Sym.kind()));
678 continue;
679 }
680
681 // Copy the symbol record so we can mutate it.
682 MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
683
684 // Re-map all the type index references.
685 MutableArrayRef<uint8_t> Contents =
686 NewData.drop_front(sizeof(RecordPrefix));
Zachary Turner3e3936d2017-11-29 19:35:21 +0000687 remapTypesInSymbolRecord(File, Sym.kind(), Contents, IndexMap, TypeRefs);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000688
689 // An object file may have S_xxx_ID symbols, but these get converted to
690 // "real" symbols in a PDB.
691 translateIdSymbols(NewData, IDTable);
692
Zachary Turner60478582018-01-05 19:12:40 +0000693 // If this record refers to an offset in the object file's string table,
694 // add that item to the global PDB string table and re-write the index.
695 recordStringTableReferences(Sym.kind(), Contents, StringTableRefs);
696
Zachary Turner59e3ae82017-08-08 18:34:44 +0000697 SymbolKind NewKind = symbolKind(NewData);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000698
Reid Kleckner3f851922017-07-06 16:39:32 +0000699 // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
Zachary Turner59e3ae82017-08-08 18:34:44 +0000700 CVSymbol NewSym(NewKind, NewData);
701 if (symbolOpensScope(NewKind))
Reid Kleckner3f851922017-07-06 16:39:32 +0000702 scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(), NewSym);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000703 else if (symbolEndsScope(NewKind))
Reid Kleckner3f851922017-07-06 16:39:32 +0000704 scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000705
Zachary Turneree9906d2017-08-11 19:00:03 +0000706 // Add the symbol to the globals stream if necessary. Do this before adding
707 // the symbol to the module since we may need to get the next symbol offset,
708 // and writing to the module's symbol stream will update that offset.
709 if (symbolGoesInGlobalsStream(NewSym))
710 addGlobalSymbol(GsiBuilder, *File, NewSym);
711
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000712 // Add the symbol to the module.
Zachary Turneree9906d2017-08-11 19:00:03 +0000713 if (symbolGoesInModuleStream(NewSym))
714 File->ModuleDBI->addSymbol(NewSym);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000715 }
716}
717
Reid Kleckner44cdb102017-06-19 17:21:45 +0000718// Allocate memory for a .debug$S section and relocate it.
719static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
720 SectionChunk *DebugChunk) {
721 uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk->getSize());
722 assert(DebugChunk->OutputSectionOff == 0 &&
723 "debug sections should not be in output sections");
724 DebugChunk->writeTo(Buffer);
725 return consumeDebugMagic(makeArrayRef(Buffer, DebugChunk->getSize()),
726 ".debug$S");
727}
728
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000729void PDBLinker::addObjFile(ObjFile *File) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000730 // Add a module descriptor for every object file. We need to put an absolute
731 // path to the object into the PDB. If this is a plain object, we make its
732 // path absolute. If it's an object in an archive, we make the archive path
733 // absolute.
734 bool InArchive = !File->ParentName.empty();
735 SmallString<128> Path = InArchive ? File->ParentName : File->getName();
736 sys::fs::make_absolute(Path);
737 sys::path::native(Path, sys::path::Style::windows);
738 StringRef Name = InArchive ? File->getName() : StringRef(Path);
Zachary Turner2897e032017-05-25 21:16:03 +0000739
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000740 File->ModuleDBI = &ExitOnErr(Builder.getDbiBuilder().addModuleInfo(Name));
741 File->ModuleDBI->setObjFileName(Path);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000742
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000743 // Before we can process symbol substreams from .debug$S, we need to process
744 // type information, file checksums, and the string table. Add type info to
745 // the PDB first, so that we can get the map from object file type and item
746 // indices to PDB type and item indices.
Reid Kleckner651db912017-07-18 00:21:25 +0000747 CVIndexMap ObjectIndexMap;
748 const CVIndexMap &IndexMap = mergeDebugT(File, ObjectIndexMap);
Zachary Turner448dea42017-07-07 18:46:14 +0000749
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000750 // Now do all live .debug$S sections.
Zachary Turner60478582018-01-05 19:12:40 +0000751 DebugStringTableSubsectionRef CVStrTab;
752 DebugChecksumsSubsectionRef Checksums;
753 std::vector<ulittle32_t *> StringTableReferences;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000754 for (SectionChunk *DebugChunk : File->getDebugChunks()) {
755 if (!DebugChunk->isLive() || DebugChunk->getSectionName() != ".debug$S")
756 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000757
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000758 ArrayRef<uint8_t> RelocatedDebugContents =
759 relocateDebugChunk(Alloc, DebugChunk);
760 if (RelocatedDebugContents.empty())
761 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000762
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000763 DebugSubsectionArray Subsections;
764 BinaryStreamReader Reader(RelocatedDebugContents, support::little);
765 ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
Rui Ueyama52896622017-01-12 03:09:25 +0000766
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000767 for (const DebugSubsectionRecord &SS : Subsections) {
768 switch (SS.kind()) {
Zachary Turner60478582018-01-05 19:12:40 +0000769 case DebugSubsectionKind::StringTable: {
770 auto Data = SS.getRecordData();
771 ArrayRef<uint8_t> Buffer;
772 cantFail(Data.readLongestContiguousChunk(0, Buffer));
773 assert(!CVStrTab.valid() &&
774 "Encountered multiple string table subsections!");
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000775 ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
776 break;
Zachary Turner60478582018-01-05 19:12:40 +0000777 }
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000778 case DebugSubsectionKind::FileChecksums:
Zachary Turner60478582018-01-05 19:12:40 +0000779 assert(!Checksums.valid() &&
780 "Encountered multiple checksum subsections!");
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000781 ExitOnErr(Checksums.initialize(SS.getRecordData()));
782 break;
783 case DebugSubsectionKind::Lines:
784 // We can add the relocated line table directly to the PDB without
785 // modification because the file checksum offsets will stay the same.
786 File->ModuleDBI->addDebugSubsection(SS);
787 break;
788 case DebugSubsectionKind::Symbols:
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000789 if (Config->DebugGHashes) {
790 mergeSymbolRecords(Alloc, File, Builder.getGsiBuilder(), IndexMap,
Zachary Turner60478582018-01-05 19:12:40 +0000791 GlobalIDTable, StringTableReferences,
792 SS.getRecordData());
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000793 } else {
794 mergeSymbolRecords(Alloc, File, Builder.getGsiBuilder(), IndexMap,
Zachary Turner60478582018-01-05 19:12:40 +0000795 IDTable, StringTableReferences,
796 SS.getRecordData());
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000797 }
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000798 break;
799 default:
800 // FIXME: Process the rest of the subsections.
801 break;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000802 }
803 }
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000804 }
Zachary Turner60478582018-01-05 19:12:40 +0000805
806 // We should have seen all debug subsections across the entire object file now
807 // which means that if a StringTable subsection and Checksums subsection were
808 // present, now is the time to handle them.
809 if (!CVStrTab.valid()) {
810 if (Checksums.valid())
811 fatal(".debug$S sections with a checksums subsection must also contain a "
812 "string table subsection");
813
814 if (!StringTableReferences.empty())
815 warn("No StringTable subsection was encountered, but there are string "
816 "table references");
817 return;
818 }
819
820 // Rewrite each string table reference based on the value that the string
821 // assumes in the final PDB.
822 for (ulittle32_t *Ref : StringTableReferences) {
823 auto ExpectedString = CVStrTab.getString(*Ref);
824 if (!ExpectedString) {
825 warn("Invalid string table reference");
826 consumeError(ExpectedString.takeError());
827 continue;
828 }
829
830 *Ref = PDBStrTab.insert(*ExpectedString);
831 }
832
833 // Make a new file checksum table that refers to offsets in the PDB-wide
834 // string table. Generally the string table subsection appears after the
835 // checksum table, so we have to do this after looping over all the
836 // subsections.
837 auto NewChecksums = make_unique<DebugChecksumsSubsection>(PDBStrTab);
838 for (FileChecksumEntry &FC : Checksums) {
839 StringRef FileName = ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
840 ExitOnErr(Builder.getDbiBuilder().addModuleSourceFile(*File->ModuleDBI,
841 FileName));
842 NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
843 }
844 File->ModuleDBI->addDebugSubsection(std::move(NewChecksums));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000845}
846
Reid Klecknereacdf042017-07-27 18:25:59 +0000847static PublicSym32 createPublic(Defined *Def) {
848 PublicSym32 Pub(SymbolKind::S_PUB32);
849 Pub.Name = Def->getName();
850 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
851 if (D->getCOFFSymbol().isFunctionDefinition())
852 Pub.Flags = PublicSymFlags::Function;
853 } else if (isa<DefinedImportThunk>(Def)) {
854 Pub.Flags = PublicSymFlags::Function;
855 }
856
857 OutputSection *OS = Def->getChunk()->getOutputSection();
858 assert(OS && "all publics should be in final image");
859 Pub.Offset = Def->getRVA() - OS->getRVA();
860 Pub.Segment = OS->SectionIndex;
861 return Pub;
862}
863
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000864// Add all object files to the PDB. Merge .debug$T sections into IpiData and
865// TpiData.
866void PDBLinker::addObjectsToPDB() {
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000867 for (ObjFile *File : ObjFile::Instances)
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000868 addObjFile(File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000869
870 Builder.getStringTableBuilder().setStrings(PDBStrTab);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000871
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000872 // Construct TPI and IPI stream contents.
873 if (Config->DebugGHashes) {
874 addTypeInfo(Builder.getTpiBuilder(), GlobalTypeTable);
875 addTypeInfo(Builder.getIpiBuilder(), GlobalIDTable);
876 } else {
877 addTypeInfo(Builder.getTpiBuilder(), TypeTable);
878 addTypeInfo(Builder.getIpiBuilder(), IDTable);
879 }
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000880
Zachary Turneree9906d2017-08-11 19:00:03 +0000881 // Compute the public and global symbols.
882 auto &GsiBuilder = Builder.getGsiBuilder();
Reid Klecknereacdf042017-07-27 18:25:59 +0000883 std::vector<PublicSym32> Publics;
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000884 Symtab->forEachSymbol([&Publics](Symbol *S) {
Reid Klecknereacdf042017-07-27 18:25:59 +0000885 // Only emit defined, live symbols that have a chunk.
Rui Ueyama616cd992017-10-31 16:10:24 +0000886 auto *Def = dyn_cast<Defined>(S);
Reid Klecknereacdf042017-07-27 18:25:59 +0000887 if (Def && Def->isLive() && Def->getChunk())
888 Publics.push_back(createPublic(Def));
889 });
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000890
Reid Klecknereacdf042017-07-27 18:25:59 +0000891 if (!Publics.empty()) {
892 // Sort the public symbols and add them to the stream.
893 std::sort(Publics.begin(), Publics.end(),
894 [](const PublicSym32 &L, const PublicSym32 &R) {
895 return L.Name < R.Name;
896 });
Reid Klecknereacdf042017-07-27 18:25:59 +0000897 for (const PublicSym32 &Pub : Publics)
Zachary Turner946204c2017-08-09 04:23:25 +0000898 GsiBuilder.addPublicSymbol(Pub);
Reid Klecknereacdf042017-07-27 18:25:59 +0000899 }
Rui Ueyama52896622017-01-12 03:09:25 +0000900}
901
Zachary Turner28e31ee2017-08-11 20:46:28 +0000902static void addCommonLinkerModuleSymbols(StringRef Path,
903 pdb::DbiModuleDescriptorBuilder &Mod,
904 BumpPtrAllocator &Allocator) {
Zachary Turner28e31ee2017-08-11 20:46:28 +0000905 ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
906 Compile3Sym CS(SymbolRecordKind::Compile3Sym);
907 EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000908
909 ONS.Name = "* Linker *";
910 ONS.Signature = 0;
911
912 CS.Machine = Config->is64() ? CPUType::X64 : CPUType::Intel80386;
Zachary Turnerb57884e2017-08-11 21:14:01 +0000913 // Interestingly, if we set the string to 0.0.0.0, then when trying to view
914 // local variables WinDbg emits an error that private symbols are not present.
915 // By setting this to a valid MSVC linker version string, local variables are
916 // displayed properly. As such, even though it is not representative of
Zachary Turnerf6822c82017-08-11 20:46:47 +0000917 // LLVM's version information, we need this for compatibility.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000918 CS.Flags = CompileSym3Flags::None;
Zachary Turnerf6822c82017-08-11 20:46:47 +0000919 CS.VersionBackendBuild = 25019;
920 CS.VersionBackendMajor = 14;
921 CS.VersionBackendMinor = 10;
Zachary Turner6708e0b2017-07-10 21:01:37 +0000922 CS.VersionBackendQFE = 0;
Zachary Turnerf6822c82017-08-11 20:46:47 +0000923
924 // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
925 // linker module (which is by definition a backend), so we don't need to do
926 // anything here. Also, it seems we can use "LLVM Linker" for the linker name
927 // without any problems. Only the backend version has to be hardcoded to a
928 // magic number.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000929 CS.VersionFrontendBuild = 0;
930 CS.VersionFrontendMajor = 0;
931 CS.VersionFrontendMinor = 0;
932 CS.VersionFrontendQFE = 0;
933 CS.Version = "LLVM Linker";
934 CS.setLanguage(SourceLanguage::Link);
935
936 ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
937 std::string ArgStr = llvm::join(Args, " ");
938 EBS.Fields.push_back("cwd");
939 SmallString<64> cwd;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000940 sys::fs::current_path(cwd);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000941 EBS.Fields.push_back(cwd);
942 EBS.Fields.push_back("exe");
Zachary Turnerf6822c82017-08-11 20:46:47 +0000943 SmallString<64> exe = Config->Argv[0];
944 llvm::sys::fs::make_absolute(exe);
945 EBS.Fields.push_back(exe);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000946 EBS.Fields.push_back("pdb");
947 EBS.Fields.push_back(Path);
948 EBS.Fields.push_back("cmd");
949 EBS.Fields.push_back(ArgStr);
950 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
951 ONS, Allocator, CodeViewContainer::Pdb));
952 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
953 CS, Allocator, CodeViewContainer::Pdb));
954 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
955 EBS, Allocator, CodeViewContainer::Pdb));
956}
957
Zachary Turner28e31ee2017-08-11 20:46:28 +0000958static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &Mod,
959 OutputSection &OS,
960 BumpPtrAllocator &Allocator) {
961 SectionSym Sym(SymbolRecordKind::SectionSym);
Zachary Turnerf6822c82017-08-11 20:46:47 +0000962 Sym.Alignment = 12; // 2^12 = 4KB
Zachary Turner28e31ee2017-08-11 20:46:28 +0000963 Sym.Characteristics = OS.getCharacteristics();
964 Sym.Length = OS.getVirtualSize();
965 Sym.Name = OS.getName();
966 Sym.Rva = OS.getRVA();
967 Sym.SectionNumber = OS.SectionIndex;
968 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
969 Sym, Allocator, CodeViewContainer::Pdb));
970}
971
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000972// Creates a PDB file.
Reid Kleckner175af4b2017-08-03 21:15:09 +0000973void coff::createPDB(SymbolTable *Symtab,
974 ArrayRef<OutputSection *> OutputSections,
975 ArrayRef<uint8_t> SectionTable,
Zachary Turner024323c2017-08-15 21:31:41 +0000976 const llvm::codeview::DebugInfo &BuildId) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000977 PDBLinker PDB(Symtab);
Zachary Turner024323c2017-08-15 21:31:41 +0000978 PDB.initialize(BuildId);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000979 PDB.addObjectsToPDB();
Reid Kleckner175af4b2017-08-03 21:15:09 +0000980 PDB.addSections(OutputSections, SectionTable);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000981 PDB.commit();
982}
983
Zachary Turner024323c2017-08-15 21:31:41 +0000984void PDBLinker::initialize(const llvm::codeview::DebugInfo &BuildId) {
Rui Ueyama12979542016-09-30 20:53:45 +0000985 ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
Rui Ueyama7f382992016-09-15 18:55:18 +0000986
Rui Ueyama8d3fb5d2016-10-05 22:08:58 +0000987 // Create streams in MSF for predefined streams, namely
988 // PDB, TPI, DBI and IPI.
989 for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
990 ExitOnErr(Builder.getMsfBuilder().addStream(0));
Rui Ueyama7f382992016-09-15 18:55:18 +0000991
Rui Ueyamabb542b32016-09-16 22:51:17 +0000992 // Add an Info stream.
993 auto &InfoBuilder = Builder.getInfoBuilder();
Zachary Turner024323c2017-08-15 21:31:41 +0000994 InfoBuilder.setAge(BuildId.PDB70.Age);
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000995
Zachary Turner024323c2017-08-15 21:31:41 +0000996 GUID uuid;
997 memcpy(&uuid, &BuildId.PDB70.Signature, sizeof(uuid));
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000998 InfoBuilder.setGuid(uuid);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000999 InfoBuilder.setSignature(time(nullptr));
Rui Ueyamabb542b32016-09-16 22:51:17 +00001000 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
Rui Ueyama7f382992016-09-15 18:55:18 +00001001
Zachary Turner6c4bfba2017-07-07 05:04:36 +00001002 // Add an empty DBI stream.
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +00001003 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Zachary Turner024323c2017-08-15 21:31:41 +00001004 DbiBuilder.setAge(BuildId.PDB70.Age);
Zachary Turnerc1e93e52017-07-07 18:45:56 +00001005 DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
Zachary Turner3a11fdf2017-07-07 20:25:39 +00001006 ExitOnErr(DbiBuilder.addDbgStream(pdb::DbgHeaderType::NewFPO, {}));
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001007}
Rui Ueyama1343fac2016-10-06 22:52:01 +00001008
Reid Kleckner175af4b2017-08-03 21:15:09 +00001009void PDBLinker::addSectionContrib(pdb::DbiModuleDescriptorBuilder &LinkerModule,
1010 OutputSection *OS, Chunk *C) {
1011 pdb::SectionContrib SC;
1012 memset(&SC, 0, sizeof(SC));
1013 SC.ISect = OS->SectionIndex;
1014 SC.Off = C->getRVA() - OS->getRVA();
1015 SC.Size = C->getSize();
1016 if (auto *SecChunk = dyn_cast<SectionChunk>(C)) {
1017 SC.Characteristics = SecChunk->Header->Characteristics;
1018 SC.Imod = SecChunk->File->ModuleDBI->getModuleIndex();
Zachary Turner676386ff2017-08-07 20:23:45 +00001019 ArrayRef<uint8_t> Contents = SecChunk->getContents();
1020 JamCRC CRC(0);
1021 ArrayRef<char> CharContents = makeArrayRef(
1022 reinterpret_cast<const char *>(Contents.data()), Contents.size());
1023 CRC.update(CharContents);
1024 SC.DataCrc = CRC.getCRC();
Reid Kleckner175af4b2017-08-03 21:15:09 +00001025 } else {
1026 SC.Characteristics = OS->getCharacteristics();
1027 // FIXME: When we start creating DBI for import libraries, use those here.
1028 SC.Imod = LinkerModule.getModuleIndex();
1029 }
Reid Kleckner175af4b2017-08-03 21:15:09 +00001030 SC.RelocCrc = 0; // FIXME
1031 Builder.getDbiBuilder().addSectionContrib(SC);
1032}
Rui Ueyama09e0b5f2016-11-12 00:00:51 +00001033
Reid Kleckner175af4b2017-08-03 21:15:09 +00001034void PDBLinker::addSections(ArrayRef<OutputSection *> OutputSections,
1035 ArrayRef<uint8_t> SectionTable) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001036 // It's not entirely clear what this is, but the * Linker * module uses it.
Reid Kleckner175af4b2017-08-03 21:15:09 +00001037 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001038 NativePath = Config->PDBPath;
1039 sys::fs::make_absolute(NativePath);
1040 sys::path::native(NativePath, sys::path::Style::windows);
1041 uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
Zachary Turner6c4bfba2017-07-07 05:04:36 +00001042 auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
1043 LinkerModule.setPdbFilePathNI(PdbFilePathNI);
Zachary Turner28e31ee2017-08-11 20:46:28 +00001044 addCommonLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
Rui Ueyamac91f7162016-11-16 01:10:46 +00001045
Reid Kleckner175af4b2017-08-03 21:15:09 +00001046 // Add section contributions. They must be ordered by ascending RVA.
Zachary Turner28e31ee2017-08-11 20:46:28 +00001047 for (OutputSection *OS : OutputSections) {
1048 addLinkerModuleSectionSymbol(LinkerModule, *OS, Alloc);
Reid Kleckner175af4b2017-08-03 21:15:09 +00001049 for (Chunk *C : OS->getChunks())
1050 addSectionContrib(LinkerModule, OS, C);
Zachary Turner28e31ee2017-08-11 20:46:28 +00001051 }
Reid Kleckner175af4b2017-08-03 21:15:09 +00001052
1053 // Add Section Map stream.
1054 ArrayRef<object::coff_section> Sections = {
1055 (const object::coff_section *)SectionTable.data(),
1056 SectionTable.size() / sizeof(object::coff_section)};
1057 SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
1058 DbiBuilder.setSectionMap(SectionMap);
1059
Rui Ueyama9f66f822016-10-11 19:45:07 +00001060 // Add COFF section header stream.
1061 ExitOnErr(
1062 DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001063}
Rui Ueyama9f66f822016-10-11 19:45:07 +00001064
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001065void PDBLinker::commit() {
Rui Ueyama3e9d6bb2016-09-26 23:53:55 +00001066 // Write to a file.
Zachary Turner6708e0b2017-07-10 21:01:37 +00001067 ExitOnErr(Builder.commit(Config->PDBPath));
Rui Ueyamae7378242015-12-04 23:11:05 +00001068}