blob: 0ca2587cb2752d99bcfbb806cfe9802e8f14acc0 [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"
Zachary Turner727f1532018-01-17 19:16:26 +000018#include "lld/Common/Timer.h"
Saleem Abdulrasooldf8a13b2017-01-04 17:56:54 +000019#include "llvm/DebugInfo/CodeView/CVDebugRecord.h"
Reid Kleckner44cdb102017-06-19 17:21:45 +000020#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
Zachary Turner0d07a8e2017-12-14 18:07:04 +000021#include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000022#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
Zachary Turnerca6dbf12017-11-30 18:39:50 +000023#include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
Zachary Turneree9906d2017-08-11 19:00:03 +000024#include "llvm/DebugInfo/CodeView/RecordName.h"
Zachary Turner59e3ae82017-08-08 18:34:44 +000025#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
Zachary Turner6708e0b2017-07-10 21:01:37 +000026#include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
Reid Kleckner651db912017-07-18 00:21:25 +000027#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000028#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerd0e6e242017-06-21 17:25:56 +000029#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
Rui Ueyama52896622017-01-12 03:09:25 +000030#include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
Rui Ueyamab28c6d42016-09-16 04:32:33 +000031#include "llvm/DebugInfo/MSF/MSFBuilder.h"
Rui Ueyama7f382992016-09-15 18:55:18 +000032#include "llvm/DebugInfo/MSF/MSFCommon.h"
Reid Kleckner651db912017-07-18 00:21:25 +000033#include "llvm/DebugInfo/PDB/GenericError.h"
Zachary Turner6708e0b2017-07-10 21:01:37 +000034#include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000035#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
36#include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
Zachary Turner946204c2017-08-09 04:23:25 +000037#include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000038#include "llvm/DebugInfo/PDB/Native/InfoStream.h"
39#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
Reid Kleckner651db912017-07-18 00:21:25 +000040#include "llvm/DebugInfo/PDB/Native/NativeSession.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000041#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
42#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
Rafael Espindolaa0f30da2017-05-02 20:19:42 +000043#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
Reid Klecknerd91ca762017-07-19 17:26:07 +000044#include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000045#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
46#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
Reid Kleckner651db912017-07-18 00:21:25 +000047#include "llvm/DebugInfo/PDB/PDB.h"
Rui Ueyama20df4ec2016-10-31 21:09:21 +000048#include "llvm/Object/COFF.h"
Zachary Turnerd9dc2822017-03-02 20:52:51 +000049#include "llvm/Support/BinaryByteStream.h"
Rui Ueyama1763c0d2015-12-08 18:39:55 +000050#include "llvm/Support/Endian.h"
Zachary Turner60478582018-01-05 19:12:40 +000051#include "llvm/Support/FormatVariadic.h"
Zachary Turner676386ff2017-08-07 20:23:45 +000052#include "llvm/Support/JamCRC.h"
Zachary Turner7b327d02017-02-16 23:35:45 +000053#include "llvm/Support/Path.h"
Rui Ueyamabe939b32016-11-21 17:22:35 +000054#include "llvm/Support/ScopedPrinter.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000055#include <memory>
56
Rui Ueyama1d99ab32016-09-15 22:24:51 +000057using namespace lld;
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000058using namespace lld::coff;
Rui Ueyamae7378242015-12-04 23:11:05 +000059using namespace llvm;
Rui Ueyamabe939b32016-11-21 17:22:35 +000060using namespace llvm::codeview;
Rui Ueyamae7378242015-12-04 23:11:05 +000061
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000062using llvm::object::coff_section;
63
Rui Ueyamab28c6d42016-09-16 04:32:33 +000064static ExitOnError ExitOnErr;
65
Zachary Turner727f1532018-01-17 19:16:26 +000066static Timer TotalPdbLinkTimer("PDB Emission (Cumulative)", Timer::root());
67
68static Timer AddObjectsTimer("Add Objects", TotalPdbLinkTimer);
69static Timer TypeMergingTimer("Type Merging", AddObjectsTimer);
70static Timer SymbolMergingTimer("Symbol Merging", AddObjectsTimer);
71static Timer GlobalsLayoutTimer("Globals Stream Layout", TotalPdbLinkTimer);
72static Timer TpiStreamLayoutTimer("TPI Stream Layout", TotalPdbLinkTimer);
73static Timer DiskCommitTimer("Commit to Disk", TotalPdbLinkTimer);
74
Reid Kleckner0faf6d72017-07-14 00:14:58 +000075namespace {
Reid Kleckner651db912017-07-18 00:21:25 +000076/// Map from type index and item index in a type server PDB to the
77/// corresponding index in the destination PDB.
78struct CVIndexMap {
79 SmallVector<TypeIndex, 0> TPIMap;
80 SmallVector<TypeIndex, 0> IPIMap;
81 bool IsTypeServerMap = false;
82};
83
Reid Kleckner0faf6d72017-07-14 00:14:58 +000084class PDBLinker {
85public:
86 PDBLinker(SymbolTable *Symtab)
Sam Cleggea244bf2017-12-14 21:09:31 +000087 : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
88 IDTable(Alloc), GlobalTypeTable(Alloc), GlobalIDTable(Alloc) {}
Reid Kleckner0faf6d72017-07-14 00:14:58 +000089
90 /// Emit the basic PDB structure: initial streams, headers, etc.
Zachary Turner024323c2017-08-15 21:31:41 +000091 void initialize(const llvm::codeview::DebugInfo &BuildId);
Reid Kleckner0faf6d72017-07-14 00:14:58 +000092
93 /// Link CodeView from each object file in the symbol table into the PDB.
94 void addObjectsToPDB();
95
96 /// Link CodeView from a single object file into the PDB.
Rui Ueyamae1b48e02017-07-26 23:05:24 +000097 void addObjFile(ObjFile *File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +000098
Reid Kleckner651db912017-07-18 00:21:25 +000099 /// Produce a mapping from the type and item indices used in the object
100 /// file to those in the destination PDB.
101 ///
102 /// If the object file uses a type server PDB (compiled with /Zi), merge TPI
103 /// and IPI from the type server PDB and return a map for it. Each unique type
104 /// server PDB is merged at most once, so this may return an existing index
105 /// mapping.
106 ///
107 /// If the object does not use a type server PDB (compiled with /Z7), we merge
108 /// all the type and item records from the .debug$S stream and fill in the
109 /// caller-provided ObjectIndexMap.
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000110 Expected<const CVIndexMap&> mergeDebugT(ObjFile *File,
111 CVIndexMap &ObjectIndexMap);
Reid Kleckner651db912017-07-18 00:21:25 +0000112
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000113 Expected<const CVIndexMap&> maybeMergeTypeServerPDB(ObjFile *File,
114 TypeServer2Record &TS);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000115
116 /// Add the section map and section contributions to the PDB.
Reid Kleckner175af4b2017-08-03 21:15:09 +0000117 void addSections(ArrayRef<OutputSection *> OutputSections,
118 ArrayRef<uint8_t> SectionTable);
119
120 void addSectionContrib(pdb::DbiModuleDescriptorBuilder &LinkerModule,
121 OutputSection *OS, Chunk *C);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000122
123 /// Write the PDB to disk.
124 void commit();
125
126private:
127 BumpPtrAllocator Alloc;
128
129 SymbolTable *Symtab;
130
131 pdb::PDBFileBuilder Builder;
132
133 /// Type records that will go into the PDB TPI stream.
Zachary Turnerca6dbf12017-11-30 18:39:50 +0000134 MergingTypeTableBuilder TypeTable;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000135
136 /// Item records that will go into the PDB IPI stream.
Zachary Turnerca6dbf12017-11-30 18:39:50 +0000137 MergingTypeTableBuilder IDTable;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000138
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000139 /// Type records that will go into the PDB TPI stream (for /DEBUG:GHASH)
140 GlobalTypeTableBuilder GlobalTypeTable;
141
142 /// Item records that will go into the PDB IPI stream (for /DEBUG:GHASH)
143 GlobalTypeTableBuilder GlobalIDTable;
144
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000145 /// PDBs use a single global string table for filenames in the file checksum
146 /// table.
147 DebugStringTableSubsection PDBStrTab;
148
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000149 llvm::SmallString<128> NativePath;
150
151 std::vector<pdb::SecMapEntry> SectionMap;
Reid Kleckner651db912017-07-18 00:21:25 +0000152
153 /// Type index mappings of type server PDBs that we've loaded so far.
154 std::map<GUID, CVIndexMap> TypeServerIndexMappings;
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000155
156 /// List of TypeServer PDBs which cannot be loaded.
157 /// Cached to prevent repeated load attempts.
158 std::set<GUID> MissingTypeServerPDBs;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000159};
160}
161
Sam Clegg0fb6faa2017-12-08 01:09:21 +0000162static SectionChunk *findByName(ArrayRef<SectionChunk *> Sections,
Rui Ueyamabe939b32016-11-21 17:22:35 +0000163 StringRef Name) {
164 for (SectionChunk *C : Sections)
165 if (C->getSectionName() == Name)
166 return C;
167 return nullptr;
168}
169
Reid Kleckner44cdb102017-06-19 17:21:45 +0000170static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
171 StringRef SecName) {
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000172 // First 4 bytes are section magic.
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000173 if (Data.size() < 4)
Rui Ueyama52896622017-01-12 03:09:25 +0000174 fatal(SecName + " too short");
Reid Kleckner44cdb102017-06-19 17:21:45 +0000175 if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
Rui Ueyama52896622017-01-12 03:09:25 +0000176 fatal(SecName + " has an invalid magic");
Rui Ueyama26186c72016-12-09 04:46:54 +0000177 return Data.slice(4);
178}
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000179
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000180static ArrayRef<uint8_t> getDebugSection(ObjFile *File, StringRef SecName) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000181 if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
182 return consumeDebugMagic(Sec->getContents(), SecName);
183 return {};
184}
185
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000186// A COFF .debug$H section is currently a clang extension. This function checks
187// if a .debug$H section is in a format that we expect / understand, so that we
188// can ignore any sections which are coincidentally also named .debug$H but do
189// not contain a format we recognize.
190static bool canUseDebugH(ArrayRef<uint8_t> DebugH) {
191 if (DebugH.size() < sizeof(object::debug_h_header))
192 return false;
193 auto *Header =
194 reinterpret_cast<const object::debug_h_header *>(DebugH.data());
195 DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
196 return Header->Magic == COFF::DEBUG_HASHES_SECTION_MAGIC &&
197 Header->Version == 0 &&
198 Header->HashAlgorithm == uint16_t(GlobalTypeHashAlg::SHA1) &&
199 (DebugH.size() % 20 == 0);
200}
201
202static Optional<ArrayRef<uint8_t>> getDebugH(ObjFile *File) {
203 SectionChunk *Sec = findByName(File->getDebugChunks(), ".debug$H");
204 if (!Sec)
205 return llvm::None;
206 ArrayRef<uint8_t> Contents = Sec->getContents();
207 if (!canUseDebugH(Contents))
208 return None;
209 return Contents;
210}
211
212static ArrayRef<GloballyHashedType>
213getHashesFromDebugH(ArrayRef<uint8_t> DebugH) {
214 assert(canUseDebugH(DebugH));
215
216 DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
217 uint32_t Count = DebugH.size() / sizeof(GloballyHashedType);
218 return {reinterpret_cast<const GloballyHashedType *>(DebugH.data()), Count};
219}
220
Reid Kleckner5d577522017-03-24 17:26:38 +0000221static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
Zachary Turner3e3936d2017-11-29 19:35:21 +0000222 TypeCollection &TypeTable) {
Reid Kleckner5d577522017-03-24 17:26:38 +0000223 // Start the TPI or IPI stream header.
224 TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
Rui Ueyama52896622017-01-12 03:09:25 +0000225
Reid Klecknerd91ca762017-07-19 17:26:07 +0000226 // Flatten the in memory type table and hash each type.
Zachary Turner3e3936d2017-11-29 19:35:21 +0000227 TypeTable.ForEachRecord([&](TypeIndex TI, const CVType &Type) {
Reid Klecknerd91ca762017-07-19 17:26:07 +0000228 auto Hash = pdb::hashTypeRecord(Type);
229 if (auto E = Hash.takeError())
230 fatal("type hashing error");
Zachary Turner3e3936d2017-11-29 19:35:21 +0000231 TpiBuilder.addTypeRecord(Type.RecordData, *Hash);
Reid Kleckner5d577522017-03-24 17:26:38 +0000232 });
Reid Kleckner5d577522017-03-24 17:26:38 +0000233}
234
Reid Kleckner651db912017-07-18 00:21:25 +0000235static Optional<TypeServer2Record>
236maybeReadTypeServerRecord(CVTypeArray &Types) {
237 auto I = Types.begin();
238 if (I == Types.end())
239 return None;
240 const CVType &Type = *I;
241 if (Type.kind() != LF_TYPESERVER2)
242 return None;
243 TypeServer2Record TS;
244 if (auto EC = TypeDeserializer::deserializeAs(const_cast<CVType &>(Type), TS))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000245 fatal("error reading type server record: " + toString(std::move(EC)));
Reid Kleckner651db912017-07-18 00:21:25 +0000246 return std::move(TS);
247}
248
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000249Expected<const CVIndexMap&> PDBLinker::mergeDebugT(ObjFile *File,
250 CVIndexMap &ObjectIndexMap) {
Zachary Turner727f1532018-01-17 19:16:26 +0000251 ScopedTimer T(TypeMergingTimer);
252
Reid Kleckner44cdb102017-06-19 17:21:45 +0000253 ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
254 if (Data.empty())
Reid Kleckner651db912017-07-18 00:21:25 +0000255 return ObjectIndexMap;
Reid Kleckner6597c282017-07-13 20:12:23 +0000256
Reid Kleckner44cdb102017-06-19 17:21:45 +0000257 BinaryByteStream Stream(Data, support::little);
258 CVTypeArray Types;
259 BinaryStreamReader Reader(Stream);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000260 if (auto EC = Reader.readArray(Types, Reader.getLength()))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000261 fatal("Reader::readArray failed: " + toString(std::move(EC)));
Reid Kleckner651db912017-07-18 00:21:25 +0000262
263 // Look through type servers. If we've already seen this type server, don't
264 // merge any type information.
265 if (Optional<TypeServer2Record> TS = maybeReadTypeServerRecord(Types))
266 return maybeMergeTypeServerPDB(File, *TS);
267
268 // This is a /Z7 object. Fill in the temporary, caller-provided
269 // ObjectIndexMap.
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000270 if (Config->DebugGHashes) {
271 ArrayRef<GloballyHashedType> Hashes;
272 std::vector<GloballyHashedType> OwnedHashes;
273 if (Optional<ArrayRef<uint8_t>> DebugH = getDebugH(File))
274 Hashes = getHashesFromDebugH(*DebugH);
275 else {
276 OwnedHashes = GloballyHashedType::hashTypes(Types);
277 Hashes = OwnedHashes;
278 }
279
280 if (auto Err = mergeTypeAndIdRecords(GlobalIDTable, GlobalTypeTable,
281 ObjectIndexMap.TPIMap, Types, Hashes))
282 fatal("codeview::mergeTypeAndIdRecords failed: " +
283 toString(std::move(Err)));
284 } else {
285 if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable,
286 ObjectIndexMap.TPIMap, Types))
287 fatal("codeview::mergeTypeAndIdRecords failed: " +
288 toString(std::move(Err)));
289 }
Reid Kleckner651db912017-07-18 00:21:25 +0000290 return ObjectIndexMap;
291}
292
293static Expected<std::unique_ptr<pdb::NativeSession>>
294tryToLoadPDB(const GUID &GuidFromObj, StringRef TSPath) {
Peter Collingbourne75257bc2017-10-20 19:48:26 +0000295 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(
296 TSPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
297 if (!MBOrErr)
298 return errorCodeToError(MBOrErr.getError());
299
Reid Kleckner651db912017-07-18 00:21:25 +0000300 std::unique_ptr<pdb::IPDBSession> ThisSession;
Peter Collingbourne75257bc2017-10-20 19:48:26 +0000301 if (auto EC = pdb::NativeSession::createFromPdb(
302 MemoryBuffer::getMemBuffer(Driver->takeBuffer(std::move(*MBOrErr)),
303 /*RequiresNullTerminator=*/false),
304 ThisSession))
Reid Kleckner651db912017-07-18 00:21:25 +0000305 return std::move(EC);
306
307 std::unique_ptr<pdb::NativeSession> NS(
308 static_cast<pdb::NativeSession *>(ThisSession.release()));
309 pdb::PDBFile &File = NS->getPDBFile();
310 auto ExpectedInfo = File.getPDBInfoStream();
311 // All PDB Files should have an Info stream.
312 if (!ExpectedInfo)
313 return ExpectedInfo.takeError();
314
315 // Just because a file with a matching name was found and it was an actual
316 // PDB file doesn't mean it matches. For it to match the InfoStream's GUID
317 // must match the GUID specified in the TypeServer2 record.
318 if (ExpectedInfo->getGuid() != GuidFromObj)
319 return make_error<pdb::GenericError>(
320 pdb::generic_error_code::type_server_not_found, TSPath);
321
322 return std::move(NS);
323}
324
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000325Expected<const CVIndexMap&> PDBLinker::maybeMergeTypeServerPDB(ObjFile *File,
326 TypeServer2Record &TS) {
327 const GUID& TSId = TS.getGuid();
328 StringRef TSPath = TS.getName();
329
330 // First, check if the PDB has previously failed to load.
331 if (MissingTypeServerPDBs.count(TSId))
332 return make_error<pdb::GenericError>(
333 pdb::generic_error_code::type_server_not_found, TSPath);
334
335 // Second, check if we already loaded a PDB with this GUID. Return the type
Reid Kleckner651db912017-07-18 00:21:25 +0000336 // index mapping if we have it.
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000337 auto Insertion = TypeServerIndexMappings.insert({TSId, CVIndexMap()});
Reid Kleckner651db912017-07-18 00:21:25 +0000338 CVIndexMap &IndexMap = Insertion.first->second;
339 if (!Insertion.second)
340 return IndexMap;
341
342 // Mark this map as a type server map.
343 IndexMap.IsTypeServerMap = true;
344
345 // Check for a PDB at:
346 // 1. The given file path
347 // 2. Next to the object file or archive file
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000348 auto ExpectedSession = tryToLoadPDB(TSId, TSPath);
Reid Kleckner651db912017-07-18 00:21:25 +0000349 if (!ExpectedSession) {
350 consumeError(ExpectedSession.takeError());
351 StringRef LocalPath =
352 !File->ParentName.empty() ? File->ParentName : File->getName();
353 SmallString<128> Path = sys::path::parent_path(LocalPath);
Reid Klecknerf8522d82017-07-18 00:33:53 +0000354 sys::path::append(
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000355 Path, sys::path::filename(TSPath, sys::path::Style::windows));
356 ExpectedSession = tryToLoadPDB(TSId, Path);
Reid Kleckner651db912017-07-18 00:21:25 +0000357 }
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000358 if (auto E = ExpectedSession.takeError()) {
359 TypeServerIndexMappings.erase(TSId);
360 MissingTypeServerPDBs.emplace(TSId);
361 return std::move(E);
362 }
Reid Kleckner651db912017-07-18 00:21:25 +0000363
Reid Kleckner651db912017-07-18 00:21:25 +0000364 auto ExpectedTpi = (*ExpectedSession)->getPDBFile().getPDBTpiStream();
365 if (auto E = ExpectedTpi.takeError())
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000366 fatal("Type server does not have TPI stream: " + toString(std::move(E)));
Reid Kleckner651db912017-07-18 00:21:25 +0000367 auto ExpectedIpi = (*ExpectedSession)->getPDBFile().getPDBIpiStream();
368 if (auto E = ExpectedIpi.takeError())
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000369 fatal("Type server does not have TPI stream: " + toString(std::move(E)));
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000370
371 if (Config->DebugGHashes) {
372 // PDBs do not actually store global hashes, so when merging a type server
373 // PDB we have to synthesize global hashes. To do this, we first synthesize
374 // global hashes for the TPI stream, since it is independent, then we
375 // synthesize hashes for the IPI stream, using the hashes for the TPI stream
376 // as inputs.
377 auto TpiHashes = GloballyHashedType::hashTypes(ExpectedTpi->typeArray());
378 auto IpiHashes =
379 GloballyHashedType::hashIds(ExpectedIpi->typeArray(), TpiHashes);
380
381 // Merge TPI first, because the IPI stream will reference type indices.
382 if (auto Err = mergeTypeRecords(GlobalTypeTable, IndexMap.TPIMap,
383 ExpectedTpi->typeArray(), TpiHashes))
384 fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
385
386 // Merge IPI.
387 if (auto Err =
388 mergeIdRecords(GlobalIDTable, IndexMap.TPIMap, IndexMap.IPIMap,
389 ExpectedIpi->typeArray(), IpiHashes))
390 fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
391 } else {
392 // Merge TPI first, because the IPI stream will reference type indices.
393 if (auto Err = mergeTypeRecords(TypeTable, IndexMap.TPIMap,
394 ExpectedTpi->typeArray()))
395 fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
396
397 // Merge IPI.
398 if (auto Err = mergeIdRecords(IDTable, IndexMap.TPIMap, IndexMap.IPIMap,
399 ExpectedIpi->typeArray()))
400 fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
401 }
Reid Kleckner651db912017-07-18 00:21:25 +0000402
403 return IndexMap;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000404}
405
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000406static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
407 if (TI.isSimple())
408 return true;
409 if (TI.toArrayIndex() >= TypeIndexMap.size())
410 return false;
411 TI = TypeIndexMap[TI.toArrayIndex()];
412 return true;
413}
414
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000415static void remapTypesInSymbolRecord(ObjFile *File, SymbolKind SymKind,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000416 MutableArrayRef<uint8_t> Contents,
Reid Kleckner651db912017-07-18 00:21:25 +0000417 const CVIndexMap &IndexMap,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000418 ArrayRef<TiReference> TypeRefs) {
419 for (const TiReference &Ref : TypeRefs) {
420 unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000421 if (Contents.size() < Ref.Offset + ByteSize)
422 fatal("symbol record too short");
Reid Kleckner651db912017-07-18 00:21:25 +0000423
424 // This can be an item index or a type index. Choose the appropriate map.
425 ArrayRef<TypeIndex> TypeOrItemMap = IndexMap.TPIMap;
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000426 bool IsItemIndex = Ref.Kind == TiRefKind::IndexRef;
427 if (IsItemIndex && IndexMap.IsTypeServerMap)
Reid Kleckner651db912017-07-18 00:21:25 +0000428 TypeOrItemMap = IndexMap.IPIMap;
429
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000430 MutableArrayRef<TypeIndex> TIs(
431 reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000432 for (TypeIndex &TI : TIs) {
Reid Kleckner651db912017-07-18 00:21:25 +0000433 if (!remapTypeIndex(TI, TypeOrItemMap)) {
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000434 log("ignoring symbol record of kind 0x" + utohexstr(SymKind) + " in " +
435 File->getName() + " with bad " + (IsItemIndex ? "item" : "type") +
436 " index 0x" + utohexstr(TI.getIndex()));
Reid Kleckner5d82f682017-10-23 22:44:51 +0000437 TI = TypeIndex(SimpleTypeKind::NotTranslated);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000438 continue;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000439 }
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000440 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000441 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000442}
443
Zachary Turner60478582018-01-05 19:12:40 +0000444static void
445recordStringTableReferenceAtOffset(MutableArrayRef<uint8_t> Contents,
446 uint32_t Offset,
447 std::vector<ulittle32_t *> &StrTableRefs) {
448 Contents =
449 Contents.drop_front(Offset).take_front(sizeof(support::ulittle32_t));
450 ulittle32_t *Index = reinterpret_cast<ulittle32_t *>(Contents.data());
451 StrTableRefs.push_back(Index);
452}
453
454static void
455recordStringTableReferences(SymbolKind Kind, MutableArrayRef<uint8_t> Contents,
456 std::vector<ulittle32_t *> &StrTableRefs) {
457 // For now we only handle S_FILESTATIC, but we may need the same logic for
458 // S_DEFRANGE and S_DEFRANGE_SUBFIELD. However, I cannot seem to generate any
459 // PDBs that contain these types of records, so because of the uncertainty
460 // they are omitted here until we can prove that it's necessary.
461 switch (Kind) {
462 case SymbolKind::S_FILESTATIC:
463 // FileStaticSym::ModFileOffset
464 recordStringTableReferenceAtOffset(Contents, 4, StrTableRefs);
465 break;
466 case SymbolKind::S_DEFRANGE:
467 case SymbolKind::S_DEFRANGE_SUBFIELD:
468 log("Not fixing up string table reference in S_DEFRANGE / "
469 "S_DEFRANGE_SUBFIELD record");
470 break;
Zachary Turner9e52e502018-01-05 19:28:39 +0000471 default:
472 break;
Zachary Turner60478582018-01-05 19:12:40 +0000473 }
474}
475
Zachary Turner59e3ae82017-08-08 18:34:44 +0000476static SymbolKind symbolKind(ArrayRef<uint8_t> RecordData) {
477 const RecordPrefix *Prefix =
478 reinterpret_cast<const RecordPrefix *>(RecordData.data());
479 return static_cast<SymbolKind>(uint16_t(Prefix->RecordKind));
480}
481
482/// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
483static void translateIdSymbols(MutableArrayRef<uint8_t> &RecordData,
Zachary Turner3e3936d2017-11-29 19:35:21 +0000484 TypeCollection &IDTable) {
Zachary Turner59e3ae82017-08-08 18:34:44 +0000485 RecordPrefix *Prefix = reinterpret_cast<RecordPrefix *>(RecordData.data());
486
487 SymbolKind Kind = symbolKind(RecordData);
488
489 if (Kind == SymbolKind::S_PROC_ID_END) {
490 Prefix->RecordKind = SymbolKind::S_END;
491 return;
492 }
493
494 // In an object file, GPROC32_ID has an embedded reference which refers to the
495 // single object file type index namespace. This has already been translated
496 // to the PDB file's ID stream index space, but we need to convert this to a
497 // symbol that refers to the type stream index space. So we remap again from
498 // ID index space to type index space.
499 if (Kind == SymbolKind::S_GPROC32_ID || Kind == SymbolKind::S_LPROC32_ID) {
500 SmallVector<TiReference, 1> Refs;
501 auto Content = RecordData.drop_front(sizeof(RecordPrefix));
502 CVSymbol Sym(Kind, RecordData);
503 discoverTypeIndicesInSymbol(Sym, Refs);
504 assert(Refs.size() == 1);
505 assert(Refs.front().Count == 1);
506
507 TypeIndex *TI =
508 reinterpret_cast<TypeIndex *>(Content.data() + Refs[0].Offset);
509 // `TI` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
510 // the IPI stream, whose `FunctionType` member refers to the TPI stream.
511 // Note that LF_FUNC_ID and LF_MEMFUNC_ID have the same record layout, and
512 // in both cases we just need the second type index.
513 if (!TI->isSimple() && !TI->isNoneType()) {
Zachary Turner3e3936d2017-11-29 19:35:21 +0000514 CVType FuncIdData = IDTable.getType(*TI);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000515 SmallVector<TypeIndex, 2> Indices;
516 discoverTypeIndices(FuncIdData, Indices);
517 assert(Indices.size() == 2);
518 *TI = Indices[1];
519 }
520
521 Kind = (Kind == SymbolKind::S_GPROC32_ID) ? SymbolKind::S_GPROC32
522 : SymbolKind::S_LPROC32;
523 Prefix->RecordKind = uint16_t(Kind);
524 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000525}
526
527/// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
528/// The object file may not be aligned.
529static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
530 BumpPtrAllocator &Alloc) {
531 size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
532 assert(Size >= 4 && "record too short");
533 assert(Size <= MaxRecordLength && "record too long");
534 void *Mem = Alloc.Allocate(Size, 4);
535
536 // Copy the symbol record and zero out any padding bytes.
537 MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
538 memcpy(NewData.data(), Sym.data().data(), Sym.length());
539 memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
540
541 // Update the record prefix length. It should point to the beginning of the
Zachary Turner59e3ae82017-08-08 18:34:44 +0000542 // next record.
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000543 auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000544 Prefix->RecordLen = Size - 2;
545 return NewData;
546}
547
Reid Kleckner3f851922017-07-06 16:39:32 +0000548/// Return true if this symbol opens a scope. This implies that the symbol has
549/// "parent" and "end" fields, which contain the offset of the S_END or
550/// S_INLINESITE_END record.
551static bool symbolOpensScope(SymbolKind Kind) {
552 switch (Kind) {
553 case SymbolKind::S_GPROC32:
554 case SymbolKind::S_LPROC32:
555 case SymbolKind::S_LPROC32_ID:
556 case SymbolKind::S_GPROC32_ID:
557 case SymbolKind::S_BLOCK32:
558 case SymbolKind::S_SEPCODE:
559 case SymbolKind::S_THUNK32:
560 case SymbolKind::S_INLINESITE:
561 case SymbolKind::S_INLINESITE2:
562 return true;
563 default:
564 break;
565 }
566 return false;
567}
568
569static bool symbolEndsScope(SymbolKind Kind) {
570 switch (Kind) {
571 case SymbolKind::S_END:
572 case SymbolKind::S_PROC_ID_END:
573 case SymbolKind::S_INLINESITE_END:
574 return true;
575 default:
576 break;
577 }
578 return false;
579}
580
581struct ScopeRecord {
582 ulittle32_t PtrParent;
583 ulittle32_t PtrEnd;
584};
585
586struct SymbolScope {
587 ScopeRecord *OpeningRecord;
588 uint32_t ScopeOffset;
589};
590
591static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
592 uint32_t CurOffset, CVSymbol &Sym) {
593 assert(symbolOpensScope(Sym.kind()));
594 SymbolScope S;
595 S.ScopeOffset = CurOffset;
596 S.OpeningRecord = const_cast<ScopeRecord *>(
597 reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
598 S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
599 Stack.push_back(S);
600}
601
602static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000603 uint32_t CurOffset, ObjFile *File) {
Reid Kleckner3f851922017-07-06 16:39:32 +0000604 if (Stack.empty()) {
605 warn("symbol scopes are not balanced in " + File->getName());
606 return;
607 }
608 SymbolScope S = Stack.pop_back_val();
609 S.OpeningRecord->PtrEnd = CurOffset;
610}
611
Zachary Turneree9906d2017-08-11 19:00:03 +0000612static bool symbolGoesInModuleStream(const CVSymbol &Sym) {
613 switch (Sym.kind()) {
614 case SymbolKind::S_GDATA32:
615 case SymbolKind::S_CONSTANT:
616 case SymbolKind::S_UDT:
617 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
618 // since they are synthesized by the linker in response to S_GPROC32 and
619 // S_LPROC32, but if we do see them, don't put them in the module stream I
620 // guess.
621 case SymbolKind::S_PROCREF:
622 case SymbolKind::S_LPROCREF:
623 return false;
624 // S_GDATA32 does not go in the module stream, but S_LDATA32 does.
625 case SymbolKind::S_LDATA32:
626 default:
627 return true;
628 }
629}
630
631static bool symbolGoesInGlobalsStream(const CVSymbol &Sym) {
632 switch (Sym.kind()) {
633 case SymbolKind::S_CONSTANT:
Zachary Turneree9906d2017-08-11 19:00:03 +0000634 case SymbolKind::S_GDATA32:
635 // S_LDATA32 goes in both the module stream and the globals stream.
636 case SymbolKind::S_LDATA32:
637 case SymbolKind::S_GPROC32:
638 case SymbolKind::S_LPROC32:
639 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
640 // since they are synthesized by the linker in response to S_GPROC32 and
641 // S_LPROC32, but if we do see them, copy them straight through.
642 case SymbolKind::S_PROCREF:
643 case SymbolKind::S_LPROCREF:
644 return true;
Zachary Turner302dc8b2017-08-14 18:44:58 +0000645 // FIXME: For now, we drop all S_UDT symbols (i.e. they don't go in the
646 // globals stream or the modules stream). These have special handling which
647 // needs more investigation before we can get right, but by putting them all
648 // into the globals stream WinDbg fails to display local variables of class
649 // types saying that it cannot find the type Foo *. So as a stopgap just to
650 // keep things working, we drop them.
651 case SymbolKind::S_UDT:
Zachary Turneree9906d2017-08-11 19:00:03 +0000652 default:
653 return false;
654 }
655}
656
657static void addGlobalSymbol(pdb::GSIStreamBuilder &Builder, ObjFile &File,
658 const CVSymbol &Sym) {
659 switch (Sym.kind()) {
660 case SymbolKind::S_CONSTANT:
661 case SymbolKind::S_UDT:
662 case SymbolKind::S_GDATA32:
663 case SymbolKind::S_LDATA32:
664 case SymbolKind::S_PROCREF:
665 case SymbolKind::S_LPROCREF:
666 Builder.addGlobalSymbol(Sym);
667 break;
668 case SymbolKind::S_GPROC32:
669 case SymbolKind::S_LPROC32: {
670 SymbolRecordKind K = SymbolRecordKind::ProcRefSym;
671 if (Sym.kind() == SymbolKind::S_LPROC32)
672 K = SymbolRecordKind::LocalProcRef;
673 ProcRefSym PS(K);
674 PS.Module = static_cast<uint16_t>(File.ModuleDBI->getModuleIndex());
675 // For some reason, MSVC seems to add one to this value.
676 ++PS.Module;
677 PS.Name = getSymbolName(Sym);
678 PS.SumName = 0;
679 PS.SymOffset = File.ModuleDBI->getNextSymbolOffset();
680 Builder.addGlobalSymbol(PS);
681 break;
682 }
683 default:
684 llvm_unreachable("Invalid symbol kind!");
685 }
686}
687
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000688static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjFile *File,
Zachary Turneree9906d2017-08-11 19:00:03 +0000689 pdb::GSIStreamBuilder &GsiBuilder,
Reid Kleckner651db912017-07-18 00:21:25 +0000690 const CVIndexMap &IndexMap,
Zachary Turner3e3936d2017-11-29 19:35:21 +0000691 TypeCollection &IDTable,
Zachary Turner60478582018-01-05 19:12:40 +0000692 std::vector<ulittle32_t *> &StringTableRefs,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000693 BinaryStreamRef SymData) {
694 // FIXME: Improve error recovery by warning and skipping records when
695 // possible.
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000696 ArrayRef<uint8_t> SymsBuffer;
697 cantFail(SymData.readBytes(0, SymData.getLength(), SymsBuffer));
Reid Kleckner3f851922017-07-06 16:39:32 +0000698 SmallVector<SymbolScope, 4> Scopes;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000699
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000700 auto EC = forEachCodeViewRecord<CVSymbol>(
701 SymsBuffer, [&](const CVSymbol &Sym) -> llvm::Error {
702 // Discover type index references in the record. Skip it if we don't
703 // know where they are.
704 SmallVector<TiReference, 32> TypeRefs;
705 if (!discoverTypeIndicesInSymbol(Sym, TypeRefs)) {
706 log("ignoring unknown symbol record with kind 0x" +
707 utohexstr(Sym.kind()));
708 return Error::success();
709 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000710
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000711 // Copy the symbol record so we can mutate it.
712 MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000713
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000714 // Re-map all the type index references.
715 MutableArrayRef<uint8_t> Contents =
716 NewData.drop_front(sizeof(RecordPrefix));
717 remapTypesInSymbolRecord(File, Sym.kind(), Contents, IndexMap,
718 TypeRefs);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000719
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000720 // An object file may have S_xxx_ID symbols, but these get converted to
721 // "real" symbols in a PDB.
722 translateIdSymbols(NewData, IDTable);
Zachary Turner60478582018-01-05 19:12:40 +0000723
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000724 // If this record refers to an offset in the object file's string table,
725 // add that item to the global PDB string table and re-write the index.
726 recordStringTableReferences(Sym.kind(), Contents, StringTableRefs);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000727
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000728 SymbolKind NewKind = symbolKind(NewData);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000729
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000730 // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
731 CVSymbol NewSym(NewKind, NewData);
732 if (symbolOpensScope(NewKind))
733 scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(),
734 NewSym);
735 else if (symbolEndsScope(NewKind))
736 scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
Zachary Turneree9906d2017-08-11 19:00:03 +0000737
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000738 // Add the symbol to the globals stream if necessary. Do this before
739 // adding the symbol to the module since we may need to get the next
740 // symbol offset, and writing to the module's symbol stream will update
741 // that offset.
742 if (symbolGoesInGlobalsStream(NewSym))
743 addGlobalSymbol(GsiBuilder, *File, NewSym);
744
745 // Add the symbol to the module.
746 if (symbolGoesInModuleStream(NewSym))
747 File->ModuleDBI->addSymbol(NewSym);
748 return Error::success();
749 });
750 cantFail(std::move(EC));
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000751}
752
Reid Kleckner44cdb102017-06-19 17:21:45 +0000753// Allocate memory for a .debug$S section and relocate it.
754static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
755 SectionChunk *DebugChunk) {
756 uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk->getSize());
757 assert(DebugChunk->OutputSectionOff == 0 &&
758 "debug sections should not be in output sections");
759 DebugChunk->writeTo(Buffer);
760 return consumeDebugMagic(makeArrayRef(Buffer, DebugChunk->getSize()),
761 ".debug$S");
762}
763
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000764void PDBLinker::addObjFile(ObjFile *File) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000765 // Add a module descriptor for every object file. We need to put an absolute
766 // path to the object into the PDB. If this is a plain object, we make its
767 // path absolute. If it's an object in an archive, we make the archive path
768 // absolute.
769 bool InArchive = !File->ParentName.empty();
770 SmallString<128> Path = InArchive ? File->ParentName : File->getName();
771 sys::fs::make_absolute(Path);
772 sys::path::native(Path, sys::path::Style::windows);
773 StringRef Name = InArchive ? File->getName() : StringRef(Path);
Zachary Turner2897e032017-05-25 21:16:03 +0000774
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000775 File->ModuleDBI = &ExitOnErr(Builder.getDbiBuilder().addModuleInfo(Name));
776 File->ModuleDBI->setObjFileName(Path);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000777
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000778 // Before we can process symbol substreams from .debug$S, we need to process
779 // type information, file checksums, and the string table. Add type info to
780 // the PDB first, so that we can get the map from object file type and item
781 // indices to PDB type and item indices.
Reid Kleckner651db912017-07-18 00:21:25 +0000782 CVIndexMap ObjectIndexMap;
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000783 auto IndexMapResult = mergeDebugT(File, ObjectIndexMap);
784
785 // If the .debug$T sections fail to merge, assume there is no debug info.
786 if (!IndexMapResult) {
787 warn("Type server PDB for " + Name + " is invalid, ignoring debug info. " +
788 toString(IndexMapResult.takeError()));
789 return;
790 }
791
792 const CVIndexMap &IndexMap = *IndexMapResult;
Zachary Turner448dea42017-07-07 18:46:14 +0000793
Zachary Turner727f1532018-01-17 19:16:26 +0000794 ScopedTimer T(SymbolMergingTimer);
795
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000796 // Now do all live .debug$S sections.
Zachary Turner60478582018-01-05 19:12:40 +0000797 DebugStringTableSubsectionRef CVStrTab;
798 DebugChecksumsSubsectionRef Checksums;
799 std::vector<ulittle32_t *> StringTableReferences;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000800 for (SectionChunk *DebugChunk : File->getDebugChunks()) {
801 if (!DebugChunk->isLive() || DebugChunk->getSectionName() != ".debug$S")
802 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000803
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000804 ArrayRef<uint8_t> RelocatedDebugContents =
805 relocateDebugChunk(Alloc, DebugChunk);
806 if (RelocatedDebugContents.empty())
807 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000808
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000809 DebugSubsectionArray Subsections;
810 BinaryStreamReader Reader(RelocatedDebugContents, support::little);
811 ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
Rui Ueyama52896622017-01-12 03:09:25 +0000812
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000813 for (const DebugSubsectionRecord &SS : Subsections) {
814 switch (SS.kind()) {
Zachary Turner60478582018-01-05 19:12:40 +0000815 case DebugSubsectionKind::StringTable: {
816 auto Data = SS.getRecordData();
817 ArrayRef<uint8_t> Buffer;
818 cantFail(Data.readLongestContiguousChunk(0, Buffer));
819 assert(!CVStrTab.valid() &&
820 "Encountered multiple string table subsections!");
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000821 ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
822 break;
Zachary Turner60478582018-01-05 19:12:40 +0000823 }
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000824 case DebugSubsectionKind::FileChecksums:
Zachary Turner60478582018-01-05 19:12:40 +0000825 assert(!Checksums.valid() &&
826 "Encountered multiple checksum subsections!");
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000827 ExitOnErr(Checksums.initialize(SS.getRecordData()));
828 break;
829 case DebugSubsectionKind::Lines:
830 // We can add the relocated line table directly to the PDB without
831 // modification because the file checksum offsets will stay the same.
832 File->ModuleDBI->addDebugSubsection(SS);
833 break;
834 case DebugSubsectionKind::Symbols:
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000835 if (Config->DebugGHashes) {
836 mergeSymbolRecords(Alloc, File, Builder.getGsiBuilder(), IndexMap,
Zachary Turner60478582018-01-05 19:12:40 +0000837 GlobalIDTable, StringTableReferences,
838 SS.getRecordData());
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000839 } else {
840 mergeSymbolRecords(Alloc, File, Builder.getGsiBuilder(), IndexMap,
Zachary Turner60478582018-01-05 19:12:40 +0000841 IDTable, StringTableReferences,
842 SS.getRecordData());
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000843 }
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000844 break;
845 default:
846 // FIXME: Process the rest of the subsections.
847 break;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000848 }
849 }
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000850 }
Zachary Turner60478582018-01-05 19:12:40 +0000851
852 // We should have seen all debug subsections across the entire object file now
853 // which means that if a StringTable subsection and Checksums subsection were
854 // present, now is the time to handle them.
855 if (!CVStrTab.valid()) {
856 if (Checksums.valid())
857 fatal(".debug$S sections with a checksums subsection must also contain a "
858 "string table subsection");
859
860 if (!StringTableReferences.empty())
861 warn("No StringTable subsection was encountered, but there are string "
862 "table references");
863 return;
864 }
865
866 // Rewrite each string table reference based on the value that the string
867 // assumes in the final PDB.
868 for (ulittle32_t *Ref : StringTableReferences) {
869 auto ExpectedString = CVStrTab.getString(*Ref);
870 if (!ExpectedString) {
871 warn("Invalid string table reference");
872 consumeError(ExpectedString.takeError());
873 continue;
874 }
875
876 *Ref = PDBStrTab.insert(*ExpectedString);
877 }
878
879 // Make a new file checksum table that refers to offsets in the PDB-wide
880 // string table. Generally the string table subsection appears after the
881 // checksum table, so we have to do this after looping over all the
882 // subsections.
883 auto NewChecksums = make_unique<DebugChecksumsSubsection>(PDBStrTab);
884 for (FileChecksumEntry &FC : Checksums) {
885 StringRef FileName = ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
886 ExitOnErr(Builder.getDbiBuilder().addModuleSourceFile(*File->ModuleDBI,
887 FileName));
888 NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
889 }
890 File->ModuleDBI->addDebugSubsection(std::move(NewChecksums));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000891}
892
Reid Klecknereacdf042017-07-27 18:25:59 +0000893static PublicSym32 createPublic(Defined *Def) {
894 PublicSym32 Pub(SymbolKind::S_PUB32);
895 Pub.Name = Def->getName();
896 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
897 if (D->getCOFFSymbol().isFunctionDefinition())
898 Pub.Flags = PublicSymFlags::Function;
899 } else if (isa<DefinedImportThunk>(Def)) {
900 Pub.Flags = PublicSymFlags::Function;
901 }
902
903 OutputSection *OS = Def->getChunk()->getOutputSection();
904 assert(OS && "all publics should be in final image");
905 Pub.Offset = Def->getRVA() - OS->getRVA();
906 Pub.Segment = OS->SectionIndex;
907 return Pub;
908}
909
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000910// Add all object files to the PDB. Merge .debug$T sections into IpiData and
911// TpiData.
912void PDBLinker::addObjectsToPDB() {
Zachary Turner727f1532018-01-17 19:16:26 +0000913 ScopedTimer T1(AddObjectsTimer);
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000914 for (ObjFile *File : ObjFile::Instances)
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000915 addObjFile(File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000916
917 Builder.getStringTableBuilder().setStrings(PDBStrTab);
Zachary Turner727f1532018-01-17 19:16:26 +0000918 T1.stop();
Reid Kleckner44cdb102017-06-19 17:21:45 +0000919
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000920 // Construct TPI and IPI stream contents.
Zachary Turner727f1532018-01-17 19:16:26 +0000921 ScopedTimer T2(TpiStreamLayoutTimer);
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000922 if (Config->DebugGHashes) {
923 addTypeInfo(Builder.getTpiBuilder(), GlobalTypeTable);
924 addTypeInfo(Builder.getIpiBuilder(), GlobalIDTable);
925 } else {
926 addTypeInfo(Builder.getTpiBuilder(), TypeTable);
927 addTypeInfo(Builder.getIpiBuilder(), IDTable);
928 }
Zachary Turner727f1532018-01-17 19:16:26 +0000929 T2.stop();
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000930
Zachary Turner727f1532018-01-17 19:16:26 +0000931 ScopedTimer T3(GlobalsLayoutTimer);
Zachary Turneree9906d2017-08-11 19:00:03 +0000932 // Compute the public and global symbols.
933 auto &GsiBuilder = Builder.getGsiBuilder();
Reid Klecknereacdf042017-07-27 18:25:59 +0000934 std::vector<PublicSym32> Publics;
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000935 Symtab->forEachSymbol([&Publics](Symbol *S) {
Reid Klecknereacdf042017-07-27 18:25:59 +0000936 // Only emit defined, live symbols that have a chunk.
Rui Ueyama616cd992017-10-31 16:10:24 +0000937 auto *Def = dyn_cast<Defined>(S);
Reid Klecknereacdf042017-07-27 18:25:59 +0000938 if (Def && Def->isLive() && Def->getChunk())
939 Publics.push_back(createPublic(Def));
940 });
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000941
Reid Klecknereacdf042017-07-27 18:25:59 +0000942 if (!Publics.empty()) {
943 // Sort the public symbols and add them to the stream.
944 std::sort(Publics.begin(), Publics.end(),
945 [](const PublicSym32 &L, const PublicSym32 &R) {
946 return L.Name < R.Name;
947 });
Reid Klecknereacdf042017-07-27 18:25:59 +0000948 for (const PublicSym32 &Pub : Publics)
Zachary Turner946204c2017-08-09 04:23:25 +0000949 GsiBuilder.addPublicSymbol(Pub);
Reid Klecknereacdf042017-07-27 18:25:59 +0000950 }
Rui Ueyama52896622017-01-12 03:09:25 +0000951}
952
Zachary Turner28e31ee2017-08-11 20:46:28 +0000953static void addCommonLinkerModuleSymbols(StringRef Path,
954 pdb::DbiModuleDescriptorBuilder &Mod,
955 BumpPtrAllocator &Allocator) {
Zachary Turner28e31ee2017-08-11 20:46:28 +0000956 ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
957 Compile3Sym CS(SymbolRecordKind::Compile3Sym);
958 EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000959
960 ONS.Name = "* Linker *";
961 ONS.Signature = 0;
962
963 CS.Machine = Config->is64() ? CPUType::X64 : CPUType::Intel80386;
Zachary Turnerb57884e2017-08-11 21:14:01 +0000964 // Interestingly, if we set the string to 0.0.0.0, then when trying to view
965 // local variables WinDbg emits an error that private symbols are not present.
966 // By setting this to a valid MSVC linker version string, local variables are
967 // displayed properly. As such, even though it is not representative of
Zachary Turnerf6822c82017-08-11 20:46:47 +0000968 // LLVM's version information, we need this for compatibility.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000969 CS.Flags = CompileSym3Flags::None;
Zachary Turnerf6822c82017-08-11 20:46:47 +0000970 CS.VersionBackendBuild = 25019;
971 CS.VersionBackendMajor = 14;
972 CS.VersionBackendMinor = 10;
Zachary Turner6708e0b2017-07-10 21:01:37 +0000973 CS.VersionBackendQFE = 0;
Zachary Turnerf6822c82017-08-11 20:46:47 +0000974
975 // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
976 // linker module (which is by definition a backend), so we don't need to do
977 // anything here. Also, it seems we can use "LLVM Linker" for the linker name
978 // without any problems. Only the backend version has to be hardcoded to a
979 // magic number.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000980 CS.VersionFrontendBuild = 0;
981 CS.VersionFrontendMajor = 0;
982 CS.VersionFrontendMinor = 0;
983 CS.VersionFrontendQFE = 0;
984 CS.Version = "LLVM Linker";
985 CS.setLanguage(SourceLanguage::Link);
986
987 ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
988 std::string ArgStr = llvm::join(Args, " ");
989 EBS.Fields.push_back("cwd");
990 SmallString<64> cwd;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000991 sys::fs::current_path(cwd);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000992 EBS.Fields.push_back(cwd);
993 EBS.Fields.push_back("exe");
Zachary Turnerf6822c82017-08-11 20:46:47 +0000994 SmallString<64> exe = Config->Argv[0];
995 llvm::sys::fs::make_absolute(exe);
996 EBS.Fields.push_back(exe);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000997 EBS.Fields.push_back("pdb");
998 EBS.Fields.push_back(Path);
999 EBS.Fields.push_back("cmd");
1000 EBS.Fields.push_back(ArgStr);
1001 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1002 ONS, Allocator, CodeViewContainer::Pdb));
1003 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1004 CS, Allocator, CodeViewContainer::Pdb));
1005 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1006 EBS, Allocator, CodeViewContainer::Pdb));
1007}
1008
Zachary Turner28e31ee2017-08-11 20:46:28 +00001009static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &Mod,
1010 OutputSection &OS,
1011 BumpPtrAllocator &Allocator) {
1012 SectionSym Sym(SymbolRecordKind::SectionSym);
Zachary Turnerf6822c82017-08-11 20:46:47 +00001013 Sym.Alignment = 12; // 2^12 = 4KB
Zachary Turner28e31ee2017-08-11 20:46:28 +00001014 Sym.Characteristics = OS.getCharacteristics();
1015 Sym.Length = OS.getVirtualSize();
1016 Sym.Name = OS.getName();
1017 Sym.Rva = OS.getRVA();
1018 Sym.SectionNumber = OS.SectionIndex;
1019 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1020 Sym, Allocator, CodeViewContainer::Pdb));
1021}
1022
Rui Ueyama09e0b5f2016-11-12 00:00:51 +00001023// Creates a PDB file.
Reid Kleckner175af4b2017-08-03 21:15:09 +00001024void coff::createPDB(SymbolTable *Symtab,
1025 ArrayRef<OutputSection *> OutputSections,
1026 ArrayRef<uint8_t> SectionTable,
Zachary Turner024323c2017-08-15 21:31:41 +00001027 const llvm::codeview::DebugInfo &BuildId) {
Zachary Turner727f1532018-01-17 19:16:26 +00001028 ScopedTimer T1(TotalPdbLinkTimer);
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001029 PDBLinker PDB(Symtab);
Zachary Turner024323c2017-08-15 21:31:41 +00001030 PDB.initialize(BuildId);
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001031 PDB.addObjectsToPDB();
Reid Kleckner175af4b2017-08-03 21:15:09 +00001032 PDB.addSections(OutputSections, SectionTable);
Zachary Turner727f1532018-01-17 19:16:26 +00001033
1034 ScopedTimer T2(DiskCommitTimer);
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001035 PDB.commit();
1036}
1037
Zachary Turner024323c2017-08-15 21:31:41 +00001038void PDBLinker::initialize(const llvm::codeview::DebugInfo &BuildId) {
Rui Ueyama12979542016-09-30 20:53:45 +00001039 ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
Rui Ueyama7f382992016-09-15 18:55:18 +00001040
Rui Ueyama8d3fb5d2016-10-05 22:08:58 +00001041 // Create streams in MSF for predefined streams, namely
1042 // PDB, TPI, DBI and IPI.
1043 for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
1044 ExitOnErr(Builder.getMsfBuilder().addStream(0));
Rui Ueyama7f382992016-09-15 18:55:18 +00001045
Rui Ueyamabb542b32016-09-16 22:51:17 +00001046 // Add an Info stream.
1047 auto &InfoBuilder = Builder.getInfoBuilder();
Zachary Turner024323c2017-08-15 21:31:41 +00001048 InfoBuilder.setAge(BuildId.PDB70.Age);
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +00001049
Zachary Turner024323c2017-08-15 21:31:41 +00001050 GUID uuid;
1051 memcpy(&uuid, &BuildId.PDB70.Signature, sizeof(uuid));
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +00001052 InfoBuilder.setGuid(uuid);
Zachary Turner3a11fdf2017-07-07 20:25:39 +00001053 InfoBuilder.setSignature(time(nullptr));
Rui Ueyamabb542b32016-09-16 22:51:17 +00001054 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
Rui Ueyama7f382992016-09-15 18:55:18 +00001055
Zachary Turner6c4bfba2017-07-07 05:04:36 +00001056 // Add an empty DBI stream.
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +00001057 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Zachary Turner024323c2017-08-15 21:31:41 +00001058 DbiBuilder.setAge(BuildId.PDB70.Age);
Zachary Turnerc1e93e52017-07-07 18:45:56 +00001059 DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
Zachary Turner3a11fdf2017-07-07 20:25:39 +00001060 ExitOnErr(DbiBuilder.addDbgStream(pdb::DbgHeaderType::NewFPO, {}));
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001061}
Rui Ueyama1343fac2016-10-06 22:52:01 +00001062
Reid Kleckner175af4b2017-08-03 21:15:09 +00001063void PDBLinker::addSectionContrib(pdb::DbiModuleDescriptorBuilder &LinkerModule,
1064 OutputSection *OS, Chunk *C) {
1065 pdb::SectionContrib SC;
1066 memset(&SC, 0, sizeof(SC));
1067 SC.ISect = OS->SectionIndex;
1068 SC.Off = C->getRVA() - OS->getRVA();
1069 SC.Size = C->getSize();
1070 if (auto *SecChunk = dyn_cast<SectionChunk>(C)) {
1071 SC.Characteristics = SecChunk->Header->Characteristics;
1072 SC.Imod = SecChunk->File->ModuleDBI->getModuleIndex();
Zachary Turner676386ff2017-08-07 20:23:45 +00001073 ArrayRef<uint8_t> Contents = SecChunk->getContents();
1074 JamCRC CRC(0);
1075 ArrayRef<char> CharContents = makeArrayRef(
1076 reinterpret_cast<const char *>(Contents.data()), Contents.size());
1077 CRC.update(CharContents);
1078 SC.DataCrc = CRC.getCRC();
Reid Kleckner175af4b2017-08-03 21:15:09 +00001079 } else {
1080 SC.Characteristics = OS->getCharacteristics();
1081 // FIXME: When we start creating DBI for import libraries, use those here.
1082 SC.Imod = LinkerModule.getModuleIndex();
1083 }
Reid Kleckner175af4b2017-08-03 21:15:09 +00001084 SC.RelocCrc = 0; // FIXME
1085 Builder.getDbiBuilder().addSectionContrib(SC);
1086}
Rui Ueyama09e0b5f2016-11-12 00:00:51 +00001087
Reid Kleckner175af4b2017-08-03 21:15:09 +00001088void PDBLinker::addSections(ArrayRef<OutputSection *> OutputSections,
1089 ArrayRef<uint8_t> SectionTable) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001090 // It's not entirely clear what this is, but the * Linker * module uses it.
Reid Kleckner175af4b2017-08-03 21:15:09 +00001091 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001092 NativePath = Config->PDBPath;
1093 sys::fs::make_absolute(NativePath);
1094 sys::path::native(NativePath, sys::path::Style::windows);
1095 uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
Zachary Turner6c4bfba2017-07-07 05:04:36 +00001096 auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
1097 LinkerModule.setPdbFilePathNI(PdbFilePathNI);
Zachary Turner28e31ee2017-08-11 20:46:28 +00001098 addCommonLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
Rui Ueyamac91f7162016-11-16 01:10:46 +00001099
Reid Kleckner175af4b2017-08-03 21:15:09 +00001100 // Add section contributions. They must be ordered by ascending RVA.
Zachary Turner28e31ee2017-08-11 20:46:28 +00001101 for (OutputSection *OS : OutputSections) {
1102 addLinkerModuleSectionSymbol(LinkerModule, *OS, Alloc);
Reid Kleckner175af4b2017-08-03 21:15:09 +00001103 for (Chunk *C : OS->getChunks())
1104 addSectionContrib(LinkerModule, OS, C);
Zachary Turner28e31ee2017-08-11 20:46:28 +00001105 }
Reid Kleckner175af4b2017-08-03 21:15:09 +00001106
1107 // Add Section Map stream.
1108 ArrayRef<object::coff_section> Sections = {
1109 (const object::coff_section *)SectionTable.data(),
1110 SectionTable.size() / sizeof(object::coff_section)};
1111 SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
1112 DbiBuilder.setSectionMap(SectionMap);
1113
Rui Ueyama9f66f822016-10-11 19:45:07 +00001114 // Add COFF section header stream.
1115 ExitOnErr(
1116 DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001117}
Rui Ueyama9f66f822016-10-11 19:45:07 +00001118
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001119void PDBLinker::commit() {
Rui Ueyama3e9d6bb2016-09-26 23:53:55 +00001120 // Write to a file.
Zachary Turner6708e0b2017-07-10 21:01:37 +00001121 ExitOnErr(Builder.commit(Config->PDBPath));
Rui Ueyamae7378242015-12-04 23:11:05 +00001122}