blob: 9b5dc1e7d059f0530929b83bfcb26d15fe2a9361 [file] [log] [blame]
Rui Ueyamae7378242015-12-04 23:11:05 +00001//===- PDB.cpp ------------------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Rui Ueyama1d99ab32016-09-15 22:24:51 +000010#include "PDB.h"
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000011#include "Chunks.h"
Rui Ueyamabe939b32016-11-21 17:22:35 +000012#include "Config.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000013#include "Error.h"
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000014#include "SymbolTable.h"
15#include "Symbols.h"
Reid Klecknereacdf042017-07-27 18:25:59 +000016#include "Writer.h"
Saleem Abdulrasooldf8a13b2017-01-04 17:56:54 +000017#include "llvm/DebugInfo/CodeView/CVDebugRecord.h"
Reid Kleckner44cdb102017-06-19 17:21:45 +000018#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000019#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
Zachary Turner59e3ae82017-08-08 18:34:44 +000020#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
Zachary Turner6708e0b2017-07-10 21:01:37 +000021#include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
Reid Kleckner651db912017-07-18 00:21:25 +000022#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000023#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerd0e6e242017-06-21 17:25:56 +000024#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
Rui Ueyama52896622017-01-12 03:09:25 +000025#include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
26#include "llvm/DebugInfo/CodeView/TypeTableBuilder.h"
Rui Ueyamab28c6d42016-09-16 04:32:33 +000027#include "llvm/DebugInfo/MSF/MSFBuilder.h"
Rui Ueyama7f382992016-09-15 18:55:18 +000028#include "llvm/DebugInfo/MSF/MSFCommon.h"
Reid Kleckner651db912017-07-18 00:21:25 +000029#include "llvm/DebugInfo/PDB/GenericError.h"
Zachary Turner6708e0b2017-07-10 21:01:37 +000030#include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000031#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
32#include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
33#include "llvm/DebugInfo/PDB/Native/InfoStream.h"
34#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
Reid Kleckner651db912017-07-18 00:21:25 +000035#include "llvm/DebugInfo/PDB/Native/NativeSession.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000036#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
37#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
Rafael Espindolaa0f30da2017-05-02 20:19:42 +000038#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
Reid Klecknereacdf042017-07-27 18:25:59 +000039#include "llvm/DebugInfo/PDB/Native/PublicsStreamBuilder.h"
Reid Klecknerd91ca762017-07-19 17:26:07 +000040#include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000041#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
42#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
Reid Kleckner651db912017-07-18 00:21:25 +000043#include "llvm/DebugInfo/PDB/PDB.h"
Rui Ueyama20df4ec2016-10-31 21:09:21 +000044#include "llvm/Object/COFF.h"
Zachary Turnerd9dc2822017-03-02 20:52:51 +000045#include "llvm/Support/BinaryByteStream.h"
Rui Ueyama1763c0d2015-12-08 18:39:55 +000046#include "llvm/Support/Endian.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000047#include "llvm/Support/FileOutputBuffer.h"
Zachary Turner676386ff2017-08-07 20:23:45 +000048#include "llvm/Support/JamCRC.h"
Zachary Turner7b327d02017-02-16 23:35:45 +000049#include "llvm/Support/Path.h"
Rui Ueyamabe939b32016-11-21 17:22:35 +000050#include "llvm/Support/ScopedPrinter.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000051#include <memory>
52
Rui Ueyama1d99ab32016-09-15 22:24:51 +000053using namespace lld;
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000054using namespace lld::coff;
Rui Ueyamae7378242015-12-04 23:11:05 +000055using namespace llvm;
Rui Ueyamabe939b32016-11-21 17:22:35 +000056using namespace llvm::codeview;
Rui Ueyamae7378242015-12-04 23:11:05 +000057
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000058using llvm::object::coff_section;
59
Rui Ueyamab28c6d42016-09-16 04:32:33 +000060static ExitOnError ExitOnErr;
61
Reid Kleckner0faf6d72017-07-14 00:14:58 +000062namespace {
Reid Kleckner651db912017-07-18 00:21:25 +000063/// Map from type index and item index in a type server PDB to the
64/// corresponding index in the destination PDB.
65struct CVIndexMap {
66 SmallVector<TypeIndex, 0> TPIMap;
67 SmallVector<TypeIndex, 0> IPIMap;
68 bool IsTypeServerMap = false;
69};
70
Reid Kleckner0faf6d72017-07-14 00:14:58 +000071class PDBLinker {
72public:
73 PDBLinker(SymbolTable *Symtab)
74 : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
75 IDTable(Alloc) {}
76
77 /// Emit the basic PDB structure: initial streams, headers, etc.
78 void initialize(const llvm::codeview::DebugInfo *DI);
79
80 /// Link CodeView from each object file in the symbol table into the PDB.
81 void addObjectsToPDB();
82
83 /// Link CodeView from a single object file into the PDB.
Rui Ueyamae1b48e02017-07-26 23:05:24 +000084 void addObjFile(ObjFile *File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +000085
Reid Kleckner651db912017-07-18 00:21:25 +000086 /// Produce a mapping from the type and item indices used in the object
87 /// file to those in the destination PDB.
88 ///
89 /// If the object file uses a type server PDB (compiled with /Zi), merge TPI
90 /// and IPI from the type server PDB and return a map for it. Each unique type
91 /// server PDB is merged at most once, so this may return an existing index
92 /// mapping.
93 ///
94 /// If the object does not use a type server PDB (compiled with /Z7), we merge
95 /// all the type and item records from the .debug$S stream and fill in the
96 /// caller-provided ObjectIndexMap.
Rui Ueyamae1b48e02017-07-26 23:05:24 +000097 const CVIndexMap &mergeDebugT(ObjFile *File, CVIndexMap &ObjectIndexMap);
Reid Kleckner651db912017-07-18 00:21:25 +000098
Rui Ueyamae1b48e02017-07-26 23:05:24 +000099 const CVIndexMap &maybeMergeTypeServerPDB(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000100 TypeServer2Record &TS);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000101
102 /// Add the section map and section contributions to the PDB.
Reid Kleckner175af4b2017-08-03 21:15:09 +0000103 void addSections(ArrayRef<OutputSection *> OutputSections,
104 ArrayRef<uint8_t> SectionTable);
105
106 void addSectionContrib(pdb::DbiModuleDescriptorBuilder &LinkerModule,
107 OutputSection *OS, Chunk *C);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000108
109 /// Write the PDB to disk.
110 void commit();
111
112private:
113 BumpPtrAllocator Alloc;
114
115 SymbolTable *Symtab;
116
117 pdb::PDBFileBuilder Builder;
118
119 /// Type records that will go into the PDB TPI stream.
120 TypeTableBuilder TypeTable;
121
122 /// Item records that will go into the PDB IPI stream.
123 TypeTableBuilder IDTable;
124
125 /// PDBs use a single global string table for filenames in the file checksum
126 /// table.
127 DebugStringTableSubsection PDBStrTab;
128
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000129 llvm::SmallString<128> NativePath;
130
131 std::vector<pdb::SecMapEntry> SectionMap;
Reid Kleckner651db912017-07-18 00:21:25 +0000132
133 /// Type index mappings of type server PDBs that we've loaded so far.
134 std::map<GUID, CVIndexMap> TypeServerIndexMappings;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000135};
136}
137
Rui Ueyamabe939b32016-11-21 17:22:35 +0000138static SectionChunk *findByName(std::vector<SectionChunk *> &Sections,
139 StringRef Name) {
140 for (SectionChunk *C : Sections)
141 if (C->getSectionName() == Name)
142 return C;
143 return nullptr;
144}
145
Reid Kleckner44cdb102017-06-19 17:21:45 +0000146static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
147 StringRef SecName) {
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000148 // First 4 bytes are section magic.
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000149 if (Data.size() < 4)
Rui Ueyama52896622017-01-12 03:09:25 +0000150 fatal(SecName + " too short");
Reid Kleckner44cdb102017-06-19 17:21:45 +0000151 if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
Rui Ueyama52896622017-01-12 03:09:25 +0000152 fatal(SecName + " has an invalid magic");
Rui Ueyama26186c72016-12-09 04:46:54 +0000153 return Data.slice(4);
154}
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000155
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000156static ArrayRef<uint8_t> getDebugSection(ObjFile *File, StringRef SecName) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000157 if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
158 return consumeDebugMagic(Sec->getContents(), SecName);
159 return {};
160}
161
Reid Kleckner5d577522017-03-24 17:26:38 +0000162static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
Reid Kleckner44cdb102017-06-19 17:21:45 +0000163 TypeTableBuilder &TypeTable) {
Reid Kleckner5d577522017-03-24 17:26:38 +0000164 // Start the TPI or IPI stream header.
165 TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
Rui Ueyama52896622017-01-12 03:09:25 +0000166
Reid Klecknerd91ca762017-07-19 17:26:07 +0000167 // Flatten the in memory type table and hash each type.
Reid Kleckner5d577522017-03-24 17:26:38 +0000168 TypeTable.ForEachRecord([&](TypeIndex TI, ArrayRef<uint8_t> Rec) {
Reid Klecknerd91ca762017-07-19 17:26:07 +0000169 assert(Rec.size() >= sizeof(RecordPrefix));
170 const RecordPrefix *P = reinterpret_cast<const RecordPrefix *>(Rec.data());
171 CVType Type(static_cast<TypeLeafKind>(unsigned(P->RecordKind)), Rec);
172 auto Hash = pdb::hashTypeRecord(Type);
173 if (auto E = Hash.takeError())
174 fatal("type hashing error");
175 TpiBuilder.addTypeRecord(Rec, *Hash);
Reid Kleckner5d577522017-03-24 17:26:38 +0000176 });
Reid Kleckner5d577522017-03-24 17:26:38 +0000177}
178
Reid Kleckner651db912017-07-18 00:21:25 +0000179static Optional<TypeServer2Record>
180maybeReadTypeServerRecord(CVTypeArray &Types) {
181 auto I = Types.begin();
182 if (I == Types.end())
183 return None;
184 const CVType &Type = *I;
185 if (Type.kind() != LF_TYPESERVER2)
186 return None;
187 TypeServer2Record TS;
188 if (auto EC = TypeDeserializer::deserializeAs(const_cast<CVType &>(Type), TS))
189 fatal(EC, "error reading type server record");
190 return std::move(TS);
191}
192
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000193const CVIndexMap &PDBLinker::mergeDebugT(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000194 CVIndexMap &ObjectIndexMap) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000195 ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
196 if (Data.empty())
Reid Kleckner651db912017-07-18 00:21:25 +0000197 return ObjectIndexMap;
Reid Kleckner6597c282017-07-13 20:12:23 +0000198
Reid Kleckner44cdb102017-06-19 17:21:45 +0000199 BinaryByteStream Stream(Data, support::little);
200 CVTypeArray Types;
201 BinaryStreamReader Reader(Stream);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000202 if (auto EC = Reader.readArray(Types, Reader.getLength()))
203 fatal(EC, "Reader::readArray failed");
Reid Kleckner651db912017-07-18 00:21:25 +0000204
205 // Look through type servers. If we've already seen this type server, don't
206 // merge any type information.
207 if (Optional<TypeServer2Record> TS = maybeReadTypeServerRecord(Types))
208 return maybeMergeTypeServerPDB(File, *TS);
209
210 // This is a /Z7 object. Fill in the temporary, caller-provided
211 // ObjectIndexMap.
212 if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable,
213 ObjectIndexMap.TPIMap, Types))
214 fatal(Err, "codeview::mergeTypeAndIdRecords failed");
215 return ObjectIndexMap;
216}
217
218static Expected<std::unique_ptr<pdb::NativeSession>>
219tryToLoadPDB(const GUID &GuidFromObj, StringRef TSPath) {
220 std::unique_ptr<pdb::IPDBSession> ThisSession;
221 if (auto EC =
222 pdb::loadDataForPDB(pdb::PDB_ReaderType::Native, TSPath, ThisSession))
223 return std::move(EC);
224
225 std::unique_ptr<pdb::NativeSession> NS(
226 static_cast<pdb::NativeSession *>(ThisSession.release()));
227 pdb::PDBFile &File = NS->getPDBFile();
228 auto ExpectedInfo = File.getPDBInfoStream();
229 // All PDB Files should have an Info stream.
230 if (!ExpectedInfo)
231 return ExpectedInfo.takeError();
232
233 // Just because a file with a matching name was found and it was an actual
234 // PDB file doesn't mean it matches. For it to match the InfoStream's GUID
235 // must match the GUID specified in the TypeServer2 record.
236 if (ExpectedInfo->getGuid() != GuidFromObj)
237 return make_error<pdb::GenericError>(
238 pdb::generic_error_code::type_server_not_found, TSPath);
239
240 return std::move(NS);
241}
242
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000243const CVIndexMap &PDBLinker::maybeMergeTypeServerPDB(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000244 TypeServer2Record &TS) {
245 // First, check if we already loaded a PDB with this GUID. Return the type
246 // index mapping if we have it.
247 auto Insertion = TypeServerIndexMappings.insert({TS.getGuid(), CVIndexMap()});
248 CVIndexMap &IndexMap = Insertion.first->second;
249 if (!Insertion.second)
250 return IndexMap;
251
252 // Mark this map as a type server map.
253 IndexMap.IsTypeServerMap = true;
254
255 // Check for a PDB at:
256 // 1. The given file path
257 // 2. Next to the object file or archive file
258 auto ExpectedSession = tryToLoadPDB(TS.getGuid(), TS.getName());
259 if (!ExpectedSession) {
260 consumeError(ExpectedSession.takeError());
261 StringRef LocalPath =
262 !File->ParentName.empty() ? File->ParentName : File->getName();
263 SmallString<128> Path = sys::path::parent_path(LocalPath);
Reid Klecknerf8522d82017-07-18 00:33:53 +0000264 sys::path::append(
265 Path, sys::path::filename(TS.getName(), sys::path::Style::windows));
Reid Kleckner651db912017-07-18 00:21:25 +0000266 ExpectedSession = tryToLoadPDB(TS.getGuid(), Path);
267 }
268 if (auto E = ExpectedSession.takeError())
269 fatal(E, "Type server PDB was not found");
270
271 // Merge TPI first, because the IPI stream will reference type indices.
272 auto ExpectedTpi = (*ExpectedSession)->getPDBFile().getPDBTpiStream();
273 if (auto E = ExpectedTpi.takeError())
274 fatal(E, "Type server does not have TPI stream");
275 if (auto Err = mergeTypeRecords(TypeTable, IndexMap.TPIMap,
276 ExpectedTpi->typeArray()))
277 fatal(Err, "codeview::mergeTypeRecords failed");
278
279 // Merge IPI.
280 auto ExpectedIpi = (*ExpectedSession)->getPDBFile().getPDBIpiStream();
281 if (auto E = ExpectedIpi.takeError())
282 fatal(E, "Type server does not have TPI stream");
283 if (auto Err = mergeIdRecords(IDTable, IndexMap.TPIMap, IndexMap.IPIMap,
284 ExpectedIpi->typeArray()))
285 fatal(Err, "codeview::mergeIdRecords failed");
286
287 return IndexMap;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000288}
289
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000290static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
291 if (TI.isSimple())
292 return true;
293 if (TI.toArrayIndex() >= TypeIndexMap.size())
294 return false;
295 TI = TypeIndexMap[TI.toArrayIndex()];
296 return true;
297}
298
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000299static void remapTypesInSymbolRecord(ObjFile *File,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000300 MutableArrayRef<uint8_t> Contents,
Reid Kleckner651db912017-07-18 00:21:25 +0000301 const CVIndexMap &IndexMap,
Zachary Turner59e3ae82017-08-08 18:34:44 +0000302 const TypeTableBuilder &IDTable,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000303 ArrayRef<TiReference> TypeRefs) {
304 for (const TiReference &Ref : TypeRefs) {
305 unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000306 if (Contents.size() < Ref.Offset + ByteSize)
307 fatal("symbol record too short");
Reid Kleckner651db912017-07-18 00:21:25 +0000308
309 // This can be an item index or a type index. Choose the appropriate map.
310 ArrayRef<TypeIndex> TypeOrItemMap = IndexMap.TPIMap;
311 if (Ref.Kind == TiRefKind::IndexRef && IndexMap.IsTypeServerMap)
312 TypeOrItemMap = IndexMap.IPIMap;
313
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000314 MutableArrayRef<TypeIndex> TIs(
315 reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000316 for (TypeIndex &TI : TIs) {
Reid Kleckner651db912017-07-18 00:21:25 +0000317 if (!remapTypeIndex(TI, TypeOrItemMap)) {
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000318 TI = TypeIndex(SimpleTypeKind::NotTranslated);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000319 log("ignoring symbol record in " + File->getName() +
320 " with bad type index 0x" + utohexstr(TI.getIndex()));
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000321 continue;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000322 }
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000323 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000324 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000325}
326
Zachary Turner59e3ae82017-08-08 18:34:44 +0000327static SymbolKind symbolKind(ArrayRef<uint8_t> RecordData) {
328 const RecordPrefix *Prefix =
329 reinterpret_cast<const RecordPrefix *>(RecordData.data());
330 return static_cast<SymbolKind>(uint16_t(Prefix->RecordKind));
331}
332
333/// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
334static void translateIdSymbols(MutableArrayRef<uint8_t> &RecordData,
335 const TypeTableBuilder &IDTable) {
336 RecordPrefix *Prefix = reinterpret_cast<RecordPrefix *>(RecordData.data());
337
338 SymbolKind Kind = symbolKind(RecordData);
339
340 if (Kind == SymbolKind::S_PROC_ID_END) {
341 Prefix->RecordKind = SymbolKind::S_END;
342 return;
343 }
344
345 // In an object file, GPROC32_ID has an embedded reference which refers to the
346 // single object file type index namespace. This has already been translated
347 // to the PDB file's ID stream index space, but we need to convert this to a
348 // symbol that refers to the type stream index space. So we remap again from
349 // ID index space to type index space.
350 if (Kind == SymbolKind::S_GPROC32_ID || Kind == SymbolKind::S_LPROC32_ID) {
351 SmallVector<TiReference, 1> Refs;
352 auto Content = RecordData.drop_front(sizeof(RecordPrefix));
353 CVSymbol Sym(Kind, RecordData);
354 discoverTypeIndicesInSymbol(Sym, Refs);
355 assert(Refs.size() == 1);
356 assert(Refs.front().Count == 1);
357
358 TypeIndex *TI =
359 reinterpret_cast<TypeIndex *>(Content.data() + Refs[0].Offset);
360 // `TI` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
361 // the IPI stream, whose `FunctionType` member refers to the TPI stream.
362 // Note that LF_FUNC_ID and LF_MEMFUNC_ID have the same record layout, and
363 // in both cases we just need the second type index.
364 if (!TI->isSimple() && !TI->isNoneType()) {
365 ArrayRef<uint8_t> FuncIdData = IDTable.records()[TI->toArrayIndex()];
366 SmallVector<TypeIndex, 2> Indices;
367 discoverTypeIndices(FuncIdData, Indices);
368 assert(Indices.size() == 2);
369 *TI = Indices[1];
370 }
371
372 Kind = (Kind == SymbolKind::S_GPROC32_ID) ? SymbolKind::S_GPROC32
373 : SymbolKind::S_LPROC32;
374 Prefix->RecordKind = uint16_t(Kind);
375 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000376}
377
378/// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
379/// The object file may not be aligned.
380static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
381 BumpPtrAllocator &Alloc) {
382 size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
383 assert(Size >= 4 && "record too short");
384 assert(Size <= MaxRecordLength && "record too long");
385 void *Mem = Alloc.Allocate(Size, 4);
386
387 // Copy the symbol record and zero out any padding bytes.
388 MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
389 memcpy(NewData.data(), Sym.data().data(), Sym.length());
390 memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
391
392 // Update the record prefix length. It should point to the beginning of the
Zachary Turner59e3ae82017-08-08 18:34:44 +0000393 // next record.
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000394 auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000395 Prefix->RecordLen = Size - 2;
396 return NewData;
397}
398
Reid Kleckner3f851922017-07-06 16:39:32 +0000399/// Return true if this symbol opens a scope. This implies that the symbol has
400/// "parent" and "end" fields, which contain the offset of the S_END or
401/// S_INLINESITE_END record.
402static bool symbolOpensScope(SymbolKind Kind) {
403 switch (Kind) {
404 case SymbolKind::S_GPROC32:
405 case SymbolKind::S_LPROC32:
406 case SymbolKind::S_LPROC32_ID:
407 case SymbolKind::S_GPROC32_ID:
408 case SymbolKind::S_BLOCK32:
409 case SymbolKind::S_SEPCODE:
410 case SymbolKind::S_THUNK32:
411 case SymbolKind::S_INLINESITE:
412 case SymbolKind::S_INLINESITE2:
413 return true;
414 default:
415 break;
416 }
417 return false;
418}
419
420static bool symbolEndsScope(SymbolKind Kind) {
421 switch (Kind) {
422 case SymbolKind::S_END:
423 case SymbolKind::S_PROC_ID_END:
424 case SymbolKind::S_INLINESITE_END:
425 return true;
426 default:
427 break;
428 }
429 return false;
430}
431
432struct ScopeRecord {
433 ulittle32_t PtrParent;
434 ulittle32_t PtrEnd;
435};
436
437struct SymbolScope {
438 ScopeRecord *OpeningRecord;
439 uint32_t ScopeOffset;
440};
441
442static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
443 uint32_t CurOffset, CVSymbol &Sym) {
444 assert(symbolOpensScope(Sym.kind()));
445 SymbolScope S;
446 S.ScopeOffset = CurOffset;
447 S.OpeningRecord = const_cast<ScopeRecord *>(
448 reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
449 S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
450 Stack.push_back(S);
451}
452
453static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000454 uint32_t CurOffset, ObjFile *File) {
Reid Kleckner3f851922017-07-06 16:39:32 +0000455 if (Stack.empty()) {
456 warn("symbol scopes are not balanced in " + File->getName());
457 return;
458 }
459 SymbolScope S = Stack.pop_back_val();
460 S.OpeningRecord->PtrEnd = CurOffset;
461}
462
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000463static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000464 const CVIndexMap &IndexMap,
Zachary Turner59e3ae82017-08-08 18:34:44 +0000465 const TypeTableBuilder &IDTable,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000466 BinaryStreamRef SymData) {
467 // FIXME: Improve error recovery by warning and skipping records when
468 // possible.
469 CVSymbolArray Syms;
470 BinaryStreamReader Reader(SymData);
471 ExitOnErr(Reader.readArray(Syms, Reader.getLength()));
Reid Kleckner3f851922017-07-06 16:39:32 +0000472 SmallVector<SymbolScope, 4> Scopes;
Zachary Turner59e3ae82017-08-08 18:34:44 +0000473 for (CVSymbol Sym : Syms) {
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000474 // Discover type index references in the record. Skip it if we don't know
475 // where they are.
476 SmallVector<TiReference, 32> TypeRefs;
Zachary Turner59e3ae82017-08-08 18:34:44 +0000477 if (!discoverTypeIndicesInSymbol(Sym, TypeRefs)) {
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000478 log("ignoring unknown symbol record with kind 0x" + utohexstr(Sym.kind()));
479 continue;
480 }
481
482 // Copy the symbol record so we can mutate it.
483 MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
484
485 // Re-map all the type index references.
486 MutableArrayRef<uint8_t> Contents =
487 NewData.drop_front(sizeof(RecordPrefix));
Zachary Turner59e3ae82017-08-08 18:34:44 +0000488 remapTypesInSymbolRecord(File, Contents, IndexMap, IDTable, TypeRefs);
489
490 // An object file may have S_xxx_ID symbols, but these get converted to
491 // "real" symbols in a PDB.
492 translateIdSymbols(NewData, IDTable);
493
494 SymbolKind NewKind = symbolKind(NewData);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000495
Reid Kleckner3f851922017-07-06 16:39:32 +0000496 // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
Zachary Turner59e3ae82017-08-08 18:34:44 +0000497 CVSymbol NewSym(NewKind, NewData);
498 if (symbolOpensScope(NewKind))
Reid Kleckner3f851922017-07-06 16:39:32 +0000499 scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(), NewSym);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000500 else if (symbolEndsScope(NewKind))
Reid Kleckner3f851922017-07-06 16:39:32 +0000501 scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000502
503 // Add the symbol to the module.
Reid Kleckner3f851922017-07-06 16:39:32 +0000504 File->ModuleDBI->addSymbol(NewSym);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000505 }
506}
507
Reid Kleckner44cdb102017-06-19 17:21:45 +0000508// Allocate memory for a .debug$S section and relocate it.
509static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
510 SectionChunk *DebugChunk) {
511 uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk->getSize());
512 assert(DebugChunk->OutputSectionOff == 0 &&
513 "debug sections should not be in output sections");
514 DebugChunk->writeTo(Buffer);
515 return consumeDebugMagic(makeArrayRef(Buffer, DebugChunk->getSize()),
516 ".debug$S");
517}
518
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000519void PDBLinker::addObjFile(ObjFile *File) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000520 // Add a module descriptor for every object file. We need to put an absolute
521 // path to the object into the PDB. If this is a plain object, we make its
522 // path absolute. If it's an object in an archive, we make the archive path
523 // absolute.
524 bool InArchive = !File->ParentName.empty();
525 SmallString<128> Path = InArchive ? File->ParentName : File->getName();
526 sys::fs::make_absolute(Path);
527 sys::path::native(Path, sys::path::Style::windows);
528 StringRef Name = InArchive ? File->getName() : StringRef(Path);
Zachary Turner2897e032017-05-25 21:16:03 +0000529
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000530 File->ModuleDBI = &ExitOnErr(Builder.getDbiBuilder().addModuleInfo(Name));
531 File->ModuleDBI->setObjFileName(Path);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000532
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000533 // Before we can process symbol substreams from .debug$S, we need to process
534 // type information, file checksums, and the string table. Add type info to
535 // the PDB first, so that we can get the map from object file type and item
536 // indices to PDB type and item indices.
Reid Kleckner651db912017-07-18 00:21:25 +0000537 CVIndexMap ObjectIndexMap;
538 const CVIndexMap &IndexMap = mergeDebugT(File, ObjectIndexMap);
Zachary Turner448dea42017-07-07 18:46:14 +0000539
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000540 // Now do all live .debug$S sections.
541 for (SectionChunk *DebugChunk : File->getDebugChunks()) {
542 if (!DebugChunk->isLive() || DebugChunk->getSectionName() != ".debug$S")
543 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000544
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000545 ArrayRef<uint8_t> RelocatedDebugContents =
546 relocateDebugChunk(Alloc, DebugChunk);
547 if (RelocatedDebugContents.empty())
548 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000549
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000550 DebugSubsectionArray Subsections;
551 BinaryStreamReader Reader(RelocatedDebugContents, support::little);
552 ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
Rui Ueyama52896622017-01-12 03:09:25 +0000553
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000554 DebugStringTableSubsectionRef CVStrTab;
555 DebugChecksumsSubsectionRef Checksums;
556 for (const DebugSubsectionRecord &SS : Subsections) {
557 switch (SS.kind()) {
558 case DebugSubsectionKind::StringTable:
559 ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
560 break;
561 case DebugSubsectionKind::FileChecksums:
562 ExitOnErr(Checksums.initialize(SS.getRecordData()));
563 break;
564 case DebugSubsectionKind::Lines:
565 // We can add the relocated line table directly to the PDB without
566 // modification because the file checksum offsets will stay the same.
567 File->ModuleDBI->addDebugSubsection(SS);
568 break;
569 case DebugSubsectionKind::Symbols:
Zachary Turner59e3ae82017-08-08 18:34:44 +0000570 mergeSymbolRecords(Alloc, File, IndexMap, IDTable, SS.getRecordData());
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000571 break;
572 default:
573 // FIXME: Process the rest of the subsections.
574 break;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000575 }
576 }
Rui Ueyama52896622017-01-12 03:09:25 +0000577
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000578 if (Checksums.valid()) {
579 // Make a new file checksum table that refers to offsets in the PDB-wide
580 // string table. Generally the string table subsection appears after the
581 // checksum table, so we have to do this after looping over all the
582 // subsections.
583 if (!CVStrTab.valid())
584 fatal(".debug$S sections must have both a string table subsection "
585 "and a checksum subsection table or neither");
586 auto NewChecksums = make_unique<DebugChecksumsSubsection>(PDBStrTab);
587 for (FileChecksumEntry &FC : Checksums) {
588 StringRef FileName = ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
589 ExitOnErr(Builder.getDbiBuilder().addModuleSourceFile(*File->ModuleDBI,
590 FileName));
591 NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
592 }
593 File->ModuleDBI->addDebugSubsection(std::move(NewChecksums));
594 }
595 }
596}
597
Reid Klecknereacdf042017-07-27 18:25:59 +0000598static PublicSym32 createPublic(Defined *Def) {
599 PublicSym32 Pub(SymbolKind::S_PUB32);
600 Pub.Name = Def->getName();
601 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
602 if (D->getCOFFSymbol().isFunctionDefinition())
603 Pub.Flags = PublicSymFlags::Function;
604 } else if (isa<DefinedImportThunk>(Def)) {
605 Pub.Flags = PublicSymFlags::Function;
606 }
607
608 OutputSection *OS = Def->getChunk()->getOutputSection();
609 assert(OS && "all publics should be in final image");
610 Pub.Offset = Def->getRVA() - OS->getRVA();
611 Pub.Segment = OS->SectionIndex;
612 return Pub;
613}
614
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000615// Add all object files to the PDB. Merge .debug$T sections into IpiData and
616// TpiData.
617void PDBLinker::addObjectsToPDB() {
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000618 for (ObjFile *File : ObjFile::Instances)
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000619 addObjFile(File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000620
621 Builder.getStringTableBuilder().setStrings(PDBStrTab);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000622
Reid Kleckner5d577522017-03-24 17:26:38 +0000623 // Construct TPI stream contents.
Reid Kleckner13fc4112017-04-04 00:56:34 +0000624 addTypeInfo(Builder.getTpiBuilder(), TypeTable);
Reid Kleckner5d577522017-03-24 17:26:38 +0000625
626 // Construct IPI stream contents.
Reid Kleckner13fc4112017-04-04 00:56:34 +0000627 addTypeInfo(Builder.getIpiBuilder(), IDTable);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000628
Reid Klecknereacdf042017-07-27 18:25:59 +0000629 // Compute the public symbols.
630 std::vector<PublicSym32> Publics;
631 Symtab->forEachSymbol([&Publics](Symbol *S) {
632 // Only emit defined, live symbols that have a chunk.
633 auto *Def = dyn_cast<Defined>(S->body());
634 if (Def && Def->isLive() && Def->getChunk())
635 Publics.push_back(createPublic(Def));
636 });
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000637
Reid Klecknereacdf042017-07-27 18:25:59 +0000638 if (!Publics.empty()) {
639 // Sort the public symbols and add them to the stream.
640 std::sort(Publics.begin(), Publics.end(),
641 [](const PublicSym32 &L, const PublicSym32 &R) {
642 return L.Name < R.Name;
643 });
644 auto &PublicsBuilder = Builder.getPublicsBuilder();
645 for (const PublicSym32 &Pub : Publics)
646 PublicsBuilder.addPublicSymbol(Pub);
647 }
Zachary Turner8d927b62017-07-31 19:36:08 +0000648 // Add globals stream. For now we don't actually write any thing useful to
649 // the globals stream, but the act of "getting" it also creates it lazily so
650 // that we write an empty stream.
651 (void)Builder.getGlobalsBuilder();
Rui Ueyama52896622017-01-12 03:09:25 +0000652}
653
Zachary Turner6708e0b2017-07-10 21:01:37 +0000654static void addLinkerModuleSymbols(StringRef Path,
655 pdb::DbiModuleDescriptorBuilder &Mod,
656 BumpPtrAllocator &Allocator) {
657 codeview::SymbolSerializer Serializer(Allocator, CodeViewContainer::Pdb);
658 codeview::ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
659 codeview::Compile3Sym CS(SymbolRecordKind::Compile3Sym);
660 codeview::EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
661
662 ONS.Name = "* Linker *";
663 ONS.Signature = 0;
664
665 CS.Machine = Config->is64() ? CPUType::X64 : CPUType::Intel80386;
666 CS.Flags = CompileSym3Flags::None;
667 CS.VersionBackendBuild = 0;
668 CS.VersionBackendMajor = 0;
669 CS.VersionBackendMinor = 0;
670 CS.VersionBackendQFE = 0;
671 CS.VersionFrontendBuild = 0;
672 CS.VersionFrontendMajor = 0;
673 CS.VersionFrontendMinor = 0;
674 CS.VersionFrontendQFE = 0;
675 CS.Version = "LLVM Linker";
676 CS.setLanguage(SourceLanguage::Link);
677
678 ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
679 std::string ArgStr = llvm::join(Args, " ");
680 EBS.Fields.push_back("cwd");
681 SmallString<64> cwd;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000682 sys::fs::current_path(cwd);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000683 EBS.Fields.push_back(cwd);
684 EBS.Fields.push_back("exe");
Zachary Turner77f23b92017-07-10 21:09:11 +0000685 EBS.Fields.push_back(Config->Argv[0]);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000686 EBS.Fields.push_back("pdb");
687 EBS.Fields.push_back(Path);
688 EBS.Fields.push_back("cmd");
689 EBS.Fields.push_back(ArgStr);
690 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
691 ONS, Allocator, CodeViewContainer::Pdb));
692 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
693 CS, Allocator, CodeViewContainer::Pdb));
694 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
695 EBS, Allocator, CodeViewContainer::Pdb));
696}
697
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000698// Creates a PDB file.
Reid Kleckner175af4b2017-08-03 21:15:09 +0000699void coff::createPDB(SymbolTable *Symtab,
700 ArrayRef<OutputSection *> OutputSections,
701 ArrayRef<uint8_t> SectionTable,
Saleem Abdulrasooldf8a13b2017-01-04 17:56:54 +0000702 const llvm::codeview::DebugInfo *DI) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000703 PDBLinker PDB(Symtab);
704 PDB.initialize(DI);
705 PDB.addObjectsToPDB();
Reid Kleckner175af4b2017-08-03 21:15:09 +0000706 PDB.addSections(OutputSections, SectionTable);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000707 PDB.commit();
708}
709
710void PDBLinker::initialize(const llvm::codeview::DebugInfo *DI) {
Rui Ueyama12979542016-09-30 20:53:45 +0000711 ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
Rui Ueyama7f382992016-09-15 18:55:18 +0000712
Rui Ueyama8d3fb5d2016-10-05 22:08:58 +0000713 // Create streams in MSF for predefined streams, namely
714 // PDB, TPI, DBI and IPI.
715 for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
716 ExitOnErr(Builder.getMsfBuilder().addStream(0));
Rui Ueyama7f382992016-09-15 18:55:18 +0000717
Rui Ueyamabb542b32016-09-16 22:51:17 +0000718 // Add an Info stream.
719 auto &InfoBuilder = Builder.getInfoBuilder();
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000720 InfoBuilder.setAge(DI ? DI->PDB70.Age : 0);
721
Reid Kleckner67653ee2017-07-17 23:59:44 +0000722 GUID uuid{};
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000723 if (DI)
724 memcpy(&uuid, &DI->PDB70.Signature, sizeof(uuid));
725 InfoBuilder.setGuid(uuid);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000726 InfoBuilder.setSignature(time(nullptr));
Rui Ueyamabb542b32016-09-16 22:51:17 +0000727 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
Rui Ueyama7f382992016-09-15 18:55:18 +0000728
Zachary Turner6c4bfba2017-07-07 05:04:36 +0000729 // Add an empty DBI stream.
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000730 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Zachary Turnerc1e93e52017-07-07 18:45:56 +0000731 DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000732 ExitOnErr(DbiBuilder.addDbgStream(pdb::DbgHeaderType::NewFPO, {}));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000733}
Rui Ueyama1343fac2016-10-06 22:52:01 +0000734
Reid Kleckner175af4b2017-08-03 21:15:09 +0000735void PDBLinker::addSectionContrib(pdb::DbiModuleDescriptorBuilder &LinkerModule,
736 OutputSection *OS, Chunk *C) {
737 pdb::SectionContrib SC;
738 memset(&SC, 0, sizeof(SC));
739 SC.ISect = OS->SectionIndex;
740 SC.Off = C->getRVA() - OS->getRVA();
741 SC.Size = C->getSize();
742 if (auto *SecChunk = dyn_cast<SectionChunk>(C)) {
743 SC.Characteristics = SecChunk->Header->Characteristics;
744 SC.Imod = SecChunk->File->ModuleDBI->getModuleIndex();
Zachary Turner676386ff2017-08-07 20:23:45 +0000745 ArrayRef<uint8_t> Contents = SecChunk->getContents();
746 JamCRC CRC(0);
747 ArrayRef<char> CharContents = makeArrayRef(
748 reinterpret_cast<const char *>(Contents.data()), Contents.size());
749 CRC.update(CharContents);
750 SC.DataCrc = CRC.getCRC();
Reid Kleckner175af4b2017-08-03 21:15:09 +0000751 } else {
752 SC.Characteristics = OS->getCharacteristics();
753 // FIXME: When we start creating DBI for import libraries, use those here.
754 SC.Imod = LinkerModule.getModuleIndex();
755 }
Reid Kleckner175af4b2017-08-03 21:15:09 +0000756 SC.RelocCrc = 0; // FIXME
757 Builder.getDbiBuilder().addSectionContrib(SC);
758}
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000759
Reid Kleckner175af4b2017-08-03 21:15:09 +0000760void PDBLinker::addSections(ArrayRef<OutputSection *> OutputSections,
761 ArrayRef<uint8_t> SectionTable) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000762 // It's not entirely clear what this is, but the * Linker * module uses it.
Reid Kleckner175af4b2017-08-03 21:15:09 +0000763 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000764 NativePath = Config->PDBPath;
765 sys::fs::make_absolute(NativePath);
766 sys::path::native(NativePath, sys::path::Style::windows);
767 uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
Zachary Turner6c4bfba2017-07-07 05:04:36 +0000768 auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
769 LinkerModule.setPdbFilePathNI(PdbFilePathNI);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000770 addLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
Rui Ueyamac91f7162016-11-16 01:10:46 +0000771
Reid Kleckner175af4b2017-08-03 21:15:09 +0000772 // Add section contributions. They must be ordered by ascending RVA.
773 for (OutputSection *OS : OutputSections)
774 for (Chunk *C : OS->getChunks())
775 addSectionContrib(LinkerModule, OS, C);
776
777 // Add Section Map stream.
778 ArrayRef<object::coff_section> Sections = {
779 (const object::coff_section *)SectionTable.data(),
780 SectionTable.size() / sizeof(object::coff_section)};
781 SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
782 DbiBuilder.setSectionMap(SectionMap);
783
Rui Ueyama9f66f822016-10-11 19:45:07 +0000784 // Add COFF section header stream.
785 ExitOnErr(
786 DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000787}
Rui Ueyama9f66f822016-10-11 19:45:07 +0000788
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000789void PDBLinker::commit() {
Rui Ueyama3e9d6bb2016-09-26 23:53:55 +0000790 // Write to a file.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000791 ExitOnErr(Builder.commit(Config->PDBPath));
Rui Ueyamae7378242015-12-04 23:11:05 +0000792}