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