blob: d6891f97bf3f9cc0a428b4475e900ddda6f8fd73 [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 Turnerca6dbf12017-11-30 18:39:50 +000021#include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
Zachary Turneree9906d2017-08-11 19:00:03 +000022#include "llvm/DebugInfo/CodeView/RecordName.h"
Zachary Turner59e3ae82017-08-08 18:34:44 +000023#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
Zachary Turner6708e0b2017-07-10 21:01:37 +000024#include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
Reid Kleckner651db912017-07-18 00:21:25 +000025#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000026#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerd0e6e242017-06-21 17:25:56 +000027#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
Rui Ueyama52896622017-01-12 03:09:25 +000028#include "llvm/DebugInfo/CodeView/TypeStreamMerger.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"
Zachary Turner676386ff2017-08-07 20:23:45 +000049#include "llvm/Support/JamCRC.h"
Zachary Turner7b327d02017-02-16 23:35:45 +000050#include "llvm/Support/Path.h"
Rui Ueyamabe939b32016-11-21 17:22:35 +000051#include "llvm/Support/ScopedPrinter.h"
Rui Ueyamae7378242015-12-04 23:11:05 +000052#include <memory>
53
Rui Ueyama1d99ab32016-09-15 22:24:51 +000054using namespace lld;
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000055using namespace lld::coff;
Rui Ueyamae7378242015-12-04 23:11:05 +000056using namespace llvm;
Rui Ueyamabe939b32016-11-21 17:22:35 +000057using namespace llvm::codeview;
Rui Ueyamae7378242015-12-04 23:11:05 +000058
Rui Ueyama09e0b5f2016-11-12 00:00:51 +000059using llvm::object::coff_section;
60
Rui Ueyamab28c6d42016-09-16 04:32:33 +000061static ExitOnError ExitOnErr;
62
Reid Kleckner0faf6d72017-07-14 00:14:58 +000063namespace {
Reid Kleckner651db912017-07-18 00:21:25 +000064/// Map from type index and item index in a type server PDB to the
65/// corresponding index in the destination PDB.
66struct CVIndexMap {
67 SmallVector<TypeIndex, 0> TPIMap;
68 SmallVector<TypeIndex, 0> IPIMap;
69 bool IsTypeServerMap = false;
70};
71
Reid Kleckner0faf6d72017-07-14 00:14:58 +000072class PDBLinker {
73public:
74 PDBLinker(SymbolTable *Symtab)
75 : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
76 IDTable(Alloc) {}
77
78 /// Emit the basic PDB structure: initial streams, headers, etc.
Zachary Turner024323c2017-08-15 21:31:41 +000079 void initialize(const llvm::codeview::DebugInfo &BuildId);
Reid Kleckner0faf6d72017-07-14 00:14:58 +000080
81 /// Link CodeView from each object file in the symbol table into the PDB.
82 void addObjectsToPDB();
83
84 /// Link CodeView from a single object file into the PDB.
Rui Ueyamae1b48e02017-07-26 23:05:24 +000085 void addObjFile(ObjFile *File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +000086
Reid Kleckner651db912017-07-18 00:21:25 +000087 /// Produce a mapping from the type and item indices used in the object
88 /// file to those in the destination PDB.
89 ///
90 /// If the object file uses a type server PDB (compiled with /Zi), merge TPI
91 /// and IPI from the type server PDB and return a map for it. Each unique type
92 /// server PDB is merged at most once, so this may return an existing index
93 /// mapping.
94 ///
95 /// If the object does not use a type server PDB (compiled with /Z7), we merge
96 /// all the type and item records from the .debug$S stream and fill in the
97 /// caller-provided ObjectIndexMap.
Rui Ueyamae1b48e02017-07-26 23:05:24 +000098 const CVIndexMap &mergeDebugT(ObjFile *File, CVIndexMap &ObjectIndexMap);
Reid Kleckner651db912017-07-18 00:21:25 +000099
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000100 const CVIndexMap &maybeMergeTypeServerPDB(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000101 TypeServer2Record &TS);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000102
103 /// Add the section map and section contributions to the PDB.
Reid Kleckner175af4b2017-08-03 21:15:09 +0000104 void addSections(ArrayRef<OutputSection *> OutputSections,
105 ArrayRef<uint8_t> SectionTable);
106
107 void addSectionContrib(pdb::DbiModuleDescriptorBuilder &LinkerModule,
108 OutputSection *OS, Chunk *C);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000109
110 /// Write the PDB to disk.
111 void commit();
112
113private:
114 BumpPtrAllocator Alloc;
115
116 SymbolTable *Symtab;
117
118 pdb::PDBFileBuilder Builder;
119
120 /// Type records that will go into the PDB TPI stream.
Zachary Turnerca6dbf12017-11-30 18:39:50 +0000121 MergingTypeTableBuilder TypeTable;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000122
123 /// Item records that will go into the PDB IPI stream.
Zachary Turnerca6dbf12017-11-30 18:39:50 +0000124 MergingTypeTableBuilder IDTable;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000125
126 /// PDBs use a single global string table for filenames in the file checksum
127 /// table.
128 DebugStringTableSubsection PDBStrTab;
129
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000130 llvm::SmallString<128> NativePath;
131
132 std::vector<pdb::SecMapEntry> SectionMap;
Reid Kleckner651db912017-07-18 00:21:25 +0000133
134 /// Type index mappings of type server PDBs that we've loaded so far.
135 std::map<GUID, CVIndexMap> TypeServerIndexMappings;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000136};
137}
138
Sam Clegg0fb6faa2017-12-08 01:09:21 +0000139static SectionChunk *findByName(ArrayRef<SectionChunk *> Sections,
Rui Ueyamabe939b32016-11-21 17:22:35 +0000140 StringRef Name) {
141 for (SectionChunk *C : Sections)
142 if (C->getSectionName() == Name)
143 return C;
144 return nullptr;
145}
146
Reid Kleckner44cdb102017-06-19 17:21:45 +0000147static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
148 StringRef SecName) {
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000149 // First 4 bytes are section magic.
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000150 if (Data.size() < 4)
Rui Ueyama52896622017-01-12 03:09:25 +0000151 fatal(SecName + " too short");
Reid Kleckner44cdb102017-06-19 17:21:45 +0000152 if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
Rui Ueyama52896622017-01-12 03:09:25 +0000153 fatal(SecName + " has an invalid magic");
Rui Ueyama26186c72016-12-09 04:46:54 +0000154 return Data.slice(4);
155}
Rui Ueyamac5cb7372016-12-01 01:22:48 +0000156
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000157static ArrayRef<uint8_t> getDebugSection(ObjFile *File, StringRef SecName) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000158 if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
159 return consumeDebugMagic(Sec->getContents(), SecName);
160 return {};
161}
162
Reid Kleckner5d577522017-03-24 17:26:38 +0000163static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
Zachary Turner3e3936d2017-11-29 19:35:21 +0000164 TypeCollection &TypeTable) {
Reid Kleckner5d577522017-03-24 17:26:38 +0000165 // Start the TPI or IPI stream header.
166 TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
Rui Ueyama52896622017-01-12 03:09:25 +0000167
Reid Klecknerd91ca762017-07-19 17:26:07 +0000168 // Flatten the in memory type table and hash each type.
Zachary Turner3e3936d2017-11-29 19:35:21 +0000169 TypeTable.ForEachRecord([&](TypeIndex TI, const CVType &Type) {
Reid Klecknerd91ca762017-07-19 17:26:07 +0000170 auto Hash = pdb::hashTypeRecord(Type);
171 if (auto E = Hash.takeError())
172 fatal("type hashing error");
Zachary Turner3e3936d2017-11-29 19:35:21 +0000173 TpiBuilder.addTypeRecord(Type.RecordData, *Hash);
Reid Kleckner5d577522017-03-24 17:26:38 +0000174 });
Reid Kleckner5d577522017-03-24 17:26:38 +0000175}
176
Reid Kleckner651db912017-07-18 00:21:25 +0000177static Optional<TypeServer2Record>
178maybeReadTypeServerRecord(CVTypeArray &Types) {
179 auto I = Types.begin();
180 if (I == Types.end())
181 return None;
182 const CVType &Type = *I;
183 if (Type.kind() != LF_TYPESERVER2)
184 return None;
185 TypeServer2Record TS;
186 if (auto EC = TypeDeserializer::deserializeAs(const_cast<CVType &>(Type), TS))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000187 fatal("error reading type server record: " + toString(std::move(EC)));
Reid Kleckner651db912017-07-18 00:21:25 +0000188 return std::move(TS);
189}
190
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000191const CVIndexMap &PDBLinker::mergeDebugT(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000192 CVIndexMap &ObjectIndexMap) {
Reid Kleckner44cdb102017-06-19 17:21:45 +0000193 ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
194 if (Data.empty())
Reid Kleckner651db912017-07-18 00:21:25 +0000195 return ObjectIndexMap;
Reid Kleckner6597c282017-07-13 20:12:23 +0000196
Reid Kleckner44cdb102017-06-19 17:21:45 +0000197 BinaryByteStream Stream(Data, support::little);
198 CVTypeArray Types;
199 BinaryStreamReader Reader(Stream);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000200 if (auto EC = Reader.readArray(Types, Reader.getLength()))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000201 fatal("Reader::readArray failed: " + toString(std::move(EC)));
Reid Kleckner651db912017-07-18 00:21:25 +0000202
203 // Look through type servers. If we've already seen this type server, don't
204 // merge any type information.
205 if (Optional<TypeServer2Record> TS = maybeReadTypeServerRecord(Types))
206 return maybeMergeTypeServerPDB(File, *TS);
207
208 // This is a /Z7 object. Fill in the temporary, caller-provided
209 // ObjectIndexMap.
210 if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable,
211 ObjectIndexMap.TPIMap, Types))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000212 fatal("codeview::mergeTypeAndIdRecords failed: " +
213 toString(std::move(Err)));
Reid Kleckner651db912017-07-18 00:21:25 +0000214 return ObjectIndexMap;
215}
216
217static Expected<std::unique_ptr<pdb::NativeSession>>
218tryToLoadPDB(const GUID &GuidFromObj, StringRef TSPath) {
Peter Collingbourne75257bc2017-10-20 19:48:26 +0000219 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(
220 TSPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
221 if (!MBOrErr)
222 return errorCodeToError(MBOrErr.getError());
223
Reid Kleckner651db912017-07-18 00:21:25 +0000224 std::unique_ptr<pdb::IPDBSession> ThisSession;
Peter Collingbourne75257bc2017-10-20 19:48:26 +0000225 if (auto EC = pdb::NativeSession::createFromPdb(
226 MemoryBuffer::getMemBuffer(Driver->takeBuffer(std::move(*MBOrErr)),
227 /*RequiresNullTerminator=*/false),
228 ThisSession))
Reid Kleckner651db912017-07-18 00:21:25 +0000229 return std::move(EC);
230
231 std::unique_ptr<pdb::NativeSession> NS(
232 static_cast<pdb::NativeSession *>(ThisSession.release()));
233 pdb::PDBFile &File = NS->getPDBFile();
234 auto ExpectedInfo = File.getPDBInfoStream();
235 // All PDB Files should have an Info stream.
236 if (!ExpectedInfo)
237 return ExpectedInfo.takeError();
238
239 // Just because a file with a matching name was found and it was an actual
240 // PDB file doesn't mean it matches. For it to match the InfoStream's GUID
241 // must match the GUID specified in the TypeServer2 record.
242 if (ExpectedInfo->getGuid() != GuidFromObj)
243 return make_error<pdb::GenericError>(
244 pdb::generic_error_code::type_server_not_found, TSPath);
245
246 return std::move(NS);
247}
248
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000249const CVIndexMap &PDBLinker::maybeMergeTypeServerPDB(ObjFile *File,
Reid Kleckner651db912017-07-18 00:21:25 +0000250 TypeServer2Record &TS) {
251 // First, check if we already loaded a PDB with this GUID. Return the type
252 // index mapping if we have it.
253 auto Insertion = TypeServerIndexMappings.insert({TS.getGuid(), CVIndexMap()});
254 CVIndexMap &IndexMap = Insertion.first->second;
255 if (!Insertion.second)
256 return IndexMap;
257
258 // Mark this map as a type server map.
259 IndexMap.IsTypeServerMap = true;
260
261 // Check for a PDB at:
262 // 1. The given file path
263 // 2. Next to the object file or archive file
264 auto ExpectedSession = tryToLoadPDB(TS.getGuid(), TS.getName());
265 if (!ExpectedSession) {
266 consumeError(ExpectedSession.takeError());
267 StringRef LocalPath =
268 !File->ParentName.empty() ? File->ParentName : File->getName();
269 SmallString<128> Path = sys::path::parent_path(LocalPath);
Reid Klecknerf8522d82017-07-18 00:33:53 +0000270 sys::path::append(
271 Path, sys::path::filename(TS.getName(), sys::path::Style::windows));
Reid Kleckner651db912017-07-18 00:21:25 +0000272 ExpectedSession = tryToLoadPDB(TS.getGuid(), Path);
273 }
274 if (auto E = ExpectedSession.takeError())
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000275 fatal("Type server PDB was not found: " + toString(std::move(E)));
Reid Kleckner651db912017-07-18 00:21:25 +0000276
277 // Merge TPI first, because the IPI stream will reference type indices.
278 auto ExpectedTpi = (*ExpectedSession)->getPDBFile().getPDBTpiStream();
279 if (auto E = ExpectedTpi.takeError())
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000280 fatal("Type server does not have TPI stream: " + toString(std::move(E)));
Reid Kleckner651db912017-07-18 00:21:25 +0000281 if (auto Err = mergeTypeRecords(TypeTable, IndexMap.TPIMap,
282 ExpectedTpi->typeArray()))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000283 fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
Reid Kleckner651db912017-07-18 00:21:25 +0000284
285 // Merge IPI.
286 auto ExpectedIpi = (*ExpectedSession)->getPDBFile().getPDBIpiStream();
287 if (auto E = ExpectedIpi.takeError())
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000288 fatal("Type server does not have TPI stream: " + toString(std::move(E)));
Reid Kleckner651db912017-07-18 00:21:25 +0000289 if (auto Err = mergeIdRecords(IDTable, IndexMap.TPIMap, IndexMap.IPIMap,
290 ExpectedIpi->typeArray()))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000291 fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
Reid Kleckner651db912017-07-18 00:21:25 +0000292
293 return IndexMap;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000294}
295
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000296static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
297 if (TI.isSimple())
298 return true;
299 if (TI.toArrayIndex() >= TypeIndexMap.size())
300 return false;
301 TI = TypeIndexMap[TI.toArrayIndex()];
302 return true;
303}
304
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000305static void remapTypesInSymbolRecord(ObjFile *File, SymbolKind SymKind,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000306 MutableArrayRef<uint8_t> Contents,
Reid Kleckner651db912017-07-18 00:21:25 +0000307 const CVIndexMap &IndexMap,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000308 ArrayRef<TiReference> TypeRefs) {
309 for (const TiReference &Ref : TypeRefs) {
310 unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000311 if (Contents.size() < Ref.Offset + ByteSize)
312 fatal("symbol record too short");
Reid Kleckner651db912017-07-18 00:21:25 +0000313
314 // This can be an item index or a type index. Choose the appropriate map.
315 ArrayRef<TypeIndex> TypeOrItemMap = IndexMap.TPIMap;
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000316 bool IsItemIndex = Ref.Kind == TiRefKind::IndexRef;
317 if (IsItemIndex && IndexMap.IsTypeServerMap)
Reid Kleckner651db912017-07-18 00:21:25 +0000318 TypeOrItemMap = IndexMap.IPIMap;
319
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000320 MutableArrayRef<TypeIndex> TIs(
321 reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000322 for (TypeIndex &TI : TIs) {
Reid Kleckner651db912017-07-18 00:21:25 +0000323 if (!remapTypeIndex(TI, TypeOrItemMap)) {
Reid Kleckner8aa32ff2017-10-24 17:02:40 +0000324 log("ignoring symbol record of kind 0x" + utohexstr(SymKind) + " in " +
325 File->getName() + " with bad " + (IsItemIndex ? "item" : "type") +
326 " index 0x" + utohexstr(TI.getIndex()));
Reid Kleckner5d82f682017-10-23 22:44:51 +0000327 TI = TypeIndex(SimpleTypeKind::NotTranslated);
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000328 continue;
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000329 }
Reid Kleckner03b5baf2017-07-12 18:49:43 +0000330 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000331 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000332}
333
Zachary Turner59e3ae82017-08-08 18:34:44 +0000334static SymbolKind symbolKind(ArrayRef<uint8_t> RecordData) {
335 const RecordPrefix *Prefix =
336 reinterpret_cast<const RecordPrefix *>(RecordData.data());
337 return static_cast<SymbolKind>(uint16_t(Prefix->RecordKind));
338}
339
340/// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
341static void translateIdSymbols(MutableArrayRef<uint8_t> &RecordData,
Zachary Turner3e3936d2017-11-29 19:35:21 +0000342 TypeCollection &IDTable) {
Zachary Turner59e3ae82017-08-08 18:34:44 +0000343 RecordPrefix *Prefix = reinterpret_cast<RecordPrefix *>(RecordData.data());
344
345 SymbolKind Kind = symbolKind(RecordData);
346
347 if (Kind == SymbolKind::S_PROC_ID_END) {
348 Prefix->RecordKind = SymbolKind::S_END;
349 return;
350 }
351
352 // In an object file, GPROC32_ID has an embedded reference which refers to the
353 // single object file type index namespace. This has already been translated
354 // to the PDB file's ID stream index space, but we need to convert this to a
355 // symbol that refers to the type stream index space. So we remap again from
356 // ID index space to type index space.
357 if (Kind == SymbolKind::S_GPROC32_ID || Kind == SymbolKind::S_LPROC32_ID) {
358 SmallVector<TiReference, 1> Refs;
359 auto Content = RecordData.drop_front(sizeof(RecordPrefix));
360 CVSymbol Sym(Kind, RecordData);
361 discoverTypeIndicesInSymbol(Sym, Refs);
362 assert(Refs.size() == 1);
363 assert(Refs.front().Count == 1);
364
365 TypeIndex *TI =
366 reinterpret_cast<TypeIndex *>(Content.data() + Refs[0].Offset);
367 // `TI` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
368 // the IPI stream, whose `FunctionType` member refers to the TPI stream.
369 // Note that LF_FUNC_ID and LF_MEMFUNC_ID have the same record layout, and
370 // in both cases we just need the second type index.
371 if (!TI->isSimple() && !TI->isNoneType()) {
Zachary Turner3e3936d2017-11-29 19:35:21 +0000372 CVType FuncIdData = IDTable.getType(*TI);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000373 SmallVector<TypeIndex, 2> Indices;
374 discoverTypeIndices(FuncIdData, Indices);
375 assert(Indices.size() == 2);
376 *TI = Indices[1];
377 }
378
379 Kind = (Kind == SymbolKind::S_GPROC32_ID) ? SymbolKind::S_GPROC32
380 : SymbolKind::S_LPROC32;
381 Prefix->RecordKind = uint16_t(Kind);
382 }
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000383}
384
385/// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
386/// The object file may not be aligned.
387static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
388 BumpPtrAllocator &Alloc) {
389 size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
390 assert(Size >= 4 && "record too short");
391 assert(Size <= MaxRecordLength && "record too long");
392 void *Mem = Alloc.Allocate(Size, 4);
393
394 // Copy the symbol record and zero out any padding bytes.
395 MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
396 memcpy(NewData.data(), Sym.data().data(), Sym.length());
397 memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
398
399 // Update the record prefix length. It should point to the beginning of the
Zachary Turner59e3ae82017-08-08 18:34:44 +0000400 // next record.
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000401 auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000402 Prefix->RecordLen = Size - 2;
403 return NewData;
404}
405
Reid Kleckner3f851922017-07-06 16:39:32 +0000406/// Return true if this symbol opens a scope. This implies that the symbol has
407/// "parent" and "end" fields, which contain the offset of the S_END or
408/// S_INLINESITE_END record.
409static bool symbolOpensScope(SymbolKind Kind) {
410 switch (Kind) {
411 case SymbolKind::S_GPROC32:
412 case SymbolKind::S_LPROC32:
413 case SymbolKind::S_LPROC32_ID:
414 case SymbolKind::S_GPROC32_ID:
415 case SymbolKind::S_BLOCK32:
416 case SymbolKind::S_SEPCODE:
417 case SymbolKind::S_THUNK32:
418 case SymbolKind::S_INLINESITE:
419 case SymbolKind::S_INLINESITE2:
420 return true;
421 default:
422 break;
423 }
424 return false;
425}
426
427static bool symbolEndsScope(SymbolKind Kind) {
428 switch (Kind) {
429 case SymbolKind::S_END:
430 case SymbolKind::S_PROC_ID_END:
431 case SymbolKind::S_INLINESITE_END:
432 return true;
433 default:
434 break;
435 }
436 return false;
437}
438
439struct ScopeRecord {
440 ulittle32_t PtrParent;
441 ulittle32_t PtrEnd;
442};
443
444struct SymbolScope {
445 ScopeRecord *OpeningRecord;
446 uint32_t ScopeOffset;
447};
448
449static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
450 uint32_t CurOffset, CVSymbol &Sym) {
451 assert(symbolOpensScope(Sym.kind()));
452 SymbolScope S;
453 S.ScopeOffset = CurOffset;
454 S.OpeningRecord = const_cast<ScopeRecord *>(
455 reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
456 S.OpeningRecord->PtrParent = Stack.empty() ? 0 : Stack.back().ScopeOffset;
457 Stack.push_back(S);
458}
459
460static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000461 uint32_t CurOffset, ObjFile *File) {
Reid Kleckner3f851922017-07-06 16:39:32 +0000462 if (Stack.empty()) {
463 warn("symbol scopes are not balanced in " + File->getName());
464 return;
465 }
466 SymbolScope S = Stack.pop_back_val();
467 S.OpeningRecord->PtrEnd = CurOffset;
468}
469
Zachary Turneree9906d2017-08-11 19:00:03 +0000470static bool symbolGoesInModuleStream(const CVSymbol &Sym) {
471 switch (Sym.kind()) {
472 case SymbolKind::S_GDATA32:
473 case SymbolKind::S_CONSTANT:
474 case SymbolKind::S_UDT:
475 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
476 // since they are synthesized by the linker in response to S_GPROC32 and
477 // S_LPROC32, but if we do see them, don't put them in the module stream I
478 // guess.
479 case SymbolKind::S_PROCREF:
480 case SymbolKind::S_LPROCREF:
481 return false;
482 // S_GDATA32 does not go in the module stream, but S_LDATA32 does.
483 case SymbolKind::S_LDATA32:
484 default:
485 return true;
486 }
487}
488
489static bool symbolGoesInGlobalsStream(const CVSymbol &Sym) {
490 switch (Sym.kind()) {
491 case SymbolKind::S_CONSTANT:
Zachary Turneree9906d2017-08-11 19:00:03 +0000492 case SymbolKind::S_GDATA32:
493 // S_LDATA32 goes in both the module stream and the globals stream.
494 case SymbolKind::S_LDATA32:
495 case SymbolKind::S_GPROC32:
496 case SymbolKind::S_LPROC32:
497 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
498 // since they are synthesized by the linker in response to S_GPROC32 and
499 // S_LPROC32, but if we do see them, copy them straight through.
500 case SymbolKind::S_PROCREF:
501 case SymbolKind::S_LPROCREF:
502 return true;
Zachary Turner302dc8b2017-08-14 18:44:58 +0000503 // FIXME: For now, we drop all S_UDT symbols (i.e. they don't go in the
504 // globals stream or the modules stream). These have special handling which
505 // needs more investigation before we can get right, but by putting them all
506 // into the globals stream WinDbg fails to display local variables of class
507 // types saying that it cannot find the type Foo *. So as a stopgap just to
508 // keep things working, we drop them.
509 case SymbolKind::S_UDT:
Zachary Turneree9906d2017-08-11 19:00:03 +0000510 default:
511 return false;
512 }
513}
514
515static void addGlobalSymbol(pdb::GSIStreamBuilder &Builder, ObjFile &File,
516 const CVSymbol &Sym) {
517 switch (Sym.kind()) {
518 case SymbolKind::S_CONSTANT:
519 case SymbolKind::S_UDT:
520 case SymbolKind::S_GDATA32:
521 case SymbolKind::S_LDATA32:
522 case SymbolKind::S_PROCREF:
523 case SymbolKind::S_LPROCREF:
524 Builder.addGlobalSymbol(Sym);
525 break;
526 case SymbolKind::S_GPROC32:
527 case SymbolKind::S_LPROC32: {
528 SymbolRecordKind K = SymbolRecordKind::ProcRefSym;
529 if (Sym.kind() == SymbolKind::S_LPROC32)
530 K = SymbolRecordKind::LocalProcRef;
531 ProcRefSym PS(K);
532 PS.Module = static_cast<uint16_t>(File.ModuleDBI->getModuleIndex());
533 // For some reason, MSVC seems to add one to this value.
534 ++PS.Module;
535 PS.Name = getSymbolName(Sym);
536 PS.SumName = 0;
537 PS.SymOffset = File.ModuleDBI->getNextSymbolOffset();
538 Builder.addGlobalSymbol(PS);
539 break;
540 }
541 default:
542 llvm_unreachable("Invalid symbol kind!");
543 }
544}
545
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000546static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjFile *File,
Zachary Turneree9906d2017-08-11 19:00:03 +0000547 pdb::GSIStreamBuilder &GsiBuilder,
Reid Kleckner651db912017-07-18 00:21:25 +0000548 const CVIndexMap &IndexMap,
Zachary Turner3e3936d2017-11-29 19:35:21 +0000549 TypeCollection &IDTable,
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000550 BinaryStreamRef SymData) {
551 // FIXME: Improve error recovery by warning and skipping records when
552 // possible.
553 CVSymbolArray Syms;
554 BinaryStreamReader Reader(SymData);
555 ExitOnErr(Reader.readArray(Syms, Reader.getLength()));
Reid Kleckner3f851922017-07-06 16:39:32 +0000556 SmallVector<SymbolScope, 4> Scopes;
Zachary Turner59e3ae82017-08-08 18:34:44 +0000557 for (CVSymbol Sym : Syms) {
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000558 // Discover type index references in the record. Skip it if we don't know
559 // where they are.
560 SmallVector<TiReference, 32> TypeRefs;
Zachary Turner59e3ae82017-08-08 18:34:44 +0000561 if (!discoverTypeIndicesInSymbol(Sym, TypeRefs)) {
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000562 log("ignoring unknown symbol record with kind 0x" + utohexstr(Sym.kind()));
563 continue;
564 }
565
566 // Copy the symbol record so we can mutate it.
567 MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
568
569 // Re-map all the type index references.
570 MutableArrayRef<uint8_t> Contents =
571 NewData.drop_front(sizeof(RecordPrefix));
Zachary Turner3e3936d2017-11-29 19:35:21 +0000572 remapTypesInSymbolRecord(File, Sym.kind(), Contents, IndexMap, TypeRefs);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000573
574 // An object file may have S_xxx_ID symbols, but these get converted to
575 // "real" symbols in a PDB.
576 translateIdSymbols(NewData, IDTable);
577
578 SymbolKind NewKind = symbolKind(NewData);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000579
Reid Kleckner3f851922017-07-06 16:39:32 +0000580 // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
Zachary Turner59e3ae82017-08-08 18:34:44 +0000581 CVSymbol NewSym(NewKind, NewData);
582 if (symbolOpensScope(NewKind))
Reid Kleckner3f851922017-07-06 16:39:32 +0000583 scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(), NewSym);
Zachary Turner59e3ae82017-08-08 18:34:44 +0000584 else if (symbolEndsScope(NewKind))
Reid Kleckner3f851922017-07-06 16:39:32 +0000585 scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000586
Zachary Turneree9906d2017-08-11 19:00:03 +0000587 // Add the symbol to the globals stream if necessary. Do this before adding
588 // the symbol to the module since we may need to get the next symbol offset,
589 // and writing to the module's symbol stream will update that offset.
590 if (symbolGoesInGlobalsStream(NewSym))
591 addGlobalSymbol(GsiBuilder, *File, NewSym);
592
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000593 // Add the symbol to the module.
Zachary Turneree9906d2017-08-11 19:00:03 +0000594 if (symbolGoesInModuleStream(NewSym))
595 File->ModuleDBI->addSymbol(NewSym);
Reid Klecknerd0e6e242017-06-21 17:25:56 +0000596 }
597}
598
Reid Kleckner44cdb102017-06-19 17:21:45 +0000599// Allocate memory for a .debug$S section and relocate it.
600static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
601 SectionChunk *DebugChunk) {
602 uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk->getSize());
603 assert(DebugChunk->OutputSectionOff == 0 &&
604 "debug sections should not be in output sections");
605 DebugChunk->writeTo(Buffer);
606 return consumeDebugMagic(makeArrayRef(Buffer, DebugChunk->getSize()),
607 ".debug$S");
608}
609
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000610void PDBLinker::addObjFile(ObjFile *File) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000611 // Add a module descriptor for every object file. We need to put an absolute
612 // path to the object into the PDB. If this is a plain object, we make its
613 // path absolute. If it's an object in an archive, we make the archive path
614 // absolute.
615 bool InArchive = !File->ParentName.empty();
616 SmallString<128> Path = InArchive ? File->ParentName : File->getName();
617 sys::fs::make_absolute(Path);
618 sys::path::native(Path, sys::path::Style::windows);
619 StringRef Name = InArchive ? File->getName() : StringRef(Path);
Zachary Turner2897e032017-05-25 21:16:03 +0000620
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000621 File->ModuleDBI = &ExitOnErr(Builder.getDbiBuilder().addModuleInfo(Name));
622 File->ModuleDBI->setObjFileName(Path);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000623
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000624 // Before we can process symbol substreams from .debug$S, we need to process
625 // type information, file checksums, and the string table. Add type info to
626 // the PDB first, so that we can get the map from object file type and item
627 // indices to PDB type and item indices.
Reid Kleckner651db912017-07-18 00:21:25 +0000628 CVIndexMap ObjectIndexMap;
629 const CVIndexMap &IndexMap = mergeDebugT(File, ObjectIndexMap);
Zachary Turner448dea42017-07-07 18:46:14 +0000630
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000631 // Now do all live .debug$S sections.
632 for (SectionChunk *DebugChunk : File->getDebugChunks()) {
633 if (!DebugChunk->isLive() || DebugChunk->getSectionName() != ".debug$S")
634 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000635
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000636 ArrayRef<uint8_t> RelocatedDebugContents =
637 relocateDebugChunk(Alloc, DebugChunk);
638 if (RelocatedDebugContents.empty())
639 continue;
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000640
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000641 DebugSubsectionArray Subsections;
642 BinaryStreamReader Reader(RelocatedDebugContents, support::little);
643 ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
Rui Ueyama52896622017-01-12 03:09:25 +0000644
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000645 DebugStringTableSubsectionRef CVStrTab;
646 DebugChecksumsSubsectionRef Checksums;
647 for (const DebugSubsectionRecord &SS : Subsections) {
648 switch (SS.kind()) {
649 case DebugSubsectionKind::StringTable:
650 ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
651 break;
652 case DebugSubsectionKind::FileChecksums:
653 ExitOnErr(Checksums.initialize(SS.getRecordData()));
654 break;
655 case DebugSubsectionKind::Lines:
656 // We can add the relocated line table directly to the PDB without
657 // modification because the file checksum offsets will stay the same.
658 File->ModuleDBI->addDebugSubsection(SS);
659 break;
660 case DebugSubsectionKind::Symbols:
Zachary Turneree9906d2017-08-11 19:00:03 +0000661 mergeSymbolRecords(Alloc, File, Builder.getGsiBuilder(), IndexMap,
662 IDTable, SS.getRecordData());
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000663 break;
664 default:
665 // FIXME: Process the rest of the subsections.
666 break;
Reid Kleckner44cdb102017-06-19 17:21:45 +0000667 }
668 }
Rui Ueyama52896622017-01-12 03:09:25 +0000669
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000670 if (Checksums.valid()) {
671 // Make a new file checksum table that refers to offsets in the PDB-wide
672 // string table. Generally the string table subsection appears after the
673 // checksum table, so we have to do this after looping over all the
674 // subsections.
675 if (!CVStrTab.valid())
676 fatal(".debug$S sections must have both a string table subsection "
677 "and a checksum subsection table or neither");
678 auto NewChecksums = make_unique<DebugChecksumsSubsection>(PDBStrTab);
679 for (FileChecksumEntry &FC : Checksums) {
680 StringRef FileName = ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
681 ExitOnErr(Builder.getDbiBuilder().addModuleSourceFile(*File->ModuleDBI,
682 FileName));
683 NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
684 }
685 File->ModuleDBI->addDebugSubsection(std::move(NewChecksums));
686 }
687 }
688}
689
Reid Klecknereacdf042017-07-27 18:25:59 +0000690static PublicSym32 createPublic(Defined *Def) {
691 PublicSym32 Pub(SymbolKind::S_PUB32);
692 Pub.Name = Def->getName();
693 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
694 if (D->getCOFFSymbol().isFunctionDefinition())
695 Pub.Flags = PublicSymFlags::Function;
696 } else if (isa<DefinedImportThunk>(Def)) {
697 Pub.Flags = PublicSymFlags::Function;
698 }
699
700 OutputSection *OS = Def->getChunk()->getOutputSection();
701 assert(OS && "all publics should be in final image");
702 Pub.Offset = Def->getRVA() - OS->getRVA();
703 Pub.Segment = OS->SectionIndex;
704 return Pub;
705}
706
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000707// Add all object files to the PDB. Merge .debug$T sections into IpiData and
708// TpiData.
709void PDBLinker::addObjectsToPDB() {
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000710 for (ObjFile *File : ObjFile::Instances)
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000711 addObjFile(File);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000712
713 Builder.getStringTableBuilder().setStrings(PDBStrTab);
Reid Kleckner44cdb102017-06-19 17:21:45 +0000714
Reid Kleckner5d577522017-03-24 17:26:38 +0000715 // Construct TPI stream contents.
Reid Kleckner13fc4112017-04-04 00:56:34 +0000716 addTypeInfo(Builder.getTpiBuilder(), TypeTable);
Reid Kleckner5d577522017-03-24 17:26:38 +0000717
718 // Construct IPI stream contents.
Reid Kleckner13fc4112017-04-04 00:56:34 +0000719 addTypeInfo(Builder.getIpiBuilder(), IDTable);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000720
Zachary Turneree9906d2017-08-11 19:00:03 +0000721 // Compute the public and global symbols.
722 auto &GsiBuilder = Builder.getGsiBuilder();
Reid Klecknereacdf042017-07-27 18:25:59 +0000723 std::vector<PublicSym32> Publics;
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000724 Symtab->forEachSymbol([&Publics](Symbol *S) {
Reid Klecknereacdf042017-07-27 18:25:59 +0000725 // Only emit defined, live symbols that have a chunk.
Rui Ueyama616cd992017-10-31 16:10:24 +0000726 auto *Def = dyn_cast<Defined>(S);
Reid Klecknereacdf042017-07-27 18:25:59 +0000727 if (Def && Def->isLive() && Def->getChunk())
728 Publics.push_back(createPublic(Def));
729 });
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000730
Reid Klecknereacdf042017-07-27 18:25:59 +0000731 if (!Publics.empty()) {
732 // Sort the public symbols and add them to the stream.
733 std::sort(Publics.begin(), Publics.end(),
734 [](const PublicSym32 &L, const PublicSym32 &R) {
735 return L.Name < R.Name;
736 });
Reid Klecknereacdf042017-07-27 18:25:59 +0000737 for (const PublicSym32 &Pub : Publics)
Zachary Turner946204c2017-08-09 04:23:25 +0000738 GsiBuilder.addPublicSymbol(Pub);
Reid Klecknereacdf042017-07-27 18:25:59 +0000739 }
Rui Ueyama52896622017-01-12 03:09:25 +0000740}
741
Zachary Turner28e31ee2017-08-11 20:46:28 +0000742static void addCommonLinkerModuleSymbols(StringRef Path,
743 pdb::DbiModuleDescriptorBuilder &Mod,
744 BumpPtrAllocator &Allocator) {
Zachary Turner28e31ee2017-08-11 20:46:28 +0000745 ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
746 Compile3Sym CS(SymbolRecordKind::Compile3Sym);
747 EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000748
749 ONS.Name = "* Linker *";
750 ONS.Signature = 0;
751
752 CS.Machine = Config->is64() ? CPUType::X64 : CPUType::Intel80386;
Zachary Turnerb57884e2017-08-11 21:14:01 +0000753 // Interestingly, if we set the string to 0.0.0.0, then when trying to view
754 // local variables WinDbg emits an error that private symbols are not present.
755 // By setting this to a valid MSVC linker version string, local variables are
756 // displayed properly. As such, even though it is not representative of
Zachary Turnerf6822c82017-08-11 20:46:47 +0000757 // LLVM's version information, we need this for compatibility.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000758 CS.Flags = CompileSym3Flags::None;
Zachary Turnerf6822c82017-08-11 20:46:47 +0000759 CS.VersionBackendBuild = 25019;
760 CS.VersionBackendMajor = 14;
761 CS.VersionBackendMinor = 10;
Zachary Turner6708e0b2017-07-10 21:01:37 +0000762 CS.VersionBackendQFE = 0;
Zachary Turnerf6822c82017-08-11 20:46:47 +0000763
764 // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
765 // linker module (which is by definition a backend), so we don't need to do
766 // anything here. Also, it seems we can use "LLVM Linker" for the linker name
767 // without any problems. Only the backend version has to be hardcoded to a
768 // magic number.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000769 CS.VersionFrontendBuild = 0;
770 CS.VersionFrontendMajor = 0;
771 CS.VersionFrontendMinor = 0;
772 CS.VersionFrontendQFE = 0;
773 CS.Version = "LLVM Linker";
774 CS.setLanguage(SourceLanguage::Link);
775
776 ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
777 std::string ArgStr = llvm::join(Args, " ");
778 EBS.Fields.push_back("cwd");
779 SmallString<64> cwd;
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000780 sys::fs::current_path(cwd);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000781 EBS.Fields.push_back(cwd);
782 EBS.Fields.push_back("exe");
Zachary Turnerf6822c82017-08-11 20:46:47 +0000783 SmallString<64> exe = Config->Argv[0];
784 llvm::sys::fs::make_absolute(exe);
785 EBS.Fields.push_back(exe);
Zachary Turner6708e0b2017-07-10 21:01:37 +0000786 EBS.Fields.push_back("pdb");
787 EBS.Fields.push_back(Path);
788 EBS.Fields.push_back("cmd");
789 EBS.Fields.push_back(ArgStr);
790 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
791 ONS, Allocator, CodeViewContainer::Pdb));
792 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
793 CS, Allocator, CodeViewContainer::Pdb));
794 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
795 EBS, Allocator, CodeViewContainer::Pdb));
796}
797
Zachary Turner28e31ee2017-08-11 20:46:28 +0000798static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &Mod,
799 OutputSection &OS,
800 BumpPtrAllocator &Allocator) {
801 SectionSym Sym(SymbolRecordKind::SectionSym);
Zachary Turnerf6822c82017-08-11 20:46:47 +0000802 Sym.Alignment = 12; // 2^12 = 4KB
Zachary Turner28e31ee2017-08-11 20:46:28 +0000803 Sym.Characteristics = OS.getCharacteristics();
804 Sym.Length = OS.getVirtualSize();
805 Sym.Name = OS.getName();
806 Sym.Rva = OS.getRVA();
807 Sym.SectionNumber = OS.SectionIndex;
808 Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
809 Sym, Allocator, CodeViewContainer::Pdb));
810}
811
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000812// Creates a PDB file.
Reid Kleckner175af4b2017-08-03 21:15:09 +0000813void coff::createPDB(SymbolTable *Symtab,
814 ArrayRef<OutputSection *> OutputSections,
815 ArrayRef<uint8_t> SectionTable,
Zachary Turner024323c2017-08-15 21:31:41 +0000816 const llvm::codeview::DebugInfo &BuildId) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000817 PDBLinker PDB(Symtab);
Zachary Turner024323c2017-08-15 21:31:41 +0000818 PDB.initialize(BuildId);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000819 PDB.addObjectsToPDB();
Reid Kleckner175af4b2017-08-03 21:15:09 +0000820 PDB.addSections(OutputSections, SectionTable);
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000821 PDB.commit();
822}
823
Zachary Turner024323c2017-08-15 21:31:41 +0000824void PDBLinker::initialize(const llvm::codeview::DebugInfo &BuildId) {
Rui Ueyama12979542016-09-30 20:53:45 +0000825 ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
Rui Ueyama7f382992016-09-15 18:55:18 +0000826
Rui Ueyama8d3fb5d2016-10-05 22:08:58 +0000827 // Create streams in MSF for predefined streams, namely
828 // PDB, TPI, DBI and IPI.
829 for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
830 ExitOnErr(Builder.getMsfBuilder().addStream(0));
Rui Ueyama7f382992016-09-15 18:55:18 +0000831
Rui Ueyamabb542b32016-09-16 22:51:17 +0000832 // Add an Info stream.
833 auto &InfoBuilder = Builder.getInfoBuilder();
Zachary Turner024323c2017-08-15 21:31:41 +0000834 InfoBuilder.setAge(BuildId.PDB70.Age);
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000835
Zachary Turner024323c2017-08-15 21:31:41 +0000836 GUID uuid;
837 memcpy(&uuid, &BuildId.PDB70.Signature, sizeof(uuid));
Saleem Abdulrasool0acd6dd2017-02-07 04:28:02 +0000838 InfoBuilder.setGuid(uuid);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000839 InfoBuilder.setSignature(time(nullptr));
Rui Ueyamabb542b32016-09-16 22:51:17 +0000840 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
Rui Ueyama7f382992016-09-15 18:55:18 +0000841
Zachary Turner6c4bfba2017-07-07 05:04:36 +0000842 // Add an empty DBI stream.
Reid Kleckner8cbdd0c2017-06-13 15:49:13 +0000843 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Zachary Turner024323c2017-08-15 21:31:41 +0000844 DbiBuilder.setAge(BuildId.PDB70.Age);
Zachary Turnerc1e93e52017-07-07 18:45:56 +0000845 DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
Zachary Turner3a11fdf2017-07-07 20:25:39 +0000846 ExitOnErr(DbiBuilder.addDbgStream(pdb::DbgHeaderType::NewFPO, {}));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000847}
Rui Ueyama1343fac2016-10-06 22:52:01 +0000848
Reid Kleckner175af4b2017-08-03 21:15:09 +0000849void PDBLinker::addSectionContrib(pdb::DbiModuleDescriptorBuilder &LinkerModule,
850 OutputSection *OS, Chunk *C) {
851 pdb::SectionContrib SC;
852 memset(&SC, 0, sizeof(SC));
853 SC.ISect = OS->SectionIndex;
854 SC.Off = C->getRVA() - OS->getRVA();
855 SC.Size = C->getSize();
856 if (auto *SecChunk = dyn_cast<SectionChunk>(C)) {
857 SC.Characteristics = SecChunk->Header->Characteristics;
858 SC.Imod = SecChunk->File->ModuleDBI->getModuleIndex();
Zachary Turner676386ff2017-08-07 20:23:45 +0000859 ArrayRef<uint8_t> Contents = SecChunk->getContents();
860 JamCRC CRC(0);
861 ArrayRef<char> CharContents = makeArrayRef(
862 reinterpret_cast<const char *>(Contents.data()), Contents.size());
863 CRC.update(CharContents);
864 SC.DataCrc = CRC.getCRC();
Reid Kleckner175af4b2017-08-03 21:15:09 +0000865 } else {
866 SC.Characteristics = OS->getCharacteristics();
867 // FIXME: When we start creating DBI for import libraries, use those here.
868 SC.Imod = LinkerModule.getModuleIndex();
869 }
Reid Kleckner175af4b2017-08-03 21:15:09 +0000870 SC.RelocCrc = 0; // FIXME
871 Builder.getDbiBuilder().addSectionContrib(SC);
872}
Rui Ueyama09e0b5f2016-11-12 00:00:51 +0000873
Reid Kleckner175af4b2017-08-03 21:15:09 +0000874void PDBLinker::addSections(ArrayRef<OutputSection *> OutputSections,
875 ArrayRef<uint8_t> SectionTable) {
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000876 // It's not entirely clear what this is, but the * Linker * module uses it.
Reid Kleckner175af4b2017-08-03 21:15:09 +0000877 pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000878 NativePath = Config->PDBPath;
879 sys::fs::make_absolute(NativePath);
880 sys::path::native(NativePath, sys::path::Style::windows);
881 uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
Zachary Turner6c4bfba2017-07-07 05:04:36 +0000882 auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
883 LinkerModule.setPdbFilePathNI(PdbFilePathNI);
Zachary Turner28e31ee2017-08-11 20:46:28 +0000884 addCommonLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
Rui Ueyamac91f7162016-11-16 01:10:46 +0000885
Reid Kleckner175af4b2017-08-03 21:15:09 +0000886 // Add section contributions. They must be ordered by ascending RVA.
Zachary Turner28e31ee2017-08-11 20:46:28 +0000887 for (OutputSection *OS : OutputSections) {
888 addLinkerModuleSectionSymbol(LinkerModule, *OS, Alloc);
Reid Kleckner175af4b2017-08-03 21:15:09 +0000889 for (Chunk *C : OS->getChunks())
890 addSectionContrib(LinkerModule, OS, C);
Zachary Turner28e31ee2017-08-11 20:46:28 +0000891 }
Reid Kleckner175af4b2017-08-03 21:15:09 +0000892
893 // Add Section Map stream.
894 ArrayRef<object::coff_section> Sections = {
895 (const object::coff_section *)SectionTable.data(),
896 SectionTable.size() / sizeof(object::coff_section)};
897 SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
898 DbiBuilder.setSectionMap(SectionMap);
899
Rui Ueyama9f66f822016-10-11 19:45:07 +0000900 // Add COFF section header stream.
901 ExitOnErr(
902 DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000903}
Rui Ueyama9f66f822016-10-11 19:45:07 +0000904
Reid Kleckner0faf6d72017-07-14 00:14:58 +0000905void PDBLinker::commit() {
Rui Ueyama3e9d6bb2016-09-26 23:53:55 +0000906 // Write to a file.
Zachary Turner6708e0b2017-07-10 21:01:37 +0000907 ExitOnErr(Builder.commit(Config->PDBPath));
Rui Ueyamae7378242015-12-04 23:11:05 +0000908}