blob: a31a2bb9e2c5d320e4a7808e4b427882a9c97fe5 [file] [log] [blame]
Rui Ueyamae7378242015-12-04 23:11:05 +00001//===- PDB.cpp ------------------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Rui Ueyama1d99ab32016-09-15 22:24:51 +000010#include "PDB.h"
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000011#include "Chunks.h"
Rui Ueyamabe939b32016-11-21 17:22:35 +000012#include "Config.h"
Peter Collingbourne75257bc2017-10-20 19:48:26 +000013#include "Driver.h"
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000014#include "SymbolTable.h"
15#include "Symbols.h"
Reid Klecknereacdf042017-07-27 18:25:59 +000016#include "Writer.h"
Bob Haarmanb8a59c82017-10-25 22:28:38 +000017#include "lld/Common/ErrorHandler.h"
Saleem Abdulrasooldf8a13b2017-01-04 17:56:54 +000018#include "llvm/DebugInfo/CodeView/CVDebugRecord.h"
Reid Kleckner44cdb102017-06-19 17:21:45 +000019#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000020#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
Zachary Turneree9906d2017-08-11 19:00:03 +000021#include "llvm/DebugInfo/CodeView/RecordName.h"
Zachary Turner59e3ae82017-08-08 18:34:44 +000022#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
Zachary Turner6708e0b2017-07-10 21:01:37 +000023#include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
Reid Kleckner651db912017-07-18 00:21:25 +000024#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000025#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerd0e6e242017-06-21 17:25:56 +000026#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
Rui Ueyama52896622017-01-12 03:09:25 +000027#include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
28#include "llvm/DebugInfo/CodeView/TypeTableBuilder.h"
Rui Ueyamab28c6d42016-09-16 04:32:33 +000029#include "llvm/DebugInfo/MSF/MSFBuilder.h"
Rui Ueyama7f382992016-09-15 18:55:18 +000030#include "llvm/DebugInfo/MSF/MSFCommon.h"
Reid Kleckner651db912017-07-18 00:21:25 +000031#include "llvm/DebugInfo/PDB/GenericError.h"
Zachary Turner6708e0b2017-07-10 21:01:37 +000032#include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000033#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
34#include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
Zachary Turner946204c2017-08-09 04:23:25 +000035#include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000036#include "llvm/DebugInfo/PDB/Native/InfoStream.h"
37#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
Reid Kleckner651db912017-07-18 00:21:25 +000038#include "llvm/DebugInfo/PDB/Native/NativeSession.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000039#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
40#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
Rafael Espindolaa0f30da2017-05-02 20:19:42 +000041#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
Reid Klecknerd91ca762017-07-19 17:26:07 +000042#include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
Adrian McCarthy6b6b8c42017-01-25 22:38:55 +000043#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
44#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
Reid Kleckner651db912017-07-18 00:21:25 +000045#include "llvm/DebugInfo/PDB/PDB.h"
Rui Ueyama20df4ec2016-10-31 21:09:21 +000046#include "llvm/Object/COFF.h"
Zachary Turnerd9dc2822017-03-02 20:52:51 +000047#include "llvm/Support/BinaryByteStream.h"
Rui Ueyama1763c0d2015-12-08 18:39:55 +000048#include "llvm/Support/Endian.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000049#include "llvm/Support/FileOutputBuffer.h"
Zachary Turner676386ff2017-08-07 20:23:45 +000050#include "llvm/Support/JamCRC.h"
Zachary Turner7b327d02017-02-16 23:35:45 +000051#include "llvm/Support/Path.h"
Rui Ueyamabe939b32016-11-21 17:22:35 +000052#include "llvm/Support/ScopedPrinter.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000053#include <memory>
54
Rui Ueyama1d99ab32016-09-15 22:24:51 +000055using namespace lld;
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000056using namespace lld::coff;
Rui Ueyamae7378242015-12-04 23:11:05 +000057using namespace llvm;
Rui Ueyamabe939b32016-11-21 17:22:35 +000058using namespace llvm::codeview;
Rui Ueyamae7378242015-12-04 23:11:05 +000059
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000060using llvm::object::coff_section;
61
Rui Ueyamab28c6d42016-09-16 04:32:33 +000062static ExitOnError ExitOnErr;
63
Reid Kleckner0faf6d72017-07-14 00:14:58 +000064namespace {
Reid Kleckner651db912017-07-18 00:21:25 +000065/// Map from type index and item index in a type server PDB to the
66/// corresponding index in the destination PDB.
67struct CVIndexMap {
68 SmallVector<TypeIndex, 0> TPIMap;
69 SmallVector<TypeIndex, 0> IPIMap;
70 bool IsTypeServerMap = false;
71};
72
Reid Kleckner0faf6d72017-07-14 00:14:58 +000073class PDBLinker {
74public:
75 PDBLinker(SymbolTable *Symtab)
76 : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
77 IDTable(Alloc) {}
78
79 /// Emit the basic PDB structure: initial streams, headers, etc.
Zachary Turner024323c2017-08-15 21:31:41 +000080 void initialize(const llvm::codeview::DebugInfo &BuildId);
Reid Kleckner0faf6d72017-07-14 00:14:58 +000081
82 /// Link CodeView from each object file in the symbol table into the PDB.
83 void addObjectsToPDB();
84
85 /// Link CodeView from a single object file into the PDB.
Rui Ueyamae1b48e02017-07-26 23:05:24 +000086 void addObjFile(ObjFile *File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +000087
Reid Kleckner651db912017-07-18 00:21:25 +000088 /// Produce a mapping from the type and item indices used in the object
89 /// file to those in the destination PDB.
90 ///
91 /// If the object file uses a type server PDB (compiled with /Zi), merge TPI
92 /// and IPI from the type server PDB and return a map for it. Each unique type
93 /// server PDB is merged at most once, so this may return an existing index
94 /// mapping.
95 ///
96 /// If the object does not use a type server PDB (compiled with /Z7), we merge
97 /// all the type and item records from the .debug$S stream and fill in the
98 /// caller-provided ObjectIndexMap.
Rui Ueyamae1b48e02017-07-26 23:05:24 +000099 const CVIndexMap &mergeDebugT(ObjFile *File, CVIndexMap &ObjectIndexMap);
Reid Kleckner651db912017-07-18 00:21:25 +0000100
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000101 const CVIndexMap &maybeMergeTypeServerPDB(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000102 TypeServer2Record &TS);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000103
104 /// Add the section map and section contributions to the PDB.
Reid Kleckner175af4b2017-08-03 21:15:09 +0000105 void addSections(ArrayRef<OutputSection *> OutputSections,
106 ArrayRef<uint8_t> SectionTable);
107
108 void addSectionContrib(pdb::DbiModuleDescriptorBuilder &LinkerModule,
109 OutputSection *OS, Chunk *C);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000110
111 /// Write the PDB to disk.
112 void commit();
113
114private:
115 BumpPtrAllocator Alloc;
116
117 SymbolTable *Symtab;
118
119 pdb::PDBFileBuilder Builder;
120
121 /// Type records that will go into the PDB TPI stream.
122 TypeTableBuilder TypeTable;
123
124 /// Item records that will go into the PDB IPI stream.
125 TypeTableBuilder IDTable;
126
127 /// PDBs use a single global string table for filenames in the file checksum
128 /// table.
129 DebugStringTableSubsection PDBStrTab;
130
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000131 llvm::SmallString<128> NativePath;
132
133 std::vector<pdb::SecMapEntry> SectionMap;
Reid Kleckner651db912017-07-18 00:21:25 +0000134
135 /// Type index mappings of type server PDBs that we've loaded so far.
136 std::map<GUID, CVIndexMap> TypeServerIndexMappings;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000137};
138}
139
Rui Ueyamabe939b32016-11-21 17:22:35 +0000140static SectionChunk *findByName(std::vector<SectionChunk *> &Sections,
141 StringRef Name) {
142 for (SectionChunk *C : Sections)
143 if (C->getSectionName() == Name)
144 return C;
145 return nullptr;
146}
147
Reid Kleckner44cdb102017-06-19 17:21:45 +0000148static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
149 StringRef SecName) {
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000150 // First 4 bytes are section magic.
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000151 if (Data.size() < 4)
Rui Ueyama52896622017-01-12 03:09:25 +0000152 fatal(SecName + " too short");
Reid Kleckner44cdb102017-06-19 17:21:45 +0000153 if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
Rui Ueyama52896622017-01-12 03:09:25 +0000154 fatal(SecName + " has an invalid magic");
Rui Ueyama26186c72016-12-09 04:46:54 +0000155 return Data.slice(4);
156}
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000157
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000158static ArrayRef<uint8_t> getDebugSection(ObjFile *File, StringRef SecName) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000159 if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
160 return consumeDebugMagic(Sec->getContents(), SecName);
161 return {};
162}
163
Reid Kleckner5d577522017-03-24 17:26:38 +0000164static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
Reid Kleckner44cdb102017-06-19 17:21:45 +0000165 TypeTableBuilder &TypeTable) {
Reid Kleckner5d577522017-03-24 17:26:38 +0000166 // Start the TPI or IPI stream header.
167 TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
Rui Ueyama52896622017-01-12 03:09:25 +0000168
Reid Klecknerd91ca762017-07-19 17:26:07 +0000169 // Flatten the in memory type table and hash each type.
Reid Kleckner5d577522017-03-24 17:26:38 +0000170 TypeTable.ForEachRecord([&](TypeIndex TI, ArrayRef<uint8_t> Rec) {
Reid Klecknerd91ca762017-07-19 17:26:07 +0000171 assert(Rec.size() >= sizeof(RecordPrefix));
172 const RecordPrefix *P = reinterpret_cast<const RecordPrefix *>(Rec.data());
173 CVType Type(static_cast<TypeLeafKind>(unsigned(P->RecordKind)), Rec);
174 auto Hash = pdb::hashTypeRecord(Type);
175 if (auto E = Hash.takeError())
176 fatal("type hashing error");
177 TpiBuilder.addTypeRecord(Rec, *Hash);
Reid Kleckner5d577522017-03-24 17:26:38 +0000178 });
Reid Kleckner5d577522017-03-24 17:26:38 +0000179}
180
Reid Kleckner651db912017-07-18 00:21:25 +0000181static Optional<TypeServer2Record>
182maybeReadTypeServerRecord(CVTypeArray &Types) {
183 auto I = Types.begin();
184 if (I == Types.end())
185 return None;
186 const CVType &Type = *I;
187 if (Type.kind() != LF_TYPESERVER2)
188 return None;
189 TypeServer2Record TS;
190 if (auto EC = TypeDeserializer::deserializeAs(const_cast<CVType &>(Type), TS))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000191 fatal("error reading type server record: " + toString(std::move(EC)));
Reid Kleckner651db912017-07-18 00:21:25 +0000192 return std::move(TS);
193}
194
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000195const CVIndexMap &PDBLinker::mergeDebugT(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000196 CVIndexMap &ObjectIndexMap) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000197 ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
198 if (Data.empty())
Reid Kleckner651db912017-07-18 00:21:25 +0000199 return ObjectIndexMap;
Reid Kleckner6597c282017-07-13 20:12:23 +0000200
Reid Kleckner44cdb102017-06-19 17:21:45 +0000201 BinaryByteStream Stream(Data, support::little);
202 CVTypeArray Types;
203 BinaryStreamReader Reader(Stream);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000204 if (auto EC = Reader.readArray(Types, Reader.getLength()))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000205 fatal("Reader::readArray failed: " + toString(std::move(EC)));
Reid Kleckner651db912017-07-18 00:21:25 +0000206
207 // Look through type servers. If we've already seen this type server, don't
208 // merge any type information.
209 if (Optional<TypeServer2Record> TS = maybeReadTypeServerRecord(Types))
210 return maybeMergeTypeServerPDB(File, *TS);
211
212 // This is a /Z7 object. Fill in the temporary, caller-provided
213 // ObjectIndexMap.
214 if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable,
215 ObjectIndexMap.TPIMap, Types))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000216 fatal("codeview::mergeTypeAndIdRecords failed: " +
217 toString(std::move(Err)));
Reid Kleckner651db912017-07-18 00:21:25 +0000218 return ObjectIndexMap;
219}
220
221static Expected<std::unique_ptr<pdb::NativeSession>>
222tryToLoadPDB(const GUID &GuidFromObj, StringRef TSPath) {
Peter Collingbourne75257bc2017-10-20 19:48:26 +0000223 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(
224 TSPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
225 if (!MBOrErr)
226 return errorCodeToError(MBOrErr.getError());
227
Reid Kleckner651db912017-07-18 00:21:25 +0000228 std::unique_ptr<pdb::IPDBSession> ThisSession;
Peter Collingbourne75257bc2017-10-20 19:48:26 +0000229 if (auto EC = pdb::NativeSession::createFromPdb(
230 MemoryBuffer::getMemBuffer(Driver->takeBuffer(std::move(*MBOrErr)),
231 /*RequiresNullTerminator=*/false),
232 ThisSession))
Reid Kleckner651db912017-07-18 00:21:25 +0000233 return std::move(EC);
234
235 std::unique_ptr<pdb::NativeSession> NS(
236 static_cast<pdb::NativeSession *>(ThisSession.release()));
237 pdb::PDBFile &File = NS->getPDBFile();
238 auto ExpectedInfo = File.getPDBInfoStream();
239 // All PDB Files should have an Info stream.
240 if (!ExpectedInfo)
241 return ExpectedInfo.takeError();
242
243 // Just because a file with a matching name was found and it was an actual
244 // PDB file doesn't mean it matches. For it to match the InfoStream's GUID
245 // must match the GUID specified in the TypeServer2 record.
246 if (ExpectedInfo->getGuid() != GuidFromObj)
247 return make_error<pdb::GenericError>(
248 pdb::generic_error_code::type_server_not_found, TSPath);
249
250 return std::move(NS);
251}
252
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000253const CVIndexMap &PDBLinker::maybeMergeTypeServerPDB(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000254 TypeServer2Record &TS) {
255 // First, check if we already loaded a PDB with this GUID. Return the type
256 // index mapping if we have it.
257 auto Insertion = TypeServerIndexMappings.insert({TS.getGuid(), CVIndexMap()});
258 CVIndexMap &IndexMap = Insertion.first->second;
259 if (!Insertion.second)
260 return IndexMap;
261
262 // Mark this map as a type server map.
263 IndexMap.IsTypeServerMap = true;
264
265 // Check for a PDB at:
266 // 1. The given file path
267 // 2. Next to the object file or archive file
268 auto ExpectedSession = tryToLoadPDB(TS.getGuid(), TS.getName());
269 if (!ExpectedSession) {
270 consumeError(ExpectedSession.takeError());
271 StringRef LocalPath =
272 !File->ParentName.empty() ? File->ParentName : File->getName();
273 SmallString<128> Path = sys::path::parent_path(LocalPath);
Reid Klecknerf8522d82017-07-18 00:33:53 +0000274 sys::path::append(
275 Path, sys::path::filename(TS.getName(), sys::path::Style::windows));
Reid Kleckner651db912017-07-18 00:21:25 +0000276 ExpectedSession = tryToLoadPDB(TS.getGuid(), Path);
277 }
278 if (auto E = ExpectedSession.takeError())
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000279 fatal("Type server PDB was not found: " + toString(std::move(E)));
Reid Kleckner651db912017-07-18 00:21:25 +0000280
281 // Merge TPI first, because the IPI stream will reference type indices.
282 auto ExpectedTpi = (*ExpectedSession)->getPDBFile().getPDBTpiStream();
283 if (auto E = ExpectedTpi.takeError())
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000284 fatal("Type server does not have TPI stream: " + toString(std::move(E)));
Reid Kleckner651db912017-07-18 00:21:25 +0000285 if (auto Err = mergeTypeRecords(TypeTable, IndexMap.TPIMap,
286 ExpectedTpi->typeArray()))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000287 fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
Reid Kleckner651db912017-07-18 00:21:25 +0000288
289 // Merge IPI.
290 auto ExpectedIpi = (*ExpectedSession)->getPDBFile().getPDBIpiStream();
291 if (auto E = ExpectedIpi.takeError())
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000292 fatal("Type server does not have TPI stream: " + toString(std::move(E)));
Reid Kleckner651db912017-07-18 00:21:25 +0000293 if (auto Err = mergeIdRecords(IDTable, IndexMap.TPIMap, IndexMap.IPIMap,
294 ExpectedIpi->typeArray()))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000295 fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
Reid Kleckner651db912017-07-18 00:21:25 +0000296
297 return IndexMap;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000298}
299
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000300static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
301 if (TI.isSimple())
302 return true;
303 if (TI.toArrayIndex() >= TypeIndexMap.size())
304 return false;
305 TI = TypeIndexMap[TI.toArrayIndex()];
306 return true;
307}
308
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000309static void remapTypesInSymbolRecord(ObjFile *File, SymbolKind SymKind,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000310 MutableArrayRef<uint8_t> Contents,
Reid Kleckner651db912017-07-18 00:21:25 +0000311 const CVIndexMap &IndexMap,
Zachary Turner59e3ae82017-08-08 18:34:44 +0000312 const TypeTableBuilder &IDTable,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000313 ArrayRef<TiReference> TypeRefs) {
314 for (const TiReference &Ref : TypeRefs) {
315 unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000316 if (Contents.size() < Ref.Offset + ByteSize)
317 fatal("symbol record too short");
Reid Kleckner651db912017-07-18 00:21:25 +0000318
319 // This can be an item index or a type index. Choose the appropriate map.
320 ArrayRef<TypeIndex> TypeOrItemMap = IndexMap.TPIMap;
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000321 bool IsItemIndex = Ref.Kind == TiRefKind::IndexRef;
322 if (IsItemIndex && IndexMap.IsTypeServerMap)
Reid Kleckner651db912017-07-18 00:21:25 +0000323 TypeOrItemMap = IndexMap.IPIMap;
324
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000325 MutableArrayRef<TypeIndex> TIs(
326 reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000327 for (TypeIndex &TI : TIs) {
Reid Kleckner651db912017-07-18 00:21:25 +0000328 if (!remapTypeIndex(TI, TypeOrItemMap)) {
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000329 log("ignoring symbol record of kind 0x" + utohexstr(SymKind) + " in " +
330 File->getName() + " with bad " + (IsItemIndex ? "item" : "type") +
331 " index 0x" + utohexstr(TI.getIndex()));
Reid Kleckner5d82f682017-10-23 22:44:51 +0000332 TI = TypeIndex(SimpleTypeKind::NotTranslated);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000333 continue;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000334 }
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000335 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000336 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000337}
338
Zachary Turner59e3ae82017-08-08 18:34:44 +0000339static SymbolKind symbolKind(ArrayRef<uint8_t> RecordData) {
340 const RecordPrefix *Prefix =
341 reinterpret_cast<const RecordPrefix *>(RecordData.data());
342 return static_cast<SymbolKind>(uint16_t(Prefix->RecordKind));
343}
344
345/// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
346static void translateIdSymbols(MutableArrayRef<uint8_t> &RecordData,
347 const TypeTableBuilder &IDTable) {
348 RecordPrefix *Prefix = reinterpret_cast<RecordPrefix *>(RecordData.data());
349
350 SymbolKind Kind = symbolKind(RecordData);
351
352 if (Kind == SymbolKind::S_PROC_ID_END) {
353 Prefix->RecordKind = SymbolKind::S_END;
354 return;
355 }
356
357 // In an object file, GPROC32_ID has an embedded reference which refers to the
358 // single object file type index namespace. This has already been translated
359 // to the PDB file's ID stream index space, but we need to convert this to a
360 // symbol that refers to the type stream index space. So we remap again from
361 // ID index space to type index space.
362 if (Kind == SymbolKind::S_GPROC32_ID || Kind == SymbolKind::S_LPROC32_ID) {
363 SmallVector<TiReference, 1> Refs;
364 auto Content = RecordData.drop_front(sizeof(RecordPrefix));
365 CVSymbol Sym(Kind, RecordData);
366 discoverTypeIndicesInSymbol(Sym, Refs);
367 assert(Refs.size() == 1);
368 assert(Refs.front().Count == 1);
369
370 TypeIndex *TI =
371 reinterpret_cast<TypeIndex *>(Content.data() + Refs[0].Offset);
372 // `TI` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
373 // the IPI stream, whose `FunctionType` member refers to the TPI stream.
374 // Note that LF_FUNC_ID and LF_MEMFUNC_ID have the same record layout, and
375 // in both cases we just need the second type index.
376 if (!TI->isSimple() && !TI->isNoneType()) {
377 ArrayRef<uint8_t> FuncIdData = IDTable.records()[TI->toArrayIndex()];
378 SmallVector<TypeIndex, 2> Indices;
379 discoverTypeIndices(FuncIdData, Indices);
380 assert(Indices.size() == 2);
381 *TI = Indices[1];
382 }
383
384 Kind = (Kind == SymbolKind::S_GPROC32_ID) ? SymbolKind::S_GPROC32
385 : SymbolKind::S_LPROC32;
386 Prefix->RecordKind = uint16_t(Kind);
387 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000388}
389
390/// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
391/// The object file may not be aligned.
392static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
393 BumpPtrAllocator &Alloc) {
394 size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
395 assert(Size >= 4 && "record too short");
396 assert(Size <= MaxRecordLength && "record too long");
397 void *Mem = Alloc.Allocate(Size, 4);
398
399 // Copy the symbol record and zero out any padding bytes.
400 MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
401 memcpy(NewData.data(), Sym.data().data(), Sym.length());
402 memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
403
404 // Update the record prefix length. It should point to the beginning of the
Zachary Turner59e3ae82017-08-08 18:34:44 +0000405 // next record.
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000406 auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000407 Prefix->RecordLen = Size - 2;
408 return NewData;
409}
410
Reid Kleckner3f851922017-07-06 16:39:32 +0000411/// Return true if this symbol opens a scope. This implies that the symbol has
412/// "parent" and "end" fields, which contain the offset of the S_END or
413/// S_INLINESITE_END record.
414static bool symbolOpensScope(SymbolKind Kind) {
415 switch (Kind) {
416 case SymbolKind::S_GPROC32:
417 case SymbolKind::S_LPROC32:
418 case SymbolKind::S_LPROC32_ID:
419 case SymbolKind::S_GPROC32_ID:
420 case SymbolKind::S_BLOCK32:
421 case SymbolKind::S_SEPCODE:
422 case SymbolKind::S_THUNK32:
423 case SymbolKind::S_INLINESITE:
424 case SymbolKind::S_INLINESITE2:
425 return true;
426 default:
427 break;
428 }
429 return false;
430}
431
432static bool symbolEndsScope(SymbolKind Kind) {
433 switch (Kind) {
434 case SymbolKind::S_END:
435 case SymbolKind::S_PROC_ID_END:
436 case SymbolKind::S_INLINESITE_END:
437 return true;
438 default:
439 break;
440 }
441 return false;
442}
443
444struct ScopeRecord {
445 ulittle32_t PtrParent;
446 ulittle32_t PtrEnd;
447};
448
449struct SymbolScope {
450 ScopeRecord *OpeningRecord;
451 uint32_t ScopeOffset;
452};
453
454static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
455 uint32_t CurOffset, CVSymbol &Sym) {
456 assert(symbolOpensScope(Sym.kind()));
457 SymbolScope S;
458 S.ScopeOffset = CurOffset;
459 S.OpeningRecord = const_cast<ScopeRecord *>(
460 reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
461 S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
462 Stack.push_back(S);
463}
464
465static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000466 uint32_t CurOffset, ObjFile *File) {
Reid Kleckner3f851922017-07-06 16:39:32 +0000467 if (Stack.empty()) {
468 warn("symbol scopes are not balanced in " + File->getName());
469 return;
470 }
471 SymbolScope S = Stack.pop_back_val();
472 S.OpeningRecord->PtrEnd = CurOffset;
473}
474
Zachary Turneree9906d2017-08-11 19:00:03 +0000475static bool symbolGoesInModuleStream(const CVSymbol &Sym) {
476 switch (Sym.kind()) {
477 case SymbolKind::S_GDATA32:
478 case SymbolKind::S_CONSTANT:
479 case SymbolKind::S_UDT:
480 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
481 // since they are synthesized by the linker in response to S_GPROC32 and
482 // S_LPROC32, but if we do see them, don't put them in the module stream I
483 // guess.
484 case SymbolKind::S_PROCREF:
485 case SymbolKind::S_LPROCREF:
486 return false;
487 // S_GDATA32 does not go in the module stream, but S_LDATA32 does.
488 case SymbolKind::S_LDATA32:
489 default:
490 return true;
491 }
492}
493
494static bool symbolGoesInGlobalsStream(const CVSymbol &Sym) {
495 switch (Sym.kind()) {
496 case SymbolKind::S_CONSTANT:
Zachary Turneree9906d2017-08-11 19:00:03 +0000497 case SymbolKind::S_GDATA32:
498 // S_LDATA32 goes in both the module stream and the globals stream.
499 case SymbolKind::S_LDATA32:
500 case SymbolKind::S_GPROC32:
501 case SymbolKind::S_LPROC32:
502 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
503 // since they are synthesized by the linker in response to S_GPROC32 and
504 // S_LPROC32, but if we do see them, copy them straight through.
505 case SymbolKind::S_PROCREF:
506 case SymbolKind::S_LPROCREF:
507 return true;
Zachary Turner302dc8b2017-08-14 18:44:58 +0000508 // FIXME: For now, we drop all S_UDT symbols (i.e. they don't go in the
509 // globals stream or the modules stream). These have special handling which
510 // needs more investigation before we can get right, but by putting them all
511 // into the globals stream WinDbg fails to display local variables of class
512 // types saying that it cannot find the type Foo *. So as a stopgap just to
513 // keep things working, we drop them.
514 case SymbolKind::S_UDT:
Zachary Turneree9906d2017-08-11 19:00:03 +0000515 default:
516 return false;
517 }
518}
519
520static void addGlobalSymbol(pdb::GSIStreamBuilder &Builder, ObjFile &File,
521 const CVSymbol &Sym) {
522 switch (Sym.kind()) {
523 case SymbolKind::S_CONSTANT:
524 case SymbolKind::S_UDT:
525 case SymbolKind::S_GDATA32:
526 case SymbolKind::S_LDATA32:
527 case SymbolKind::S_PROCREF:
528 case SymbolKind::S_LPROCREF:
529 Builder.addGlobalSymbol(Sym);
530 break;
531 case SymbolKind::S_GPROC32:
532 case SymbolKind::S_LPROC32: {
533 SymbolRecordKind K = SymbolRecordKind::ProcRefSym;
534 if (Sym.kind() == SymbolKind::S_LPROC32)
535 K = SymbolRecordKind::LocalProcRef;
536 ProcRefSym PS(K);
537 PS.Module = static_cast<uint16_t>(File.ModuleDBI->getModuleIndex());
538 // For some reason, MSVC seems to add one to this value.
539 ++PS.Module;
540 PS.Name = getSymbolName(Sym);
541 PS.SumName = 0;
542 PS.SymOffset = File.ModuleDBI->getNextSymbolOffset();
543 Builder.addGlobalSymbol(PS);
544 break;
545 }
546 default:
547 llvm_unreachable("Invalid symbol kind!");
548 }
549}
550
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000551static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjFile *File,
Zachary Turneree9906d2017-08-11 19:00:03 +0000552 pdb::GSIStreamBuilder &GsiBuilder,
Reid Kleckner651db912017-07-18 00:21:25 +0000553 const CVIndexMap &IndexMap,
Zachary Turner59e3ae82017-08-08 18:34:44 +0000554 const TypeTableBuilder &IDTable,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000555 BinaryStreamRef SymData) {
556 // FIXME: Improve error recovery by warning and skipping records when
557 // possible.
558 CVSymbolArray Syms;
559 BinaryStreamReader Reader(SymData);
560 ExitOnErr(Reader.readArray(Syms, Reader.getLength()));
Reid Kleckner3f851922017-07-06 16:39:32 +0000561 SmallVector<SymbolScope, 4> Scopes;
Zachary Turner59e3ae82017-08-08 18:34:44 +0000562 for (CVSymbol Sym : Syms) {
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000563 // Discover type index references in the record. Skip it if we don't know
564 // where they are.
565 SmallVector<TiReference, 32> TypeRefs;
Zachary Turner59e3ae82017-08-08 18:34:44 +0000566 if (!discoverTypeIndicesInSymbol(Sym, TypeRefs)) {
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000567 log("ignoring unknown symbol record with kind 0x" + utohexstr(Sym.kind()));
568 continue;
569 }
570
571 // Copy the symbol record so we can mutate it.
572 MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
573
574 // Re-map all the type index references.
575 MutableArrayRef<uint8_t> Contents =
576 NewData.drop_front(sizeof(RecordPrefix));
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000577 remapTypesInSymbolRecord(File, Sym.kind(), Contents, IndexMap, IDTable,
578 TypeRefs);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000579
580 // An object file may have S_xxx_ID symbols, but these get converted to
581 // "real" symbols in a PDB.
582 translateIdSymbols(NewData, IDTable);
583
584 SymbolKind NewKind = symbolKind(NewData);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000585
Reid Kleckner3f851922017-07-06 16:39:32 +0000586 // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
Zachary Turner59e3ae82017-08-08 18:34:44 +0000587 CVSymbol NewSym(NewKind, NewData);
588 if (symbolOpensScope(NewKind))
Reid Kleckner3f851922017-07-06 16:39:32 +0000589 scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(), NewSym);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000590 else if (symbolEndsScope(NewKind))
Reid Kleckner3f851922017-07-06 16:39:32 +0000591 scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000592
Zachary Turneree9906d2017-08-11 19:00:03 +0000593 // Add the symbol to the globals stream if necessary. Do this before adding
594 // the symbol to the module since we may need to get the next symbol offset,
595 // and writing to the module's symbol stream will update that offset.
596 if (symbolGoesInGlobalsStream(NewSym))
597 addGlobalSymbol(GsiBuilder, *File, NewSym);
598
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000599 // Add the symbol to the module.
Zachary Turneree9906d2017-08-11 19:00:03 +0000600 if (symbolGoesInModuleStream(NewSym))
601 File->ModuleDBI->addSymbol(NewSym);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000602 }
603}
604
Reid Kleckner44cdb102017-06-19 17:21:45 +0000605// Allocate memory for a .debug$S section and relocate it.
606static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
607 SectionChunk *DebugChunk) {
608 uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk->getSize());
609 assert(DebugChunk->OutputSectionOff == 0 &&
610 "debug sections should not be in output sections");
611 DebugChunk->writeTo(Buffer);
612 return consumeDebugMagic(makeArrayRef(Buffer, DebugChunk->getSize()),
613 ".debug$S");
614}
615
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000616void PDBLinker::addObjFile(ObjFile *File) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000617 // Add a module descriptor for every object file. We need to put an absolute
618 // path to the object into the PDB. If this is a plain object, we make its
619 // path absolute. If it's an object in an archive, we make the archive path
620 // absolute.
621 bool InArchive = !File->ParentName.empty();
622 SmallString<128> Path = InArchive ? File->ParentName : File->getName();
623 sys::fs::make_absolute(Path);
624 sys::path::native(Path, sys::path::Style::windows);
625 StringRef Name = InArchive ? File->getName() : StringRef(Path);
Zachary Turner2897e032017-05-25 21:16:03 +0000626
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000627 File->ModuleDBI = &ExitOnErr(Builder.getDbiBuilder().addModuleInfo(Name));
628 File->ModuleDBI->setObjFileName(Path);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000629
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000630 // Before we can process symbol substreams from .debug$S, we need to process
631 // type information, file checksums, and the string table. Add type info to
632 // the PDB first, so that we can get the map from object file type and item
633 // indices to PDB type and item indices.
Reid Kleckner651db912017-07-18 00:21:25 +0000634 CVIndexMap ObjectIndexMap;
635 const CVIndexMap &IndexMap = mergeDebugT(File, ObjectIndexMap);
Zachary Turner448dea42017-07-07 18:46:14 +0000636
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000637 // Now do all live .debug$S sections.
638 for (SectionChunk *DebugChunk : File->getDebugChunks()) {
639 if (!DebugChunk->isLive() || DebugChunk->getSectionName() != ".debug$S")
640 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000641
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000642 ArrayRef<uint8_t> RelocatedDebugContents =
643 relocateDebugChunk(Alloc, DebugChunk);
644 if (RelocatedDebugContents.empty())
645 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000646
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000647 DebugSubsectionArray Subsections;
648 BinaryStreamReader Reader(RelocatedDebugContents, support::little);
649 ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
Rui Ueyama52896622017-01-12 03:09:25 +0000650
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000651 DebugStringTableSubsectionRef CVStrTab;
652 DebugChecksumsSubsectionRef Checksums;
653 for (const DebugSubsectionRecord &SS : Subsections) {
654 switch (SS.kind()) {
655 case DebugSubsectionKind::StringTable:
656 ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
657 break;
658 case DebugSubsectionKind::FileChecksums:
659 ExitOnErr(Checksums.initialize(SS.getRecordData()));
660 break;
661 case DebugSubsectionKind::Lines:
662 // We can add the relocated line table directly to the PDB without
663 // modification because the file checksum offsets will stay the same.
664 File->ModuleDBI->addDebugSubsection(SS);
665 break;
666 case DebugSubsectionKind::Symbols:
Zachary Turneree9906d2017-08-11 19:00:03 +0000667 mergeSymbolRecords(Alloc, File, Builder.getGsiBuilder(), IndexMap,
668 IDTable, SS.getRecordData());
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000669 break;
670 default:
671 // FIXME: Process the rest of the subsections.
672 break;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000673 }
674 }
Rui Ueyama52896622017-01-12 03:09:25 +0000675
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000676 if (Checksums.valid()) {
677 // Make a new file checksum table that refers to offsets in the PDB-wide
678 // string table. Generally the string table subsection appears after the
679 // checksum table, so we have to do this after looping over all the
680 // subsections.
681 if (!CVStrTab.valid())
682 fatal(".debug$S sections must have both a string table subsection "
683 "and a checksum subsection table or neither");
684 auto NewChecksums = make_unique<DebugChecksumsSubsection>(PDBStrTab);
685 for (FileChecksumEntry &FC : Checksums) {
686 StringRef FileName = ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
687 ExitOnErr(Builder.getDbiBuilder().addModuleSourceFile(*File->ModuleDBI,
688 FileName));
689 NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
690 }
691 File->ModuleDBI->addDebugSubsection(std::move(NewChecksums));
692 }
693 }
694}
695
Reid Klecknereacdf042017-07-27 18:25:59 +0000696static PublicSym32 createPublic(Defined *Def) {
697 PublicSym32 Pub(SymbolKind::S_PUB32);
698 Pub.Name = Def->getName();
699 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
700 if (D->getCOFFSymbol().isFunctionDefinition())
701 Pub.Flags = PublicSymFlags::Function;
702 } else if (isa<DefinedImportThunk>(Def)) {
703 Pub.Flags = PublicSymFlags::Function;
704 }
705
706 OutputSection *OS = Def->getChunk()->getOutputSection();
707 assert(OS && "all publics should be in final image");
708 Pub.Offset = Def->getRVA() - OS->getRVA();
709 Pub.Segment = OS->SectionIndex;
710 return Pub;
711}
712
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000713// Add all object files to the PDB. Merge .debug$T sections into IpiData and
714// TpiData.
715void PDBLinker::addObjectsToPDB() {
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000716 for (ObjFile *File : ObjFile::Instances)
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000717 addObjFile(File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000718
719 Builder.getStringTableBuilder().setStrings(PDBStrTab);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000720
Reid Kleckner5d577522017-03-24 17:26:38 +0000721 // Construct TPI stream contents.
Reid Kleckner13fc4112017-04-04 00:56:34 +0000722 addTypeInfo(Builder.getTpiBuilder(), TypeTable);
Reid Kleckner5d577522017-03-24 17:26:38 +0000723
724 // Construct IPI stream contents.
Reid Kleckner13fc4112017-04-04 00:56:34 +0000725 addTypeInfo(Builder.getIpiBuilder(), IDTable);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000726
Zachary Turneree9906d2017-08-11 19:00:03 +0000727 // Compute the public and global symbols.
728 auto &GsiBuilder = Builder.getGsiBuilder();
Reid Klecknereacdf042017-07-27 18:25:59 +0000729 std::vector<PublicSym32> Publics;
Rui Ueyama616cd992017-10-31 16:10:24 +0000730 Symtab->forEachSymbol([&Publics](SymbolBody *S) {
Reid Klecknereacdf042017-07-27 18:25:59 +0000731 // Only emit defined, live symbols that have a chunk.
Rui Ueyama616cd992017-10-31 16:10:24 +0000732 auto *Def = dyn_cast<Defined>(S);
Reid Klecknereacdf042017-07-27 18:25:59 +0000733 if (Def && Def->isLive() && Def->getChunk())
734 Publics.push_back(createPublic(Def));
735 });
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000736
Reid Klecknereacdf042017-07-27 18:25:59 +0000737 if (!Publics.empty()) {
738 // Sort the public symbols and add them to the stream.
739 std::sort(Publics.begin(), Publics.end(),
740 [](const PublicSym32 &L, const PublicSym32 &R) {
741 return L.Name < R.Name;
742 });
Reid Klecknereacdf042017-07-27 18:25:59 +0000743 for (const PublicSym32 &Pub : Publics)
Zachary Turner946204c2017-08-09 04:23:25 +0000744 GsiBuilder.addPublicSymbol(Pub);
Reid Klecknereacdf042017-07-27 18:25:59 +0000745 }
Rui Ueyama52896622017-01-12 03:09:25 +0000746}
747
Zachary Turner28e31ee2017-08-11 20:46:28 +0000748static void addCommonLinkerModuleSymbols(StringRef Path,
749 pdb::DbiModuleDescriptorBuilder &Mod,
750 BumpPtrAllocator &Allocator) {
Zachary Turner28e31ee2017-08-11 20:46:28 +0000751 ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
752 Compile3Sym CS(SymbolRecordKind::Compile3Sym);
753 EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000754
755 ONS.Name = "* Linker *";
756 ONS.Signature = 0;
757
758 CS.Machine = Config->is64() ? CPUType::X64 : CPUType::Intel80386;
Zachary Turnerb57884e2017-08-11 21:14:01 +0000759 // Interestingly, if we set the string to 0.0.0.0, then when trying to view
760 // local variables WinDbg emits an error that private symbols are not present.
761 // By setting this to a valid MSVC linker version string, local variables are
762 // displayed properly. As such, even though it is not representative of
Zachary Turnerf6822c82017-08-11 20:46:47 +0000763 // LLVM's version information, we need this for compatibility.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000764 CS.Flags = CompileSym3Flags::None;
Zachary Turnerf6822c82017-08-11 20:46:47 +0000765 CS.VersionBackendBuild = 25019;
766 CS.VersionBackendMajor = 14;
767 CS.VersionBackendMinor = 10;
Zachary Turner6708e0b2017-07-10 21:01:37 +0000768 CS.VersionBackendQFE = 0;
Zachary Turnerf6822c82017-08-11 20:46:47 +0000769
770 // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
771 // linker module (which is by definition a backend), so we don't need to do
772 // anything here. Also, it seems we can use "LLVM Linker" for the linker name
773 // without any problems. Only the backend version has to be hardcoded to a
774 // magic number.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000775 CS.VersionFrontendBuild = 0;
776 CS.VersionFrontendMajor = 0;
777 CS.VersionFrontendMinor = 0;
778 CS.VersionFrontendQFE = 0;
779 CS.Version = "LLVM Linker";
780 CS.setLanguage(SourceLanguage::Link);
781
782 ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
783 std::string ArgStr = llvm::join(Args, " ");
784 EBS.Fields.push_back("cwd");
785 SmallString<64> cwd;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000786 sys::fs::current_path(cwd);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000787 EBS.Fields.push_back(cwd);
788 EBS.Fields.push_back("exe");
Zachary Turnerf6822c82017-08-11 20:46:47 +0000789 SmallString<64> exe = Config->Argv[0];
790 llvm::sys::fs::make_absolute(exe);
791 EBS.Fields.push_back(exe);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000792 EBS.Fields.push_back("pdb");
793 EBS.Fields.push_back(Path);
794 EBS.Fields.push_back("cmd");
795 EBS.Fields.push_back(ArgStr);
796 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
797 ONS, Allocator, CodeViewContainer::Pdb));
798 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
799 CS, Allocator, CodeViewContainer::Pdb));
800 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
801 EBS, Allocator, CodeViewContainer::Pdb));
802}
803
Zachary Turner28e31ee2017-08-11 20:46:28 +0000804static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &Mod,
805 OutputSection &OS,
806 BumpPtrAllocator &Allocator) {
807 SectionSym Sym(SymbolRecordKind::SectionSym);
Zachary Turnerf6822c82017-08-11 20:46:47 +0000808 Sym.Alignment = 12; // 2^12 = 4KB
Zachary Turner28e31ee2017-08-11 20:46:28 +0000809 Sym.Characteristics = OS.getCharacteristics();
810 Sym.Length = OS.getVirtualSize();
811 Sym.Name = OS.getName();
812 Sym.Rva = OS.getRVA();
813 Sym.SectionNumber = OS.SectionIndex;
814 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
815 Sym, Allocator, CodeViewContainer::Pdb));
816}
817
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000818// Creates a PDB file.
Reid Kleckner175af4b2017-08-03 21:15:09 +0000819void coff::createPDB(SymbolTable *Symtab,
820 ArrayRef<OutputSection *> OutputSections,
821 ArrayRef<uint8_t> SectionTable,
Zachary Turner024323c2017-08-15 21:31:41 +0000822 const llvm::codeview::DebugInfo &BuildId) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000823 PDBLinker PDB(Symtab);
Zachary Turner024323c2017-08-15 21:31:41 +0000824 PDB.initialize(BuildId);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000825 PDB.addObjectsToPDB();
Reid Kleckner175af4b2017-08-03 21:15:09 +0000826 PDB.addSections(OutputSections, SectionTable);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000827 PDB.commit();
828}
829
Zachary Turner024323c2017-08-15 21:31:41 +0000830void PDBLinker::initialize(const llvm::codeview::DebugInfo &BuildId) {
Rui Ueyama12979542016-09-30 20:53:45 +0000831 ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
Rui Ueyama7f382992016-09-15 18:55:18 +0000832
Rui Ueyama8d3fb5d2016-10-05 22:08:58 +0000833 // Create streams in MSF for predefined streams, namely
834 // PDB, TPI, DBI and IPI.
835 for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
836 ExitOnErr(Builder.getMsfBuilder().addStream(0));
Rui Ueyama7f382992016-09-15 18:55:18 +0000837
Rui Ueyamabb542b32016-09-16 22:51:17 +0000838 // Add an Info stream.
839 auto &InfoBuilder = Builder.getInfoBuilder();
Zachary Turner024323c2017-08-15 21:31:41 +0000840 InfoBuilder.setAge(BuildId.PDB70.Age);
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000841
Zachary Turner024323c2017-08-15 21:31:41 +0000842 GUID uuid;
843 memcpy(&uuid, &BuildId.PDB70.Signature, sizeof(uuid));
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000844 InfoBuilder.setGuid(uuid);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000845 InfoBuilder.setSignature(time(nullptr));
Rui Ueyamabb542b32016-09-16 22:51:17 +0000846 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
Rui Ueyama7f382992016-09-15 18:55:18 +0000847
Zachary Turner6c4bfba2017-07-07 05:04:36 +0000848 // Add an empty DBI stream.
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000849 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Zachary Turner024323c2017-08-15 21:31:41 +0000850 DbiBuilder.setAge(BuildId.PDB70.Age);
Zachary Turnerc1e93e52017-07-07 18:45:56 +0000851 DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000852 ExitOnErr(DbiBuilder.addDbgStream(pdb::DbgHeaderType::NewFPO, {}));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000853}
Rui Ueyama1343fac2016-10-06 22:52:01 +0000854
Reid Kleckner175af4b2017-08-03 21:15:09 +0000855void PDBLinker::addSectionContrib(pdb::DbiModuleDescriptorBuilder &LinkerModule,
856 OutputSection *OS, Chunk *C) {
857 pdb::SectionContrib SC;
858 memset(&SC, 0, sizeof(SC));
859 SC.ISect = OS->SectionIndex;
860 SC.Off = C->getRVA() - OS->getRVA();
861 SC.Size = C->getSize();
862 if (auto *SecChunk = dyn_cast<SectionChunk>(C)) {
863 SC.Characteristics = SecChunk->Header->Characteristics;
864 SC.Imod = SecChunk->File->ModuleDBI->getModuleIndex();
Zachary Turner676386ff2017-08-07 20:23:45 +0000865 ArrayRef<uint8_t> Contents = SecChunk->getContents();
866 JamCRC CRC(0);
867 ArrayRef<char> CharContents = makeArrayRef(
868 reinterpret_cast<const char *>(Contents.data()), Contents.size());
869 CRC.update(CharContents);
870 SC.DataCrc = CRC.getCRC();
Reid Kleckner175af4b2017-08-03 21:15:09 +0000871 } else {
872 SC.Characteristics = OS->getCharacteristics();
873 // FIXME: When we start creating DBI for import libraries, use those here.
874 SC.Imod = LinkerModule.getModuleIndex();
875 }
Reid Kleckner175af4b2017-08-03 21:15:09 +0000876 SC.RelocCrc = 0; // FIXME
877 Builder.getDbiBuilder().addSectionContrib(SC);
878}
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000879
Reid Kleckner175af4b2017-08-03 21:15:09 +0000880void PDBLinker::addSections(ArrayRef<OutputSection *> OutputSections,
881 ArrayRef<uint8_t> SectionTable) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000882 // It's not entirely clear what this is, but the * Linker * module uses it.
Reid Kleckner175af4b2017-08-03 21:15:09 +0000883 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000884 NativePath = Config->PDBPath;
885 sys::fs::make_absolute(NativePath);
886 sys::path::native(NativePath, sys::path::Style::windows);
887 uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
Zachary Turner6c4bfba2017-07-07 05:04:36 +0000888 auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
889 LinkerModule.setPdbFilePathNI(PdbFilePathNI);
Zachary Turner28e31ee2017-08-11 20:46:28 +0000890 addCommonLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
Rui Ueyamac91f7162016-11-16 01:10:46 +0000891
Reid Kleckner175af4b2017-08-03 21:15:09 +0000892 // Add section contributions. They must be ordered by ascending RVA.
Zachary Turner28e31ee2017-08-11 20:46:28 +0000893 for (OutputSection *OS : OutputSections) {
894 addLinkerModuleSectionSymbol(LinkerModule, *OS, Alloc);
Reid Kleckner175af4b2017-08-03 21:15:09 +0000895 for (Chunk *C : OS->getChunks())
896 addSectionContrib(LinkerModule, OS, C);
Zachary Turner28e31ee2017-08-11 20:46:28 +0000897 }
Reid Kleckner175af4b2017-08-03 21:15:09 +0000898
899 // Add Section Map stream.
900 ArrayRef<object::coff_section> Sections = {
901 (const object::coff_section *)SectionTable.data(),
902 SectionTable.size() / sizeof(object::coff_section)};
903 SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
904 DbiBuilder.setSectionMap(SectionMap);
905
Rui Ueyama9f66f822016-10-11 19:45:07 +0000906 // Add COFF section header stream.
907 ExitOnErr(
908 DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000909}
Rui Ueyama9f66f822016-10-11 19:45:07 +0000910
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000911void PDBLinker::commit() {
Rui Ueyama3e9d6bb2016-09-26 23:53:55 +0000912 // Write to a file.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000913 ExitOnErr(Builder.commit(Config->PDBPath));
Rui Ueyamae7378242015-12-04 23:11:05 +0000914}