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