blob: c2b08265e840bad62e46b818cde9a7ae7309c099 [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"
Reid Kleckner44cdb102017-06-19 17:21:45 +000019#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
Zachary Turner0d07a8e2017-12-14 18:07:04 +000020#include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000021#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
Zachary Turnerca6dbf12017-11-30 18:39:50 +000022#include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
Zachary Turneree9906d2017-08-11 19:00:03 +000023#include "llvm/DebugInfo/CodeView/RecordName.h"
Zachary Turner59e3ae82017-08-08 18:34:44 +000024#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
Zachary Turner6708e0b2017-07-10 21:01:37 +000025#include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
Reid Kleckner651db912017-07-18 00:21:25 +000026#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000027#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerd0e6e242017-06-21 17:25:56 +000028#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
Rui Ueyama52896622017-01-12 03:09:25 +000029#include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
Rui Ueyamab28c6d42016-09-16 04:32:33 +000030#include "llvm/DebugInfo/MSF/MSFBuilder.h"
Rui Ueyama7f382992016-09-15 18:55:18 +000031#include "llvm/DebugInfo/MSF/MSFCommon.h"
Reid Kleckner651db912017-07-18 00:21:25 +000032#include "llvm/DebugInfo/PDB/GenericError.h"
Zachary Turner6708e0b2017-07-10 21:01:37 +000033#include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000034#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
35#include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
Zachary Turner946204c2017-08-09 04:23:25 +000036#include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000037#include "llvm/DebugInfo/PDB/Native/InfoStream.h"
38#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
Reid Kleckner651db912017-07-18 00:21:25 +000039#include "llvm/DebugInfo/PDB/Native/NativeSession.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000040#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
41#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
Rafael Espindolaa0f30da2017-05-02 20:19:42 +000042#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
Reid Klecknerd91ca762017-07-19 17:26:07 +000043#include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000044#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
45#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
Reid Kleckner651db912017-07-18 00:21:25 +000046#include "llvm/DebugInfo/PDB/PDB.h"
Rui Ueyama20df4ec2016-10-31 21:09:21 +000047#include "llvm/Object/COFF.h"
David Blaikieddcd8562018-03-26 23:43:29 +000048#include "llvm/Object/CVDebugRecord.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),
Zachary Turnera6fb5362018-03-23 18:43:39 +000088 IDTable(Alloc), GlobalTypeTable(Alloc), GlobalIDTable(Alloc) {
89 // This isn't strictly necessary, but link.exe usually puts an empty string
90 // as the first "valid" string in the string table, so we do the same in
91 // order to maintain as much byte-for-byte compatibility as possible.
92 PDBStrTab.insert("");
93 }
Reid Kleckner0faf6d72017-07-14 00:14:58 +000094
95 /// Emit the basic PDB structure: initial streams, headers, etc.
Zachary Turner024323c2017-08-15 21:31:41 +000096 void initialize(const llvm::codeview::DebugInfo &BuildId);
Reid Kleckner0faf6d72017-07-14 00:14:58 +000097
Zachary Turnerf2282762018-03-23 19:57:25 +000098 /// Add natvis files specified on the command line.
99 void addNatvisFiles();
100
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000101 /// Link CodeView from each object file in the symbol table into the PDB.
102 void addObjectsToPDB();
103
104 /// Link CodeView from a single object file into the PDB.
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000105 void addObjFile(ObjFile *File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000106
Reid Kleckner651db912017-07-18 00:21:25 +0000107 /// Produce a mapping from the type and item indices used in the object
108 /// file to those in the destination PDB.
109 ///
110 /// If the object file uses a type server PDB (compiled with /Zi), merge TPI
111 /// and IPI from the type server PDB and return a map for it. Each unique type
112 /// server PDB is merged at most once, so this may return an existing index
113 /// mapping.
114 ///
115 /// If the object does not use a type server PDB (compiled with /Z7), we merge
116 /// all the type and item records from the .debug$S stream and fill in the
117 /// caller-provided ObjectIndexMap.
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000118 Expected<const CVIndexMap&> mergeDebugT(ObjFile *File,
119 CVIndexMap &ObjectIndexMap);
Reid Kleckner651db912017-07-18 00:21:25 +0000120
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000121 Expected<const CVIndexMap&> maybeMergeTypeServerPDB(ObjFile *File,
122 TypeServer2Record &TS);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000123
124 /// Add the section map and section contributions to the PDB.
Reid Kleckner175af4b2017-08-03 21:15:09 +0000125 void addSections(ArrayRef<OutputSection *> OutputSections,
126 ArrayRef<uint8_t> SectionTable);
127
128 void addSectionContrib(pdb::DbiModuleDescriptorBuilder &LinkerModule,
129 OutputSection *OS, Chunk *C);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000130
131 /// Write the PDB to disk.
132 void commit();
133
134private:
135 BumpPtrAllocator Alloc;
136
137 SymbolTable *Symtab;
138
139 pdb::PDBFileBuilder Builder;
140
141 /// Type records that will go into the PDB TPI stream.
Zachary Turnerca6dbf12017-11-30 18:39:50 +0000142 MergingTypeTableBuilder TypeTable;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000143
144 /// Item records that will go into the PDB IPI stream.
Zachary Turnerca6dbf12017-11-30 18:39:50 +0000145 MergingTypeTableBuilder IDTable;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000146
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000147 /// Type records that will go into the PDB TPI stream (for /DEBUG:GHASH)
148 GlobalTypeTableBuilder GlobalTypeTable;
149
150 /// Item records that will go into the PDB IPI stream (for /DEBUG:GHASH)
151 GlobalTypeTableBuilder GlobalIDTable;
152
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000153 /// PDBs use a single global string table for filenames in the file checksum
154 /// table.
155 DebugStringTableSubsection PDBStrTab;
156
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000157 llvm::SmallString<128> NativePath;
158
Zachary Turner3868cfd2018-02-28 18:09:18 +0000159 /// A list of other PDBs which are loaded during the linking process and which
160 /// we need to keep around since the linking operation may reference pointers
161 /// inside of these PDBs.
162 llvm::SmallVector<std::unique_ptr<pdb::NativeSession>, 2> LoadedPDBs;
163
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000164 std::vector<pdb::SecMapEntry> SectionMap;
Reid Kleckner651db912017-07-18 00:21:25 +0000165
166 /// Type index mappings of type server PDBs that we've loaded so far.
167 std::map<GUID, CVIndexMap> TypeServerIndexMappings;
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000168
169 /// List of TypeServer PDBs which cannot be loaded.
170 /// Cached to prevent repeated load attempts.
171 std::set<GUID> MissingTypeServerPDBs;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000172};
173}
174
Sam Clegg0fb6faa2017-12-08 01:09:21 +0000175static SectionChunk *findByName(ArrayRef<SectionChunk *> Sections,
Rui Ueyamabe939b32016-11-21 17:22:35 +0000176 StringRef Name) {
177 for (SectionChunk *C : Sections)
178 if (C->getSectionName() == Name)
179 return C;
180 return nullptr;
181}
182
Reid Kleckner44cdb102017-06-19 17:21:45 +0000183static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
184 StringRef SecName) {
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000185 // First 4 bytes are section magic.
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000186 if (Data.size() < 4)
Rui Ueyama52896622017-01-12 03:09:25 +0000187 fatal(SecName + " too short");
Reid Kleckner44cdb102017-06-19 17:21:45 +0000188 if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
Rui Ueyama52896622017-01-12 03:09:25 +0000189 fatal(SecName + " has an invalid magic");
Rui Ueyama26186c72016-12-09 04:46:54 +0000190 return Data.slice(4);
191}
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000192
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000193static ArrayRef<uint8_t> getDebugSection(ObjFile *File, StringRef SecName) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000194 if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
195 return consumeDebugMagic(Sec->getContents(), SecName);
196 return {};
197}
198
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000199// A COFF .debug$H section is currently a clang extension. This function checks
200// if a .debug$H section is in a format that we expect / understand, so that we
201// can ignore any sections which are coincidentally also named .debug$H but do
202// not contain a format we recognize.
203static bool canUseDebugH(ArrayRef<uint8_t> DebugH) {
204 if (DebugH.size() < sizeof(object::debug_h_header))
205 return false;
206 auto *Header =
207 reinterpret_cast<const object::debug_h_header *>(DebugH.data());
208 DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
209 return Header->Magic == COFF::DEBUG_HASHES_SECTION_MAGIC &&
210 Header->Version == 0 &&
211 Header->HashAlgorithm == uint16_t(GlobalTypeHashAlg::SHA1) &&
212 (DebugH.size() % 20 == 0);
213}
214
215static Optional<ArrayRef<uint8_t>> getDebugH(ObjFile *File) {
216 SectionChunk *Sec = findByName(File->getDebugChunks(), ".debug$H");
217 if (!Sec)
218 return llvm::None;
219 ArrayRef<uint8_t> Contents = Sec->getContents();
220 if (!canUseDebugH(Contents))
221 return None;
222 return Contents;
223}
224
225static ArrayRef<GloballyHashedType>
226getHashesFromDebugH(ArrayRef<uint8_t> DebugH) {
227 assert(canUseDebugH(DebugH));
228
229 DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
230 uint32_t Count = DebugH.size() / sizeof(GloballyHashedType);
231 return {reinterpret_cast<const GloballyHashedType *>(DebugH.data()), Count};
232}
233
Reid Kleckner5d577522017-03-24 17:26:38 +0000234static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
Zachary Turner3e3936d2017-11-29 19:35:21 +0000235 TypeCollection &TypeTable) {
Reid Kleckner5d577522017-03-24 17:26:38 +0000236 // Start the TPI or IPI stream header.
237 TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
Rui Ueyama52896622017-01-12 03:09:25 +0000238
Reid Klecknerd91ca762017-07-19 17:26:07 +0000239 // Flatten the in memory type table and hash each type.
Zachary Turner3e3936d2017-11-29 19:35:21 +0000240 TypeTable.ForEachRecord([&](TypeIndex TI, const CVType &Type) {
Reid Klecknerd91ca762017-07-19 17:26:07 +0000241 auto Hash = pdb::hashTypeRecord(Type);
242 if (auto E = Hash.takeError())
243 fatal("type hashing error");
Zachary Turner3e3936d2017-11-29 19:35:21 +0000244 TpiBuilder.addTypeRecord(Type.RecordData, *Hash);
Reid Kleckner5d577522017-03-24 17:26:38 +0000245 });
Reid Kleckner5d577522017-03-24 17:26:38 +0000246}
247
Reid Kleckner651db912017-07-18 00:21:25 +0000248static Optional<TypeServer2Record>
249maybeReadTypeServerRecord(CVTypeArray &Types) {
250 auto I = Types.begin();
251 if (I == Types.end())
252 return None;
253 const CVType &Type = *I;
254 if (Type.kind() != LF_TYPESERVER2)
255 return None;
256 TypeServer2Record TS;
257 if (auto EC = TypeDeserializer::deserializeAs(const_cast<CVType &>(Type), TS))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000258 fatal("error reading type server record: " + toString(std::move(EC)));
Reid Kleckner651db912017-07-18 00:21:25 +0000259 return std::move(TS);
260}
261
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000262Expected<const CVIndexMap&> PDBLinker::mergeDebugT(ObjFile *File,
263 CVIndexMap &ObjectIndexMap) {
Zachary Turner727f1532018-01-17 19:16:26 +0000264 ScopedTimer T(TypeMergingTimer);
265
Reid Kleckner44cdb102017-06-19 17:21:45 +0000266 ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
267 if (Data.empty())
Reid Kleckner651db912017-07-18 00:21:25 +0000268 return ObjectIndexMap;
Reid Kleckner6597c282017-07-13 20:12:23 +0000269
Reid Kleckner44cdb102017-06-19 17:21:45 +0000270 BinaryByteStream Stream(Data, support::little);
271 CVTypeArray Types;
272 BinaryStreamReader Reader(Stream);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000273 if (auto EC = Reader.readArray(Types, Reader.getLength()))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000274 fatal("Reader::readArray failed: " + toString(std::move(EC)));
Reid Kleckner651db912017-07-18 00:21:25 +0000275
276 // Look through type servers. If we've already seen this type server, don't
277 // merge any type information.
278 if (Optional<TypeServer2Record> TS = maybeReadTypeServerRecord(Types))
279 return maybeMergeTypeServerPDB(File, *TS);
280
281 // This is a /Z7 object. Fill in the temporary, caller-provided
282 // ObjectIndexMap.
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000283 if (Config->DebugGHashes) {
284 ArrayRef<GloballyHashedType> Hashes;
285 std::vector<GloballyHashedType> OwnedHashes;
286 if (Optional<ArrayRef<uint8_t>> DebugH = getDebugH(File))
287 Hashes = getHashesFromDebugH(*DebugH);
288 else {
289 OwnedHashes = GloballyHashedType::hashTypes(Types);
290 Hashes = OwnedHashes;
291 }
292
293 if (auto Err = mergeTypeAndIdRecords(GlobalIDTable, GlobalTypeTable,
294 ObjectIndexMap.TPIMap, Types, Hashes))
295 fatal("codeview::mergeTypeAndIdRecords failed: " +
296 toString(std::move(Err)));
297 } else {
298 if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable,
299 ObjectIndexMap.TPIMap, Types))
300 fatal("codeview::mergeTypeAndIdRecords failed: " +
301 toString(std::move(Err)));
302 }
Reid Kleckner651db912017-07-18 00:21:25 +0000303 return ObjectIndexMap;
304}
305
306static Expected<std::unique_ptr<pdb::NativeSession>>
307tryToLoadPDB(const GUID &GuidFromObj, StringRef TSPath) {
Peter Collingbourne75257bc2017-10-20 19:48:26 +0000308 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(
309 TSPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
310 if (!MBOrErr)
311 return errorCodeToError(MBOrErr.getError());
312
Reid Kleckner651db912017-07-18 00:21:25 +0000313 std::unique_ptr<pdb::IPDBSession> ThisSession;
Peter Collingbourne75257bc2017-10-20 19:48:26 +0000314 if (auto EC = pdb::NativeSession::createFromPdb(
315 MemoryBuffer::getMemBuffer(Driver->takeBuffer(std::move(*MBOrErr)),
316 /*RequiresNullTerminator=*/false),
317 ThisSession))
Reid Kleckner651db912017-07-18 00:21:25 +0000318 return std::move(EC);
319
320 std::unique_ptr<pdb::NativeSession> NS(
321 static_cast<pdb::NativeSession *>(ThisSession.release()));
322 pdb::PDBFile &File = NS->getPDBFile();
323 auto ExpectedInfo = File.getPDBInfoStream();
324 // All PDB Files should have an Info stream.
325 if (!ExpectedInfo)
326 return ExpectedInfo.takeError();
327
328 // Just because a file with a matching name was found and it was an actual
329 // PDB file doesn't mean it matches. For it to match the InfoStream's GUID
330 // must match the GUID specified in the TypeServer2 record.
331 if (ExpectedInfo->getGuid() != GuidFromObj)
332 return make_error<pdb::GenericError>(
333 pdb::generic_error_code::type_server_not_found, TSPath);
334
335 return std::move(NS);
336}
337
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000338Expected<const CVIndexMap&> PDBLinker::maybeMergeTypeServerPDB(ObjFile *File,
339 TypeServer2Record &TS) {
340 const GUID& TSId = TS.getGuid();
341 StringRef TSPath = TS.getName();
342
343 // First, check if the PDB has previously failed to load.
344 if (MissingTypeServerPDBs.count(TSId))
345 return make_error<pdb::GenericError>(
346 pdb::generic_error_code::type_server_not_found, TSPath);
347
348 // Second, check if we already loaded a PDB with this GUID. Return the type
Reid Kleckner651db912017-07-18 00:21:25 +0000349 // index mapping if we have it.
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000350 auto Insertion = TypeServerIndexMappings.insert({TSId, CVIndexMap()});
Reid Kleckner651db912017-07-18 00:21:25 +0000351 CVIndexMap &IndexMap = Insertion.first->second;
352 if (!Insertion.second)
353 return IndexMap;
354
355 // Mark this map as a type server map.
356 IndexMap.IsTypeServerMap = true;
357
358 // Check for a PDB at:
359 // 1. The given file path
360 // 2. Next to the object file or archive file
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000361 auto ExpectedSession = tryToLoadPDB(TSId, TSPath);
Reid Kleckner651db912017-07-18 00:21:25 +0000362 if (!ExpectedSession) {
363 consumeError(ExpectedSession.takeError());
364 StringRef LocalPath =
365 !File->ParentName.empty() ? File->ParentName : File->getName();
366 SmallString<128> Path = sys::path::parent_path(LocalPath);
Reid Klecknerf8522d82017-07-18 00:33:53 +0000367 sys::path::append(
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000368 Path, sys::path::filename(TSPath, sys::path::Style::windows));
369 ExpectedSession = tryToLoadPDB(TSId, Path);
Reid Kleckner651db912017-07-18 00:21:25 +0000370 }
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000371 if (auto E = ExpectedSession.takeError()) {
372 TypeServerIndexMappings.erase(TSId);
373 MissingTypeServerPDBs.emplace(TSId);
374 return std::move(E);
375 }
Reid Kleckner651db912017-07-18 00:21:25 +0000376
Zachary Turner3868cfd2018-02-28 18:09:18 +0000377 pdb::NativeSession *Session = ExpectedSession->get();
378
379 // Keep a strong reference to this PDB, so that it's safe to hold pointers
380 // into the file.
381 LoadedPDBs.push_back(std::move(*ExpectedSession));
382
383 auto ExpectedTpi = Session->getPDBFile().getPDBTpiStream();
Reid Kleckner651db912017-07-18 00:21:25 +0000384 if (auto E = ExpectedTpi.takeError())
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000385 fatal("Type server does not have TPI stream: " + toString(std::move(E)));
Zachary Turner3868cfd2018-02-28 18:09:18 +0000386 auto ExpectedIpi = Session->getPDBFile().getPDBIpiStream();
Reid Kleckner651db912017-07-18 00:21:25 +0000387 if (auto E = ExpectedIpi.takeError())
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000388 fatal("Type server does not have TPI stream: " + toString(std::move(E)));
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000389
390 if (Config->DebugGHashes) {
391 // PDBs do not actually store global hashes, so when merging a type server
392 // PDB we have to synthesize global hashes. To do this, we first synthesize
393 // global hashes for the TPI stream, since it is independent, then we
394 // synthesize hashes for the IPI stream, using the hashes for the TPI stream
395 // as inputs.
396 auto TpiHashes = GloballyHashedType::hashTypes(ExpectedTpi->typeArray());
397 auto IpiHashes =
398 GloballyHashedType::hashIds(ExpectedIpi->typeArray(), TpiHashes);
399
400 // Merge TPI first, because the IPI stream will reference type indices.
401 if (auto Err = mergeTypeRecords(GlobalTypeTable, IndexMap.TPIMap,
402 ExpectedTpi->typeArray(), TpiHashes))
403 fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
404
405 // Merge IPI.
406 if (auto Err =
407 mergeIdRecords(GlobalIDTable, IndexMap.TPIMap, IndexMap.IPIMap,
408 ExpectedIpi->typeArray(), IpiHashes))
409 fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
410 } else {
411 // Merge TPI first, because the IPI stream will reference type indices.
412 if (auto Err = mergeTypeRecords(TypeTable, IndexMap.TPIMap,
413 ExpectedTpi->typeArray()))
414 fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
415
416 // Merge IPI.
417 if (auto Err = mergeIdRecords(IDTable, IndexMap.TPIMap, IndexMap.IPIMap,
418 ExpectedIpi->typeArray()))
419 fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
420 }
Reid Kleckner651db912017-07-18 00:21:25 +0000421
422 return IndexMap;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000423}
424
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000425static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
426 if (TI.isSimple())
427 return true;
428 if (TI.toArrayIndex() >= TypeIndexMap.size())
429 return false;
430 TI = TypeIndexMap[TI.toArrayIndex()];
431 return true;
432}
433
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000434static void remapTypesInSymbolRecord(ObjFile *File, SymbolKind SymKind,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000435 MutableArrayRef<uint8_t> Contents,
Reid Kleckner651db912017-07-18 00:21:25 +0000436 const CVIndexMap &IndexMap,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000437 ArrayRef<TiReference> TypeRefs) {
438 for (const TiReference &Ref : TypeRefs) {
439 unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000440 if (Contents.size() < Ref.Offset + ByteSize)
441 fatal("symbol record too short");
Reid Kleckner651db912017-07-18 00:21:25 +0000442
443 // This can be an item index or a type index. Choose the appropriate map.
444 ArrayRef<TypeIndex> TypeOrItemMap = IndexMap.TPIMap;
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000445 bool IsItemIndex = Ref.Kind == TiRefKind::IndexRef;
446 if (IsItemIndex && IndexMap.IsTypeServerMap)
Reid Kleckner651db912017-07-18 00:21:25 +0000447 TypeOrItemMap = IndexMap.IPIMap;
448
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000449 MutableArrayRef<TypeIndex> TIs(
450 reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000451 for (TypeIndex &TI : TIs) {
Reid Kleckner651db912017-07-18 00:21:25 +0000452 if (!remapTypeIndex(TI, TypeOrItemMap)) {
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000453 log("ignoring symbol record of kind 0x" + utohexstr(SymKind) + " in " +
454 File->getName() + " with bad " + (IsItemIndex ? "item" : "type") +
455 " index 0x" + utohexstr(TI.getIndex()));
Reid Kleckner5d82f682017-10-23 22:44:51 +0000456 TI = TypeIndex(SimpleTypeKind::NotTranslated);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000457 continue;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000458 }
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000459 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000460 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000461}
462
Zachary Turner60478582018-01-05 19:12:40 +0000463static void
464recordStringTableReferenceAtOffset(MutableArrayRef<uint8_t> Contents,
465 uint32_t Offset,
466 std::vector<ulittle32_t *> &StrTableRefs) {
467 Contents =
468 Contents.drop_front(Offset).take_front(sizeof(support::ulittle32_t));
469 ulittle32_t *Index = reinterpret_cast<ulittle32_t *>(Contents.data());
470 StrTableRefs.push_back(Index);
471}
472
473static void
474recordStringTableReferences(SymbolKind Kind, MutableArrayRef<uint8_t> Contents,
475 std::vector<ulittle32_t *> &StrTableRefs) {
476 // For now we only handle S_FILESTATIC, but we may need the same logic for
477 // S_DEFRANGE and S_DEFRANGE_SUBFIELD. However, I cannot seem to generate any
478 // PDBs that contain these types of records, so because of the uncertainty
479 // they are omitted here until we can prove that it's necessary.
480 switch (Kind) {
481 case SymbolKind::S_FILESTATIC:
482 // FileStaticSym::ModFileOffset
483 recordStringTableReferenceAtOffset(Contents, 4, StrTableRefs);
484 break;
485 case SymbolKind::S_DEFRANGE:
486 case SymbolKind::S_DEFRANGE_SUBFIELD:
487 log("Not fixing up string table reference in S_DEFRANGE / "
488 "S_DEFRANGE_SUBFIELD record");
489 break;
Zachary Turner9e52e502018-01-05 19:28:39 +0000490 default:
491 break;
Zachary Turner60478582018-01-05 19:12:40 +0000492 }
493}
494
Zachary Turner59e3ae82017-08-08 18:34:44 +0000495static SymbolKind symbolKind(ArrayRef<uint8_t> RecordData) {
496 const RecordPrefix *Prefix =
497 reinterpret_cast<const RecordPrefix *>(RecordData.data());
498 return static_cast<SymbolKind>(uint16_t(Prefix->RecordKind));
499}
500
501/// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
502static void translateIdSymbols(MutableArrayRef<uint8_t> &RecordData,
Zachary Turner3e3936d2017-11-29 19:35:21 +0000503 TypeCollection &IDTable) {
Zachary Turner59e3ae82017-08-08 18:34:44 +0000504 RecordPrefix *Prefix = reinterpret_cast<RecordPrefix *>(RecordData.data());
505
506 SymbolKind Kind = symbolKind(RecordData);
507
508 if (Kind == SymbolKind::S_PROC_ID_END) {
509 Prefix->RecordKind = SymbolKind::S_END;
510 return;
511 }
512
513 // In an object file, GPROC32_ID has an embedded reference which refers to the
514 // single object file type index namespace. This has already been translated
515 // to the PDB file's ID stream index space, but we need to convert this to a
516 // symbol that refers to the type stream index space. So we remap again from
517 // ID index space to type index space.
518 if (Kind == SymbolKind::S_GPROC32_ID || Kind == SymbolKind::S_LPROC32_ID) {
519 SmallVector<TiReference, 1> Refs;
520 auto Content = RecordData.drop_front(sizeof(RecordPrefix));
521 CVSymbol Sym(Kind, RecordData);
522 discoverTypeIndicesInSymbol(Sym, Refs);
523 assert(Refs.size() == 1);
524 assert(Refs.front().Count == 1);
525
526 TypeIndex *TI =
527 reinterpret_cast<TypeIndex *>(Content.data() + Refs[0].Offset);
528 // `TI` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
529 // the IPI stream, whose `FunctionType` member refers to the TPI stream.
530 // Note that LF_FUNC_ID and LF_MEMFUNC_ID have the same record layout, and
531 // in both cases we just need the second type index.
532 if (!TI->isSimple() && !TI->isNoneType()) {
Zachary Turner3e3936d2017-11-29 19:35:21 +0000533 CVType FuncIdData = IDTable.getType(*TI);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000534 SmallVector<TypeIndex, 2> Indices;
535 discoverTypeIndices(FuncIdData, Indices);
536 assert(Indices.size() == 2);
537 *TI = Indices[1];
538 }
539
540 Kind = (Kind == SymbolKind::S_GPROC32_ID) ? SymbolKind::S_GPROC32
541 : SymbolKind::S_LPROC32;
542 Prefix->RecordKind = uint16_t(Kind);
543 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000544}
545
546/// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
547/// The object file may not be aligned.
548static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
549 BumpPtrAllocator &Alloc) {
550 size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
551 assert(Size >= 4 && "record too short");
552 assert(Size <= MaxRecordLength && "record too long");
553 void *Mem = Alloc.Allocate(Size, 4);
554
555 // Copy the symbol record and zero out any padding bytes.
556 MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
557 memcpy(NewData.data(), Sym.data().data(), Sym.length());
558 memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
559
560 // Update the record prefix length. It should point to the beginning of the
Zachary Turner59e3ae82017-08-08 18:34:44 +0000561 // next record.
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000562 auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000563 Prefix->RecordLen = Size - 2;
564 return NewData;
565}
566
Reid Kleckner3f851922017-07-06 16:39:32 +0000567/// Return true if this symbol opens a scope. This implies that the symbol has
568/// "parent" and "end" fields, which contain the offset of the S_END or
569/// S_INLINESITE_END record.
570static bool symbolOpensScope(SymbolKind Kind) {
571 switch (Kind) {
572 case SymbolKind::S_GPROC32:
573 case SymbolKind::S_LPROC32:
574 case SymbolKind::S_LPROC32_ID:
575 case SymbolKind::S_GPROC32_ID:
576 case SymbolKind::S_BLOCK32:
577 case SymbolKind::S_SEPCODE:
578 case SymbolKind::S_THUNK32:
579 case SymbolKind::S_INLINESITE:
580 case SymbolKind::S_INLINESITE2:
581 return true;
582 default:
583 break;
584 }
585 return false;
586}
587
588static bool symbolEndsScope(SymbolKind Kind) {
589 switch (Kind) {
590 case SymbolKind::S_END:
591 case SymbolKind::S_PROC_ID_END:
592 case SymbolKind::S_INLINESITE_END:
593 return true;
594 default:
595 break;
596 }
597 return false;
598}
599
600struct ScopeRecord {
601 ulittle32_t PtrParent;
602 ulittle32_t PtrEnd;
603};
604
605struct SymbolScope {
606 ScopeRecord *OpeningRecord;
607 uint32_t ScopeOffset;
608};
609
610static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
611 uint32_t CurOffset, CVSymbol &Sym) {
612 assert(symbolOpensScope(Sym.kind()));
613 SymbolScope S;
614 S.ScopeOffset = CurOffset;
615 S.OpeningRecord = const_cast<ScopeRecord *>(
616 reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
617 S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
618 Stack.push_back(S);
619}
620
621static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000622 uint32_t CurOffset, ObjFile *File) {
Reid Kleckner3f851922017-07-06 16:39:32 +0000623 if (Stack.empty()) {
624 warn("symbol scopes are not balanced in " + File->getName());
625 return;
626 }
627 SymbolScope S = Stack.pop_back_val();
628 S.OpeningRecord->PtrEnd = CurOffset;
629}
630
Zachary Turneree9906d2017-08-11 19:00:03 +0000631static bool symbolGoesInModuleStream(const CVSymbol &Sym) {
632 switch (Sym.kind()) {
633 case SymbolKind::S_GDATA32:
634 case SymbolKind::S_CONSTANT:
635 case SymbolKind::S_UDT:
636 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
637 // since they are synthesized by the linker in response to S_GPROC32 and
638 // S_LPROC32, but if we do see them, don't put them in the module stream I
639 // guess.
640 case SymbolKind::S_PROCREF:
641 case SymbolKind::S_LPROCREF:
642 return false;
643 // S_GDATA32 does not go in the module stream, but S_LDATA32 does.
644 case SymbolKind::S_LDATA32:
645 default:
646 return true;
647 }
648}
649
650static bool symbolGoesInGlobalsStream(const CVSymbol &Sym) {
651 switch (Sym.kind()) {
652 case SymbolKind::S_CONSTANT:
Zachary Turneree9906d2017-08-11 19:00:03 +0000653 case SymbolKind::S_GDATA32:
654 // S_LDATA32 goes in both the module stream and the globals stream.
655 case SymbolKind::S_LDATA32:
656 case SymbolKind::S_GPROC32:
657 case SymbolKind::S_LPROC32:
658 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
659 // since they are synthesized by the linker in response to S_GPROC32 and
660 // S_LPROC32, but if we do see them, copy them straight through.
661 case SymbolKind::S_PROCREF:
662 case SymbolKind::S_LPROCREF:
663 return true;
Zachary Turner302dc8b2017-08-14 18:44:58 +0000664 // FIXME: For now, we drop all S_UDT symbols (i.e. they don't go in the
665 // globals stream or the modules stream). These have special handling which
666 // needs more investigation before we can get right, but by putting them all
667 // into the globals stream WinDbg fails to display local variables of class
668 // types saying that it cannot find the type Foo *. So as a stopgap just to
669 // keep things working, we drop them.
670 case SymbolKind::S_UDT:
Zachary Turneree9906d2017-08-11 19:00:03 +0000671 default:
672 return false;
673 }
674}
675
676static void addGlobalSymbol(pdb::GSIStreamBuilder &Builder, ObjFile &File,
677 const CVSymbol &Sym) {
678 switch (Sym.kind()) {
679 case SymbolKind::S_CONSTANT:
680 case SymbolKind::S_UDT:
681 case SymbolKind::S_GDATA32:
682 case SymbolKind::S_LDATA32:
683 case SymbolKind::S_PROCREF:
684 case SymbolKind::S_LPROCREF:
685 Builder.addGlobalSymbol(Sym);
686 break;
687 case SymbolKind::S_GPROC32:
688 case SymbolKind::S_LPROC32: {
689 SymbolRecordKind K = SymbolRecordKind::ProcRefSym;
690 if (Sym.kind() == SymbolKind::S_LPROC32)
691 K = SymbolRecordKind::LocalProcRef;
692 ProcRefSym PS(K);
693 PS.Module = static_cast<uint16_t>(File.ModuleDBI->getModuleIndex());
694 // For some reason, MSVC seems to add one to this value.
695 ++PS.Module;
696 PS.Name = getSymbolName(Sym);
697 PS.SumName = 0;
698 PS.SymOffset = File.ModuleDBI->getNextSymbolOffset();
699 Builder.addGlobalSymbol(PS);
700 break;
701 }
702 default:
703 llvm_unreachable("Invalid symbol kind!");
704 }
705}
706
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000707static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjFile *File,
Zachary Turneree9906d2017-08-11 19:00:03 +0000708 pdb::GSIStreamBuilder &GsiBuilder,
Reid Kleckner651db912017-07-18 00:21:25 +0000709 const CVIndexMap &IndexMap,
Zachary Turner3e3936d2017-11-29 19:35:21 +0000710 TypeCollection &IDTable,
Zachary Turner60478582018-01-05 19:12:40 +0000711 std::vector<ulittle32_t *> &StringTableRefs,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000712 BinaryStreamRef SymData) {
713 // FIXME: Improve error recovery by warning and skipping records when
714 // possible.
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000715 ArrayRef<uint8_t> SymsBuffer;
716 cantFail(SymData.readBytes(0, SymData.getLength(), SymsBuffer));
Reid Kleckner3f851922017-07-06 16:39:32 +0000717 SmallVector<SymbolScope, 4> Scopes;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000718
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000719 auto EC = forEachCodeViewRecord<CVSymbol>(
720 SymsBuffer, [&](const CVSymbol &Sym) -> llvm::Error {
721 // Discover type index references in the record. Skip it if we don't
722 // know where they are.
723 SmallVector<TiReference, 32> TypeRefs;
724 if (!discoverTypeIndicesInSymbol(Sym, TypeRefs)) {
725 log("ignoring unknown symbol record with kind 0x" +
726 utohexstr(Sym.kind()));
727 return Error::success();
728 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000729
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000730 // Copy the symbol record so we can mutate it.
731 MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000732
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000733 // Re-map all the type index references.
734 MutableArrayRef<uint8_t> Contents =
735 NewData.drop_front(sizeof(RecordPrefix));
736 remapTypesInSymbolRecord(File, Sym.kind(), Contents, IndexMap,
737 TypeRefs);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000738
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000739 // An object file may have S_xxx_ID symbols, but these get converted to
740 // "real" symbols in a PDB.
741 translateIdSymbols(NewData, IDTable);
Zachary Turner60478582018-01-05 19:12:40 +0000742
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000743 // If this record refers to an offset in the object file's string table,
744 // add that item to the global PDB string table and re-write the index.
745 recordStringTableReferences(Sym.kind(), Contents, StringTableRefs);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000746
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000747 SymbolKind NewKind = symbolKind(NewData);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000748
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000749 // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
750 CVSymbol NewSym(NewKind, NewData);
751 if (symbolOpensScope(NewKind))
752 scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(),
753 NewSym);
754 else if (symbolEndsScope(NewKind))
755 scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
Zachary Turneree9906d2017-08-11 19:00:03 +0000756
Zachary Turner1bc2ce62018-01-18 18:35:01 +0000757 // Add the symbol to the globals stream if necessary. Do this before
758 // adding the symbol to the module since we may need to get the next
759 // symbol offset, and writing to the module's symbol stream will update
760 // that offset.
761 if (symbolGoesInGlobalsStream(NewSym))
762 addGlobalSymbol(GsiBuilder, *File, NewSym);
763
764 // Add the symbol to the module.
765 if (symbolGoesInModuleStream(NewSym))
766 File->ModuleDBI->addSymbol(NewSym);
767 return Error::success();
768 });
769 cantFail(std::move(EC));
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000770}
771
Reid Kleckner44cdb102017-06-19 17:21:45 +0000772// Allocate memory for a .debug$S section and relocate it.
773static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
774 SectionChunk *DebugChunk) {
775 uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk->getSize());
776 assert(DebugChunk->OutputSectionOff == 0 &&
777 "debug sections should not be in output sections");
778 DebugChunk->writeTo(Buffer);
779 return consumeDebugMagic(makeArrayRef(Buffer, DebugChunk->getSize()),
780 ".debug$S");
781}
782
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000783void PDBLinker::addObjFile(ObjFile *File) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000784 // Add a module descriptor for every object file. We need to put an absolute
785 // path to the object into the PDB. If this is a plain object, we make its
786 // path absolute. If it's an object in an archive, we make the archive path
787 // absolute.
788 bool InArchive = !File->ParentName.empty();
789 SmallString<128> Path = InArchive ? File->ParentName : File->getName();
790 sys::fs::make_absolute(Path);
791 sys::path::native(Path, sys::path::Style::windows);
792 StringRef Name = InArchive ? File->getName() : StringRef(Path);
Zachary Turner2897e032017-05-25 21:16:03 +0000793
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000794 File->ModuleDBI = &ExitOnErr(Builder.getDbiBuilder().addModuleInfo(Name));
795 File->ModuleDBI->setObjFileName(Path);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000796
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000797 // Before we can process symbol substreams from .debug$S, we need to process
798 // type information, file checksums, and the string table. Add type info to
799 // the PDB first, so that we can get the map from object file type and item
800 // indices to PDB type and item indices.
Reid Kleckner651db912017-07-18 00:21:25 +0000801 CVIndexMap ObjectIndexMap;
Colden Cullenb9b6ed92018-01-31 17:48:04 +0000802 auto IndexMapResult = mergeDebugT(File, ObjectIndexMap);
803
804 // If the .debug$T sections fail to merge, assume there is no debug info.
805 if (!IndexMapResult) {
806 warn("Type server PDB for " + Name + " is invalid, ignoring debug info. " +
807 toString(IndexMapResult.takeError()));
808 return;
809 }
810
811 const CVIndexMap &IndexMap = *IndexMapResult;
Zachary Turner448dea42017-07-07 18:46:14 +0000812
Zachary Turner727f1532018-01-17 19:16:26 +0000813 ScopedTimer T(SymbolMergingTimer);
814
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000815 // Now do all live .debug$S sections.
Zachary Turner60478582018-01-05 19:12:40 +0000816 DebugStringTableSubsectionRef CVStrTab;
817 DebugChecksumsSubsectionRef Checksums;
818 std::vector<ulittle32_t *> StringTableReferences;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000819 for (SectionChunk *DebugChunk : File->getDebugChunks()) {
820 if (!DebugChunk->isLive() || DebugChunk->getSectionName() != ".debug$S")
821 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000822
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000823 ArrayRef<uint8_t> RelocatedDebugContents =
824 relocateDebugChunk(Alloc, DebugChunk);
825 if (RelocatedDebugContents.empty())
826 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000827
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000828 DebugSubsectionArray Subsections;
829 BinaryStreamReader Reader(RelocatedDebugContents, support::little);
830 ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
Rui Ueyama52896622017-01-12 03:09:25 +0000831
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000832 for (const DebugSubsectionRecord &SS : Subsections) {
833 switch (SS.kind()) {
Zachary Turner60478582018-01-05 19:12:40 +0000834 case DebugSubsectionKind::StringTable: {
Zachary Turner60478582018-01-05 19:12:40 +0000835 assert(!CVStrTab.valid() &&
836 "Encountered multiple string table subsections!");
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000837 ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
838 break;
Zachary Turner60478582018-01-05 19:12:40 +0000839 }
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000840 case DebugSubsectionKind::FileChecksums:
Zachary Turner60478582018-01-05 19:12:40 +0000841 assert(!Checksums.valid() &&
842 "Encountered multiple checksum subsections!");
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000843 ExitOnErr(Checksums.initialize(SS.getRecordData()));
844 break;
845 case DebugSubsectionKind::Lines:
846 // We can add the relocated line table directly to the PDB without
847 // modification because the file checksum offsets will stay the same.
848 File->ModuleDBI->addDebugSubsection(SS);
849 break;
850 case DebugSubsectionKind::Symbols:
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000851 if (Config->DebugGHashes) {
852 mergeSymbolRecords(Alloc, File, Builder.getGsiBuilder(), IndexMap,
Zachary Turner60478582018-01-05 19:12:40 +0000853 GlobalIDTable, StringTableReferences,
854 SS.getRecordData());
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000855 } else {
856 mergeSymbolRecords(Alloc, File, Builder.getGsiBuilder(), IndexMap,
Zachary Turner60478582018-01-05 19:12:40 +0000857 IDTable, StringTableReferences,
858 SS.getRecordData());
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000859 }
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000860 break;
861 default:
862 // FIXME: Process the rest of the subsections.
863 break;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000864 }
865 }
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000866 }
Zachary Turner60478582018-01-05 19:12:40 +0000867
868 // We should have seen all debug subsections across the entire object file now
869 // which means that if a StringTable subsection and Checksums subsection were
870 // present, now is the time to handle them.
871 if (!CVStrTab.valid()) {
872 if (Checksums.valid())
873 fatal(".debug$S sections with a checksums subsection must also contain a "
874 "string table subsection");
875
876 if (!StringTableReferences.empty())
877 warn("No StringTable subsection was encountered, but there are string "
878 "table references");
879 return;
880 }
881
882 // Rewrite each string table reference based on the value that the string
883 // assumes in the final PDB.
884 for (ulittle32_t *Ref : StringTableReferences) {
885 auto ExpectedString = CVStrTab.getString(*Ref);
886 if (!ExpectedString) {
887 warn("Invalid string table reference");
888 consumeError(ExpectedString.takeError());
889 continue;
890 }
891
892 *Ref = PDBStrTab.insert(*ExpectedString);
893 }
894
895 // Make a new file checksum table that refers to offsets in the PDB-wide
896 // string table. Generally the string table subsection appears after the
897 // checksum table, so we have to do this after looping over all the
898 // subsections.
899 auto NewChecksums = make_unique<DebugChecksumsSubsection>(PDBStrTab);
900 for (FileChecksumEntry &FC : Checksums) {
901 StringRef FileName = ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
902 ExitOnErr(Builder.getDbiBuilder().addModuleSourceFile(*File->ModuleDBI,
903 FileName));
904 NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
905 }
906 File->ModuleDBI->addDebugSubsection(std::move(NewChecksums));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000907}
908
Reid Klecknereacdf042017-07-27 18:25:59 +0000909static PublicSym32 createPublic(Defined *Def) {
910 PublicSym32 Pub(SymbolKind::S_PUB32);
911 Pub.Name = Def->getName();
912 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
913 if (D->getCOFFSymbol().isFunctionDefinition())
914 Pub.Flags = PublicSymFlags::Function;
915 } else if (isa<DefinedImportThunk>(Def)) {
916 Pub.Flags = PublicSymFlags::Function;
917 }
918
919 OutputSection *OS = Def->getChunk()->getOutputSection();
920 assert(OS && "all publics should be in final image");
921 Pub.Offset = Def->getRVA() - OS->getRVA();
922 Pub.Segment = OS->SectionIndex;
923 return Pub;
924}
925
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000926// Add all object files to the PDB. Merge .debug$T sections into IpiData and
927// TpiData.
928void PDBLinker::addObjectsToPDB() {
Zachary Turner727f1532018-01-17 19:16:26 +0000929 ScopedTimer T1(AddObjectsTimer);
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000930 for (ObjFile *File : ObjFile::Instances)
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000931 addObjFile(File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000932
933 Builder.getStringTableBuilder().setStrings(PDBStrTab);
Zachary Turner727f1532018-01-17 19:16:26 +0000934 T1.stop();
Reid Kleckner44cdb102017-06-19 17:21:45 +0000935
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000936 // Construct TPI and IPI stream contents.
Zachary Turner727f1532018-01-17 19:16:26 +0000937 ScopedTimer T2(TpiStreamLayoutTimer);
Zachary Turner0d07a8e2017-12-14 18:07:04 +0000938 if (Config->DebugGHashes) {
939 addTypeInfo(Builder.getTpiBuilder(), GlobalTypeTable);
940 addTypeInfo(Builder.getIpiBuilder(), GlobalIDTable);
941 } else {
942 addTypeInfo(Builder.getTpiBuilder(), TypeTable);
943 addTypeInfo(Builder.getIpiBuilder(), IDTable);
944 }
Zachary Turner727f1532018-01-17 19:16:26 +0000945 T2.stop();
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000946
Zachary Turner727f1532018-01-17 19:16:26 +0000947 ScopedTimer T3(GlobalsLayoutTimer);
Zachary Turneree9906d2017-08-11 19:00:03 +0000948 // Compute the public and global symbols.
949 auto &GsiBuilder = Builder.getGsiBuilder();
Reid Klecknereacdf042017-07-27 18:25:59 +0000950 std::vector<PublicSym32> Publics;
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000951 Symtab->forEachSymbol([&Publics](Symbol *S) {
Reid Klecknereacdf042017-07-27 18:25:59 +0000952 // Only emit defined, live symbols that have a chunk.
Rui Ueyama616cd992017-10-31 16:10:24 +0000953 auto *Def = dyn_cast<Defined>(S);
Reid Klecknereacdf042017-07-27 18:25:59 +0000954 if (Def && Def->isLive() && Def->getChunk())
955 Publics.push_back(createPublic(Def));
956 });
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000957
Reid Klecknereacdf042017-07-27 18:25:59 +0000958 if (!Publics.empty()) {
959 // Sort the public symbols and add them to the stream.
960 std::sort(Publics.begin(), Publics.end(),
961 [](const PublicSym32 &L, const PublicSym32 &R) {
962 return L.Name < R.Name;
963 });
Reid Klecknereacdf042017-07-27 18:25:59 +0000964 for (const PublicSym32 &Pub : Publics)
Zachary Turner946204c2017-08-09 04:23:25 +0000965 GsiBuilder.addPublicSymbol(Pub);
Reid Klecknereacdf042017-07-27 18:25:59 +0000966 }
Rui Ueyama52896622017-01-12 03:09:25 +0000967}
968
Zachary Turnerf2282762018-03-23 19:57:25 +0000969void PDBLinker::addNatvisFiles() {
970 for (StringRef File : Config->NatvisFiles) {
971 ErrorOr<std::unique_ptr<MemoryBuffer>> DataOrErr =
972 MemoryBuffer::getFile(File);
973 if (!DataOrErr) {
974 warn("Cannot open input file: " + File);
975 continue;
976 }
977 Builder.addInjectedSource(File, std::move(*DataOrErr));
978 }
979}
980
Zachary Turnere3fe6692018-04-16 18:17:13 +0000981static codeview::CPUType toCodeViewMachine(COFF::MachineTypes Machine) {
982 switch (Machine) {
983 case COFF::IMAGE_FILE_MACHINE_AMD64:
984 return codeview::CPUType::X64;
985 case COFF::IMAGE_FILE_MACHINE_ARM:
986 return codeview::CPUType::ARM7;
987 case COFF::IMAGE_FILE_MACHINE_ARM64:
988 return codeview::CPUType::ARM64;
989 case COFF::IMAGE_FILE_MACHINE_ARMNT:
990 return codeview::CPUType::ARMNT;
991 case COFF::IMAGE_FILE_MACHINE_I386:
992 return codeview::CPUType::Intel80386;
993 default:
994 llvm_unreachable("Unsupported CPU Type");
995 }
996}
997
Zachary Turner28e31ee2017-08-11 20:46:28 +0000998static void addCommonLinkerModuleSymbols(StringRef Path,
999 pdb::DbiModuleDescriptorBuilder &Mod,
1000 BumpPtrAllocator &Allocator) {
Zachary Turner28e31ee2017-08-11 20:46:28 +00001001 ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
1002 Compile3Sym CS(SymbolRecordKind::Compile3Sym);
1003 EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
Zachary Turner6708e0b2017-07-10 21:01:37 +00001004
1005 ONS.Name = "* Linker *";
1006 ONS.Signature = 0;
1007
Zachary Turnere3fe6692018-04-16 18:17:13 +00001008 CS.Machine = toCodeViewMachine(Config->Machine);
Zachary Turnerb57884e2017-08-11 21:14:01 +00001009 // Interestingly, if we set the string to 0.0.0.0, then when trying to view
1010 // local variables WinDbg emits an error that private symbols are not present.
1011 // By setting this to a valid MSVC linker version string, local variables are
1012 // displayed properly. As such, even though it is not representative of
Zachary Turnerf6822c82017-08-11 20:46:47 +00001013 // LLVM's version information, we need this for compatibility.
Zachary Turner6708e0b2017-07-10 21:01:37 +00001014 CS.Flags = CompileSym3Flags::None;
Zachary Turnerf6822c82017-08-11 20:46:47 +00001015 CS.VersionBackendBuild = 25019;
1016 CS.VersionBackendMajor = 14;
1017 CS.VersionBackendMinor = 10;
Zachary Turner6708e0b2017-07-10 21:01:37 +00001018 CS.VersionBackendQFE = 0;
Zachary Turnerf6822c82017-08-11 20:46:47 +00001019
1020 // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
1021 // linker module (which is by definition a backend), so we don't need to do
1022 // anything here. Also, it seems we can use "LLVM Linker" for the linker name
1023 // without any problems. Only the backend version has to be hardcoded to a
1024 // magic number.
Zachary Turner6708e0b2017-07-10 21:01:37 +00001025 CS.VersionFrontendBuild = 0;
1026 CS.VersionFrontendMajor = 0;
1027 CS.VersionFrontendMinor = 0;
1028 CS.VersionFrontendQFE = 0;
1029 CS.Version = "LLVM Linker";
1030 CS.setLanguage(SourceLanguage::Link);
1031
1032 ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
1033 std::string ArgStr = llvm::join(Args, " ");
1034 EBS.Fields.push_back("cwd");
1035 SmallString<64> cwd;
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001036 sys::fs::current_path(cwd);
Zachary Turner6708e0b2017-07-10 21:01:37 +00001037 EBS.Fields.push_back(cwd);
1038 EBS.Fields.push_back("exe");
Zachary Turnerf6822c82017-08-11 20:46:47 +00001039 SmallString<64> exe = Config->Argv[0];
1040 llvm::sys::fs::make_absolute(exe);
1041 EBS.Fields.push_back(exe);
Zachary Turner6708e0b2017-07-10 21:01:37 +00001042 EBS.Fields.push_back("pdb");
1043 EBS.Fields.push_back(Path);
1044 EBS.Fields.push_back("cmd");
1045 EBS.Fields.push_back(ArgStr);
1046 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1047 ONS, Allocator, CodeViewContainer::Pdb));
1048 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1049 CS, Allocator, CodeViewContainer::Pdb));
1050 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1051 EBS, Allocator, CodeViewContainer::Pdb));
1052}
1053
Zachary Turner28e31ee2017-08-11 20:46:28 +00001054static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &Mod,
1055 OutputSection &OS,
1056 BumpPtrAllocator &Allocator) {
1057 SectionSym Sym(SymbolRecordKind::SectionSym);
Zachary Turnerf6822c82017-08-11 20:46:47 +00001058 Sym.Alignment = 12; // 2^12 = 4KB
Zachary Turner28e31ee2017-08-11 20:46:28 +00001059 Sym.Characteristics = OS.getCharacteristics();
1060 Sym.Length = OS.getVirtualSize();
Peter Collingbourne435b09912018-03-15 21:13:46 +00001061 Sym.Name = OS.Name;
Zachary Turner28e31ee2017-08-11 20:46:28 +00001062 Sym.Rva = OS.getRVA();
1063 Sym.SectionNumber = OS.SectionIndex;
1064 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1065 Sym, Allocator, CodeViewContainer::Pdb));
1066}
1067
Rui Ueyama09e0b5f2016-11-12 00:00:51 +00001068// Creates a PDB file.
Reid Kleckner175af4b2017-08-03 21:15:09 +00001069void coff::createPDB(SymbolTable *Symtab,
1070 ArrayRef<OutputSection *> OutputSections,
1071 ArrayRef<uint8_t> SectionTable,
Zachary Turner024323c2017-08-15 21:31:41 +00001072 const llvm::codeview::DebugInfo &BuildId) {
Zachary Turner727f1532018-01-17 19:16:26 +00001073 ScopedTimer T1(TotalPdbLinkTimer);
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001074 PDBLinker PDB(Symtab);
Zachary Turnerf2282762018-03-23 19:57:25 +00001075
Zachary Turner024323c2017-08-15 21:31:41 +00001076 PDB.initialize(BuildId);
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001077 PDB.addObjectsToPDB();
Reid Kleckner175af4b2017-08-03 21:15:09 +00001078 PDB.addSections(OutputSections, SectionTable);
Zachary Turnerf2282762018-03-23 19:57:25 +00001079 PDB.addNatvisFiles();
Zachary Turner727f1532018-01-17 19:16:26 +00001080
1081 ScopedTimer T2(DiskCommitTimer);
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001082 PDB.commit();
1083}
1084
Zachary Turner024323c2017-08-15 21:31:41 +00001085void PDBLinker::initialize(const llvm::codeview::DebugInfo &BuildId) {
Rui Ueyama12979542016-09-30 20:53:45 +00001086 ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
Rui Ueyama7f382992016-09-15 18:55:18 +00001087
Rui Ueyama8d3fb5d2016-10-05 22:08:58 +00001088 // Create streams in MSF for predefined streams, namely
1089 // PDB, TPI, DBI and IPI.
1090 for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
1091 ExitOnErr(Builder.getMsfBuilder().addStream(0));
Rui Ueyama7f382992016-09-15 18:55:18 +00001092
Rui Ueyamabb542b32016-09-16 22:51:17 +00001093 // Add an Info stream.
1094 auto &InfoBuilder = Builder.getInfoBuilder();
Zachary Turner024323c2017-08-15 21:31:41 +00001095 GUID uuid;
1096 memcpy(&uuid, &BuildId.PDB70.Signature, sizeof(uuid));
Zachary Turnerc6a75a62018-03-01 18:00:29 +00001097 InfoBuilder.setAge(BuildId.PDB70.Age);
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +00001098 InfoBuilder.setGuid(uuid);
Rui Ueyamabb542b32016-09-16 22:51:17 +00001099 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
Rui Ueyama7f382992016-09-15 18:55:18 +00001100
Zachary Turner6c4bfba2017-07-07 05:04:36 +00001101 // Add an empty DBI stream.
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +00001102 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Zachary Turner024323c2017-08-15 21:31:41 +00001103 DbiBuilder.setAge(BuildId.PDB70.Age);
Zachary Turnerc1e93e52017-07-07 18:45:56 +00001104 DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
Zachary Turnerd8d97de2018-04-16 20:42:06 +00001105 DbiBuilder.setMachineType(Config->Machine);
Zachary Turnere3fe6692018-04-16 18:17:13 +00001106 // Technically we are not link.exe 14.11, but there are known cases where
1107 // debugging tools on Windows expect Microsoft-specific version numbers or
1108 // they fail to work at all. Since we know we produce PDBs that are
1109 // compatible with LINK 14.11, we set that version number here.
1110 DbiBuilder.setBuildNumber(14, 11);
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001111}
Rui Ueyama1343fac2016-10-06 22:52:01 +00001112
Reid Kleckner175af4b2017-08-03 21:15:09 +00001113void PDBLinker::addSectionContrib(pdb::DbiModuleDescriptorBuilder &LinkerModule,
1114 OutputSection *OS, Chunk *C) {
1115 pdb::SectionContrib SC;
1116 memset(&SC, 0, sizeof(SC));
1117 SC.ISect = OS->SectionIndex;
1118 SC.Off = C->getRVA() - OS->getRVA();
1119 SC.Size = C->getSize();
1120 if (auto *SecChunk = dyn_cast<SectionChunk>(C)) {
1121 SC.Characteristics = SecChunk->Header->Characteristics;
1122 SC.Imod = SecChunk->File->ModuleDBI->getModuleIndex();
Zachary Turner676386ff2017-08-07 20:23:45 +00001123 ArrayRef<uint8_t> Contents = SecChunk->getContents();
1124 JamCRC CRC(0);
1125 ArrayRef<char> CharContents = makeArrayRef(
1126 reinterpret_cast<const char *>(Contents.data()), Contents.size());
1127 CRC.update(CharContents);
1128 SC.DataCrc = CRC.getCRC();
Reid Kleckner175af4b2017-08-03 21:15:09 +00001129 } else {
1130 SC.Characteristics = OS->getCharacteristics();
1131 // FIXME: When we start creating DBI for import libraries, use those here.
1132 SC.Imod = LinkerModule.getModuleIndex();
1133 }
Reid Kleckner175af4b2017-08-03 21:15:09 +00001134 SC.RelocCrc = 0; // FIXME
1135 Builder.getDbiBuilder().addSectionContrib(SC);
1136}
Rui Ueyama09e0b5f2016-11-12 00:00:51 +00001137
Reid Kleckner175af4b2017-08-03 21:15:09 +00001138void PDBLinker::addSections(ArrayRef<OutputSection *> OutputSections,
1139 ArrayRef<uint8_t> SectionTable) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001140 // It's not entirely clear what this is, but the * Linker * module uses it.
Reid Kleckner175af4b2017-08-03 21:15:09 +00001141 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001142 NativePath = Config->PDBPath;
1143 sys::fs::make_absolute(NativePath);
1144 sys::path::native(NativePath, sys::path::Style::windows);
1145 uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
Zachary Turner6c4bfba2017-07-07 05:04:36 +00001146 auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
1147 LinkerModule.setPdbFilePathNI(PdbFilePathNI);
Zachary Turner28e31ee2017-08-11 20:46:28 +00001148 addCommonLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
Rui Ueyamac91f7162016-11-16 01:10:46 +00001149
Reid Kleckner175af4b2017-08-03 21:15:09 +00001150 // Add section contributions. They must be ordered by ascending RVA.
Zachary Turner28e31ee2017-08-11 20:46:28 +00001151 for (OutputSection *OS : OutputSections) {
1152 addLinkerModuleSectionSymbol(LinkerModule, *OS, Alloc);
Reid Kleckner175af4b2017-08-03 21:15:09 +00001153 for (Chunk *C : OS->getChunks())
1154 addSectionContrib(LinkerModule, OS, C);
Zachary Turner28e31ee2017-08-11 20:46:28 +00001155 }
Reid Kleckner175af4b2017-08-03 21:15:09 +00001156
1157 // Add Section Map stream.
1158 ArrayRef<object::coff_section> Sections = {
1159 (const object::coff_section *)SectionTable.data(),
1160 SectionTable.size() / sizeof(object::coff_section)};
1161 SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
1162 DbiBuilder.setSectionMap(SectionMap);
1163
Rui Ueyama9f66f822016-10-11 19:45:07 +00001164 // Add COFF section header stream.
1165 ExitOnErr(
1166 DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001167}
Rui Ueyama9f66f822016-10-11 19:45:07 +00001168
Reid Kleckner0faf6d72017-07-14 00:14:58 +00001169void PDBLinker::commit() {
Rui Ueyama3e9d6bb2016-09-26 23:53:55 +00001170 // Write to a file.
Zachary Turner6708e0b2017-07-10 21:01:37 +00001171 ExitOnErr(Builder.commit(Config->PDBPath));
Rui Ueyamae7378242015-12-04 23:11:05 +00001172}