1 //===- PDB.cpp ------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "PDB.h"
10 #include "Chunks.h"
11 #include "Config.h"
12 #include "DebugTypes.h"
13 #include "Driver.h"
14 #include "SymbolTable.h"
15 #include "Symbols.h"
16 #include "TypeMerger.h"
17 #include "Writer.h"
18 #include "lld/Common/ErrorHandler.h"
19 #include "lld/Common/Timer.h"
20 #include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
21 #include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
22 #include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"
23 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
24 #include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
25 #include "llvm/DebugInfo/CodeView/RecordName.h"
26 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
27 #include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h"
28 #include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
29 #include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
30 #include "llvm/DebugInfo/MSF/MSFBuilder.h"
31 #include "llvm/DebugInfo/MSF/MSFCommon.h"
32 #include "llvm/DebugInfo/PDB/GenericError.h"
33 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
34 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
35 #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
36 #include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h"
37 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
38 #include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
39 #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
40 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
41 #include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
42 #include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
43 #include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
44 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
45 #include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
46 #include "llvm/DebugInfo/PDB/PDB.h"
47 #include "llvm/Object/COFF.h"
48 #include "llvm/Object/CVDebugRecord.h"
49 #include "llvm/Support/BinaryByteStream.h"
50 #include "llvm/Support/CRC.h"
51 #include "llvm/Support/Endian.h"
52 #include "llvm/Support/Errc.h"
53 #include "llvm/Support/FormatAdapters.h"
54 #include "llvm/Support/FormatVariadic.h"
55 #include "llvm/Support/Path.h"
56 #include "llvm/Support/ScopedPrinter.h"
57 #include <memory>
58
59 using namespace llvm;
60 using namespace llvm::codeview;
61 using namespace lld;
62 using namespace lld::coff;
63
64 using llvm::object::coff_section;
65
66 static ExitOnError exitOnErr;
67
68 static Timer totalPdbLinkTimer("PDB Emission (Cumulative)", Timer::root());
69 static Timer addObjectsTimer("Add Objects", totalPdbLinkTimer);
70 Timer lld::coff::loadGHashTimer("Global Type Hashing", addObjectsTimer);
71 Timer lld::coff::mergeGHashTimer("GHash Type Merging", addObjectsTimer);
72 static Timer typeMergingTimer("Type Merging", addObjectsTimer);
73 static Timer symbolMergingTimer("Symbol Merging", addObjectsTimer);
74 static Timer publicsLayoutTimer("Publics Stream Layout", totalPdbLinkTimer);
75 static Timer tpiStreamLayoutTimer("TPI Stream Layout", totalPdbLinkTimer);
76 static Timer diskCommitTimer("Commit to Disk", totalPdbLinkTimer);
77
78 namespace {
79 class DebugSHandler;
80
81 class PDBLinker {
82 friend DebugSHandler;
83
84 public:
PDBLinker(SymbolTable * symtab)85 PDBLinker(SymbolTable *symtab)
86 : symtab(symtab), builder(bAlloc), tMerger(bAlloc) {
87 // This isn't strictly necessary, but link.exe usually puts an empty string
88 // as the first "valid" string in the string table, so we do the same in
89 // order to maintain as much byte-for-byte compatibility as possible.
90 pdbStrTab.insert("");
91 }
92
93 /// Emit the basic PDB structure: initial streams, headers, etc.
94 void initialize(llvm::codeview::DebugInfo *buildId);
95
96 /// Add natvis files specified on the command line.
97 void addNatvisFiles();
98
99 /// Add named streams specified on the command line.
100 void addNamedStreams();
101
102 /// Link CodeView from each object file in the symbol table into the PDB.
103 void addObjectsToPDB();
104
105 /// Add every live, defined public symbol to the PDB.
106 void addPublicsToPDB();
107
108 /// Link info for each import file in the symbol table into the PDB.
109 void addImportFilesToPDB(ArrayRef<OutputSection *> outputSections);
110
111 /// Link CodeView from a single object file into the target (output) PDB.
112 /// When a precompiled headers object is linked, its TPI map might be provided
113 /// externally.
114 void addDebug(TpiSource *source);
115
116 void addDebugSymbols(TpiSource *source);
117
118 void mergeSymbolRecords(TpiSource *source,
119 std::vector<ulittle32_t *> &stringTableRefs,
120 BinaryStreamRef symData);
121
122 /// Add the section map and section contributions to the PDB.
123 void addSections(ArrayRef<OutputSection *> outputSections,
124 ArrayRef<uint8_t> sectionTable);
125
126 /// Write the PDB to disk and store the Guid generated for it in *Guid.
127 void commit(codeview::GUID *guid);
128
129 // Print statistics regarding the final PDB
130 void printStats();
131
132 private:
133 SymbolTable *symtab;
134
135 pdb::PDBFileBuilder builder;
136
137 TypeMerger tMerger;
138
139 /// PDBs use a single global string table for filenames in the file checksum
140 /// table.
141 DebugStringTableSubsection pdbStrTab;
142
143 llvm::SmallString<128> nativePath;
144
145 // For statistics
146 uint64_t globalSymbols = 0;
147 uint64_t moduleSymbols = 0;
148 uint64_t publicSymbols = 0;
149 uint64_t nbTypeRecords = 0;
150 uint64_t nbTypeRecordsBytes = 0;
151 };
152
153 class DebugSHandler {
154 PDBLinker &linker;
155
156 /// The object file whose .debug$S sections we're processing.
157 ObjFile &file;
158
159 /// The result of merging type indices.
160 TpiSource *source;
161
162 /// The DEBUG_S_STRINGTABLE subsection. These strings are referred to by
163 /// index from other records in the .debug$S section. All of these strings
164 /// need to be added to the global PDB string table, and all references to
165 /// these strings need to have their indices re-written to refer to the
166 /// global PDB string table.
167 DebugStringTableSubsectionRef cvStrTab;
168
169 /// The DEBUG_S_FILECHKSMS subsection. As above, these are referred to
170 /// by other records in the .debug$S section and need to be merged into the
171 /// PDB.
172 DebugChecksumsSubsectionRef checksums;
173
174 /// The DEBUG_S_FRAMEDATA subsection(s). There can be more than one of
175 /// these and they need not appear in any specific order. However, they
176 /// contain string table references which need to be re-written, so we
177 /// collect them all here and re-write them after all subsections have been
178 /// discovered and processed.
179 std::vector<DebugFrameDataSubsectionRef> newFpoFrames;
180
181 /// Pointers to raw memory that we determine have string table references
182 /// that need to be re-written. We first process all .debug$S subsections
183 /// to ensure that we can handle subsections written in any order, building
184 /// up this list as we go. At the end, we use the string table (which must
185 /// have been discovered by now else it is an error) to re-write these
186 /// references.
187 std::vector<ulittle32_t *> stringTableReferences;
188
189 void mergeInlineeLines(const DebugSubsectionRecord &inlineeLines);
190
191 public:
DebugSHandler(PDBLinker & linker,ObjFile & file,TpiSource * source)192 DebugSHandler(PDBLinker &linker, ObjFile &file, TpiSource *source)
193 : linker(linker), file(file), source(source) {}
194
195 void handleDebugS(ArrayRef<uint8_t> relocatedDebugContents);
196
197 void finish();
198 };
199 }
200
201 // Visual Studio's debugger requires absolute paths in various places in the
202 // PDB to work without additional configuration:
203 // https://docs.microsoft.com/en-us/visualstudio/debugger/debug-source-files-common-properties-solution-property-pages-dialog-box
pdbMakeAbsolute(SmallVectorImpl<char> & fileName)204 static void pdbMakeAbsolute(SmallVectorImpl<char> &fileName) {
205 // The default behavior is to produce paths that are valid within the context
206 // of the machine that you perform the link on. If the linker is running on
207 // a POSIX system, we will output absolute POSIX paths. If the linker is
208 // running on a Windows system, we will output absolute Windows paths. If the
209 // user desires any other kind of behavior, they should explicitly pass
210 // /pdbsourcepath, in which case we will treat the exact string the user
211 // passed in as the gospel and not normalize, canonicalize it.
212 if (sys::path::is_absolute(fileName, sys::path::Style::windows) ||
213 sys::path::is_absolute(fileName, sys::path::Style::posix))
214 return;
215
216 // It's not absolute in any path syntax. Relative paths necessarily refer to
217 // the local file system, so we can make it native without ending up with a
218 // nonsensical path.
219 if (config->pdbSourcePath.empty()) {
220 sys::path::native(fileName);
221 sys::fs::make_absolute(fileName);
222 return;
223 }
224
225 // Try to guess whether /PDBSOURCEPATH is a unix path or a windows path.
226 // Since PDB's are more of a Windows thing, we make this conservative and only
227 // decide that it's a unix path if we're fairly certain. Specifically, if
228 // it starts with a forward slash.
229 SmallString<128> absoluteFileName = config->pdbSourcePath;
230 sys::path::Style guessedStyle = absoluteFileName.startswith("/")
231 ? sys::path::Style::posix
232 : sys::path::Style::windows;
233 sys::path::append(absoluteFileName, guessedStyle, fileName);
234 sys::path::native(absoluteFileName, guessedStyle);
235 sys::path::remove_dots(absoluteFileName, true, guessedStyle);
236
237 fileName = std::move(absoluteFileName);
238 }
239
addTypeInfo(pdb::TpiStreamBuilder & tpiBuilder,TypeCollection & typeTable)240 static void addTypeInfo(pdb::TpiStreamBuilder &tpiBuilder,
241 TypeCollection &typeTable) {
242 // Start the TPI or IPI stream header.
243 tpiBuilder.setVersionHeader(pdb::PdbTpiV80);
244
245 // Flatten the in memory type table and hash each type.
246 typeTable.ForEachRecord([&](TypeIndex ti, const CVType &type) {
247 auto hash = pdb::hashTypeRecord(type);
248 if (auto e = hash.takeError())
249 fatal("type hashing error");
250 tpiBuilder.addTypeRecord(type.RecordData, *hash);
251 });
252 }
253
addGHashTypeInfo(pdb::PDBFileBuilder & builder)254 static void addGHashTypeInfo(pdb::PDBFileBuilder &builder) {
255 // Start the TPI or IPI stream header.
256 builder.getTpiBuilder().setVersionHeader(pdb::PdbTpiV80);
257 builder.getIpiBuilder().setVersionHeader(pdb::PdbTpiV80);
258 for_each(TpiSource::instances, [&](TpiSource *source) {
259 builder.getTpiBuilder().addTypeRecords(source->mergedTpi.recs,
260 source->mergedTpi.recSizes,
261 source->mergedTpi.recHashes);
262 builder.getIpiBuilder().addTypeRecords(source->mergedIpi.recs,
263 source->mergedIpi.recSizes,
264 source->mergedIpi.recHashes);
265 });
266 }
267
268 static void
recordStringTableReferenceAtOffset(MutableArrayRef<uint8_t> contents,uint32_t offset,std::vector<ulittle32_t * > & strTableRefs)269 recordStringTableReferenceAtOffset(MutableArrayRef<uint8_t> contents,
270 uint32_t offset,
271 std::vector<ulittle32_t *> &strTableRefs) {
272 contents =
273 contents.drop_front(offset).take_front(sizeof(support::ulittle32_t));
274 ulittle32_t *index = reinterpret_cast<ulittle32_t *>(contents.data());
275 strTableRefs.push_back(index);
276 }
277
278 static void
recordStringTableReferences(SymbolKind kind,MutableArrayRef<uint8_t> contents,std::vector<ulittle32_t * > & strTableRefs)279 recordStringTableReferences(SymbolKind kind, MutableArrayRef<uint8_t> contents,
280 std::vector<ulittle32_t *> &strTableRefs) {
281 // For now we only handle S_FILESTATIC, but we may need the same logic for
282 // S_DEFRANGE and S_DEFRANGE_SUBFIELD. However, I cannot seem to generate any
283 // PDBs that contain these types of records, so because of the uncertainty
284 // they are omitted here until we can prove that it's necessary.
285 switch (kind) {
286 case SymbolKind::S_FILESTATIC:
287 // FileStaticSym::ModFileOffset
288 recordStringTableReferenceAtOffset(contents, 8, strTableRefs);
289 break;
290 case SymbolKind::S_DEFRANGE:
291 case SymbolKind::S_DEFRANGE_SUBFIELD:
292 log("Not fixing up string table reference in S_DEFRANGE / "
293 "S_DEFRANGE_SUBFIELD record");
294 break;
295 default:
296 break;
297 }
298 }
299
symbolKind(ArrayRef<uint8_t> recordData)300 static SymbolKind symbolKind(ArrayRef<uint8_t> recordData) {
301 const RecordPrefix *prefix =
302 reinterpret_cast<const RecordPrefix *>(recordData.data());
303 return static_cast<SymbolKind>(uint16_t(prefix->RecordKind));
304 }
305
306 /// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
translateIdSymbols(MutableArrayRef<uint8_t> & recordData,TypeMerger & tMerger,TpiSource * source)307 static void translateIdSymbols(MutableArrayRef<uint8_t> &recordData,
308 TypeMerger &tMerger, TpiSource *source) {
309 RecordPrefix *prefix = reinterpret_cast<RecordPrefix *>(recordData.data());
310
311 SymbolKind kind = symbolKind(recordData);
312
313 if (kind == SymbolKind::S_PROC_ID_END) {
314 prefix->RecordKind = SymbolKind::S_END;
315 return;
316 }
317
318 // In an object file, GPROC32_ID has an embedded reference which refers to the
319 // single object file type index namespace. This has already been translated
320 // to the PDB file's ID stream index space, but we need to convert this to a
321 // symbol that refers to the type stream index space. So we remap again from
322 // ID index space to type index space.
323 if (kind == SymbolKind::S_GPROC32_ID || kind == SymbolKind::S_LPROC32_ID) {
324 SmallVector<TiReference, 1> refs;
325 auto content = recordData.drop_front(sizeof(RecordPrefix));
326 CVSymbol sym(recordData);
327 discoverTypeIndicesInSymbol(sym, refs);
328 assert(refs.size() == 1);
329 assert(refs.front().Count == 1);
330
331 TypeIndex *ti =
332 reinterpret_cast<TypeIndex *>(content.data() + refs[0].Offset);
333 // `ti` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
334 // the IPI stream, whose `FunctionType` member refers to the TPI stream.
335 // Note that LF_FUNC_ID and LF_MFUNC_ID have the same record layout, and
336 // in both cases we just need the second type index.
337 if (!ti->isSimple() && !ti->isNoneType()) {
338 if (config->debugGHashes) {
339 auto idToType = tMerger.funcIdToType.find(*ti);
340 if (idToType == tMerger.funcIdToType.end()) {
341 warn(formatv("S_[GL]PROC32_ID record in {0} refers to PDB item "
342 "index {1:X} which is not a LF_[M]FUNC_ID record",
343 source->file->getName(), ti->getIndex()));
344 *ti = TypeIndex(SimpleTypeKind::NotTranslated);
345 } else {
346 *ti = idToType->second;
347 }
348 } else {
349 CVType funcIdData = tMerger.getIDTable().getType(*ti);
350 ArrayRef<uint8_t> tiBuf = funcIdData.data().slice(8, 4);
351 assert(tiBuf.size() == 4 && "corrupt LF_[M]FUNC_ID record");
352 *ti = *reinterpret_cast<const TypeIndex *>(tiBuf.data());
353 }
354 }
355
356 kind = (kind == SymbolKind::S_GPROC32_ID) ? SymbolKind::S_GPROC32
357 : SymbolKind::S_LPROC32;
358 prefix->RecordKind = uint16_t(kind);
359 }
360 }
361
362 /// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
363 /// The object file may not be aligned.
364 static MutableArrayRef<uint8_t>
copyAndAlignSymbol(const CVSymbol & sym,MutableArrayRef<uint8_t> & alignedMem)365 copyAndAlignSymbol(const CVSymbol &sym, MutableArrayRef<uint8_t> &alignedMem) {
366 size_t size = alignTo(sym.length(), alignOf(CodeViewContainer::Pdb));
367 assert(size >= 4 && "record too short");
368 assert(size <= MaxRecordLength && "record too long");
369 assert(alignedMem.size() >= size && "didn't preallocate enough");
370
371 // Copy the symbol record and zero out any padding bytes.
372 MutableArrayRef<uint8_t> newData = alignedMem.take_front(size);
373 alignedMem = alignedMem.drop_front(size);
374 memcpy(newData.data(), sym.data().data(), sym.length());
375 memset(newData.data() + sym.length(), 0, size - sym.length());
376
377 // Update the record prefix length. It should point to the beginning of the
378 // next record.
379 auto *prefix = reinterpret_cast<RecordPrefix *>(newData.data());
380 prefix->RecordLen = size - 2;
381 return newData;
382 }
383
384 struct ScopeRecord {
385 ulittle32_t ptrParent;
386 ulittle32_t ptrEnd;
387 };
388
389 struct SymbolScope {
390 ScopeRecord *openingRecord;
391 uint32_t scopeOffset;
392 };
393
scopeStackOpen(SmallVectorImpl<SymbolScope> & stack,uint32_t curOffset,CVSymbol & sym)394 static void scopeStackOpen(SmallVectorImpl<SymbolScope> &stack,
395 uint32_t curOffset, CVSymbol &sym) {
396 assert(symbolOpensScope(sym.kind()));
397 SymbolScope s;
398 s.scopeOffset = curOffset;
399 s.openingRecord = const_cast<ScopeRecord *>(
400 reinterpret_cast<const ScopeRecord *>(sym.content().data()));
401 s.openingRecord->ptrParent = stack.empty() ? 0 : stack.back().scopeOffset;
402 stack.push_back(s);
403 }
404
scopeStackClose(SmallVectorImpl<SymbolScope> & stack,uint32_t curOffset,InputFile * file)405 static void scopeStackClose(SmallVectorImpl<SymbolScope> &stack,
406 uint32_t curOffset, InputFile *file) {
407 if (stack.empty()) {
408 warn("symbol scopes are not balanced in " + file->getName());
409 return;
410 }
411 SymbolScope s = stack.pop_back_val();
412 s.openingRecord->ptrEnd = curOffset;
413 }
414
symbolGoesInModuleStream(const CVSymbol & sym,bool isGlobalScope)415 static bool symbolGoesInModuleStream(const CVSymbol &sym, bool isGlobalScope) {
416 switch (sym.kind()) {
417 case SymbolKind::S_GDATA32:
418 case SymbolKind::S_CONSTANT:
419 case SymbolKind::S_GTHREAD32:
420 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
421 // since they are synthesized by the linker in response to S_GPROC32 and
422 // S_LPROC32, but if we do see them, don't put them in the module stream I
423 // guess.
424 case SymbolKind::S_PROCREF:
425 case SymbolKind::S_LPROCREF:
426 return false;
427 // S_UDT records go in the module stream if it is not a global S_UDT.
428 case SymbolKind::S_UDT:
429 return !isGlobalScope;
430 // S_GDATA32 does not go in the module stream, but S_LDATA32 does.
431 case SymbolKind::S_LDATA32:
432 case SymbolKind::S_LTHREAD32:
433 default:
434 return true;
435 }
436 }
437
symbolGoesInGlobalsStream(const CVSymbol & sym,bool isFunctionScope)438 static bool symbolGoesInGlobalsStream(const CVSymbol &sym,
439 bool isFunctionScope) {
440 switch (sym.kind()) {
441 case SymbolKind::S_CONSTANT:
442 case SymbolKind::S_GDATA32:
443 case SymbolKind::S_GTHREAD32:
444 case SymbolKind::S_GPROC32:
445 case SymbolKind::S_LPROC32:
446 // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
447 // since they are synthesized by the linker in response to S_GPROC32 and
448 // S_LPROC32, but if we do see them, copy them straight through.
449 case SymbolKind::S_PROCREF:
450 case SymbolKind::S_LPROCREF:
451 return true;
452 // Records that go in the globals stream, unless they are function-local.
453 case SymbolKind::S_UDT:
454 case SymbolKind::S_LDATA32:
455 case SymbolKind::S_LTHREAD32:
456 return !isFunctionScope;
457 default:
458 return false;
459 }
460 }
461
addGlobalSymbol(pdb::GSIStreamBuilder & builder,uint16_t modIndex,unsigned symOffset,const CVSymbol & sym)462 static void addGlobalSymbol(pdb::GSIStreamBuilder &builder, uint16_t modIndex,
463 unsigned symOffset, const CVSymbol &sym) {
464 switch (sym.kind()) {
465 case SymbolKind::S_CONSTANT:
466 case SymbolKind::S_UDT:
467 case SymbolKind::S_GDATA32:
468 case SymbolKind::S_GTHREAD32:
469 case SymbolKind::S_LTHREAD32:
470 case SymbolKind::S_LDATA32:
471 case SymbolKind::S_PROCREF:
472 case SymbolKind::S_LPROCREF:
473 builder.addGlobalSymbol(sym);
474 break;
475 case SymbolKind::S_GPROC32:
476 case SymbolKind::S_LPROC32: {
477 SymbolRecordKind k = SymbolRecordKind::ProcRefSym;
478 if (sym.kind() == SymbolKind::S_LPROC32)
479 k = SymbolRecordKind::LocalProcRef;
480 ProcRefSym ps(k);
481 ps.Module = modIndex;
482 // For some reason, MSVC seems to add one to this value.
483 ++ps.Module;
484 ps.Name = getSymbolName(sym);
485 ps.SumName = 0;
486 ps.SymOffset = symOffset;
487 builder.addGlobalSymbol(ps);
488 break;
489 }
490 default:
491 llvm_unreachable("Invalid symbol kind!");
492 }
493 }
494
mergeSymbolRecords(TpiSource * source,std::vector<ulittle32_t * > & stringTableRefs,BinaryStreamRef symData)495 void PDBLinker::mergeSymbolRecords(TpiSource *source,
496 std::vector<ulittle32_t *> &stringTableRefs,
497 BinaryStreamRef symData) {
498 ObjFile *file = source->file;
499 ArrayRef<uint8_t> symsBuffer;
500 cantFail(symData.readBytes(0, symData.getLength(), symsBuffer));
501 SmallVector<SymbolScope, 4> scopes;
502
503 if (symsBuffer.empty())
504 warn("empty symbols subsection in " + file->getName());
505
506 // Iterate every symbol to check if any need to be realigned, and if so, how
507 // much space we need to allocate for them.
508 bool needsRealignment = false;
509 unsigned totalRealignedSize = 0;
510 auto ec = forEachCodeViewRecord<CVSymbol>(
511 symsBuffer, [&](CVSymbol sym) -> llvm::Error {
512 unsigned realignedSize =
513 alignTo(sym.length(), alignOf(CodeViewContainer::Pdb));
514 needsRealignment |= realignedSize != sym.length();
515 totalRealignedSize += realignedSize;
516 return Error::success();
517 });
518
519 // If any of the symbol record lengths was corrupt, ignore them all, warn
520 // about it, and move on.
521 if (ec) {
522 warn("corrupt symbol records in " + file->getName());
523 consumeError(std::move(ec));
524 return;
525 }
526
527 // If any symbol needed realignment, allocate enough contiguous memory for
528 // them all. Typically symbol subsections are small enough that this will not
529 // cause fragmentation.
530 MutableArrayRef<uint8_t> alignedSymbolMem;
531 if (needsRealignment) {
532 void *alignedData =
533 bAlloc.Allocate(totalRealignedSize, alignOf(CodeViewContainer::Pdb));
534 alignedSymbolMem = makeMutableArrayRef(
535 reinterpret_cast<uint8_t *>(alignedData), totalRealignedSize);
536 }
537
538 // Iterate again, this time doing the real work.
539 unsigned curSymOffset = file->moduleDBI->getNextSymbolOffset();
540 ArrayRef<uint8_t> bulkSymbols;
541 cantFail(forEachCodeViewRecord<CVSymbol>(
542 symsBuffer, [&](CVSymbol sym) -> llvm::Error {
543 // Align the record if required.
544 MutableArrayRef<uint8_t> recordBytes;
545 if (needsRealignment) {
546 recordBytes = copyAndAlignSymbol(sym, alignedSymbolMem);
547 sym = CVSymbol(recordBytes);
548 } else {
549 // Otherwise, we can actually mutate the symbol directly, since we
550 // copied it to apply relocations.
551 recordBytes = makeMutableArrayRef(
552 const_cast<uint8_t *>(sym.data().data()), sym.length());
553 }
554
555 // Re-map all the type index references.
556 if (!source->remapTypesInSymbolRecord(recordBytes)) {
557 log("error remapping types in symbol of kind 0x" +
558 utohexstr(sym.kind()) + ", ignoring");
559 return Error::success();
560 }
561
562 // An object file may have S_xxx_ID symbols, but these get converted to
563 // "real" symbols in a PDB.
564 translateIdSymbols(recordBytes, tMerger, source);
565 sym = CVSymbol(recordBytes);
566
567 // If this record refers to an offset in the object file's string table,
568 // add that item to the global PDB string table and re-write the index.
569 recordStringTableReferences(sym.kind(), recordBytes, stringTableRefs);
570
571 // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
572 if (symbolOpensScope(sym.kind()))
573 scopeStackOpen(scopes, curSymOffset, sym);
574 else if (symbolEndsScope(sym.kind()))
575 scopeStackClose(scopes, curSymOffset, file);
576
577 // Add the symbol to the globals stream if necessary. Do this before
578 // adding the symbol to the module since we may need to get the next
579 // symbol offset, and writing to the module's symbol stream will update
580 // that offset.
581 if (symbolGoesInGlobalsStream(sym, !scopes.empty())) {
582 addGlobalSymbol(builder.getGsiBuilder(),
583 file->moduleDBI->getModuleIndex(), curSymOffset, sym);
584 ++globalSymbols;
585 }
586
587 if (symbolGoesInModuleStream(sym, scopes.empty())) {
588 // Add symbols to the module in bulk. If this symbol is contiguous
589 // with the previous run of symbols to add, combine the ranges. If
590 // not, close the previous range of symbols and start a new one.
591 if (sym.data().data() == bulkSymbols.end()) {
592 bulkSymbols = makeArrayRef(bulkSymbols.data(),
593 bulkSymbols.size() + sym.length());
594 } else {
595 file->moduleDBI->addSymbolsInBulk(bulkSymbols);
596 bulkSymbols = recordBytes;
597 }
598 curSymOffset += sym.length();
599 ++moduleSymbols;
600 }
601 return Error::success();
602 }));
603
604 // Add any remaining symbols we've accumulated.
605 file->moduleDBI->addSymbolsInBulk(bulkSymbols);
606 }
607
createSectionContrib(const Chunk * c,uint32_t modi)608 static pdb::SectionContrib createSectionContrib(const Chunk *c, uint32_t modi) {
609 OutputSection *os = c ? c->getOutputSection() : nullptr;
610 pdb::SectionContrib sc;
611 memset(&sc, 0, sizeof(sc));
612 sc.ISect = os ? os->sectionIndex : llvm::pdb::kInvalidStreamIndex;
613 sc.Off = c && os ? c->getRVA() - os->getRVA() : 0;
614 sc.Size = c ? c->getSize() : -1;
615 if (auto *secChunk = dyn_cast_or_null<SectionChunk>(c)) {
616 sc.Characteristics = secChunk->header->Characteristics;
617 sc.Imod = secChunk->file->moduleDBI->getModuleIndex();
618 ArrayRef<uint8_t> contents = secChunk->getContents();
619 JamCRC crc(0);
620 crc.update(contents);
621 sc.DataCrc = crc.getCRC();
622 } else {
623 sc.Characteristics = os ? os->header.Characteristics : 0;
624 sc.Imod = modi;
625 }
626 sc.RelocCrc = 0; // FIXME
627
628 return sc;
629 }
630
631 static uint32_t
translateStringTableIndex(uint32_t objIndex,const DebugStringTableSubsectionRef & objStrTable,DebugStringTableSubsection & pdbStrTable)632 translateStringTableIndex(uint32_t objIndex,
633 const DebugStringTableSubsectionRef &objStrTable,
634 DebugStringTableSubsection &pdbStrTable) {
635 auto expectedString = objStrTable.getString(objIndex);
636 if (!expectedString) {
637 warn("Invalid string table reference");
638 consumeError(expectedString.takeError());
639 return 0;
640 }
641
642 return pdbStrTable.insert(*expectedString);
643 }
644
handleDebugS(ArrayRef<uint8_t> relocatedDebugContents)645 void DebugSHandler::handleDebugS(ArrayRef<uint8_t> relocatedDebugContents) {
646 relocatedDebugContents =
647 SectionChunk::consumeDebugMagic(relocatedDebugContents, ".debug$S");
648
649 DebugSubsectionArray subsections;
650 BinaryStreamReader reader(relocatedDebugContents, support::little);
651 exitOnErr(reader.readArray(subsections, relocatedDebugContents.size()));
652
653 for (const DebugSubsectionRecord &ss : subsections) {
654 // Ignore subsections with the 'ignore' bit. Some versions of the Visual C++
655 // runtime have subsections with this bit set.
656 if (uint32_t(ss.kind()) & codeview::SubsectionIgnoreFlag)
657 continue;
658
659 switch (ss.kind()) {
660 case DebugSubsectionKind::StringTable: {
661 assert(!cvStrTab.valid() &&
662 "Encountered multiple string table subsections!");
663 exitOnErr(cvStrTab.initialize(ss.getRecordData()));
664 break;
665 }
666 case DebugSubsectionKind::FileChecksums:
667 assert(!checksums.valid() &&
668 "Encountered multiple checksum subsections!");
669 exitOnErr(checksums.initialize(ss.getRecordData()));
670 break;
671 case DebugSubsectionKind::Lines:
672 // We can add the relocated line table directly to the PDB without
673 // modification because the file checksum offsets will stay the same.
674 file.moduleDBI->addDebugSubsection(ss);
675 break;
676 case DebugSubsectionKind::InlineeLines:
677 // The inlinee lines subsection also has file checksum table references
678 // that can be used directly, but it contains function id references that
679 // must be remapped.
680 mergeInlineeLines(ss);
681 break;
682 case DebugSubsectionKind::FrameData: {
683 // We need to re-write string table indices here, so save off all
684 // frame data subsections until we've processed the entire list of
685 // subsections so that we can be sure we have the string table.
686 DebugFrameDataSubsectionRef fds;
687 exitOnErr(fds.initialize(ss.getRecordData()));
688 newFpoFrames.push_back(std::move(fds));
689 break;
690 }
691 case DebugSubsectionKind::Symbols: {
692 linker.mergeSymbolRecords(source, stringTableReferences,
693 ss.getRecordData());
694 break;
695 }
696
697 case DebugSubsectionKind::CrossScopeImports:
698 case DebugSubsectionKind::CrossScopeExports:
699 // These appear to relate to cross-module optimization, so we might use
700 // these for ThinLTO.
701 break;
702
703 case DebugSubsectionKind::ILLines:
704 case DebugSubsectionKind::FuncMDTokenMap:
705 case DebugSubsectionKind::TypeMDTokenMap:
706 case DebugSubsectionKind::MergedAssemblyInput:
707 // These appear to relate to .Net assembly info.
708 break;
709
710 case DebugSubsectionKind::CoffSymbolRVA:
711 // Unclear what this is for.
712 break;
713
714 default:
715 warn("ignoring unknown debug$S subsection kind 0x" +
716 utohexstr(uint32_t(ss.kind())) + " in file " + toString(&file));
717 break;
718 }
719 }
720 }
721
722 static Expected<StringRef>
getFileName(const DebugStringTableSubsectionRef & strings,const DebugChecksumsSubsectionRef & checksums,uint32_t fileID)723 getFileName(const DebugStringTableSubsectionRef &strings,
724 const DebugChecksumsSubsectionRef &checksums, uint32_t fileID) {
725 auto iter = checksums.getArray().at(fileID);
726 if (iter == checksums.getArray().end())
727 return make_error<CodeViewError>(cv_error_code::no_records);
728 uint32_t offset = iter->FileNameOffset;
729 return strings.getString(offset);
730 }
731
mergeInlineeLines(const DebugSubsectionRecord & inlineeSubsection)732 void DebugSHandler::mergeInlineeLines(
733 const DebugSubsectionRecord &inlineeSubsection) {
734 DebugInlineeLinesSubsectionRef inlineeLines;
735 exitOnErr(inlineeLines.initialize(inlineeSubsection.getRecordData()));
736 if (!source) {
737 warn("ignoring inlinee lines section in file that lacks type information");
738 return;
739 }
740
741 // Remap type indices in inlinee line records in place.
742 for (const InlineeSourceLine &line : inlineeLines) {
743 TypeIndex &inlinee = *const_cast<TypeIndex *>(&line.Header->Inlinee);
744 if (!source->remapTypeIndex(inlinee, TiRefKind::IndexRef)) {
745 log("bad inlinee line record in " + file.getName() +
746 " with bad inlinee index 0x" + utohexstr(inlinee.getIndex()));
747 }
748 }
749
750 // Add the modified inlinee line subsection directly.
751 file.moduleDBI->addDebugSubsection(inlineeSubsection);
752 }
753
finish()754 void DebugSHandler::finish() {
755 pdb::DbiStreamBuilder &dbiBuilder = linker.builder.getDbiBuilder();
756
757 // We should have seen all debug subsections across the entire object file now
758 // which means that if a StringTable subsection and Checksums subsection were
759 // present, now is the time to handle them.
760 if (!cvStrTab.valid()) {
761 if (checksums.valid())
762 fatal(".debug$S sections with a checksums subsection must also contain a "
763 "string table subsection");
764
765 if (!stringTableReferences.empty())
766 warn("No StringTable subsection was encountered, but there are string "
767 "table references");
768 return;
769 }
770
771 // Rewrite string table indices in the Fpo Data and symbol records to refer to
772 // the global PDB string table instead of the object file string table.
773 for (DebugFrameDataSubsectionRef &fds : newFpoFrames) {
774 const ulittle32_t *reloc = fds.getRelocPtr();
775 for (codeview::FrameData fd : fds) {
776 fd.RvaStart += *reloc;
777 fd.FrameFunc =
778 translateStringTableIndex(fd.FrameFunc, cvStrTab, linker.pdbStrTab);
779 dbiBuilder.addNewFpoData(fd);
780 }
781 }
782
783 for (ulittle32_t *ref : stringTableReferences)
784 *ref = translateStringTableIndex(*ref, cvStrTab, linker.pdbStrTab);
785
786 // Make a new file checksum table that refers to offsets in the PDB-wide
787 // string table. Generally the string table subsection appears after the
788 // checksum table, so we have to do this after looping over all the
789 // subsections. The new checksum table must have the exact same layout and
790 // size as the original. Otherwise, the file references in the line and
791 // inlinee line tables will be incorrect.
792 auto newChecksums = std::make_unique<DebugChecksumsSubsection>(linker.pdbStrTab);
793 for (FileChecksumEntry &fc : checksums) {
794 SmallString<128> filename =
795 exitOnErr(cvStrTab.getString(fc.FileNameOffset));
796 pdbMakeAbsolute(filename);
797 exitOnErr(dbiBuilder.addModuleSourceFile(*file.moduleDBI, filename));
798 newChecksums->addChecksum(filename, fc.Kind, fc.Checksum);
799 }
800 assert(checksums.getArray().getUnderlyingStream().getLength() ==
801 newChecksums->calculateSerializedSize() &&
802 "file checksum table must have same layout");
803
804 file.moduleDBI->addDebugSubsection(std::move(newChecksums));
805 }
806
warnUnusable(InputFile * f,Error e)807 static void warnUnusable(InputFile *f, Error e) {
808 if (!config->warnDebugInfoUnusable) {
809 consumeError(std::move(e));
810 return;
811 }
812 auto msg = "Cannot use debug info for '" + toString(f) + "' [LNK4099]";
813 if (e)
814 warn(msg + "\n>>> failed to load reference " + toString(std::move(e)));
815 else
816 warn(msg);
817 }
818
819 // Allocate memory for a .debug$S / .debug$F section and relocate it.
relocateDebugChunk(SectionChunk & debugChunk)820 static ArrayRef<uint8_t> relocateDebugChunk(SectionChunk &debugChunk) {
821 uint8_t *buffer = bAlloc.Allocate<uint8_t>(debugChunk.getSize());
822 assert(debugChunk.getOutputSectionIdx() == 0 &&
823 "debug sections should not be in output sections");
824 debugChunk.writeTo(buffer);
825 return makeArrayRef(buffer, debugChunk.getSize());
826 }
827
addDebugSymbols(TpiSource * source)828 void PDBLinker::addDebugSymbols(TpiSource *source) {
829 // If this TpiSource doesn't have an object file, it must be from a type
830 // server PDB. Type server PDBs do not contain symbols, so stop here.
831 if (!source->file)
832 return;
833
834 ScopedTimer t(symbolMergingTimer);
835 pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
836 DebugSHandler dsh(*this, *source->file, source);
837 // Now do all live .debug$S and .debug$F sections.
838 for (SectionChunk *debugChunk : source->file->getDebugChunks()) {
839 if (!debugChunk->live || debugChunk->getSize() == 0)
840 continue;
841
842 bool isDebugS = debugChunk->getSectionName() == ".debug$S";
843 bool isDebugF = debugChunk->getSectionName() == ".debug$F";
844 if (!isDebugS && !isDebugF)
845 continue;
846
847 ArrayRef<uint8_t> relocatedDebugContents = relocateDebugChunk(*debugChunk);
848
849 if (isDebugS) {
850 dsh.handleDebugS(relocatedDebugContents);
851 } else if (isDebugF) {
852 FixedStreamArray<object::FpoData> fpoRecords;
853 BinaryStreamReader reader(relocatedDebugContents, support::little);
854 uint32_t count = relocatedDebugContents.size() / sizeof(object::FpoData);
855 exitOnErr(reader.readArray(fpoRecords, count));
856
857 // These are already relocated and don't refer to the string table, so we
858 // can just copy it.
859 for (const object::FpoData &fd : fpoRecords)
860 dbiBuilder.addOldFpoData(fd);
861 }
862 }
863
864 // Do any post-processing now that all .debug$S sections have been processed.
865 dsh.finish();
866 }
867
868 // Add a module descriptor for every object file. We need to put an absolute
869 // path to the object into the PDB. If this is a plain object, we make its
870 // path absolute. If it's an object in an archive, we make the archive path
871 // absolute.
createModuleDBI(pdb::PDBFileBuilder & builder,ObjFile * file)872 static void createModuleDBI(pdb::PDBFileBuilder &builder, ObjFile *file) {
873 pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
874 SmallString<128> objName;
875
876 bool inArchive = !file->parentName.empty();
877 objName = inArchive ? file->parentName : file->getName();
878 pdbMakeAbsolute(objName);
879 StringRef modName = inArchive ? file->getName() : StringRef(objName);
880
881 file->moduleDBI = &exitOnErr(dbiBuilder.addModuleInfo(modName));
882 file->moduleDBI->setObjFileName(objName);
883
884 ArrayRef<Chunk *> chunks = file->getChunks();
885 uint32_t modi = file->moduleDBI->getModuleIndex();
886
887 for (Chunk *c : chunks) {
888 auto *secChunk = dyn_cast<SectionChunk>(c);
889 if (!secChunk || !secChunk->live)
890 continue;
891 pdb::SectionContrib sc = createSectionContrib(secChunk, modi);
892 file->moduleDBI->setFirstSectionContrib(sc);
893 break;
894 }
895 }
896
addDebug(TpiSource * source)897 void PDBLinker::addDebug(TpiSource *source) {
898 // Before we can process symbol substreams from .debug$S, we need to process
899 // type information, file checksums, and the string table. Add type info to
900 // the PDB first, so that we can get the map from object file type and item
901 // indices to PDB type and item indices. If we are using ghashes, types have
902 // already been merged.
903 if (!config->debugGHashes) {
904 ScopedTimer t(typeMergingTimer);
905 if (Error e = source->mergeDebugT(&tMerger)) {
906 // If type merging failed, ignore the symbols.
907 warnUnusable(source->file, std::move(e));
908 return;
909 }
910 }
911
912 // If type merging failed, ignore the symbols.
913 Error typeError = std::move(source->typeMergingError);
914 if (typeError) {
915 warnUnusable(source->file, std::move(typeError));
916 return;
917 }
918
919 addDebugSymbols(source);
920 }
921
createPublic(Defined * def)922 static pdb::BulkPublic createPublic(Defined *def) {
923 pdb::BulkPublic pub;
924 pub.Name = def->getName().data();
925 pub.NameLen = def->getName().size();
926
927 PublicSymFlags flags = PublicSymFlags::None;
928 if (auto *d = dyn_cast<DefinedCOFF>(def)) {
929 if (d->getCOFFSymbol().isFunctionDefinition())
930 flags = PublicSymFlags::Function;
931 } else if (isa<DefinedImportThunk>(def)) {
932 flags = PublicSymFlags::Function;
933 }
934 pub.setFlags(flags);
935
936 OutputSection *os = def->getChunk()->getOutputSection();
937 assert(os && "all publics should be in final image");
938 pub.Offset = def->getRVA() - os->getRVA();
939 pub.Segment = os->sectionIndex;
940 return pub;
941 }
942
943 // Add all object files to the PDB. Merge .debug$T sections into IpiData and
944 // TpiData.
addObjectsToPDB()945 void PDBLinker::addObjectsToPDB() {
946 ScopedTimer t1(addObjectsTimer);
947
948 // Create module descriptors
949 for_each(ObjFile::instances,
950 [&](ObjFile *obj) { createModuleDBI(builder, obj); });
951
952 // Reorder dependency type sources to come first.
953 TpiSource::sortDependencies();
954
955 // Merge type information from input files using global type hashing.
956 if (config->debugGHashes)
957 tMerger.mergeTypesWithGHash();
958
959 // Merge dependencies and then regular objects.
960 for_each(TpiSource::dependencySources,
961 [&](TpiSource *source) { addDebug(source); });
962 for_each(TpiSource::objectSources,
963 [&](TpiSource *source) { addDebug(source); });
964
965 builder.getStringTableBuilder().setStrings(pdbStrTab);
966 t1.stop();
967
968 // Construct TPI and IPI stream contents.
969 ScopedTimer t2(tpiStreamLayoutTimer);
970 // Collect all the merged types.
971 if (config->debugGHashes) {
972 addGHashTypeInfo(builder);
973 } else {
974 addTypeInfo(builder.getTpiBuilder(), tMerger.getTypeTable());
975 addTypeInfo(builder.getIpiBuilder(), tMerger.getIDTable());
976 }
977 t2.stop();
978
979 if (config->showSummary) {
980 for_each(TpiSource::instances, [&](TpiSource *source) {
981 nbTypeRecords += source->nbTypeRecords;
982 nbTypeRecordsBytes += source->nbTypeRecordsBytes;
983 });
984 }
985 }
986
addPublicsToPDB()987 void PDBLinker::addPublicsToPDB() {
988 ScopedTimer t3(publicsLayoutTimer);
989 // Compute the public symbols.
990 auto &gsiBuilder = builder.getGsiBuilder();
991 std::vector<pdb::BulkPublic> publics;
992 symtab->forEachSymbol([&publics](Symbol *s) {
993 // Only emit external, defined, live symbols that have a chunk. Static,
994 // non-external symbols do not appear in the symbol table.
995 auto *def = dyn_cast<Defined>(s);
996 if (def && def->isLive() && def->getChunk())
997 publics.push_back(createPublic(def));
998 });
999
1000 if (!publics.empty()) {
1001 publicSymbols = publics.size();
1002 gsiBuilder.addPublicSymbols(std::move(publics));
1003 }
1004 }
1005
printStats()1006 void PDBLinker::printStats() {
1007 if (!config->showSummary)
1008 return;
1009
1010 SmallString<256> buffer;
1011 raw_svector_ostream stream(buffer);
1012
1013 stream << center_justify("Summary", 80) << '\n'
1014 << std::string(80, '-') << '\n';
1015
1016 auto print = [&](uint64_t v, StringRef s) {
1017 stream << format_decimal(v, 15) << " " << s << '\n';
1018 };
1019
1020 print(ObjFile::instances.size(),
1021 "Input OBJ files (expanded from all cmd-line inputs)");
1022 print(TpiSource::countTypeServerPDBs(), "PDB type server dependencies");
1023 print(TpiSource::countPrecompObjs(), "Precomp OBJ dependencies");
1024 print(nbTypeRecords, "Input type records");
1025 print(nbTypeRecordsBytes, "Input type records bytes");
1026 print(builder.getTpiBuilder().getRecordCount(), "Merged TPI records");
1027 print(builder.getIpiBuilder().getRecordCount(), "Merged IPI records");
1028 print(pdbStrTab.size(), "Output PDB strings");
1029 print(globalSymbols, "Global symbol records");
1030 print(moduleSymbols, "Module symbol records");
1031 print(publicSymbols, "Public symbol records");
1032
1033 auto printLargeInputTypeRecs = [&](StringRef name,
1034 ArrayRef<uint32_t> recCounts,
1035 TypeCollection &records) {
1036 // Figure out which type indices were responsible for the most duplicate
1037 // bytes in the input files. These should be frequently emitted LF_CLASS and
1038 // LF_FIELDLIST records.
1039 struct TypeSizeInfo {
1040 uint32_t typeSize;
1041 uint32_t dupCount;
1042 TypeIndex typeIndex;
1043 uint64_t totalInputSize() const { return uint64_t(dupCount) * typeSize; }
1044 bool operator<(const TypeSizeInfo &rhs) const {
1045 if (totalInputSize() == rhs.totalInputSize())
1046 return typeIndex < rhs.typeIndex;
1047 return totalInputSize() < rhs.totalInputSize();
1048 }
1049 };
1050 SmallVector<TypeSizeInfo, 0> tsis;
1051 for (auto e : enumerate(recCounts)) {
1052 TypeIndex typeIndex = TypeIndex::fromArrayIndex(e.index());
1053 uint32_t typeSize = records.getType(typeIndex).length();
1054 uint32_t dupCount = e.value();
1055 tsis.push_back({typeSize, dupCount, typeIndex});
1056 }
1057
1058 if (!tsis.empty()) {
1059 stream << "\nTop 10 types responsible for the most " << name
1060 << " input:\n";
1061 stream << " index total bytes count size\n";
1062 llvm::sort(tsis);
1063 unsigned i = 0;
1064 for (const auto &tsi : reverse(tsis)) {
1065 stream << formatv(" {0,10:X}: {1,14:N} = {2,5:N} * {3,6:N}\n",
1066 tsi.typeIndex.getIndex(), tsi.totalInputSize(),
1067 tsi.dupCount, tsi.typeSize);
1068 if (++i >= 10)
1069 break;
1070 }
1071 stream
1072 << "Run llvm-pdbutil to print details about a particular record:\n";
1073 stream << formatv("llvm-pdbutil dump -{0}s -{0}-index {1:X} {2}\n",
1074 (name == "TPI" ? "type" : "id"),
1075 tsis.back().typeIndex.getIndex(), config->pdbPath);
1076 }
1077 };
1078
1079 if (!config->debugGHashes) {
1080 // FIXME: Reimplement for ghash.
1081 printLargeInputTypeRecs("TPI", tMerger.tpiCounts, tMerger.getTypeTable());
1082 printLargeInputTypeRecs("IPI", tMerger.ipiCounts, tMerger.getIDTable());
1083 }
1084
1085 message(buffer);
1086 }
1087
addNatvisFiles()1088 void PDBLinker::addNatvisFiles() {
1089 for (StringRef file : config->natvisFiles) {
1090 ErrorOr<std::unique_ptr<MemoryBuffer>> dataOrErr =
1091 MemoryBuffer::getFile(file);
1092 if (!dataOrErr) {
1093 warn("Cannot open input file: " + file);
1094 continue;
1095 }
1096 builder.addInjectedSource(file, std::move(*dataOrErr));
1097 }
1098 }
1099
addNamedStreams()1100 void PDBLinker::addNamedStreams() {
1101 for (const auto &streamFile : config->namedStreams) {
1102 const StringRef stream = streamFile.getKey(), file = streamFile.getValue();
1103 ErrorOr<std::unique_ptr<MemoryBuffer>> dataOrErr =
1104 MemoryBuffer::getFile(file);
1105 if (!dataOrErr) {
1106 warn("Cannot open input file: " + file);
1107 continue;
1108 }
1109 exitOnErr(builder.addNamedStream(stream, (*dataOrErr)->getBuffer()));
1110 }
1111 }
1112
toCodeViewMachine(COFF::MachineTypes machine)1113 static codeview::CPUType toCodeViewMachine(COFF::MachineTypes machine) {
1114 switch (machine) {
1115 case COFF::IMAGE_FILE_MACHINE_AMD64:
1116 return codeview::CPUType::X64;
1117 case COFF::IMAGE_FILE_MACHINE_ARM:
1118 return codeview::CPUType::ARM7;
1119 case COFF::IMAGE_FILE_MACHINE_ARM64:
1120 return codeview::CPUType::ARM64;
1121 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1122 return codeview::CPUType::ARMNT;
1123 case COFF::IMAGE_FILE_MACHINE_I386:
1124 return codeview::CPUType::Intel80386;
1125 default:
1126 llvm_unreachable("Unsupported CPU Type");
1127 }
1128 }
1129
1130 // Mimic MSVC which surrounds arguments containing whitespace with quotes.
1131 // Double double-quotes are handled, so that the resulting string can be
1132 // executed again on the cmd-line.
quote(ArrayRef<StringRef> args)1133 static std::string quote(ArrayRef<StringRef> args) {
1134 std::string r;
1135 r.reserve(256);
1136 for (StringRef a : args) {
1137 if (!r.empty())
1138 r.push_back(' ');
1139 bool hasWS = a.find(' ') != StringRef::npos;
1140 bool hasQ = a.find('"') != StringRef::npos;
1141 if (hasWS || hasQ)
1142 r.push_back('"');
1143 if (hasQ) {
1144 SmallVector<StringRef, 4> s;
1145 a.split(s, '"');
1146 r.append(join(s, "\"\""));
1147 } else {
1148 r.append(std::string(a));
1149 }
1150 if (hasWS || hasQ)
1151 r.push_back('"');
1152 }
1153 return r;
1154 }
1155
fillLinkerVerRecord(Compile3Sym & cs)1156 static void fillLinkerVerRecord(Compile3Sym &cs) {
1157 cs.Machine = toCodeViewMachine(config->machine);
1158 // Interestingly, if we set the string to 0.0.0.0, then when trying to view
1159 // local variables WinDbg emits an error that private symbols are not present.
1160 // By setting this to a valid MSVC linker version string, local variables are
1161 // displayed properly. As such, even though it is not representative of
1162 // LLVM's version information, we need this for compatibility.
1163 cs.Flags = CompileSym3Flags::None;
1164 cs.VersionBackendBuild = 25019;
1165 cs.VersionBackendMajor = 14;
1166 cs.VersionBackendMinor = 10;
1167 cs.VersionBackendQFE = 0;
1168
1169 // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
1170 // linker module (which is by definition a backend), so we don't need to do
1171 // anything here. Also, it seems we can use "LLVM Linker" for the linker name
1172 // without any problems. Only the backend version has to be hardcoded to a
1173 // magic number.
1174 cs.VersionFrontendBuild = 0;
1175 cs.VersionFrontendMajor = 0;
1176 cs.VersionFrontendMinor = 0;
1177 cs.VersionFrontendQFE = 0;
1178 cs.Version = "LLVM Linker";
1179 cs.setLanguage(SourceLanguage::Link);
1180 }
1181
addCommonLinkerModuleSymbols(StringRef path,pdb::DbiModuleDescriptorBuilder & mod)1182 static void addCommonLinkerModuleSymbols(StringRef path,
1183 pdb::DbiModuleDescriptorBuilder &mod) {
1184 ObjNameSym ons(SymbolRecordKind::ObjNameSym);
1185 EnvBlockSym ebs(SymbolRecordKind::EnvBlockSym);
1186 Compile3Sym cs(SymbolRecordKind::Compile3Sym);
1187 fillLinkerVerRecord(cs);
1188
1189 ons.Name = "* Linker *";
1190 ons.Signature = 0;
1191
1192 ArrayRef<StringRef> args = makeArrayRef(config->argv).drop_front();
1193 std::string argStr = quote(args);
1194 ebs.Fields.push_back("cwd");
1195 SmallString<64> cwd;
1196 if (config->pdbSourcePath.empty())
1197 sys::fs::current_path(cwd);
1198 else
1199 cwd = config->pdbSourcePath;
1200 ebs.Fields.push_back(cwd);
1201 ebs.Fields.push_back("exe");
1202 SmallString<64> exe = config->argv[0];
1203 pdbMakeAbsolute(exe);
1204 ebs.Fields.push_back(exe);
1205 ebs.Fields.push_back("pdb");
1206 ebs.Fields.push_back(path);
1207 ebs.Fields.push_back("cmd");
1208 ebs.Fields.push_back(argStr);
1209 mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1210 ons, bAlloc, CodeViewContainer::Pdb));
1211 mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1212 cs, bAlloc, CodeViewContainer::Pdb));
1213 mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1214 ebs, bAlloc, CodeViewContainer::Pdb));
1215 }
1216
addLinkerModuleCoffGroup(PartialSection * sec,pdb::DbiModuleDescriptorBuilder & mod,OutputSection & os)1217 static void addLinkerModuleCoffGroup(PartialSection *sec,
1218 pdb::DbiModuleDescriptorBuilder &mod,
1219 OutputSection &os) {
1220 // If there's a section, there's at least one chunk
1221 assert(!sec->chunks.empty());
1222 const Chunk *firstChunk = *sec->chunks.begin();
1223 const Chunk *lastChunk = *sec->chunks.rbegin();
1224
1225 // Emit COFF group
1226 CoffGroupSym cgs(SymbolRecordKind::CoffGroupSym);
1227 cgs.Name = sec->name;
1228 cgs.Segment = os.sectionIndex;
1229 cgs.Offset = firstChunk->getRVA() - os.getRVA();
1230 cgs.Size = lastChunk->getRVA() + lastChunk->getSize() - firstChunk->getRVA();
1231 cgs.Characteristics = sec->characteristics;
1232
1233 // Somehow .idata sections & sections groups in the debug symbol stream have
1234 // the "write" flag set. However the section header for the corresponding
1235 // .idata section doesn't have it.
1236 if (cgs.Name.startswith(".idata"))
1237 cgs.Characteristics |= llvm::COFF::IMAGE_SCN_MEM_WRITE;
1238
1239 mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1240 cgs, bAlloc, CodeViewContainer::Pdb));
1241 }
1242
addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder & mod,OutputSection & os)1243 static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &mod,
1244 OutputSection &os) {
1245 SectionSym sym(SymbolRecordKind::SectionSym);
1246 sym.Alignment = 12; // 2^12 = 4KB
1247 sym.Characteristics = os.header.Characteristics;
1248 sym.Length = os.getVirtualSize();
1249 sym.Name = os.name;
1250 sym.Rva = os.getRVA();
1251 sym.SectionNumber = os.sectionIndex;
1252 mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1253 sym, bAlloc, CodeViewContainer::Pdb));
1254
1255 // Skip COFF groups in MinGW because it adds a significant footprint to the
1256 // PDB, due to each function being in its own section
1257 if (config->mingw)
1258 return;
1259
1260 // Output COFF groups for individual chunks of this section.
1261 for (PartialSection *sec : os.contribSections) {
1262 addLinkerModuleCoffGroup(sec, mod, os);
1263 }
1264 }
1265
1266 // Add all import files as modules to the PDB.
addImportFilesToPDB(ArrayRef<OutputSection * > outputSections)1267 void PDBLinker::addImportFilesToPDB(ArrayRef<OutputSection *> outputSections) {
1268 if (ImportFile::instances.empty())
1269 return;
1270
1271 std::map<std::string, llvm::pdb::DbiModuleDescriptorBuilder *> dllToModuleDbi;
1272
1273 for (ImportFile *file : ImportFile::instances) {
1274 if (!file->live)
1275 continue;
1276
1277 if (!file->thunkSym)
1278 continue;
1279
1280 if (!file->thunkLive)
1281 continue;
1282
1283 std::string dll = StringRef(file->dllName).lower();
1284 llvm::pdb::DbiModuleDescriptorBuilder *&mod = dllToModuleDbi[dll];
1285 if (!mod) {
1286 pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1287 SmallString<128> libPath = file->parentName;
1288 pdbMakeAbsolute(libPath);
1289 sys::path::native(libPath);
1290
1291 // Name modules similar to MSVC's link.exe.
1292 // The first module is the simple dll filename
1293 llvm::pdb::DbiModuleDescriptorBuilder &firstMod =
1294 exitOnErr(dbiBuilder.addModuleInfo(file->dllName));
1295 firstMod.setObjFileName(libPath);
1296 pdb::SectionContrib sc =
1297 createSectionContrib(nullptr, llvm::pdb::kInvalidStreamIndex);
1298 firstMod.setFirstSectionContrib(sc);
1299
1300 // The second module is where the import stream goes.
1301 mod = &exitOnErr(dbiBuilder.addModuleInfo("Import:" + file->dllName));
1302 mod->setObjFileName(libPath);
1303 }
1304
1305 DefinedImportThunk *thunk = cast<DefinedImportThunk>(file->thunkSym);
1306 Chunk *thunkChunk = thunk->getChunk();
1307 OutputSection *thunkOS = thunkChunk->getOutputSection();
1308
1309 ObjNameSym ons(SymbolRecordKind::ObjNameSym);
1310 Compile3Sym cs(SymbolRecordKind::Compile3Sym);
1311 Thunk32Sym ts(SymbolRecordKind::Thunk32Sym);
1312 ScopeEndSym es(SymbolRecordKind::ScopeEndSym);
1313
1314 ons.Name = file->dllName;
1315 ons.Signature = 0;
1316
1317 fillLinkerVerRecord(cs);
1318
1319 ts.Name = thunk->getName();
1320 ts.Parent = 0;
1321 ts.End = 0;
1322 ts.Next = 0;
1323 ts.Thunk = ThunkOrdinal::Standard;
1324 ts.Length = thunkChunk->getSize();
1325 ts.Segment = thunkOS->sectionIndex;
1326 ts.Offset = thunkChunk->getRVA() - thunkOS->getRVA();
1327
1328 mod->addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1329 ons, bAlloc, CodeViewContainer::Pdb));
1330 mod->addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1331 cs, bAlloc, CodeViewContainer::Pdb));
1332
1333 SmallVector<SymbolScope, 4> scopes;
1334 CVSymbol newSym = codeview::SymbolSerializer::writeOneSymbol(
1335 ts, bAlloc, CodeViewContainer::Pdb);
1336 scopeStackOpen(scopes, mod->getNextSymbolOffset(), newSym);
1337
1338 mod->addSymbol(newSym);
1339
1340 newSym = codeview::SymbolSerializer::writeOneSymbol(es, bAlloc,
1341 CodeViewContainer::Pdb);
1342 scopeStackClose(scopes, mod->getNextSymbolOffset(), file);
1343
1344 mod->addSymbol(newSym);
1345
1346 pdb::SectionContrib sc =
1347 createSectionContrib(thunk->getChunk(), mod->getModuleIndex());
1348 mod->setFirstSectionContrib(sc);
1349 }
1350 }
1351
1352 // Creates a PDB file.
createPDB(SymbolTable * symtab,ArrayRef<OutputSection * > outputSections,ArrayRef<uint8_t> sectionTable,llvm::codeview::DebugInfo * buildId)1353 void lld::coff::createPDB(SymbolTable *symtab,
1354 ArrayRef<OutputSection *> outputSections,
1355 ArrayRef<uint8_t> sectionTable,
1356 llvm::codeview::DebugInfo *buildId) {
1357 ScopedTimer t1(totalPdbLinkTimer);
1358 PDBLinker pdb(symtab);
1359
1360 pdb.initialize(buildId);
1361 pdb.addObjectsToPDB();
1362 pdb.addImportFilesToPDB(outputSections);
1363 pdb.addSections(outputSections, sectionTable);
1364 pdb.addNatvisFiles();
1365 pdb.addNamedStreams();
1366 pdb.addPublicsToPDB();
1367
1368 ScopedTimer t2(diskCommitTimer);
1369 codeview::GUID guid;
1370 pdb.commit(&guid);
1371 memcpy(&buildId->PDB70.Signature, &guid, 16);
1372
1373 t2.stop();
1374 t1.stop();
1375 pdb.printStats();
1376 }
1377
initialize(llvm::codeview::DebugInfo * buildId)1378 void PDBLinker::initialize(llvm::codeview::DebugInfo *buildId) {
1379 exitOnErr(builder.initialize(4096)); // 4096 is blocksize
1380
1381 buildId->Signature.CVSignature = OMF::Signature::PDB70;
1382 // Signature is set to a hash of the PDB contents when the PDB is done.
1383 memset(buildId->PDB70.Signature, 0, 16);
1384 buildId->PDB70.Age = 1;
1385
1386 // Create streams in MSF for predefined streams, namely
1387 // PDB, TPI, DBI and IPI.
1388 for (int i = 0; i < (int)pdb::kSpecialStreamCount; ++i)
1389 exitOnErr(builder.getMsfBuilder().addStream(0));
1390
1391 // Add an Info stream.
1392 auto &infoBuilder = builder.getInfoBuilder();
1393 infoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
1394 infoBuilder.setHashPDBContentsToGUID(true);
1395
1396 // Add an empty DBI stream.
1397 pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1398 dbiBuilder.setAge(buildId->PDB70.Age);
1399 dbiBuilder.setVersionHeader(pdb::PdbDbiV70);
1400 dbiBuilder.setMachineType(config->machine);
1401 // Technically we are not link.exe 14.11, but there are known cases where
1402 // debugging tools on Windows expect Microsoft-specific version numbers or
1403 // they fail to work at all. Since we know we produce PDBs that are
1404 // compatible with LINK 14.11, we set that version number here.
1405 dbiBuilder.setBuildNumber(14, 11);
1406 }
1407
addSections(ArrayRef<OutputSection * > outputSections,ArrayRef<uint8_t> sectionTable)1408 void PDBLinker::addSections(ArrayRef<OutputSection *> outputSections,
1409 ArrayRef<uint8_t> sectionTable) {
1410 // It's not entirely clear what this is, but the * Linker * module uses it.
1411 pdb::DbiStreamBuilder &dbiBuilder = builder.getDbiBuilder();
1412 nativePath = config->pdbPath;
1413 pdbMakeAbsolute(nativePath);
1414 uint32_t pdbFilePathNI = dbiBuilder.addECName(nativePath);
1415 auto &linkerModule = exitOnErr(dbiBuilder.addModuleInfo("* Linker *"));
1416 linkerModule.setPdbFilePathNI(pdbFilePathNI);
1417 addCommonLinkerModuleSymbols(nativePath, linkerModule);
1418
1419 // Add section contributions. They must be ordered by ascending RVA.
1420 for (OutputSection *os : outputSections) {
1421 addLinkerModuleSectionSymbol(linkerModule, *os);
1422 for (Chunk *c : os->chunks) {
1423 pdb::SectionContrib sc =
1424 createSectionContrib(c, linkerModule.getModuleIndex());
1425 builder.getDbiBuilder().addSectionContrib(sc);
1426 }
1427 }
1428
1429 // The * Linker * first section contrib is only used along with /INCREMENTAL,
1430 // to provide trampolines thunks for incremental function patching. Set this
1431 // as "unused" because LLD doesn't support /INCREMENTAL link.
1432 pdb::SectionContrib sc =
1433 createSectionContrib(nullptr, llvm::pdb::kInvalidStreamIndex);
1434 linkerModule.setFirstSectionContrib(sc);
1435
1436 // Add Section Map stream.
1437 ArrayRef<object::coff_section> sections = {
1438 (const object::coff_section *)sectionTable.data(),
1439 sectionTable.size() / sizeof(object::coff_section)};
1440 dbiBuilder.createSectionMap(sections);
1441
1442 // Add COFF section header stream.
1443 exitOnErr(
1444 dbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, sectionTable));
1445 }
1446
commit(codeview::GUID * guid)1447 void PDBLinker::commit(codeview::GUID *guid) {
1448 ExitOnError exitOnErr((config->pdbPath + ": ").str());
1449 // Write to a file.
1450 exitOnErr(builder.commit(config->pdbPath, guid));
1451 }
1452
getSecrelReloc()1453 static uint32_t getSecrelReloc() {
1454 switch (config->machine) {
1455 case AMD64:
1456 return COFF::IMAGE_REL_AMD64_SECREL;
1457 case I386:
1458 return COFF::IMAGE_REL_I386_SECREL;
1459 case ARMNT:
1460 return COFF::IMAGE_REL_ARM_SECREL;
1461 case ARM64:
1462 return COFF::IMAGE_REL_ARM64_SECREL;
1463 default:
1464 llvm_unreachable("unknown machine type");
1465 }
1466 }
1467
1468 // Try to find a line table for the given offset Addr into the given chunk C.
1469 // If a line table was found, the line table, the string and checksum tables
1470 // that are used to interpret the line table, and the offset of Addr in the line
1471 // table are stored in the output arguments. Returns whether a line table was
1472 // found.
findLineTable(const SectionChunk * c,uint32_t addr,DebugStringTableSubsectionRef & cvStrTab,DebugChecksumsSubsectionRef & checksums,DebugLinesSubsectionRef & lines,uint32_t & offsetInLinetable)1473 static bool findLineTable(const SectionChunk *c, uint32_t addr,
1474 DebugStringTableSubsectionRef &cvStrTab,
1475 DebugChecksumsSubsectionRef &checksums,
1476 DebugLinesSubsectionRef &lines,
1477 uint32_t &offsetInLinetable) {
1478 ExitOnError exitOnErr;
1479 uint32_t secrelReloc = getSecrelReloc();
1480
1481 for (SectionChunk *dbgC : c->file->getDebugChunks()) {
1482 if (dbgC->getSectionName() != ".debug$S")
1483 continue;
1484
1485 // Build a mapping of SECREL relocations in dbgC that refer to `c`.
1486 DenseMap<uint32_t, uint32_t> secrels;
1487 for (const coff_relocation &r : dbgC->getRelocs()) {
1488 if (r.Type != secrelReloc)
1489 continue;
1490
1491 if (auto *s = dyn_cast_or_null<DefinedRegular>(
1492 c->file->getSymbols()[r.SymbolTableIndex]))
1493 if (s->getChunk() == c)
1494 secrels[r.VirtualAddress] = s->getValue();
1495 }
1496
1497 ArrayRef<uint8_t> contents =
1498 SectionChunk::consumeDebugMagic(dbgC->getContents(), ".debug$S");
1499 DebugSubsectionArray subsections;
1500 BinaryStreamReader reader(contents, support::little);
1501 exitOnErr(reader.readArray(subsections, contents.size()));
1502
1503 for (const DebugSubsectionRecord &ss : subsections) {
1504 switch (ss.kind()) {
1505 case DebugSubsectionKind::StringTable: {
1506 assert(!cvStrTab.valid() &&
1507 "Encountered multiple string table subsections!");
1508 exitOnErr(cvStrTab.initialize(ss.getRecordData()));
1509 break;
1510 }
1511 case DebugSubsectionKind::FileChecksums:
1512 assert(!checksums.valid() &&
1513 "Encountered multiple checksum subsections!");
1514 exitOnErr(checksums.initialize(ss.getRecordData()));
1515 break;
1516 case DebugSubsectionKind::Lines: {
1517 ArrayRef<uint8_t> bytes;
1518 auto ref = ss.getRecordData();
1519 exitOnErr(ref.readLongestContiguousChunk(0, bytes));
1520 size_t offsetInDbgC = bytes.data() - dbgC->getContents().data();
1521
1522 // Check whether this line table refers to C.
1523 auto i = secrels.find(offsetInDbgC);
1524 if (i == secrels.end())
1525 break;
1526
1527 // Check whether this line table covers Addr in C.
1528 DebugLinesSubsectionRef linesTmp;
1529 exitOnErr(linesTmp.initialize(BinaryStreamReader(ref)));
1530 uint32_t offsetInC = i->second + linesTmp.header()->RelocOffset;
1531 if (addr < offsetInC || addr >= offsetInC + linesTmp.header()->CodeSize)
1532 break;
1533
1534 assert(!lines.header() &&
1535 "Encountered multiple line tables for function!");
1536 exitOnErr(lines.initialize(BinaryStreamReader(ref)));
1537 offsetInLinetable = addr - offsetInC;
1538 break;
1539 }
1540 default:
1541 break;
1542 }
1543
1544 if (cvStrTab.valid() && checksums.valid() && lines.header())
1545 return true;
1546 }
1547 }
1548
1549 return false;
1550 }
1551
1552 // Use CodeView line tables to resolve a file and line number for the given
1553 // offset into the given chunk and return them, or None if a line table was
1554 // not found.
1555 Optional<std::pair<StringRef, uint32_t>>
getFileLineCodeView(const SectionChunk * c,uint32_t addr)1556 lld::coff::getFileLineCodeView(const SectionChunk *c, uint32_t addr) {
1557 ExitOnError exitOnErr;
1558
1559 DebugStringTableSubsectionRef cvStrTab;
1560 DebugChecksumsSubsectionRef checksums;
1561 DebugLinesSubsectionRef lines;
1562 uint32_t offsetInLinetable;
1563
1564 if (!findLineTable(c, addr, cvStrTab, checksums, lines, offsetInLinetable))
1565 return None;
1566
1567 Optional<uint32_t> nameIndex;
1568 Optional<uint32_t> lineNumber;
1569 for (LineColumnEntry &entry : lines) {
1570 for (const LineNumberEntry &ln : entry.LineNumbers) {
1571 LineInfo li(ln.Flags);
1572 if (ln.Offset > offsetInLinetable) {
1573 if (!nameIndex) {
1574 nameIndex = entry.NameIndex;
1575 lineNumber = li.getStartLine();
1576 }
1577 StringRef filename =
1578 exitOnErr(getFileName(cvStrTab, checksums, *nameIndex));
1579 return std::make_pair(filename, *lineNumber);
1580 }
1581 nameIndex = entry.NameIndex;
1582 lineNumber = li.getStartLine();
1583 }
1584 }
1585 if (!nameIndex)
1586 return None;
1587 StringRef filename = exitOnErr(getFileName(cvStrTab, checksums, *nameIndex));
1588 return std::make_pair(filename, *lineNumber);
1589 }
1590