blob: 9a9ad48c26feb71f3375b2f3fe3881cda0042839 [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"
Zachary Turner42e7cc1b2018-09-11 22:35:01 +000019#include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.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"
David Blaikieddcd8562018-03-26 23:43:29 +000049#include "llvm/Object/CVDebugRecord.h"
Zachary Turnerd9dc2822017-03-02 20:52:51 +000050#include "llvm/Support/BinaryByteStream.h"
Rui Ueyama1763c0d2015-12-08 18:39:55 +000051#include "llvm/Support/Endian.h"
Zachary Turner60478582018-01-05 19:12:40 +000052#include "llvm/Support/FormatVariadic.h"
Zachary Turner676386ff2017-08-07 20:23:45 +000053#include "llvm/Support/JamCRC.h"
Zachary Turner7b327d02017-02-16 23:35:45 +000054#include "llvm/Support/Path.h"
Rui Ueyamabe939b32016-11-21 17:22:35 +000055#include "llvm/Support/ScopedPrinter.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000056#include <memory>
57
Rui Ueyama1d99ab32016-09-15 22:24:51 +000058using namespace lld;
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000059using namespace lld::coff;
Rui Ueyamae7378242015-12-04 23:11:05 +000060using namespace llvm;
Rui Ueyamabe939b32016-11-21 17:22:35 +000061using namespace llvm::codeview;
Rui Ueyamae7378242015-12-04 23:11:05 +000062
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000063using llvm::object::coff_section;
64
Rui Ueyamab28c6d42016-09-16 04:32:33 +000065static ExitOnError ExitOnErr;
66
Zachary Turner727f1532018-01-17 19:16:26 +000067static Timer TotalPdbLinkTimer("PDB Emission (Cumulative)", Timer::root());
68
69static Timer AddObjectsTimer("Add Objects", TotalPdbLinkTimer);
70static Timer TypeMergingTimer("Type Merging", AddObjectsTimer);
71static Timer SymbolMergingTimer("Symbol Merging", AddObjectsTimer);
72static Timer GlobalsLayoutTimer("Globals Stream Layout", TotalPdbLinkTimer);
73static Timer TpiStreamLayoutTimer("TPI Stream Layout", TotalPdbLinkTimer);
74static Timer DiskCommitTimer("Commit to Disk", TotalPdbLinkTimer);
75
Reid Kleckner0faf6d72017-07-14 00:14:58 +000076namespace {
Reid Kleckner651db912017-07-18 00:21:25 +000077/// Map from type index and item index in a type server PDB to the
78/// corresponding index in the destination PDB.
79struct CVIndexMap {
80 SmallVector<TypeIndex, 0> TPIMap;
81 SmallVector<TypeIndex, 0> IPIMap;
82 bool IsTypeServerMap = false;
83};
84
Reid Kleckner0faf6d72017-07-14 00:14:58 +000085class PDBLinker {
86public:
87 PDBLinker(SymbolTable *Symtab)
Sam Cleggea244bf2017-12-14 21:09:31 +000088 : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
Zachary Turnera6fb5362018-03-23 18:43:39 +000089 IDTable(Alloc), GlobalTypeTable(Alloc), GlobalIDTable(Alloc) {
90 // This isn't strictly necessary, but link.exe usually puts an empty string
91 // as the first "valid" string in the string table, so we do the same in
92 // order to maintain as much byte-for-byte compatibility as possible.
93 PDBStrTab.insert("");
94 }
Reid Kleckner0faf6d72017-07-14 00:14:58 +000095
96 /// Emit the basic PDB structure: initial streams, headers, etc.
Zachary Turner024323c2017-08-15 21:31:41 +000097 void initialize(const llvm::codeview::DebugInfo &BuildId);
Reid Kleckner0faf6d72017-07-14 00:14:58 +000098
Zachary Turnerf2282762018-03-23 19:57:25 +000099 /// Add natvis files specified on the command line.
100 void addNatvisFiles();
101
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000102 /// Link CodeView from each object file in the symbol table into the PDB.
103 void addObjectsToPDB();
104
105 /// Link CodeView from a single object file into the PDB.
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000106 void addObjFile(ObjFile *File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000107
Reid Kleckner651db912017-07-18 00:21:25 +0000108 /// Produce a mapping from the type and item indices used in the object
109 /// file to those in the destination PDB.
110 ///
111 /// If the object file uses a type server PDB (compiled with /Zi), merge TPI
112 /// and IPI from the type server PDB and return a map for it. Each unique type
113 /// server PDB is merged at most once, so this may return an existing index
114 /// mapping.
115 ///
116 /// If the object does not use a type server PDB (compiled with /Z7), we merge
117 /// all the type and item records from the .debug$S stream and fill in the
118 /// caller-provided ObjectIndexMap.
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000119 Expected<const CVIndexMap&> mergeDebugT(ObjFile *File,
120 CVIndexMap &ObjectIndexMap);
Reid Kleckner651db912017-07-18 00:21:25 +0000121
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000122 Expected<const CVIndexMap&> maybeMergeTypeServerPDB(ObjFile *File,
123 TypeServer2Record &TS);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000124
125 /// Add the section map and section contributions to the PDB.
Reid Kleckner175af4b2017-08-03 21:15:09 +0000126 void addSections(ArrayRef<OutputSection *> OutputSections,
127 ArrayRef<uint8_t> SectionTable);
128
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000129 /// Write the PDB to disk.
130 void commit();
131
132private:
133 BumpPtrAllocator Alloc;
134
135 SymbolTable *Symtab;
136
137 pdb::PDBFileBuilder Builder;
138
139 /// Type records that will go into the PDB TPI stream.
Zachary Turnerca6dbf12017-11-30 18:39:50 +0000140 MergingTypeTableBuilder TypeTable;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000141
142 /// Item records that will go into the PDB IPI stream.
Zachary Turnerca6dbf12017-11-30 18:39:50 +0000143 MergingTypeTableBuilder IDTable;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000144
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000145 /// Type records that will go into the PDB TPI stream (for /DEBUG:GHASH)
146 GlobalTypeTableBuilder GlobalTypeTable;
147
148 /// Item records that will go into the PDB IPI stream (for /DEBUG:GHASH)
149 GlobalTypeTableBuilder GlobalIDTable;
150
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000151 /// PDBs use a single global string table for filenames in the file checksum
152 /// table.
153 DebugStringTableSubsection PDBStrTab;
154
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000155 llvm::SmallString<128> NativePath;
156
Zachary Turner3868cfd2018-02-28 18:09:18 +0000157 /// A list of other PDBs which are loaded during the linking process and which
158 /// we need to keep around since the linking operation may reference pointers
159 /// inside of these PDBs.
160 llvm::SmallVector<std::unique_ptr<pdb::NativeSession>, 2> LoadedPDBs;
161
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000162 std::vector<pdb::SecMapEntry> SectionMap;
Reid Kleckner651db912017-07-18 00:21:25 +0000163
164 /// Type index mappings of type server PDBs that we've loaded so far.
165 std::map<GUID, CVIndexMap> TypeServerIndexMappings;
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000166
167 /// List of TypeServer PDBs which cannot be loaded.
168 /// Cached to prevent repeated load attempts.
Alexandre Ganead93b07f2018-09-10 13:51:21 +0000169 std::map<GUID, std::string> MissingTypeServerPDBs;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000170};
171}
172
Sam Clegg0fb6faa2017-12-08 01:09:21 +0000173static SectionChunk *findByName(ArrayRef<SectionChunk *> Sections,
Rui Ueyamabe939b32016-11-21 17:22:35 +0000174 StringRef Name) {
175 for (SectionChunk *C : Sections)
176 if (C->getSectionName() == Name)
177 return C;
178 return nullptr;
179}
180
Reid Kleckner44cdb102017-06-19 17:21:45 +0000181static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
182 StringRef SecName) {
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000183 // First 4 bytes are section magic.
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000184 if (Data.size() < 4)
Rui Ueyama52896622017-01-12 03:09:25 +0000185 fatal(SecName + " too short");
Reid Kleckner44cdb102017-06-19 17:21:45 +0000186 if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
Rui Ueyama52896622017-01-12 03:09:25 +0000187 fatal(SecName + " has an invalid magic");
Rui Ueyama26186c72016-12-09 04:46:54 +0000188 return Data.slice(4);
189}
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000190
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000191static ArrayRef<uint8_t> getDebugSection(ObjFile *File, StringRef SecName) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000192 if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
193 return consumeDebugMagic(Sec->getContents(), SecName);
194 return {};
195}
196
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000197// A COFF .debug$H section is currently a clang extension. This function checks
198// if a .debug$H section is in a format that we expect / understand, so that we
199// can ignore any sections which are coincidentally also named .debug$H but do
200// not contain a format we recognize.
201static bool canUseDebugH(ArrayRef<uint8_t> DebugH) {
202 if (DebugH.size() < sizeof(object::debug_h_header))
203 return false;
204 auto *Header =
205 reinterpret_cast<const object::debug_h_header *>(DebugH.data());
206 DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
207 return Header->Magic == COFF::DEBUG_HASHES_SECTION_MAGIC &&
208 Header->Version == 0 &&
Zachary Turnerc7626662018-05-17 22:55:15 +0000209 Header->HashAlgorithm == uint16_t(GlobalTypeHashAlg::SHA1_8) &&
210 (DebugH.size() % 8 == 0);
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000211}
212
213static Optional<ArrayRef<uint8_t>> getDebugH(ObjFile *File) {
214 SectionChunk *Sec = findByName(File->getDebugChunks(), ".debug$H");
215 if (!Sec)
216 return llvm::None;
217 ArrayRef<uint8_t> Contents = Sec->getContents();
218 if (!canUseDebugH(Contents))
219 return None;
220 return Contents;
221}
222
223static ArrayRef<GloballyHashedType>
224getHashesFromDebugH(ArrayRef<uint8_t> DebugH) {
225 assert(canUseDebugH(DebugH));
226
227 DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
228 uint32_t Count = DebugH.size() / sizeof(GloballyHashedType);
229 return {reinterpret_cast<const GloballyHashedType *>(DebugH.data()), Count};
230}
231
Reid Kleckner5d577522017-03-24 17:26:38 +0000232static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
Zachary Turner3e3936d2017-11-29 19:35:21 +0000233 TypeCollection &TypeTable) {
Reid Kleckner5d577522017-03-24 17:26:38 +0000234 // Start the TPI or IPI stream header.
235 TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
Rui Ueyama52896622017-01-12 03:09:25 +0000236
Reid Klecknerd91ca762017-07-19 17:26:07 +0000237 // Flatten the in memory type table and hash each type.
Zachary Turner3e3936d2017-11-29 19:35:21 +0000238 TypeTable.ForEachRecord([&](TypeIndex TI, const CVType &Type) {
Reid Klecknerd91ca762017-07-19 17:26:07 +0000239 auto Hash = pdb::hashTypeRecord(Type);
240 if (auto E = Hash.takeError())
241 fatal("type hashing error");
Zachary Turner3e3936d2017-11-29 19:35:21 +0000242 TpiBuilder.addTypeRecord(Type.RecordData, *Hash);
Reid Kleckner5d577522017-03-24 17:26:38 +0000243 });
Reid Kleckner5d577522017-03-24 17:26:38 +0000244}
245
Reid Kleckner651db912017-07-18 00:21:25 +0000246static Optional<TypeServer2Record>
247maybeReadTypeServerRecord(CVTypeArray &Types) {
248 auto I = Types.begin();
249 if (I == Types.end())
250 return None;
251 const CVType &Type = *I;
252 if (Type.kind() != LF_TYPESERVER2)
253 return None;
254 TypeServer2Record TS;
255 if (auto EC = TypeDeserializer::deserializeAs(const_cast<CVType &>(Type), TS))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000256 fatal("error reading type server record: " + toString(std::move(EC)));
Reid Kleckner651db912017-07-18 00:21:25 +0000257 return std::move(TS);
258}
259
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000260Expected<const CVIndexMap&> PDBLinker::mergeDebugT(ObjFile *File,
261 CVIndexMap &ObjectIndexMap) {
Zachary Turner727f1532018-01-17 19:16:26 +0000262 ScopedTimer T(TypeMergingTimer);
263
Reid Kleckner44cdb102017-06-19 17:21:45 +0000264 ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
265 if (Data.empty())
Reid Kleckner651db912017-07-18 00:21:25 +0000266 return ObjectIndexMap;
Reid Kleckner6597c282017-07-13 20:12:23 +0000267
Reid Kleckner44cdb102017-06-19 17:21:45 +0000268 BinaryByteStream Stream(Data, support::little);
269 CVTypeArray Types;
270 BinaryStreamReader Reader(Stream);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000271 if (auto EC = Reader.readArray(Types, Reader.getLength()))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000272 fatal("Reader::readArray failed: " + toString(std::move(EC)));
Reid Kleckner651db912017-07-18 00:21:25 +0000273
274 // Look through type servers. If we've already seen this type server, don't
275 // merge any type information.
276 if (Optional<TypeServer2Record> TS = maybeReadTypeServerRecord(Types))
277 return maybeMergeTypeServerPDB(File, *TS);
278
279 // This is a /Z7 object. Fill in the temporary, caller-provided
280 // ObjectIndexMap.
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000281 if (Config->DebugGHashes) {
282 ArrayRef<GloballyHashedType> Hashes;
283 std::vector<GloballyHashedType> OwnedHashes;
284 if (Optional<ArrayRef<uint8_t>> DebugH = getDebugH(File))
285 Hashes = getHashesFromDebugH(*DebugH);
286 else {
287 OwnedHashes = GloballyHashedType::hashTypes(Types);
288 Hashes = OwnedHashes;
289 }
290
291 if (auto Err = mergeTypeAndIdRecords(GlobalIDTable, GlobalTypeTable,
292 ObjectIndexMap.TPIMap, Types, Hashes))
293 fatal("codeview::mergeTypeAndIdRecords failed: " +
294 toString(std::move(Err)));
295 } else {
296 if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable,
297 ObjectIndexMap.TPIMap, Types))
298 fatal("codeview::mergeTypeAndIdRecords failed: " +
299 toString(std::move(Err)));
300 }
Reid Kleckner651db912017-07-18 00:21:25 +0000301 return ObjectIndexMap;
302}
303
304static Expected<std::unique_ptr<pdb::NativeSession>>
305tryToLoadPDB(const GUID &GuidFromObj, StringRef TSPath) {
Peter Collingbourne75257bc2017-10-20 19:48:26 +0000306 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(
307 TSPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
308 if (!MBOrErr)
309 return errorCodeToError(MBOrErr.getError());
310
Reid Kleckner651db912017-07-18 00:21:25 +0000311 std::unique_ptr<pdb::IPDBSession> ThisSession;
Peter Collingbourne75257bc2017-10-20 19:48:26 +0000312 if (auto EC = pdb::NativeSession::createFromPdb(
313 MemoryBuffer::getMemBuffer(Driver->takeBuffer(std::move(*MBOrErr)),
314 /*RequiresNullTerminator=*/false),
315 ThisSession))
Reid Kleckner651db912017-07-18 00:21:25 +0000316 return std::move(EC);
317
318 std::unique_ptr<pdb::NativeSession> NS(
319 static_cast<pdb::NativeSession *>(ThisSession.release()));
320 pdb::PDBFile &File = NS->getPDBFile();
321 auto ExpectedInfo = File.getPDBInfoStream();
322 // All PDB Files should have an Info stream.
323 if (!ExpectedInfo)
324 return ExpectedInfo.takeError();
325
326 // Just because a file with a matching name was found and it was an actual
327 // PDB file doesn't mean it matches. For it to match the InfoStream's GUID
328 // must match the GUID specified in the TypeServer2 record.
329 if (ExpectedInfo->getGuid() != GuidFromObj)
Alexandre Ganead93b07f2018-09-10 13:51:21 +0000330 return make_error<pdb::PDBError>(pdb::pdb_error_code::signature_out_of_date);
Reid Kleckner651db912017-07-18 00:21:25 +0000331
332 return std::move(NS);
333}
334
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000335Expected<const CVIndexMap&> PDBLinker::maybeMergeTypeServerPDB(ObjFile *File,
336 TypeServer2Record &TS) {
Alexandre Ganead93b07f2018-09-10 13:51:21 +0000337 const GUID &TSId = TS.getGuid();
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000338 StringRef TSPath = TS.getName();
339
340 // First, check if the PDB has previously failed to load.
Alexandre Ganead93b07f2018-09-10 13:51:21 +0000341 auto PrevErr = MissingTypeServerPDBs.find(TSId);
342 if (PrevErr != MissingTypeServerPDBs.end())
343 return createFileError(
Alexandre Ganea472e9b0a2018-09-10 14:07:11 +0000344 TSPath,
345 make_error<StringError>(PrevErr->second, inconvertibleErrorCode()));
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000346
347 // Second, check if we already loaded a PDB with this GUID. Return the type
Reid Kleckner651db912017-07-18 00:21:25 +0000348 // index mapping if we have it.
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000349 auto Insertion = TypeServerIndexMappings.insert({TSId, CVIndexMap()});
Reid Kleckner651db912017-07-18 00:21:25 +0000350 CVIndexMap &IndexMap = Insertion.first->second;
351 if (!Insertion.second)
352 return IndexMap;
353
354 // Mark this map as a type server map.
355 IndexMap.IsTypeServerMap = true;
356
357 // Check for a PDB at:
358 // 1. The given file path
359 // 2. Next to the object file or archive file
Alexandre Ganead93b07f2018-09-10 13:51:21 +0000360 auto ExpectedSession = handleExpected(
361 tryToLoadPDB(TSId, TSPath),
362 [&]() {
363 StringRef LocalPath =
364 !File->ParentName.empty() ? File->ParentName : File->getName();
365 SmallString<128> Path = sys::path::parent_path(LocalPath);
366 sys::path::append(
367 Path, sys::path::filename(TSPath, sys::path::Style::windows));
368 return tryToLoadPDB(TSId, Path);
369 },
370 [&](std::unique_ptr<ECError> EC) -> Error {
371 auto SysErr = EC->convertToErrorCode();
372 // Only re-try loading if the previous error was "No such file or
373 // directory"
374 if (SysErr.category() == std::generic_category() &&
375 SysErr.value() == ENOENT)
376 return Error::success();
377 return Error(std::move(EC));
378 });
379
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000380 if (auto E = ExpectedSession.takeError()) {
381 TypeServerIndexMappings.erase(TSId);
Alexandre Ganead93b07f2018-09-10 13:51:21 +0000382
383 // Flatten the error to a string, for later display, if the error occurs
384 // again on the same PDB.
385 std::string ErrMsg;
386 raw_string_ostream S(ErrMsg);
387 S << E;
Alexandre Ganea472e9b0a2018-09-10 14:07:11 +0000388 MissingTypeServerPDBs.emplace(TSId, S.str());
Alexandre Ganead93b07f2018-09-10 13:51:21 +0000389
390 return createFileError(TSPath, std::move(E));
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000391 }
Reid Kleckner651db912017-07-18 00:21:25 +0000392
Zachary Turner3868cfd2018-02-28 18:09:18 +0000393 pdb::NativeSession *Session = ExpectedSession->get();
394
395 // Keep a strong reference to this PDB, so that it's safe to hold pointers
396 // into the file.
397 LoadedPDBs.push_back(std::move(*ExpectedSession));
398
399 auto ExpectedTpi = Session->getPDBFile().getPDBTpiStream();
Reid Kleckner651db912017-07-18 00:21:25 +0000400 if (auto E = ExpectedTpi.takeError())
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000401 fatal("Type server does not have TPI stream: " + toString(std::move(E)));
Zachary Turner3868cfd2018-02-28 18:09:18 +0000402 auto ExpectedIpi = Session->getPDBFile().getPDBIpiStream();
Reid Kleckner651db912017-07-18 00:21:25 +0000403 if (auto E = ExpectedIpi.takeError())
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000404 fatal("Type server does not have TPI stream: " + toString(std::move(E)));
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000405
406 if (Config->DebugGHashes) {
407 // PDBs do not actually store global hashes, so when merging a type server
408 // PDB we have to synthesize global hashes. To do this, we first synthesize
409 // global hashes for the TPI stream, since it is independent, then we
410 // synthesize hashes for the IPI stream, using the hashes for the TPI stream
411 // as inputs.
412 auto TpiHashes = GloballyHashedType::hashTypes(ExpectedTpi->typeArray());
413 auto IpiHashes =
414 GloballyHashedType::hashIds(ExpectedIpi->typeArray(), TpiHashes);
415
416 // Merge TPI first, because the IPI stream will reference type indices.
417 if (auto Err = mergeTypeRecords(GlobalTypeTable, IndexMap.TPIMap,
418 ExpectedTpi->typeArray(), TpiHashes))
419 fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
420
421 // Merge IPI.
422 if (auto Err =
423 mergeIdRecords(GlobalIDTable, IndexMap.TPIMap, IndexMap.IPIMap,
424 ExpectedIpi->typeArray(), IpiHashes))
425 fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
426 } else {
427 // Merge TPI first, because the IPI stream will reference type indices.
428 if (auto Err = mergeTypeRecords(TypeTable, IndexMap.TPIMap,
429 ExpectedTpi->typeArray()))
430 fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
431
432 // Merge IPI.
433 if (auto Err = mergeIdRecords(IDTable, IndexMap.TPIMap, IndexMap.IPIMap,
434 ExpectedIpi->typeArray()))
435 fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
436 }
Reid Kleckner651db912017-07-18 00:21:25 +0000437
438 return IndexMap;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000439}
440
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000441static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
442 if (TI.isSimple())
443 return true;
444 if (TI.toArrayIndex() >= TypeIndexMap.size())
445 return false;
446 TI = TypeIndexMap[TI.toArrayIndex()];
447 return true;
448}
449
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000450static void remapTypesInSymbolRecord(ObjFile *File, SymbolKind SymKind,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000451 MutableArrayRef<uint8_t> Contents,
Reid Kleckner651db912017-07-18 00:21:25 +0000452 const CVIndexMap &IndexMap,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000453 ArrayRef<TiReference> TypeRefs) {
454 for (const TiReference &Ref : TypeRefs) {
455 unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000456 if (Contents.size() < Ref.Offset + ByteSize)
457 fatal("symbol record too short");
Reid Kleckner651db912017-07-18 00:21:25 +0000458
459 // This can be an item index or a type index. Choose the appropriate map.
460 ArrayRef<TypeIndex> TypeOrItemMap = IndexMap.TPIMap;
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000461 bool IsItemIndex = Ref.Kind == TiRefKind::IndexRef;
462 if (IsItemIndex && IndexMap.IsTypeServerMap)
Reid Kleckner651db912017-07-18 00:21:25 +0000463 TypeOrItemMap = IndexMap.IPIMap;
464
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000465 MutableArrayRef<TypeIndex> TIs(
466 reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000467 for (TypeIndex &TI : TIs) {
Reid Kleckner651db912017-07-18 00:21:25 +0000468 if (!remapTypeIndex(TI, TypeOrItemMap)) {
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000469 log("ignoring symbol record of kind 0x" + utohexstr(SymKind) + " in " +
470 File->getName() + " with bad " + (IsItemIndex ? "item" : "type") +
471 " index 0x" + utohexstr(TI.getIndex()));
Reid Kleckner5d82f682017-10-23 22:44:51 +0000472 TI = TypeIndex(SimpleTypeKind::NotTranslated);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000473 continue;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000474 }
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000475 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000476 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000477}
478
Zachary Turner60478582018-01-05 19:12:40 +0000479static void
480recordStringTableReferenceAtOffset(MutableArrayRef<uint8_t> Contents,
481 uint32_t Offset,
482 std::vector<ulittle32_t *> &StrTableRefs) {
483 Contents =
484 Contents.drop_front(Offset).take_front(sizeof(support::ulittle32_t));
485 ulittle32_t *Index = reinterpret_cast<ulittle32_t *>(Contents.data());
486 StrTableRefs.push_back(Index);
487}
488
489static void
490recordStringTableReferences(SymbolKind Kind, MutableArrayRef<uint8_t> Contents,
491 std::vector<ulittle32_t *> &StrTableRefs) {
492 // For now we only handle S_FILESTATIC, but we may need the same logic for
493 // S_DEFRANGE and S_DEFRANGE_SUBFIELD. However, I cannot seem to generate any
494 // PDBs that contain these types of records, so because of the uncertainty
495 // they are omitted here until we can prove that it's necessary.
496 switch (Kind) {
497 case SymbolKind::S_FILESTATIC:
498 // FileStaticSym::ModFileOffset
499 recordStringTableReferenceAtOffset(Contents, 4, StrTableRefs);
500 break;
501 case SymbolKind::S_DEFRANGE:
502 case SymbolKind::S_DEFRANGE_SUBFIELD:
503 log("Not fixing up string table reference in S_DEFRANGE / "
504 "S_DEFRANGE_SUBFIELD record");
505 break;
Zachary Turner9e52e502018-01-05 19:28:39 +0000506 default:
507 break;
Zachary Turner60478582018-01-05 19:12:40 +0000508 }
509}
510
Zachary Turner59e3ae82017-08-08 18:34:44 +0000511static SymbolKind symbolKind(ArrayRef<uint8_t> RecordData) {
512 const RecordPrefix *Prefix =
513 reinterpret_cast<const RecordPrefix *>(RecordData.data());
514 return static_cast<SymbolKind>(uint16_t(Prefix->RecordKind));
515}
516
517/// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
518static void translateIdSymbols(MutableArrayRef<uint8_t> &RecordData,
Zachary Turner3e3936d2017-11-29 19:35:21 +0000519 TypeCollection &IDTable) {
Zachary Turner59e3ae82017-08-08 18:34:44 +0000520 RecordPrefix *Prefix = reinterpret_cast<RecordPrefix *>(RecordData.data());
521
522 SymbolKind Kind = symbolKind(RecordData);
523
524 if (Kind == SymbolKind::S_PROC_ID_END) {
525 Prefix->RecordKind = SymbolKind::S_END;
526 return;
527 }
528
529 // In an object file, GPROC32_ID has an embedded reference which refers to the
530 // single object file type index namespace. This has already been translated
531 // to the PDB file's ID stream index space, but we need to convert this to a
532 // symbol that refers to the type stream index space. So we remap again from
533 // ID index space to type index space.
534 if (Kind == SymbolKind::S_GPROC32_ID || Kind == SymbolKind::S_LPROC32_ID) {
535 SmallVector<TiReference, 1> Refs;
536 auto Content = RecordData.drop_front(sizeof(RecordPrefix));
537 CVSymbol Sym(Kind, RecordData);
538 discoverTypeIndicesInSymbol(Sym, Refs);
539 assert(Refs.size() == 1);
540 assert(Refs.front().Count == 1);
541
542 TypeIndex *TI =
543 reinterpret_cast<TypeIndex *>(Content.data() + Refs[0].Offset);
544 // `TI` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
545 // the IPI stream, whose `FunctionType` member refers to the TPI stream.
546 // Note that LF_FUNC_ID and LF_MEMFUNC_ID have the same record layout, and
547 // in both cases we just need the second type index.
548 if (!TI->isSimple() && !TI->isNoneType()) {
Zachary Turner3e3936d2017-11-29 19:35:21 +0000549 CVType FuncIdData = IDTable.getType(*TI);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000550 SmallVector<TypeIndex, 2> Indices;
551 discoverTypeIndices(FuncIdData, Indices);
552 assert(Indices.size() == 2);
553 *TI = Indices[1];
554 }
555
556 Kind = (Kind == SymbolKind::S_GPROC32_ID) ? SymbolKind::S_GPROC32
557 : SymbolKind::S_LPROC32;
558 Prefix->RecordKind = uint16_t(Kind);
559 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000560}
561
562/// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
563/// The object file may not be aligned.
564static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
565 BumpPtrAllocator &Alloc) {
566 size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
567 assert(Size >= 4 && "record too short");
568 assert(Size <= MaxRecordLength && "record too long");
569 void *Mem = Alloc.Allocate(Size, 4);
570
571 // Copy the symbol record and zero out any padding bytes.
572 MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
573 memcpy(NewData.data(), Sym.data().data(), Sym.length());
574 memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
575
576 // Update the record prefix length. It should point to the beginning of the
Zachary Turner59e3ae82017-08-08 18:34:44 +0000577 // next record.
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000578 auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000579 Prefix->RecordLen = Size - 2;
580 return NewData;
581}
582
Reid Kleckner3f851922017-07-06 16:39:32 +0000583/// Return true if this symbol opens a scope. This implies that the symbol has
584/// "parent" and "end" fields, which contain the offset of the S_END or
585/// S_INLINESITE_END record.
586static bool symbolOpensScope(SymbolKind Kind) {
587 switch (Kind) {
588 case SymbolKind::S_GPROC32:
589 case SymbolKind::S_LPROC32:
590 case SymbolKind::S_LPROC32_ID:
591 case SymbolKind::S_GPROC32_ID:
592 case SymbolKind::S_BLOCK32:
593 case SymbolKind::S_SEPCODE:
594 case SymbolKind::S_THUNK32:
595 case SymbolKind::S_INLINESITE:
596 case SymbolKind::S_INLINESITE2:
597 return true;
598 default:
599 break;
600 }
601 return false;
602}
603
604static bool symbolEndsScope(SymbolKind Kind) {
605 switch (Kind) {
606 case SymbolKind::S_END:
607 case SymbolKind::S_PROC_ID_END:
608 case SymbolKind::S_INLINESITE_END:
609 return true;
610 default:
611 break;
612 }
613 return false;
614}
615
616struct ScopeRecord {
617 ulittle32_t PtrParent;
618 ulittle32_t PtrEnd;
619};
620
621struct SymbolScope {
622 ScopeRecord *OpeningRecord;
623 uint32_t ScopeOffset;
624};
625
626static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
627 uint32_t CurOffset, CVSymbol &Sym) {
628 assert(symbolOpensScope(Sym.kind()));
629 SymbolScope S;
630 S.ScopeOffset = CurOffset;
631 S.OpeningRecord = const_cast<ScopeRecord *>(
632 reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
633 S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
634 Stack.push_back(S);
635}
636
637static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000638 uint32_t CurOffset, ObjFile *File) {
Reid Kleckner3f851922017-07-06 16:39:32 +0000639 if (Stack.empty()) {
640 warn("symbol scopes are not balanced in " + File->getName());
641 return;
642 }
643 SymbolScope S = Stack.pop_back_val();
644 S.OpeningRecord->PtrEnd = CurOffset;
645}
646
Zachary Turneree9906d2017-08-11 19:00:03 +0000647static bool symbolGoesInModuleStream(const CVSymbol &Sym) {
648 switch (Sym.kind()) {
649 case SymbolKind::S_GDATA32:
650 case SymbolKind::S_CONSTANT:
651 case SymbolKind::S_UDT:
652 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
653 // since they are synthesized by the linker in response to S_GPROC32 and
654 // S_LPROC32, but if we do see them, don't put them in the module stream I
655 // guess.
656 case SymbolKind::S_PROCREF:
657 case SymbolKind::S_LPROCREF:
658 return false;
659 // S_GDATA32 does not go in the module stream, but S_LDATA32 does.
660 case SymbolKind::S_LDATA32:
661 default:
662 return true;
663 }
664}
665
666static bool symbolGoesInGlobalsStream(const CVSymbol &Sym) {
667 switch (Sym.kind()) {
668 case SymbolKind::S_CONSTANT:
Zachary Turneree9906d2017-08-11 19:00:03 +0000669 case SymbolKind::S_GDATA32:
670 // S_LDATA32 goes in both the module stream and the globals stream.
671 case SymbolKind::S_LDATA32:
672 case SymbolKind::S_GPROC32:
673 case SymbolKind::S_LPROC32:
674 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
675 // since they are synthesized by the linker in response to S_GPROC32 and
676 // S_LPROC32, but if we do see them, copy them straight through.
677 case SymbolKind::S_PROCREF:
678 case SymbolKind::S_LPROCREF:
679 return true;
Zachary Turner302dc8b2017-08-14 18:44:58 +0000680 // FIXME: For now, we drop all S_UDT symbols (i.e. they don't go in the
681 // globals stream or the modules stream). These have special handling which
682 // needs more investigation before we can get right, but by putting them all
683 // into the globals stream WinDbg fails to display local variables of class
684 // types saying that it cannot find the type Foo *. So as a stopgap just to
685 // keep things working, we drop them.
686 case SymbolKind::S_UDT:
Zachary Turneree9906d2017-08-11 19:00:03 +0000687 default:
688 return false;
689 }
690}
691
692static void addGlobalSymbol(pdb::GSIStreamBuilder &Builder, ObjFile &File,
693 const CVSymbol &Sym) {
694 switch (Sym.kind()) {
695 case SymbolKind::S_CONSTANT:
696 case SymbolKind::S_UDT:
697 case SymbolKind::S_GDATA32:
698 case SymbolKind::S_LDATA32:
699 case SymbolKind::S_PROCREF:
700 case SymbolKind::S_LPROCREF:
701 Builder.addGlobalSymbol(Sym);
702 break;
703 case SymbolKind::S_GPROC32:
704 case SymbolKind::S_LPROC32: {
705 SymbolRecordKind K = SymbolRecordKind::ProcRefSym;
706 if (Sym.kind() == SymbolKind::S_LPROC32)
707 K = SymbolRecordKind::LocalProcRef;
708 ProcRefSym PS(K);
709 PS.Module = static_cast<uint16_t>(File.ModuleDBI->getModuleIndex());
710 // For some reason, MSVC seems to add one to this value.
711 ++PS.Module;
712 PS.Name = getSymbolName(Sym);
713 PS.SumName = 0;
714 PS.SymOffset = File.ModuleDBI->getNextSymbolOffset();
715 Builder.addGlobalSymbol(PS);
716 break;
717 }
718 default:
719 llvm_unreachable("Invalid symbol kind!");
720 }
721}
722
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000723static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjFile *File,
Zachary Turneree9906d2017-08-11 19:00:03 +0000724 pdb::GSIStreamBuilder &GsiBuilder,
Reid Kleckner651db912017-07-18 00:21:25 +0000725 const CVIndexMap &IndexMap,
Zachary Turner3e3936d2017-11-29 19:35:21 +0000726 TypeCollection &IDTable,
Zachary Turner60478582018-01-05 19:12:40 +0000727 std::vector<ulittle32_t *> &StringTableRefs,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000728 BinaryStreamRef SymData) {
729 // FIXME: Improve error recovery by warning and skipping records when
730 // possible.
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000731 ArrayRef<uint8_t> SymsBuffer;
732 cantFail(SymData.readBytes(0, SymData.getLength(), SymsBuffer));
Reid Kleckner3f851922017-07-06 16:39:32 +0000733 SmallVector<SymbolScope, 4> Scopes;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000734
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000735 auto EC = forEachCodeViewRecord<CVSymbol>(
736 SymsBuffer, [&](const CVSymbol &Sym) -> llvm::Error {
737 // Discover type index references in the record. Skip it if we don't
738 // know where they are.
739 SmallVector<TiReference, 32> TypeRefs;
740 if (!discoverTypeIndicesInSymbol(Sym, TypeRefs)) {
741 log("ignoring unknown symbol record with kind 0x" +
742 utohexstr(Sym.kind()));
743 return Error::success();
744 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000745
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000746 // Copy the symbol record so we can mutate it.
747 MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000748
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000749 // Re-map all the type index references.
750 MutableArrayRef<uint8_t> Contents =
751 NewData.drop_front(sizeof(RecordPrefix));
752 remapTypesInSymbolRecord(File, Sym.kind(), Contents, IndexMap,
753 TypeRefs);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000754
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000755 // An object file may have S_xxx_ID symbols, but these get converted to
756 // "real" symbols in a PDB.
757 translateIdSymbols(NewData, IDTable);
Zachary Turner60478582018-01-05 19:12:40 +0000758
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000759 // If this record refers to an offset in the object file's string table,
760 // add that item to the global PDB string table and re-write the index.
761 recordStringTableReferences(Sym.kind(), Contents, StringTableRefs);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000762
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000763 SymbolKind NewKind = symbolKind(NewData);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000764
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000765 // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
766 CVSymbol NewSym(NewKind, NewData);
767 if (symbolOpensScope(NewKind))
768 scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(),
769 NewSym);
770 else if (symbolEndsScope(NewKind))
771 scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
Zachary Turneree9906d2017-08-11 19:00:03 +0000772
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000773 // Add the symbol to the globals stream if necessary. Do this before
774 // adding the symbol to the module since we may need to get the next
775 // symbol offset, and writing to the module's symbol stream will update
776 // that offset.
777 if (symbolGoesInGlobalsStream(NewSym))
778 addGlobalSymbol(GsiBuilder, *File, NewSym);
779
780 // Add the symbol to the module.
781 if (symbolGoesInModuleStream(NewSym))
782 File->ModuleDBI->addSymbol(NewSym);
783 return Error::success();
784 });
785 cantFail(std::move(EC));
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000786}
787
Reid Kleckner44cdb102017-06-19 17:21:45 +0000788// Allocate memory for a .debug$S section and relocate it.
789static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
790 SectionChunk *DebugChunk) {
791 uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk->getSize());
792 assert(DebugChunk->OutputSectionOff == 0 &&
793 "debug sections should not be in output sections");
794 DebugChunk->writeTo(Buffer);
795 return consumeDebugMagic(makeArrayRef(Buffer, DebugChunk->getSize()),
796 ".debug$S");
797}
798
Zachary Turner194be872018-04-20 18:00:46 +0000799static pdb::SectionContrib createSectionContrib(const Chunk *C, uint32_t Modi) {
800 OutputSection *OS = C->getOutputSection();
801 pdb::SectionContrib SC;
802 memset(&SC, 0, sizeof(SC));
803 SC.ISect = OS->SectionIndex;
804 SC.Off = C->getRVA() - OS->getRVA();
805 SC.Size = C->getSize();
806 if (auto *SecChunk = dyn_cast<SectionChunk>(C)) {
807 SC.Characteristics = SecChunk->Header->Characteristics;
808 SC.Imod = SecChunk->File->ModuleDBI->getModuleIndex();
809 ArrayRef<uint8_t> Contents = SecChunk->getContents();
810 JamCRC CRC(0);
811 ArrayRef<char> CharContents = makeArrayRef(
812 reinterpret_cast<const char *>(Contents.data()), Contents.size());
813 CRC.update(CharContents);
814 SC.DataCrc = CRC.getCRC();
815 } else {
816 SC.Characteristics = OS->Header.Characteristics;
817 // FIXME: When we start creating DBI for import libraries, use those here.
818 SC.Imod = Modi;
819 }
820 SC.RelocCrc = 0; // FIXME
821
822 return SC;
823}
824
Zachary Turner42e7cc1b2018-09-11 22:35:01 +0000825static uint32_t
826translateStringTableIndex(uint32_t ObjIndex,
827 const DebugStringTableSubsectionRef &ObjStrTable,
828 DebugStringTableSubsection &PdbStrTable) {
829 auto ExpectedString = ObjStrTable.getString(ObjIndex);
830 if (!ExpectedString) {
831 warn("Invalid string table reference");
832 consumeError(ExpectedString.takeError());
833 return 0;
834 }
835
836 return PdbStrTable.insert(*ExpectedString);
837}
838
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000839void PDBLinker::addObjFile(ObjFile *File) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000840 // Add a module descriptor for every object file. We need to put an absolute
841 // path to the object into the PDB. If this is a plain object, we make its
842 // path absolute. If it's an object in an archive, we make the archive path
843 // absolute.
844 bool InArchive = !File->ParentName.empty();
845 SmallString<128> Path = InArchive ? File->ParentName : File->getName();
846 sys::fs::make_absolute(Path);
847 sys::path::native(Path, sys::path::Style::windows);
848 StringRef Name = InArchive ? File->getName() : StringRef(Path);
Zachary Turner2897e032017-05-25 21:16:03 +0000849
Zachary Turner42e7cc1b2018-09-11 22:35:01 +0000850 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
851 File->ModuleDBI = &ExitOnErr(DbiBuilder.addModuleInfo(Name));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000852 File->ModuleDBI->setObjFileName(Path);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000853
Zachary Turner194be872018-04-20 18:00:46 +0000854 auto Chunks = File->getChunks();
Zachary Turner194be872018-04-20 18:00:46 +0000855 uint32_t Modi = File->ModuleDBI->getModuleIndex();
856 for (Chunk *C : Chunks) {
857 auto *SecChunk = dyn_cast<SectionChunk>(C);
Martin Storsjo802fcb42018-08-31 07:45:20 +0000858 if (!SecChunk || !SecChunk->Live)
Zachary Turner194be872018-04-20 18:00:46 +0000859 continue;
860 pdb::SectionContrib SC = createSectionContrib(SecChunk, Modi);
861 File->ModuleDBI->setFirstSectionContrib(SC);
862 break;
863 }
864
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000865 // Before we can process symbol substreams from .debug$S, we need to process
866 // type information, file checksums, and the string table. Add type info to
867 // the PDB first, so that we can get the map from object file type and item
868 // indices to PDB type and item indices.
Reid Kleckner651db912017-07-18 00:21:25 +0000869 CVIndexMap ObjectIndexMap;
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000870 auto IndexMapResult = mergeDebugT(File, ObjectIndexMap);
871
872 // If the .debug$T sections fail to merge, assume there is no debug info.
873 if (!IndexMapResult) {
Alexandre Ganead93b07f2018-09-10 13:51:21 +0000874 auto FileName = sys::path::filename(Path);
875 warn("Cannot use debug info for '" + FileName + "'\n" +
876 ">>> failed to load reference " +
877 StringRef(toString(IndexMapResult.takeError())));
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000878 return;
879 }
880
881 const CVIndexMap &IndexMap = *IndexMapResult;
Zachary Turner448dea42017-07-07 18:46:14 +0000882
Zachary Turner727f1532018-01-17 19:16:26 +0000883 ScopedTimer T(SymbolMergingTimer);
884
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000885 // Now do all live .debug$S sections.
Zachary Turner60478582018-01-05 19:12:40 +0000886 DebugStringTableSubsectionRef CVStrTab;
887 DebugChecksumsSubsectionRef Checksums;
888 std::vector<ulittle32_t *> StringTableReferences;
Zachary Turner42e7cc1b2018-09-11 22:35:01 +0000889 std::vector<DebugFrameDataSubsectionRef> FpoFrames;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000890 for (SectionChunk *DebugChunk : File->getDebugChunks()) {
Martin Storsjo802fcb42018-08-31 07:45:20 +0000891 if (!DebugChunk->Live || DebugChunk->getSectionName() != ".debug$S")
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000892 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000893
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000894 ArrayRef<uint8_t> RelocatedDebugContents =
895 relocateDebugChunk(Alloc, DebugChunk);
896 if (RelocatedDebugContents.empty())
897 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000898
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000899 DebugSubsectionArray Subsections;
900 BinaryStreamReader Reader(RelocatedDebugContents, support::little);
901 ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
Rui Ueyama52896622017-01-12 03:09:25 +0000902
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000903 for (const DebugSubsectionRecord &SS : Subsections) {
904 switch (SS.kind()) {
Zachary Turner60478582018-01-05 19:12:40 +0000905 case DebugSubsectionKind::StringTable: {
Zachary Turner60478582018-01-05 19:12:40 +0000906 assert(!CVStrTab.valid() &&
907 "Encountered multiple string table subsections!");
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000908 ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
909 break;
Zachary Turner60478582018-01-05 19:12:40 +0000910 }
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000911 case DebugSubsectionKind::FileChecksums:
Zachary Turner60478582018-01-05 19:12:40 +0000912 assert(!Checksums.valid() &&
913 "Encountered multiple checksum subsections!");
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000914 ExitOnErr(Checksums.initialize(SS.getRecordData()));
915 break;
916 case DebugSubsectionKind::Lines:
917 // We can add the relocated line table directly to the PDB without
918 // modification because the file checksum offsets will stay the same.
919 File->ModuleDBI->addDebugSubsection(SS);
920 break;
Zachary Turner42e7cc1b2018-09-11 22:35:01 +0000921 case DebugSubsectionKind::FrameData: {
922 // We need to re-write string table indices here, so save off all
923 // frame data subsections until we've processed the entire list of
924 // subsections so that we can be sure we have the string table.
925 DebugFrameDataSubsectionRef FDS;
926 ExitOnErr(FDS.initialize(SS.getRecordData()));
927 FpoFrames.push_back(std::move(FDS));
928 break;
929 }
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000930 case DebugSubsectionKind::Symbols:
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000931 if (Config->DebugGHashes) {
932 mergeSymbolRecords(Alloc, File, Builder.getGsiBuilder(), IndexMap,
Zachary Turner60478582018-01-05 19:12:40 +0000933 GlobalIDTable, StringTableReferences,
934 SS.getRecordData());
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000935 } else {
936 mergeSymbolRecords(Alloc, File, Builder.getGsiBuilder(), IndexMap,
Zachary Turner60478582018-01-05 19:12:40 +0000937 IDTable, StringTableReferences,
938 SS.getRecordData());
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000939 }
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000940 break;
941 default:
942 // FIXME: Process the rest of the subsections.
943 break;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000944 }
945 }
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000946 }
Zachary Turner60478582018-01-05 19:12:40 +0000947
948 // We should have seen all debug subsections across the entire object file now
949 // which means that if a StringTable subsection and Checksums subsection were
950 // present, now is the time to handle them.
951 if (!CVStrTab.valid()) {
952 if (Checksums.valid())
953 fatal(".debug$S sections with a checksums subsection must also contain a "
954 "string table subsection");
955
956 if (!StringTableReferences.empty())
957 warn("No StringTable subsection was encountered, but there are string "
958 "table references");
959 return;
960 }
961
Zachary Turner42e7cc1b2018-09-11 22:35:01 +0000962 // Rewrite string table indices in the Fpo Data and symbol records to refer to
963 // the global PDB string table instead of the object file string table.
964 for (DebugFrameDataSubsectionRef &FDS : FpoFrames) {
965 const uint32_t *Reloc = FDS.getRelocPtr();
966 for (codeview::FrameData FD : FDS) {
967 FD.RvaStart += *Reloc;
968 FD.FrameFunc =
969 translateStringTableIndex(FD.FrameFunc, CVStrTab, PDBStrTab);
970 DbiBuilder.addFrameData(FD);
Zachary Turner60478582018-01-05 19:12:40 +0000971 }
Zachary Turner60478582018-01-05 19:12:40 +0000972 }
973
Zachary Turner42e7cc1b2018-09-11 22:35:01 +0000974 for (ulittle32_t *Ref : StringTableReferences)
975 *Ref = translateStringTableIndex(*Ref, CVStrTab, PDBStrTab);
976
Zachary Turner60478582018-01-05 19:12:40 +0000977 // Make a new file checksum table that refers to offsets in the PDB-wide
978 // string table. Generally the string table subsection appears after the
979 // checksum table, so we have to do this after looping over all the
980 // subsections.
981 auto NewChecksums = make_unique<DebugChecksumsSubsection>(PDBStrTab);
982 for (FileChecksumEntry &FC : Checksums) {
Takuto Ikutad8559282018-07-19 04:56:22 +0000983 SmallString<128> FileName = ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
984 if (!sys::path::is_absolute(FileName) &&
985 !Config->PDBSourcePath.empty()) {
986 SmallString<128> AbsoluteFileName = Config->PDBSourcePath;
987 sys::path::append(AbsoluteFileName, FileName);
988 sys::path::native(AbsoluteFileName);
989 sys::path::remove_dots(AbsoluteFileName, /*remove_dot_dots=*/true);
990 FileName = std::move(AbsoluteFileName);
991 }
Zachary Turner60478582018-01-05 19:12:40 +0000992 ExitOnErr(Builder.getDbiBuilder().addModuleSourceFile(*File->ModuleDBI,
993 FileName));
994 NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
995 }
996 File->ModuleDBI->addDebugSubsection(std::move(NewChecksums));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000997}
998
Reid Klecknereacdf042017-07-27 18:25:59 +0000999static PublicSym32 createPublic(Defined *Def) {
1000 PublicSym32 Pub(SymbolKind::S_PUB32);
1001 Pub.Name = Def->getName();
1002 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
1003 if (D->getCOFFSymbol().isFunctionDefinition())
1004 Pub.Flags = PublicSymFlags::Function;
1005 } else if (isa<DefinedImportThunk>(Def)) {
1006 Pub.Flags = PublicSymFlags::Function;
1007 }
1008
1009 OutputSection *OS = Def->getChunk()->getOutputSection();
1010 assert(OS && "all publics should be in final image");
1011 Pub.Offset = Def->getRVA() - OS->getRVA();
1012 Pub.Segment = OS->SectionIndex;
1013 return Pub;
1014}
1015
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001016// Add all object files to the PDB. Merge .debug$T sections into IpiData and
1017// TpiData.
1018void PDBLinker::addObjectsToPDB() {
Zachary Turner727f1532018-01-17 19:16:26 +00001019 ScopedTimer T1(AddObjectsTimer);
Rui Ueyamaacd632d2017-07-27 00:45:26 +00001020 for (ObjFile *File : ObjFile::Instances)
Rui Ueyamae1b48e02017-07-26 23:05:24 +00001021 addObjFile(File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001022
1023 Builder.getStringTableBuilder().setStrings(PDBStrTab);
Zachary Turner727f1532018-01-17 19:16:26 +00001024 T1.stop();
Reid Kleckner44cdb102017-06-19 17:21:45 +00001025
Zachary Turner0d07a8e2017-12-14 18:07:04 +00001026 // Construct TPI and IPI stream contents.
Zachary Turner727f1532018-01-17 19:16:26 +00001027 ScopedTimer T2(TpiStreamLayoutTimer);
Zachary Turner0d07a8e2017-12-14 18:07:04 +00001028 if (Config->DebugGHashes) {
1029 addTypeInfo(Builder.getTpiBuilder(), GlobalTypeTable);
1030 addTypeInfo(Builder.getIpiBuilder(), GlobalIDTable);
1031 } else {
1032 addTypeInfo(Builder.getTpiBuilder(), TypeTable);
1033 addTypeInfo(Builder.getIpiBuilder(), IDTable);
1034 }
Zachary Turner727f1532018-01-17 19:16:26 +00001035 T2.stop();
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001036
Zachary Turner727f1532018-01-17 19:16:26 +00001037 ScopedTimer T3(GlobalsLayoutTimer);
Zachary Turneree9906d2017-08-11 19:00:03 +00001038 // Compute the public and global symbols.
1039 auto &GsiBuilder = Builder.getGsiBuilder();
Reid Klecknereacdf042017-07-27 18:25:59 +00001040 std::vector<PublicSym32> Publics;
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001041 Symtab->forEachSymbol([&Publics](Symbol *S) {
Reid Klecknereacdf042017-07-27 18:25:59 +00001042 // Only emit defined, live symbols that have a chunk.
Rui Ueyama616cd992017-10-31 16:10:24 +00001043 auto *Def = dyn_cast<Defined>(S);
Reid Klecknereacdf042017-07-27 18:25:59 +00001044 if (Def && Def->isLive() && Def->getChunk())
1045 Publics.push_back(createPublic(Def));
1046 });
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001047
Reid Klecknereacdf042017-07-27 18:25:59 +00001048 if (!Publics.empty()) {
1049 // Sort the public symbols and add them to the stream.
1050 std::sort(Publics.begin(), Publics.end(),
1051 [](const PublicSym32 &L, const PublicSym32 &R) {
1052 return L.Name < R.Name;
1053 });
Reid Klecknereacdf042017-07-27 18:25:59 +00001054 for (const PublicSym32 &Pub : Publics)
Zachary Turner946204c2017-08-09 04:23:25 +00001055 GsiBuilder.addPublicSymbol(Pub);
Reid Klecknereacdf042017-07-27 18:25:59 +00001056 }
Rui Ueyama52896622017-01-12 03:09:25 +00001057}
1058
Zachary Turnerf2282762018-03-23 19:57:25 +00001059void PDBLinker::addNatvisFiles() {
1060 for (StringRef File : Config->NatvisFiles) {
1061 ErrorOr<std::unique_ptr<MemoryBuffer>> DataOrErr =
1062 MemoryBuffer::getFile(File);
1063 if (!DataOrErr) {
1064 warn("Cannot open input file: " + File);
1065 continue;
1066 }
1067 Builder.addInjectedSource(File, std::move(*DataOrErr));
1068 }
1069}
1070
Zachary Turnere3fe6692018-04-16 18:17:13 +00001071static codeview::CPUType toCodeViewMachine(COFF::MachineTypes Machine) {
1072 switch (Machine) {
1073 case COFF::IMAGE_FILE_MACHINE_AMD64:
1074 return codeview::CPUType::X64;
1075 case COFF::IMAGE_FILE_MACHINE_ARM:
1076 return codeview::CPUType::ARM7;
1077 case COFF::IMAGE_FILE_MACHINE_ARM64:
1078 return codeview::CPUType::ARM64;
1079 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1080 return codeview::CPUType::ARMNT;
1081 case COFF::IMAGE_FILE_MACHINE_I386:
1082 return codeview::CPUType::Intel80386;
1083 default:
1084 llvm_unreachable("Unsupported CPU Type");
1085 }
1086}
1087
Zachary Turner28e31ee2017-08-11 20:46:28 +00001088static void addCommonLinkerModuleSymbols(StringRef Path,
1089 pdb::DbiModuleDescriptorBuilder &Mod,
1090 BumpPtrAllocator &Allocator) {
Zachary Turner28e31ee2017-08-11 20:46:28 +00001091 ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
1092 Compile3Sym CS(SymbolRecordKind::Compile3Sym);
1093 EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
Zachary Turner6708e0b2017-07-10 21:01:37 +00001094
1095 ONS.Name = "* Linker *";
1096 ONS.Signature = 0;
1097
Zachary Turnere3fe6692018-04-16 18:17:13 +00001098 CS.Machine = toCodeViewMachine(Config->Machine);
Zachary Turnerb57884e2017-08-11 21:14:01 +00001099 // Interestingly, if we set the string to 0.0.0.0, then when trying to view
1100 // local variables WinDbg emits an error that private symbols are not present.
1101 // By setting this to a valid MSVC linker version string, local variables are
1102 // displayed properly. As such, even though it is not representative of
Zachary Turnerf6822c82017-08-11 20:46:47 +00001103 // LLVM's version information, we need this for compatibility.
Zachary Turner6708e0b2017-07-10 21:01:37 +00001104 CS.Flags = CompileSym3Flags::None;
Zachary Turnerf6822c82017-08-11 20:46:47 +00001105 CS.VersionBackendBuild = 25019;
1106 CS.VersionBackendMajor = 14;
1107 CS.VersionBackendMinor = 10;
Zachary Turner6708e0b2017-07-10 21:01:37 +00001108 CS.VersionBackendQFE = 0;
Zachary Turnerf6822c82017-08-11 20:46:47 +00001109
1110 // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
1111 // linker module (which is by definition a backend), so we don't need to do
1112 // anything here. Also, it seems we can use "LLVM Linker" for the linker name
1113 // without any problems. Only the backend version has to be hardcoded to a
1114 // magic number.
Zachary Turner6708e0b2017-07-10 21:01:37 +00001115 CS.VersionFrontendBuild = 0;
1116 CS.VersionFrontendMajor = 0;
1117 CS.VersionFrontendMinor = 0;
1118 CS.VersionFrontendQFE = 0;
1119 CS.Version = "LLVM Linker";
1120 CS.setLanguage(SourceLanguage::Link);
1121
1122 ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
1123 std::string ArgStr = llvm::join(Args, " ");
1124 EBS.Fields.push_back("cwd");
1125 SmallString<64> cwd;
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001126 sys::fs::current_path(cwd);
Zachary Turner6708e0b2017-07-10 21:01:37 +00001127 EBS.Fields.push_back(cwd);
1128 EBS.Fields.push_back("exe");
Zachary Turnerf6822c82017-08-11 20:46:47 +00001129 SmallString<64> exe = Config->Argv[0];
1130 llvm::sys::fs::make_absolute(exe);
1131 EBS.Fields.push_back(exe);
Zachary Turner6708e0b2017-07-10 21:01:37 +00001132 EBS.Fields.push_back("pdb");
1133 EBS.Fields.push_back(Path);
1134 EBS.Fields.push_back("cmd");
1135 EBS.Fields.push_back(ArgStr);
1136 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1137 ONS, Allocator, CodeViewContainer::Pdb));
1138 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1139 CS, Allocator, CodeViewContainer::Pdb));
1140 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1141 EBS, Allocator, CodeViewContainer::Pdb));
1142}
1143
Zachary Turner28e31ee2017-08-11 20:46:28 +00001144static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &Mod,
1145 OutputSection &OS,
1146 BumpPtrAllocator &Allocator) {
1147 SectionSym Sym(SymbolRecordKind::SectionSym);
Zachary Turnerf6822c82017-08-11 20:46:47 +00001148 Sym.Alignment = 12; // 2^12 = 4KB
Peter Collingbournebe084ec2018-04-19 21:48:37 +00001149 Sym.Characteristics = OS.Header.Characteristics;
Zachary Turner28e31ee2017-08-11 20:46:28 +00001150 Sym.Length = OS.getVirtualSize();
Peter Collingbourne435b09912018-03-15 21:13:46 +00001151 Sym.Name = OS.Name;
Zachary Turner28e31ee2017-08-11 20:46:28 +00001152 Sym.Rva = OS.getRVA();
1153 Sym.SectionNumber = OS.SectionIndex;
1154 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1155 Sym, Allocator, CodeViewContainer::Pdb));
1156}
1157
Rui Ueyama09e0b5f2016-11-12 00:00:51 +00001158// Creates a PDB file.
Reid Kleckner175af4b2017-08-03 21:15:09 +00001159void coff::createPDB(SymbolTable *Symtab,
1160 ArrayRef<OutputSection *> OutputSections,
1161 ArrayRef<uint8_t> SectionTable,
Zachary Turner024323c2017-08-15 21:31:41 +00001162 const llvm::codeview::DebugInfo &BuildId) {
Zachary Turner727f1532018-01-17 19:16:26 +00001163 ScopedTimer T1(TotalPdbLinkTimer);
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001164 PDBLinker PDB(Symtab);
Zachary Turnerf2282762018-03-23 19:57:25 +00001165
Zachary Turner024323c2017-08-15 21:31:41 +00001166 PDB.initialize(BuildId);
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001167 PDB.addObjectsToPDB();
Reid Kleckner175af4b2017-08-03 21:15:09 +00001168 PDB.addSections(OutputSections, SectionTable);
Zachary Turnerf2282762018-03-23 19:57:25 +00001169 PDB.addNatvisFiles();
Zachary Turner727f1532018-01-17 19:16:26 +00001170
1171 ScopedTimer T2(DiskCommitTimer);
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001172 PDB.commit();
1173}
1174
Zachary Turner024323c2017-08-15 21:31:41 +00001175void PDBLinker::initialize(const llvm::codeview::DebugInfo &BuildId) {
Rui Ueyama12979542016-09-30 20:53:45 +00001176 ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
Rui Ueyama7f382992016-09-15 18:55:18 +00001177
Rui Ueyama8d3fb5d2016-10-05 22:08:58 +00001178 // Create streams in MSF for predefined streams, namely
1179 // PDB, TPI, DBI and IPI.
1180 for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
1181 ExitOnErr(Builder.getMsfBuilder().addStream(0));
Rui Ueyama7f382992016-09-15 18:55:18 +00001182
Rui Ueyamabb542b32016-09-16 22:51:17 +00001183 // Add an Info stream.
1184 auto &InfoBuilder = Builder.getInfoBuilder();
Zachary Turner024323c2017-08-15 21:31:41 +00001185 GUID uuid;
1186 memcpy(&uuid, &BuildId.PDB70.Signature, sizeof(uuid));
Zachary Turnerc6a75a62018-03-01 18:00:29 +00001187 InfoBuilder.setAge(BuildId.PDB70.Age);
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +00001188 InfoBuilder.setGuid(uuid);
Rui Ueyamabb542b32016-09-16 22:51:17 +00001189 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
Rui Ueyama7f382992016-09-15 18:55:18 +00001190
Zachary Turner6c4bfba2017-07-07 05:04:36 +00001191 // Add an empty DBI stream.
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +00001192 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Zachary Turner024323c2017-08-15 21:31:41 +00001193 DbiBuilder.setAge(BuildId.PDB70.Age);
Zachary Turnerc1e93e52017-07-07 18:45:56 +00001194 DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
Zachary Turnerd8d97de2018-04-16 20:42:06 +00001195 DbiBuilder.setMachineType(Config->Machine);
Zachary Turnere3fe6692018-04-16 18:17:13 +00001196 // Technically we are not link.exe 14.11, but there are known cases where
1197 // debugging tools on Windows expect Microsoft-specific version numbers or
1198 // they fail to work at all. Since we know we produce PDBs that are
1199 // compatible with LINK 14.11, we set that version number here.
1200 DbiBuilder.setBuildNumber(14, 11);
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001201}
Rui Ueyama1343fac2016-10-06 22:52:01 +00001202
Reid Kleckner175af4b2017-08-03 21:15:09 +00001203void PDBLinker::addSections(ArrayRef<OutputSection *> OutputSections,
1204 ArrayRef<uint8_t> SectionTable) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001205 // It's not entirely clear what this is, but the * Linker * module uses it.
Reid Kleckner175af4b2017-08-03 21:15:09 +00001206 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001207 NativePath = Config->PDBPath;
1208 sys::fs::make_absolute(NativePath);
1209 sys::path::native(NativePath, sys::path::Style::windows);
1210 uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
Zachary Turner6c4bfba2017-07-07 05:04:36 +00001211 auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
1212 LinkerModule.setPdbFilePathNI(PdbFilePathNI);
Zachary Turner28e31ee2017-08-11 20:46:28 +00001213 addCommonLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
Rui Ueyamac91f7162016-11-16 01:10:46 +00001214
Reid Kleckner175af4b2017-08-03 21:15:09 +00001215 // Add section contributions. They must be ordered by ascending RVA.
Zachary Turner28e31ee2017-08-11 20:46:28 +00001216 for (OutputSection *OS : OutputSections) {
1217 addLinkerModuleSectionSymbol(LinkerModule, *OS, Alloc);
Zachary Turner194be872018-04-20 18:00:46 +00001218 for (Chunk *C : OS->getChunks()) {
1219 pdb::SectionContrib SC =
1220 createSectionContrib(C, LinkerModule.getModuleIndex());
1221 Builder.getDbiBuilder().addSectionContrib(SC);
1222 }
Zachary Turner28e31ee2017-08-11 20:46:28 +00001223 }
Reid Kleckner175af4b2017-08-03 21:15:09 +00001224
1225 // Add Section Map stream.
1226 ArrayRef<object::coff_section> Sections = {
1227 (const object::coff_section *)SectionTable.data(),
1228 SectionTable.size() / sizeof(object::coff_section)};
1229 SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
1230 DbiBuilder.setSectionMap(SectionMap);
1231
Rui Ueyama9f66f822016-10-11 19:45:07 +00001232 // Add COFF section header stream.
1233 ExitOnErr(
1234 DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001235}
Rui Ueyama9f66f822016-10-11 19:45:07 +00001236
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001237void PDBLinker::commit() {
Rui Ueyama3e9d6bb2016-09-26 23:53:55 +00001238 // Write to a file.
Zachary Turner6708e0b2017-07-10 21:01:37 +00001239 ExitOnErr(Builder.commit(Config->PDBPath));
Rui Ueyamae7378242015-12-04 23:11:05 +00001240}
Peter Collingbourne31088022018-04-17 23:32:33 +00001241
1242static Expected<StringRef>
1243getFileName(const DebugStringTableSubsectionRef &Strings,
1244 const DebugChecksumsSubsectionRef &Checksums, uint32_t FileID) {
1245 auto Iter = Checksums.getArray().at(FileID);
1246 if (Iter == Checksums.getArray().end())
1247 return make_error<CodeViewError>(cv_error_code::no_records);
1248 uint32_t Offset = Iter->FileNameOffset;
1249 return Strings.getString(Offset);
1250}
1251
1252static uint32_t getSecrelReloc() {
1253 switch (Config->Machine) {
1254 case AMD64:
1255 return COFF::IMAGE_REL_AMD64_SECREL;
1256 case I386:
1257 return COFF::IMAGE_REL_I386_SECREL;
1258 case ARMNT:
1259 return COFF::IMAGE_REL_ARM_SECREL;
1260 case ARM64:
1261 return COFF::IMAGE_REL_ARM64_SECREL;
1262 default:
1263 llvm_unreachable("unknown machine type");
1264 }
1265}
1266
1267// Try to find a line table for the given offset Addr into the given chunk C.
1268// If a line table was found, the line table, the string and checksum tables
1269// that are used to interpret the line table, and the offset of Addr in the line
1270// table are stored in the output arguments. Returns whether a line table was
1271// found.
1272static bool findLineTable(const SectionChunk *C, uint32_t Addr,
1273 DebugStringTableSubsectionRef &CVStrTab,
1274 DebugChecksumsSubsectionRef &Checksums,
1275 DebugLinesSubsectionRef &Lines,
1276 uint32_t &OffsetInLinetable) {
1277 ExitOnError ExitOnErr;
1278 uint32_t SecrelReloc = getSecrelReloc();
1279
1280 for (SectionChunk *DbgC : C->File->getDebugChunks()) {
1281 if (DbgC->getSectionName() != ".debug$S")
1282 continue;
1283
1284 // Build a mapping of SECREL relocations in DbgC that refer to C.
1285 DenseMap<uint32_t, uint32_t> Secrels;
1286 for (const coff_relocation &R : DbgC->Relocs) {
1287 if (R.Type != SecrelReloc)
1288 continue;
1289
1290 if (auto *S = dyn_cast_or_null<DefinedRegular>(
1291 C->File->getSymbols()[R.SymbolTableIndex]))
1292 if (S->getChunk() == C)
1293 Secrels[R.VirtualAddress] = S->getValue();
1294 }
1295
1296 ArrayRef<uint8_t> Contents =
1297 consumeDebugMagic(DbgC->getContents(), ".debug$S");
1298 DebugSubsectionArray Subsections;
1299 BinaryStreamReader Reader(Contents, support::little);
1300 ExitOnErr(Reader.readArray(Subsections, Contents.size()));
1301
1302 for (const DebugSubsectionRecord &SS : Subsections) {
1303 switch (SS.kind()) {
1304 case DebugSubsectionKind::StringTable: {
1305 assert(!CVStrTab.valid() &&
1306 "Encountered multiple string table subsections!");
1307 ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
1308 break;
1309 }
1310 case DebugSubsectionKind::FileChecksums:
1311 assert(!Checksums.valid() &&
1312 "Encountered multiple checksum subsections!");
1313 ExitOnErr(Checksums.initialize(SS.getRecordData()));
1314 break;
1315 case DebugSubsectionKind::Lines: {
1316 ArrayRef<uint8_t> Bytes;
1317 auto Ref = SS.getRecordData();
1318 ExitOnErr(Ref.readLongestContiguousChunk(0, Bytes));
1319 size_t OffsetInDbgC = Bytes.data() - DbgC->getContents().data();
1320
1321 // Check whether this line table refers to C.
1322 auto I = Secrels.find(OffsetInDbgC);
1323 if (I == Secrels.end())
1324 break;
1325
1326 // Check whether this line table covers Addr in C.
1327 DebugLinesSubsectionRef LinesTmp;
1328 ExitOnErr(LinesTmp.initialize(BinaryStreamReader(Ref)));
1329 uint32_t OffsetInC = I->second + LinesTmp.header()->RelocOffset;
1330 if (Addr < OffsetInC || Addr >= OffsetInC + LinesTmp.header()->CodeSize)
1331 break;
1332
1333 assert(!Lines.header() &&
1334 "Encountered multiple line tables for function!");
1335 ExitOnErr(Lines.initialize(BinaryStreamReader(Ref)));
1336 OffsetInLinetable = Addr - OffsetInC;
1337 break;
1338 }
1339 default:
1340 break;
1341 }
1342
1343 if (CVStrTab.valid() && Checksums.valid() && Lines.header())
1344 return true;
1345 }
1346 }
1347
1348 return false;
1349}
1350
1351// Use CodeView line tables to resolve a file and line number for the given
1352// offset into the given chunk and return them, or {"", 0} if a line table was
1353// not found.
1354std::pair<StringRef, uint32_t> coff::getFileLine(const SectionChunk *C,
1355 uint32_t Addr) {
1356 ExitOnError ExitOnErr;
1357
1358 DebugStringTableSubsectionRef CVStrTab;
1359 DebugChecksumsSubsectionRef Checksums;
1360 DebugLinesSubsectionRef Lines;
1361 uint32_t OffsetInLinetable;
1362
1363 if (!findLineTable(C, Addr, CVStrTab, Checksums, Lines, OffsetInLinetable))
1364 return {"", 0};
1365
1366 uint32_t NameIndex;
1367 uint32_t LineNumber;
1368 for (LineColumnEntry &Entry : Lines) {
1369 for (const LineNumberEntry &LN : Entry.LineNumbers) {
1370 if (LN.Offset > OffsetInLinetable) {
1371 StringRef Filename =
1372 ExitOnErr(getFileName(CVStrTab, Checksums, NameIndex));
1373 return {Filename, LineNumber};
1374 }
1375 LineInfo LI(LN.Flags);
1376 NameIndex = Entry.NameIndex;
1377 LineNumber = LI.getStartLine();
1378 }
1379 }
1380 StringRef Filename = ExitOnErr(getFileName(CVStrTab, Checksums, NameIndex));
1381 return {Filename, LineNumber};
1382}