Coverage Report

Created: 2018-10-23 15:26

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/COFF/PDB.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- PDB.cpp ------------------------------------------------------------===//
2
//
3
//                             The LLVM Linker
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
10
#include "PDB.h"
11
#include "Chunks.h"
12
#include "Config.h"
13
#include "Driver.h"
14
#include "SymbolTable.h"
15
#include "Symbols.h"
16
#include "Writer.h"
17
#include "lld/Common/ErrorHandler.h"
18
#include "lld/Common/Timer.h"
19
#include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
20
#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
21
#include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"
22
#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
23
#include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
24
#include "llvm/DebugInfo/CodeView/RecordName.h"
25
#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
26
#include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
27
#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
28
#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
29
#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
30
#include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
31
#include "llvm/DebugInfo/MSF/MSFBuilder.h"
32
#include "llvm/DebugInfo/MSF/MSFCommon.h"
33
#include "llvm/DebugInfo/PDB/GenericError.h"
34
#include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
35
#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
36
#include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
37
#include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h"
38
#include "llvm/DebugInfo/PDB/Native/InfoStream.h"
39
#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
40
#include "llvm/DebugInfo/PDB/Native/NativeSession.h"
41
#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
42
#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
43
#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
44
#include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
45
#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
46
#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
47
#include "llvm/DebugInfo/PDB/PDB.h"
48
#include "llvm/Object/COFF.h"
49
#include "llvm/Object/CVDebugRecord.h"
50
#include "llvm/Support/BinaryByteStream.h"
51
#include "llvm/Support/Endian.h"
52
#include "llvm/Support/FormatVariadic.h"
53
#include "llvm/Support/JamCRC.h"
54
#include "llvm/Support/Path.h"
55
#include "llvm/Support/ScopedPrinter.h"
56
#include <memory>
57
58
using namespace lld;
59
using namespace lld::coff;
60
using namespace llvm;
61
using namespace llvm::codeview;
62
63
using llvm::object::coff_section;
64
65
static ExitOnError ExitOnErr;
66
67
static Timer TotalPdbLinkTimer("PDB Emission (Cumulative)", Timer::root());
68
69
static Timer AddObjectsTimer("Add Objects", TotalPdbLinkTimer);
70
static Timer TypeMergingTimer("Type Merging", AddObjectsTimer);
71
static Timer SymbolMergingTimer("Symbol Merging", AddObjectsTimer);
72
static Timer GlobalsLayoutTimer("Globals Stream Layout", TotalPdbLinkTimer);
73
static Timer TpiStreamLayoutTimer("TPI Stream Layout", TotalPdbLinkTimer);
74
static Timer DiskCommitTimer("Commit to Disk", TotalPdbLinkTimer);
75
76
namespace {
77
/// Map from type index and item index in a type server PDB to the
78
/// corresponding index in the destination PDB.
79
struct CVIndexMap {
80
  SmallVector<TypeIndex, 0> TPIMap;
81
  SmallVector<TypeIndex, 0> IPIMap;
82
  bool IsTypeServerMap = false;
83
};
84
85
class DebugSHandler;
86
87
class PDBLinker {
88
  friend DebugSHandler;
89
90
public:
91
  PDBLinker(SymbolTable *Symtab)
92
      : Alloc(), Symtab(Symtab), Builder(Alloc), TypeTable(Alloc),
93
87
        IDTable(Alloc), GlobalTypeTable(Alloc), GlobalIDTable(Alloc) {
94
87
    // This isn't strictly necessary, but link.exe usually puts an empty string
95
87
    // as the first "valid" string in the string table, so we do the same in
96
87
    // order to maintain as much byte-for-byte compatibility as possible.
97
87
    PDBStrTab.insert("");
98
87
  }
99
100
  /// Emit the basic PDB structure: initial streams, headers, etc.
101
  void initialize(llvm::codeview::DebugInfo *BuildId);
102
103
  /// Add natvis files specified on the command line.
104
  void addNatvisFiles();
105
106
  /// Link CodeView from each object file in the symbol table into the PDB.
107
  void addObjectsToPDB();
108
109
  /// Link CodeView from a single object file into the PDB.
110
  void addObjFile(ObjFile *File);
111
112
  /// Produce a mapping from the type and item indices used in the object
113
  /// file to those in the destination PDB.
114
  ///
115
  /// If the object file uses a type server PDB (compiled with /Zi), merge TPI
116
  /// and IPI from the type server PDB and return a map for it. Each unique type
117
  /// server PDB is merged at most once, so this may return an existing index
118
  /// mapping.
119
  ///
120
  /// If the object does not use a type server PDB (compiled with /Z7), we merge
121
  /// all the type and item records from the .debug$S stream and fill in the
122
  /// caller-provided ObjectIndexMap.
123
  Expected<const CVIndexMap&> mergeDebugT(ObjFile *File,
124
                                          CVIndexMap &ObjectIndexMap);
125
126
  Expected<const CVIndexMap&> maybeMergeTypeServerPDB(ObjFile *File,
127
                                                      TypeServer2Record &TS);
128
129
  /// Add the section map and section contributions to the PDB.
130
  void addSections(ArrayRef<OutputSection *> OutputSections,
131
                   ArrayRef<uint8_t> SectionTable);
132
133
  /// Write the PDB to disk and store the Guid generated for it in *Guid.
134
  void commit(codeview::GUID *Guid);
135
136
private:
137
  BumpPtrAllocator Alloc;
138
139
  SymbolTable *Symtab;
140
141
  pdb::PDBFileBuilder Builder;
142
143
  /// Type records that will go into the PDB TPI stream.
144
  MergingTypeTableBuilder TypeTable;
145
146
  /// Item records that will go into the PDB IPI stream.
147
  MergingTypeTableBuilder IDTable;
148
149
  /// Type records that will go into the PDB TPI stream (for /DEBUG:GHASH)
150
  GlobalTypeTableBuilder GlobalTypeTable;
151
152
  /// Item records that will go into the PDB IPI stream (for /DEBUG:GHASH)
153
  GlobalTypeTableBuilder GlobalIDTable;
154
155
  /// PDBs use a single global string table for filenames in the file checksum
156
  /// table.
157
  DebugStringTableSubsection PDBStrTab;
158
159
  llvm::SmallString<128> NativePath;
160
161
  /// A list of other PDBs which are loaded during the linking process and which
162
  /// we need to keep around since the linking operation may reference pointers
163
  /// inside of these PDBs.
164
  llvm::SmallVector<std::unique_ptr<pdb::NativeSession>, 2> LoadedPDBs;
165
166
  std::vector<pdb::SecMapEntry> SectionMap;
167
168
  /// Type index mappings of type server PDBs that we've loaded so far.
169
  std::map<GUID, CVIndexMap> TypeServerIndexMappings;
170
171
  /// List of TypeServer PDBs which cannot be loaded.
172
  /// Cached to prevent repeated load attempts.
173
  std::map<GUID, std::string> MissingTypeServerPDBs;
174
};
175
176
class DebugSHandler {
177
  PDBLinker &Linker;
178
179
  /// The object file whose .debug$S sections we're processing.
180
  ObjFile &File;
181
182
  /// The result of merging type indices.
183
  const CVIndexMap &IndexMap;
184
185
  /// The DEBUG_S_STRINGTABLE subsection.  These strings are referred to by
186
  /// index from other records in the .debug$S section.  All of these strings
187
  /// need to be added to the global PDB string table, and all references to
188
  /// these strings need to have their indices re-written to refer to the
189
  /// global PDB string table.
190
  DebugStringTableSubsectionRef CVStrTab;
191
192
  /// The DEBUG_S_FILECHKSMS subsection.  As above, these are referred to
193
  /// by other records in the .debug$S section and need to be merged into the
194
  /// PDB.
195
  DebugChecksumsSubsectionRef Checksums;
196
197
  /// The DEBUG_S_FRAMEDATA subsection(s).  There can be more than one of
198
  /// these and they need not appear in any specific order.  However, they
199
  /// contain string table references which need to be re-written, so we
200
  /// collect them all here and re-write them after all subsections have been
201
  /// discovered and processed.
202
  std::vector<DebugFrameDataSubsectionRef> NewFpoFrames;
203
204
  /// Pointers to raw memory that we determine have string table references
205
  /// that need to be re-written.  We first process all .debug$S subsections
206
  /// to ensure that we can handle subsections written in any order, building
207
  /// up this list as we go.  At the end, we use the string table (which must
208
  /// have been discovered by now else it is an error) to re-write these
209
  /// references.
210
  std::vector<ulittle32_t *> StringTableReferences;
211
212
public:
213
  DebugSHandler(PDBLinker &Linker, ObjFile &File, const CVIndexMap &IndexMap)
214
111
      : Linker(Linker), File(File), IndexMap(IndexMap) {}
215
216
  void handleDebugS(lld::coff::SectionChunk &DebugS);
217
  void finish();
218
};
219
}
220
221
// Visual Studio's debugger requires absolute paths in various places in the
222
// PDB to work without additional configuration:
223
// https://docs.microsoft.com/en-us/visualstudio/debugger/debug-source-files-common-properties-solution-property-pages-dialog-box
224
351
static void pdbMakeAbsolute(SmallVectorImpl<char> &FileName) {
225
351
  // The default behavior is to produce paths that are valid within the context
226
351
  // of the machine that you perform the link on.  If the linker is running on
227
351
  // a POSIX system, we will output absolute POSIX paths.  If the linker is
228
351
  // running on a Windows system, we will output absolute Windows paths.  If the
229
351
  // user desires any other kind of behavior, they should explicitly pass
230
351
  // /pdbsourcepath, in which case we will treat the exact string the user
231
351
  // passed in as the gospel and not normalize, canonicalize it.
232
351
  if (sys::path::is_absolute(FileName, sys::path::Style::windows) ||
233
351
      
sys::path::is_absolute(FileName, sys::path::Style::posix)296
)
234
322
    return;
235
29
236
29
  // It's not absolute in any path syntax.  Relative paths necessarily refer to
237
29
  // the local file system, so we can make it native without ending up with a
238
29
  // nonsensical path.
239
29
  sys::path::native(FileName);
240
29
  if (Config->PDBSourcePath.empty()) {
241
15
    sys::fs::make_absolute(FileName);
242
15
    return;
243
15
  }
244
14
  // Only apply native and dot removal to the relative file path.  We want to
245
14
  // leave the path the user specified untouched since we assume they specified
246
14
  // it for a reason.
247
14
  sys::path::remove_dots(FileName, /*remove_dot_dots=*/true);
248
14
249
14
  SmallString<128> AbsoluteFileName = Config->PDBSourcePath;
250
14
  sys::path::append(AbsoluteFileName, FileName);
251
14
  FileName = std::move(AbsoluteFileName);
252
14
}
253
254
static SectionChunk *findByName(ArrayRef<SectionChunk *> Sections,
255
119
                                StringRef Name) {
256
119
  for (SectionChunk *C : Sections)
257
128
    if (C->getSectionName() == Name)
258
58
      return C;
259
119
  
return nullptr61
;
260
119
}
261
262
static ArrayRef<uint8_t> consumeDebugMagic(ArrayRef<uint8_t> Data,
263
149
                                           StringRef SecName) {
264
149
  // First 4 bytes are section magic.
265
149
  if (Data.size() < 4)
266
0
    fatal(SecName + " too short");
267
149
  if (support::endian::read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
268
0
    fatal(SecName + " has an invalid magic");
269
149
  return Data.slice(4);
270
149
}
271
272
115
static ArrayRef<uint8_t> getDebugSection(ObjFile *File, StringRef SecName) {
273
115
  if (SectionChunk *Sec = findByName(File->getDebugChunks(), SecName))
274
55
    return consumeDebugMagic(Sec->getContents(), SecName);
275
60
  return {};
276
60
}
277
278
// A COFF .debug$H section is currently a clang extension.  This function checks
279
// if a .debug$H section is in a format that we expect / understand, so that we
280
// can ignore any sections which are coincidentally also named .debug$H but do
281
// not contain a format we recognize.
282
3
static bool canUseDebugH(ArrayRef<uint8_t> DebugH) {
283
3
  if (DebugH.size() < sizeof(object::debug_h_header))
284
0
    return false;
285
3
  auto *Header =
286
3
      reinterpret_cast<const object::debug_h_header *>(DebugH.data());
287
3
  DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
288
3
  return Header->Magic == COFF::DEBUG_HASHES_SECTION_MAGIC &&
289
3
         Header->Version == 0 &&
290
3
         Header->HashAlgorithm == uint16_t(GlobalTypeHashAlg::SHA1_8) &&
291
3
         (DebugH.size() % 8 == 0);
292
3
}
293
294
4
static Optional<ArrayRef<uint8_t>> getDebugH(ObjFile *File) {
295
4
  SectionChunk *Sec = findByName(File->getDebugChunks(), ".debug$H");
296
4
  if (!Sec)
297
1
    return llvm::None;
298
3
  ArrayRef<uint8_t> Contents = Sec->getContents();
299
3
  if (!canUseDebugH(Contents))
300
0
    return None;
301
3
  return Contents;
302
3
}
303
304
static ArrayRef<GloballyHashedType>
305
3
getHashesFromDebugH(ArrayRef<uint8_t> DebugH) {
306
3
  assert(canUseDebugH(DebugH));
307
3
308
3
  DebugH = DebugH.drop_front(sizeof(object::debug_h_header));
309
3
  uint32_t Count = DebugH.size() / sizeof(GloballyHashedType);
310
3
  return {reinterpret_cast<const GloballyHashedType *>(DebugH.data()), Count};
311
3
}
312
313
static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
314
174
                        TypeCollection &TypeTable) {
315
174
  // Start the TPI or IPI stream header.
316
174
  TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
317
174
318
174
  // Flatten the in memory type table and hash each type.
319
972
  TypeTable.ForEachRecord([&](TypeIndex TI, const CVType &Type) {
320
972
    auto Hash = pdb::hashTypeRecord(Type);
321
972
    if (auto E = Hash.takeError())
322
0
      fatal("type hashing error");
323
972
    TpiBuilder.addTypeRecord(Type.RecordData, *Hash);
324
972
  });
325
174
}
326
327
static Optional<TypeServer2Record>
328
55
maybeReadTypeServerRecord(CVTypeArray &Types) {
329
55
  auto I = Types.begin();
330
55
  if (I == Types.end())
331
0
    return None;
332
55
  const CVType &Type = *I;
333
55
  if (Type.kind() != LF_TYPESERVER2)
334
48
    return None;
335
7
  TypeServer2Record TS;
336
7
  if (auto EC = TypeDeserializer::deserializeAs(const_cast<CVType &>(Type), TS))
337
0
    fatal("error reading type server record: " + toString(std::move(EC)));
338
7
  return std::move(TS);
339
7
}
340
341
Expected<const CVIndexMap&> PDBLinker::mergeDebugT(ObjFile *File,
342
115
                                                   CVIndexMap &ObjectIndexMap) {
343
115
  ScopedTimer T(TypeMergingTimer);
344
115
345
115
  ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
346
115
  if (Data.empty())
347
60
    return ObjectIndexMap;
348
55
349
55
  BinaryByteStream Stream(Data, support::little);
350
55
  CVTypeArray Types;
351
55
  BinaryStreamReader Reader(Stream);
352
55
  if (auto EC = Reader.readArray(Types, Reader.getLength()))
353
0
    fatal("Reader::readArray failed: " + toString(std::move(EC)));
354
55
355
55
  // Look through type servers. If we've already seen this type server, don't
356
55
  // merge any type information.
357
55
  if (Optional<TypeServer2Record> TS = maybeReadTypeServerRecord(Types))
358
7
    return maybeMergeTypeServerPDB(File, *TS);
359
48
360
48
  // This is a /Z7 object. Fill in the temporary, caller-provided
361
48
  // ObjectIndexMap.
362
48
  if (Config->DebugGHashes) {
363
4
    ArrayRef<GloballyHashedType> Hashes;
364
4
    std::vector<GloballyHashedType> OwnedHashes;
365
4
    if (Optional<ArrayRef<uint8_t>> DebugH = getDebugH(File))
366
3
      Hashes = getHashesFromDebugH(*DebugH);
367
1
    else {
368
1
      OwnedHashes = GloballyHashedType::hashTypes(Types);
369
1
      Hashes = OwnedHashes;
370
1
    }
371
4
372
4
    if (auto Err = mergeTypeAndIdRecords(GlobalIDTable, GlobalTypeTable,
373
0
                                         ObjectIndexMap.TPIMap, Types, Hashes))
374
0
      fatal("codeview::mergeTypeAndIdRecords failed: " +
375
0
            toString(std::move(Err)));
376
44
  } else {
377
44
    if (auto Err = mergeTypeAndIdRecords(IDTable, TypeTable,
378
0
                                         ObjectIndexMap.TPIMap, Types))
379
0
      fatal("codeview::mergeTypeAndIdRecords failed: " +
380
0
            toString(std::move(Err)));
381
48
  }
382
48
  return ObjectIndexMap;
383
48
}
384
385
static Expected<std::unique_ptr<pdb::NativeSession>>
386
7
tryToLoadPDB(const GUID &GuidFromObj, StringRef TSPath) {
387
7
  // Ensure the file exists before anything else. We want to return ENOENT,
388
7
  // "file not found", even if the path points to a removable device (in which
389
7
  // case the return message would be EAGAIN, "resource unavailable try again")
390
7
  if (!llvm::sys::fs::exists(TSPath))
391
3
    return errorCodeToError(std::error_code(ENOENT, std::generic_category()));
392
4
393
4
  ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(
394
4
      TSPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
395
4
  if (!MBOrErr)
396
0
    return errorCodeToError(MBOrErr.getError());
397
4
398
4
  std::unique_ptr<pdb::IPDBSession> ThisSession;
399
4
  if (auto EC = pdb::NativeSession::createFromPdb(
400
1
          MemoryBuffer::getMemBuffer(Driver->takeBuffer(std::move(*MBOrErr)),
401
1
                                     /*RequiresNullTerminator=*/false),
402
1
          ThisSession))
403
1
    return std::move(EC);
404
3
405
3
  std::unique_ptr<pdb::NativeSession> NS(
406
3
      static_cast<pdb::NativeSession *>(ThisSession.release()));
407
3
  pdb::PDBFile &File = NS->getPDBFile();
408
3
  auto ExpectedInfo = File.getPDBInfoStream();
409
3
  // All PDB Files should have an Info stream.
410
3
  if (!ExpectedInfo)
411
0
    return ExpectedInfo.takeError();
412
3
413
3
  // Just because a file with a matching name was found and it was an actual
414
3
  // PDB file doesn't mean it matches.  For it to match the InfoStream's GUID
415
3
  // must match the GUID specified in the TypeServer2 record.
416
3
  if (ExpectedInfo->getGuid() != GuidFromObj)
417
1
    return make_error<pdb::PDBError>(pdb::pdb_error_code::signature_out_of_date);
418
2
419
2
  return std::move(NS);
420
2
}
421
422
Expected<const CVIndexMap &>
423
7
PDBLinker::maybeMergeTypeServerPDB(ObjFile *File, TypeServer2Record &TS) {
424
7
  const GUID &TSId = TS.getGuid();
425
7
  StringRef TSPath = TS.getName();
426
7
427
7
  // First, check if the PDB has previously failed to load.
428
7
  auto PrevErr = MissingTypeServerPDBs.find(TSId);
429
7
  if (PrevErr != MissingTypeServerPDBs.end())
430
1
    return createFileError(
431
1
        TSPath,
432
1
        make_error<StringError>(PrevErr->second, inconvertibleErrorCode()));
433
6
434
6
  // Second, check if we already loaded a PDB with this GUID. Return the type
435
6
  // index mapping if we have it.
436
6
  auto Insertion = TypeServerIndexMappings.insert({TSId, CVIndexMap()});
437
6
  CVIndexMap &IndexMap = Insertion.first->second;
438
6
  if (!Insertion.second)
439
1
    return IndexMap;
440
5
441
5
  // Mark this map as a type server map.
442
5
  IndexMap.IsTypeServerMap = true;
443
5
444
5
  // Check for a PDB at:
445
5
  // 1. The given file path
446
5
  // 2. Next to the object file or archive file
447
5
  auto ExpectedSession = handleExpected(
448
5
      tryToLoadPDB(TSId, TSPath),
449
5
      [&]() {
450
2
        StringRef LocalPath =
451
2
            !File->ParentName.empty() ? 
File->ParentName0
: File->getName();
452
2
        SmallString<128> Path = sys::path::parent_path(LocalPath);
453
2
        // Currently, type server PDBs are only created by cl, which only runs
454
2
        // on Windows, so we can assume type server paths are Windows style.
455
2
        sys::path::append(
456
2
            Path, sys::path::filename(TSPath, sys::path::Style::windows));
457
2
        return tryToLoadPDB(TSId, Path);
458
2
      },
459
5
      [&](std::unique_ptr<ECError> EC) -> Error {
460
2
        auto SysErr = EC->convertToErrorCode();
461
2
        // Only re-try loading if the previous error was "No such file or
462
2
        // directory"
463
2
        if (SysErr.category() == std::generic_category() &&
464
2
            SysErr.value() == ENOENT)
465
2
          return Error::success();
466
0
        return Error(std::move(EC));
467
0
      });
468
5
469
5
  if (auto E = ExpectedSession.takeError()) {
470
3
    TypeServerIndexMappings.erase(TSId);
471
3
472
3
    // Flatten the error to a string, for later display, if the error occurs
473
3
    // again on the same PDB.
474
3
    std::string ErrMsg;
475
3
    raw_string_ostream S(ErrMsg);
476
3
    S << E;
477
3
    MissingTypeServerPDBs.emplace(TSId, S.str());
478
3
479
3
    return createFileError(TSPath, std::move(E));
480
3
  }
481
2
482
2
  pdb::NativeSession *Session = ExpectedSession->get();
483
2
484
2
  // Keep a strong reference to this PDB, so that it's safe to hold pointers
485
2
  // into the file.
486
2
  LoadedPDBs.push_back(std::move(*ExpectedSession));
487
2
488
2
  auto ExpectedTpi = Session->getPDBFile().getPDBTpiStream();
489
2
  if (auto E = ExpectedTpi.takeError())
490
0
    fatal("Type server does not have TPI stream: " + toString(std::move(E)));
491
2
  auto ExpectedIpi = Session->getPDBFile().getPDBIpiStream();
492
2
  if (auto E = ExpectedIpi.takeError())
493
0
    fatal("Type server does not have TPI stream: " + toString(std::move(E)));
494
2
495
2
  if (Config->DebugGHashes) {
496
0
    // PDBs do not actually store global hashes, so when merging a type server
497
0
    // PDB we have to synthesize global hashes.  To do this, we first synthesize
498
0
    // global hashes for the TPI stream, since it is independent, then we
499
0
    // synthesize hashes for the IPI stream, using the hashes for the TPI stream
500
0
    // as inputs.
501
0
    auto TpiHashes = GloballyHashedType::hashTypes(ExpectedTpi->typeArray());
502
0
    auto IpiHashes =
503
0
        GloballyHashedType::hashIds(ExpectedIpi->typeArray(), TpiHashes);
504
0
505
0
    // Merge TPI first, because the IPI stream will reference type indices.
506
0
    if (auto Err = mergeTypeRecords(GlobalTypeTable, IndexMap.TPIMap,
507
0
                                    ExpectedTpi->typeArray(), TpiHashes))
508
0
      fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
509
0
510
0
    // Merge IPI.
511
0
    if (auto Err =
512
0
            mergeIdRecords(GlobalIDTable, IndexMap.TPIMap, IndexMap.IPIMap,
513
0
                           ExpectedIpi->typeArray(), IpiHashes))
514
0
      fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
515
2
  } else {
516
2
    // Merge TPI first, because the IPI stream will reference type indices.
517
2
    if (auto Err = mergeTypeRecords(TypeTable, IndexMap.TPIMap,
518
0
                                    ExpectedTpi->typeArray()))
519
0
      fatal("codeview::mergeTypeRecords failed: " + toString(std::move(Err)));
520
2
521
2
    // Merge IPI.
522
2
    if (auto Err = mergeIdRecords(IDTable, IndexMap.TPIMap, IndexMap.IPIMap,
523
0
                                  ExpectedIpi->typeArray()))
524
0
      fatal("codeview::mergeIdRecords failed: " + toString(std::move(Err)));
525
2
  }
526
2
527
2
  return IndexMap;
528
2
}
529
530
283
static bool remapTypeIndex(TypeIndex &TI, ArrayRef<TypeIndex> TypeIndexMap) {
531
283
  if (TI.isSimple())
532
45
    return true;
533
238
  if (TI.toArrayIndex() >= TypeIndexMap.size())
534
2
    return false;
535
236
  TI = TypeIndexMap[TI.toArrayIndex()];
536
236
  return true;
537
236
}
538
539
static void remapTypesInSymbolRecord(ObjFile *File, SymbolKind SymKind,
540
                                     MutableArrayRef<uint8_t> Contents,
541
                                     const CVIndexMap &IndexMap,
542
547
                                     ArrayRef<TiReference> TypeRefs) {
543
547
  for (const TiReference &Ref : TypeRefs) {
544
283
    unsigned ByteSize = Ref.Count * sizeof(TypeIndex);
545
283
    if (Contents.size() < Ref.Offset + ByteSize)
546
0
      fatal("symbol record too short");
547
283
548
283
    // This can be an item index or a type index. Choose the appropriate map.
549
283
    ArrayRef<TypeIndex> TypeOrItemMap = IndexMap.TPIMap;
550
283
    bool IsItemIndex = Ref.Kind == TiRefKind::IndexRef;
551
283
    if (IsItemIndex && 
IndexMap.IsTypeServerMap111
)
552
5
      TypeOrItemMap = IndexMap.IPIMap;
553
283
554
283
    MutableArrayRef<TypeIndex> TIs(
555
283
        reinterpret_cast<TypeIndex *>(Contents.data() + Ref.Offset), Ref.Count);
556
283
    for (TypeIndex &TI : TIs) {
557
283
      if (!remapTypeIndex(TI, TypeOrItemMap)) {
558
2
        log("ignoring symbol record of kind 0x" + utohexstr(SymKind) + " in " +
559
2
            File->getName() + " with bad " + (IsItemIndex ? "item" : 
"type"0
) +
560
2
            " index 0x" + utohexstr(TI.getIndex()));
561
2
        TI = TypeIndex(SimpleTypeKind::NotTranslated);
562
2
        continue;
563
2
      }
564
283
    }
565
283
  }
566
547
}
567
568
static void
569
recordStringTableReferenceAtOffset(MutableArrayRef<uint8_t> Contents,
570
                                   uint32_t Offset,
571
3
                                   std::vector<ulittle32_t *> &StrTableRefs) {
572
3
  Contents =
573
3
      Contents.drop_front(Offset).take_front(sizeof(support::ulittle32_t));
574
3
  ulittle32_t *Index = reinterpret_cast<ulittle32_t *>(Contents.data());
575
3
  StrTableRefs.push_back(Index);
576
3
}
577
578
static void
579
recordStringTableReferences(SymbolKind Kind, MutableArrayRef<uint8_t> Contents,
580
547
                            std::vector<ulittle32_t *> &StrTableRefs) {
581
547
  // For now we only handle S_FILESTATIC, but we may need the same logic for
582
547
  // S_DEFRANGE and S_DEFRANGE_SUBFIELD.  However, I cannot seem to generate any
583
547
  // PDBs that contain these types of records, so because of the uncertainty
584
547
  // they are omitted here until we can prove that it's necessary.
585
547
  switch (Kind) {
586
547
  case SymbolKind::S_FILESTATIC:
587
3
    // FileStaticSym::ModFileOffset
588
3
    recordStringTableReferenceAtOffset(Contents, 4, StrTableRefs);
589
3
    break;
590
547
  case SymbolKind::S_DEFRANGE:
591
0
  case SymbolKind::S_DEFRANGE_SUBFIELD:
592
0
    log("Not fixing up string table reference in S_DEFRANGE / "
593
0
        "S_DEFRANGE_SUBFIELD record");
594
0
    break;
595
544
  default:
596
544
    break;
597
547
  }
598
547
}
599
600
1.09k
static SymbolKind symbolKind(ArrayRef<uint8_t> RecordData) {
601
1.09k
  const RecordPrefix *Prefix =
602
1.09k
      reinterpret_cast<const RecordPrefix *>(RecordData.data());
603
1.09k
  return static_cast<SymbolKind>(uint16_t(Prefix->RecordKind));
604
1.09k
}
605
606
/// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
607
static void translateIdSymbols(MutableArrayRef<uint8_t> &RecordData,
608
547
                               TypeCollection &IDTable) {
609
547
  RecordPrefix *Prefix = reinterpret_cast<RecordPrefix *>(RecordData.data());
610
547
611
547
  SymbolKind Kind = symbolKind(RecordData);
612
547
613
547
  if (Kind == SymbolKind::S_PROC_ID_END) {
614
73
    Prefix->RecordKind = SymbolKind::S_END;
615
73
    return;
616
73
  }
617
474
618
474
  // In an object file, GPROC32_ID has an embedded reference which refers to the
619
474
  // single object file type index namespace.  This has already been translated
620
474
  // to the PDB file's ID stream index space, but we need to convert this to a
621
474
  // symbol that refers to the type stream index space.  So we remap again from
622
474
  // ID index space to type index space.
623
474
  if (Kind == SymbolKind::S_GPROC32_ID || 
Kind == SymbolKind::S_LPROC32_ID403
) {
624
72
    SmallVector<TiReference, 1> Refs;
625
72
    auto Content = RecordData.drop_front(sizeof(RecordPrefix));
626
72
    CVSymbol Sym(Kind, RecordData);
627
72
    discoverTypeIndicesInSymbol(Sym, Refs);
628
72
    assert(Refs.size() == 1);
629
72
    assert(Refs.front().Count == 1);
630
72
631
72
    TypeIndex *TI =
632
72
        reinterpret_cast<TypeIndex *>(Content.data() + Refs[0].Offset);
633
72
    // `TI` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
634
72
    // the IPI stream, whose `FunctionType` member refers to the TPI stream.
635
72
    // Note that LF_FUNC_ID and LF_MEMFUNC_ID have the same record layout, and
636
72
    // in both cases we just need the second type index.
637
72
    if (!TI->isSimple() && 
!TI->isNoneType()69
) {
638
69
      CVType FuncIdData = IDTable.getType(*TI);
639
69
      SmallVector<TypeIndex, 2> Indices;
640
69
      discoverTypeIndices(FuncIdData, Indices);
641
69
      assert(Indices.size() == 2);
642
69
      *TI = Indices[1];
643
69
    }
644
72
645
72
    Kind = (Kind == SymbolKind::S_GPROC32_ID) ? 
SymbolKind::S_GPROC3271
646
72
                                              : 
SymbolKind::S_LPROC321
;
647
72
    Prefix->RecordKind = uint16_t(Kind);
648
72
  }
649
474
}
650
651
/// Copy the symbol record. In a PDB, symbol records must be 4 byte aligned.
652
/// The object file may not be aligned.
653
static MutableArrayRef<uint8_t> copySymbolForPdb(const CVSymbol &Sym,
654
547
                                                 BumpPtrAllocator &Alloc) {
655
547
  size_t Size = alignTo(Sym.length(), alignOf(CodeViewContainer::Pdb));
656
547
  assert(Size >= 4 && "record too short");
657
547
  assert(Size <= MaxRecordLength && "record too long");
658
547
  void *Mem = Alloc.Allocate(Size, 4);
659
547
660
547
  // Copy the symbol record and zero out any padding bytes.
661
547
  MutableArrayRef<uint8_t> NewData(reinterpret_cast<uint8_t *>(Mem), Size);
662
547
  memcpy(NewData.data(), Sym.data().data(), Sym.length());
663
547
  memset(NewData.data() + Sym.length(), 0, Size - Sym.length());
664
547
665
547
  // Update the record prefix length. It should point to the beginning of the
666
547
  // next record.
667
547
  auto *Prefix = reinterpret_cast<RecordPrefix *>(Mem);
668
547
  Prefix->RecordLen = Size - 2;
669
547
  return NewData;
670
547
}
671
672
/// Return true if this symbol opens a scope. This implies that the symbol has
673
/// "parent" and "end" fields, which contain the offset of the S_END or
674
/// S_INLINESITE_END record.
675
547
static bool symbolOpensScope(SymbolKind Kind) {
676
547
  switch (Kind) {
677
547
  case SymbolKind::S_GPROC32:
678
78
  case SymbolKind::S_LPROC32:
679
78
  case SymbolKind::S_LPROC32_ID:
680
78
  case SymbolKind::S_GPROC32_ID:
681
78
  case SymbolKind::S_BLOCK32:
682
78
  case SymbolKind::S_SEPCODE:
683
78
  case SymbolKind::S_THUNK32:
684
78
  case SymbolKind::S_INLINESITE:
685
78
  case SymbolKind::S_INLINESITE2:
686
78
    return true;
687
469
  default:
688
469
    break;
689
469
  }
690
469
  return false;
691
469
}
692
693
469
static bool symbolEndsScope(SymbolKind Kind) {
694
469
  switch (Kind) {
695
469
  case SymbolKind::S_END:
696
78
  case SymbolKind::S_PROC_ID_END:
697
78
  case SymbolKind::S_INLINESITE_END:
698
78
    return true;
699
391
  default:
700
391
    break;
701
391
  }
702
391
  return false;
703
391
}
704
705
struct ScopeRecord {
706
  ulittle32_t PtrParent;
707
  ulittle32_t PtrEnd;
708
};
709
710
struct SymbolScope {
711
  ScopeRecord *OpeningRecord;
712
  uint32_t ScopeOffset;
713
};
714
715
static void scopeStackOpen(SmallVectorImpl<SymbolScope> &Stack,
716
78
                           uint32_t CurOffset, CVSymbol &Sym) {
717
78
  assert(symbolOpensScope(Sym.kind()));
718
78
  SymbolScope S;
719
78
  S.ScopeOffset = CurOffset;
720
78
  S.OpeningRecord = const_cast<ScopeRecord *>(
721
78
      reinterpret_cast<const ScopeRecord *>(Sym.content().data()));
722
78
  S.OpeningRecord->PtrParent = Stack.empty() ? 
073
:
Stack.back().ScopeOffset5
;
723
78
  Stack.push_back(S);
724
78
}
725
726
static void scopeStackClose(SmallVectorImpl<SymbolScope> &Stack,
727
78
                            uint32_t CurOffset, ObjFile *File) {
728
78
  if (Stack.empty()) {
729
0
    warn("symbol scopes are not balanced in " + File->getName());
730
0
    return;
731
0
  }
732
78
  SymbolScope S = Stack.pop_back_val();
733
78
  S.OpeningRecord->PtrEnd = CurOffset;
734
78
}
735
736
547
static bool symbolGoesInModuleStream(const CVSymbol &Sym) {
737
547
  switch (Sym.kind()) {
738
547
  case SymbolKind::S_GDATA32:
739
108
  case SymbolKind::S_CONSTANT:
740
108
  case SymbolKind::S_UDT:
741
108
  // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
742
108
  // since they are synthesized by the linker in response to S_GPROC32 and
743
108
  // S_LPROC32, but if we do see them, don't put them in the module stream I
744
108
  // guess.
745
108
  case SymbolKind::S_PROCREF:
746
108
  case SymbolKind::S_LPROCREF:
747
108
    return false;
748
108
  // S_GDATA32 does not go in the module stream, but S_LDATA32 does.
749
108
  case SymbolKind::S_LDATA32:
750
439
  default:
751
439
    return true;
752
547
  }
753
547
}
754
755
547
static bool symbolGoesInGlobalsStream(const CVSymbol &Sym) {
756
547
  switch (Sym.kind()) {
757
547
  case SymbolKind::S_CONSTANT:
758
91
  case SymbolKind::S_GDATA32:
759
91
  // S_LDATA32 goes in both the module stream and the globals stream.
760
91
  case SymbolKind::S_LDATA32:
761
91
  case SymbolKind::S_GPROC32:
762
91
  case SymbolKind::S_LPROC32:
763
91
  // We really should not be seeing S_PROCREF and S_LPROCREF in the first place
764
91
  // since they are synthesized by the linker in response to S_GPROC32 and
765
91
  // S_LPROC32, but if we do see them, copy them straight through.
766
91
  case SymbolKind::S_PROCREF:
767
91
  case SymbolKind::S_LPROCREF:
768
91
    return true;
769
91
  // FIXME: For now, we drop all S_UDT symbols (i.e. they don't go in the
770
91
  // globals stream or the modules stream).  These have special handling which
771
91
  // needs more investigation before we can get right, but by putting them all
772
91
  // into the globals stream WinDbg fails to display local variables of class
773
91
  // types saying that it cannot find the type Foo *.  So as a stopgap just to
774
91
  // keep things working, we drop them.
775
92
  case SymbolKind::S_UDT:
776
456
  default:
777
456
    return false;
778
547
  }
779
547
}
780
781
static void addGlobalSymbol(pdb::GSIStreamBuilder &Builder, ObjFile &File,
782
91
                            const CVSymbol &Sym) {
783
91
  switch (Sym.kind()) {
784
91
  case SymbolKind::S_CONSTANT:
785
19
  case SymbolKind::S_UDT:
786
19
  case SymbolKind::S_GDATA32:
787
19
  case SymbolKind::S_LDATA32:
788
19
  case SymbolKind::S_PROCREF:
789
19
  case SymbolKind::S_LPROCREF:
790
19
    Builder.addGlobalSymbol(Sym);
791
19
    break;
792
72
  case SymbolKind::S_GPROC32:
793
72
  case SymbolKind::S_LPROC32: {
794
72
    SymbolRecordKind K = SymbolRecordKind::ProcRefSym;
795
72
    if (Sym.kind() == SymbolKind::S_LPROC32)
796
1
      K = SymbolRecordKind::LocalProcRef;
797
72
    ProcRefSym PS(K);
798
72
    PS.Module = static_cast<uint16_t>(File.ModuleDBI->getModuleIndex());
799
72
    // For some reason, MSVC seems to add one to this value.
800
72
    ++PS.Module;
801
72
    PS.Name = getSymbolName(Sym);
802
72
    PS.SumName = 0;
803
72
    PS.SymOffset = File.ModuleDBI->getNextSymbolOffset();
804
72
    Builder.addGlobalSymbol(PS);
805
72
    break;
806
72
  }
807
72
  default:
808
0
    llvm_unreachable("Invalid symbol kind!");
809
91
  }
810
91
}
811
812
static void mergeSymbolRecords(BumpPtrAllocator &Alloc, ObjFile *File,
813
                               pdb::GSIStreamBuilder &GsiBuilder,
814
                               const CVIndexMap &IndexMap,
815
                               TypeCollection &IDTable,
816
                               std::vector<ulittle32_t *> &StringTableRefs,
817
186
                               BinaryStreamRef SymData) {
818
186
  // FIXME: Improve error recovery by warning and skipping records when
819
186
  // possible.
820
186
  ArrayRef<uint8_t> SymsBuffer;
821
186
  cantFail(SymData.readBytes(0, SymData.getLength(), SymsBuffer));
822
186
  SmallVector<SymbolScope, 4> Scopes;
823
186
824
186
  auto EC = forEachCodeViewRecord<CVSymbol>(
825
547
      SymsBuffer, [&](const CVSymbol &Sym) -> llvm::Error {
826
547
        // Discover type index references in the record. Skip it if we don't
827
547
        // know where they are.
828
547
        SmallVector<TiReference, 32> TypeRefs;
829
547
        if (!discoverTypeIndicesInSymbol(Sym, TypeRefs)) {
830
0
          log("ignoring unknown symbol record with kind 0x" +
831
0
              utohexstr(Sym.kind()));
832
0
          return Error::success();
833
0
        }
834
547
835
547
        // Copy the symbol record so we can mutate it.
836
547
        MutableArrayRef<uint8_t> NewData = copySymbolForPdb(Sym, Alloc);
837
547
838
547
        // Re-map all the type index references.
839
547
        MutableArrayRef<uint8_t> Contents =
840
547
            NewData.drop_front(sizeof(RecordPrefix));
841
547
        remapTypesInSymbolRecord(File, Sym.kind(), Contents, IndexMap,
842
547
                                 TypeRefs);
843
547
844
547
        // An object file may have S_xxx_ID symbols, but these get converted to
845
547
        // "real" symbols in a PDB.
846
547
        translateIdSymbols(NewData, IDTable);
847
547
848
547
        // If this record refers to an offset in the object file's string table,
849
547
        // add that item to the global PDB string table and re-write the index.
850
547
        recordStringTableReferences(Sym.kind(), Contents, StringTableRefs);
851
547
852
547
        SymbolKind NewKind = symbolKind(NewData);
853
547
854
547
        // Fill in "Parent" and "End" fields by maintaining a stack of scopes.
855
547
        CVSymbol NewSym(NewKind, NewData);
856
547
        if (symbolOpensScope(NewKind))
857
78
          scopeStackOpen(Scopes, File->ModuleDBI->getNextSymbolOffset(),
858
78
                         NewSym);
859
469
        else if (symbolEndsScope(NewKind))
860
78
          scopeStackClose(Scopes, File->ModuleDBI->getNextSymbolOffset(), File);
861
547
862
547
        // Add the symbol to the globals stream if necessary.  Do this before
863
547
        // adding the symbol to the module since we may need to get the next
864
547
        // symbol offset, and writing to the module's symbol stream will update
865
547
        // that offset.
866
547
        if (symbolGoesInGlobalsStream(NewSym))
867
91
          addGlobalSymbol(GsiBuilder, *File, NewSym);
868
547
869
547
        // Add the symbol to the module.
870
547
        if (symbolGoesInModuleStream(NewSym))
871
439
          File->ModuleDBI->addSymbol(NewSym);
872
547
        return Error::success();
873
547
      });
874
186
  cantFail(std::move(EC));
875
186
}
876
877
// Allocate memory for a .debug$S / .debug$F section and relocate it.
878
static ArrayRef<uint8_t> relocateDebugChunk(BumpPtrAllocator &Alloc,
879
78
                                            SectionChunk &DebugChunk) {
880
78
  uint8_t *Buffer = Alloc.Allocate<uint8_t>(DebugChunk.getSize());
881
78
  assert(DebugChunk.OutputSectionOff == 0 &&
882
78
         "debug sections should not be in output sections");
883
78
  DebugChunk.readRelocTargets();
884
78
  DebugChunk.writeTo(Buffer);
885
78
  return makeArrayRef(Buffer, DebugChunk.getSize());
886
78
}
887
888
657
static pdb::SectionContrib createSectionContrib(const Chunk *C, uint32_t Modi) {
889
657
  OutputSection *OS = C->getOutputSection();
890
657
  pdb::SectionContrib SC;
891
657
  memset(&SC, 0, sizeof(SC));
892
657
  SC.ISect = OS->SectionIndex;
893
657
  SC.Off = C->getRVA() - OS->getRVA();
894
657
  SC.Size = C->getSize();
895
657
  if (auto *SecChunk = dyn_cast<SectionChunk>(C)) {
896
351
    SC.Characteristics = SecChunk->Header->Characteristics;
897
351
    SC.Imod = SecChunk->File->ModuleDBI->getModuleIndex();
898
351
    ArrayRef<uint8_t> Contents = SecChunk->getContents();
899
351
    JamCRC CRC(0);
900
351
    ArrayRef<char> CharContents = makeArrayRef(
901
351
        reinterpret_cast<const char *>(Contents.data()), Contents.size());
902
351
    CRC.update(CharContents);
903
351
    SC.DataCrc = CRC.getCRC();
904
351
  } else {
905
306
    SC.Characteristics = OS->Header.Characteristics;
906
306
    // FIXME: When we start creating DBI for import libraries, use those here.
907
306
    SC.Imod = Modi;
908
306
  }
909
657
  SC.RelocCrc = 0; // FIXME
910
657
911
657
  return SC;
912
657
}
913
914
static uint32_t
915
translateStringTableIndex(uint32_t ObjIndex,
916
                          const DebugStringTableSubsectionRef &ObjStrTable,
917
41
                          DebugStringTableSubsection &PdbStrTable) {
918
41
  auto ExpectedString = ObjStrTable.getString(ObjIndex);
919
41
  if (!ExpectedString) {
920
0
    warn("Invalid string table reference");
921
0
    consumeError(ExpectedString.takeError());
922
0
    return 0;
923
0
  }
924
41
925
41
  return PdbStrTable.insert(*ExpectedString);
926
41
}
927
928
77
void DebugSHandler::handleDebugS(lld::coff::SectionChunk &DebugS) {
929
77
  DebugSubsectionArray Subsections;
930
77
931
77
  ArrayRef<uint8_t> RelocatedDebugContents = consumeDebugMagic(
932
77
      relocateDebugChunk(Linker.Alloc, DebugS), DebugS.getSectionName());
933
77
934
77
  BinaryStreamReader Reader(RelocatedDebugContents, support::little);
935
77
  ExitOnErr(Reader.readArray(Subsections, RelocatedDebugContents.size()));
936
77
937
377
  for (const DebugSubsectionRecord &SS : Subsections) {
938
377
    switch (SS.kind()) {
939
377
    case DebugSubsectionKind::StringTable: {
940
56
      assert(!CVStrTab.valid() &&
941
56
             "Encountered multiple string table subsections!");
942
56
      ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
943
56
      break;
944
377
    }
945
377
    case DebugSubsectionKind::FileChecksums:
946
52
      assert(!Checksums.valid() &&
947
52
             "Encountered multiple checksum subsections!");
948
52
      ExitOnErr(Checksums.initialize(SS.getRecordData()));
949
52
      break;
950
377
    case DebugSubsectionKind::Lines:
951
70
      // We can add the relocated line table directly to the PDB without
952
70
      // modification because the file checksum offsets will stay the same.
953
70
      File.ModuleDBI->addDebugSubsection(SS);
954
70
      break;
955
377
    case DebugSubsectionKind::FrameData: {
956
12
      // We need to re-write string table indices here, so save off all
957
12
      // frame data subsections until we've processed the entire list of
958
12
      // subsections so that we can be sure we have the string table.
959
12
      DebugFrameDataSubsectionRef FDS;
960
12
      ExitOnErr(FDS.initialize(SS.getRecordData()));
961
12
      NewFpoFrames.push_back(std::move(FDS));
962
12
      break;
963
377
    }
964
377
    case DebugSubsectionKind::Symbols:
965
186
      if (Config->DebugGHashes) {
966
14
        mergeSymbolRecords(Linker.Alloc, &File, Linker.Builder.getGsiBuilder(),
967
14
                           IndexMap, Linker.GlobalIDTable,
968
14
                           StringTableReferences, SS.getRecordData());
969
172
      } else {
970
172
        mergeSymbolRecords(Linker.Alloc, &File, Linker.Builder.getGsiBuilder(),
971
172
                           IndexMap, Linker.IDTable, StringTableReferences,
972
172
                           SS.getRecordData());
973
172
      }
974
186
      break;
975
377
    default:
976
1
      // FIXME: Process the rest of the subsections.
977
1
      break;
978
377
    }
979
377
  }
980
77
}
981
982
111
void DebugSHandler::finish() {
983
111
  pdb::DbiStreamBuilder &DbiBuilder = Linker.Builder.getDbiBuilder();
984
111
985
111
  // We should have seen all debug subsections across the entire object file now
986
111
  // which means that if a StringTable subsection and Checksums subsection were
987
111
  // present, now is the time to handle them.
988
111
  if (!CVStrTab.valid()) {
989
55
    if (Checksums.valid())
990
0
      fatal(".debug$S sections with a checksums subsection must also contain a "
991
0
            "string table subsection");
992
55
993
55
    if (!StringTableReferences.empty())
994
0
      warn("No StringTable subsection was encountered, but there are string "
995
0
           "table references");
996
55
    return;
997
55
  }
998
56
999
56
  // Rewrite string table indices in the Fpo Data and symbol records to refer to
1000
56
  // the global PDB string table instead of the object file string table.
1001
56
  for (DebugFrameDataSubsectionRef &FDS : NewFpoFrames) {
1002
12
    const uint32_t *Reloc = FDS.getRelocPtr();
1003
38
    for (codeview::FrameData FD : FDS) {
1004
38
      FD.RvaStart += *Reloc;
1005
38
      FD.FrameFunc =
1006
38
          translateStringTableIndex(FD.FrameFunc, CVStrTab, Linker.PDBStrTab);
1007
38
      DbiBuilder.addNewFpoData(FD);
1008
38
    }
1009
12
  }
1010
56
1011
56
  for (ulittle32_t *Ref : StringTableReferences)
1012
3
    *Ref = translateStringTableIndex(*Ref, CVStrTab, Linker.PDBStrTab);
1013
56
1014
56
  // Make a new file checksum table that refers to offsets in the PDB-wide
1015
56
  // string table. Generally the string table subsection appears after the
1016
56
  // checksum table, so we have to do this after looping over all the
1017
56
  // subsections.
1018
56
  auto NewChecksums = make_unique<DebugChecksumsSubsection>(Linker.PDBStrTab);
1019
62
  for (FileChecksumEntry &FC : Checksums) {
1020
62
    SmallString<128> FileName =
1021
62
        ExitOnErr(CVStrTab.getString(FC.FileNameOffset));
1022
62
    pdbMakeAbsolute(FileName);
1023
62
    ExitOnErr(Linker.Builder.getDbiBuilder().addModuleSourceFile(
1024
62
        *File.ModuleDBI, FileName));
1025
62
    NewChecksums->addChecksum(FileName, FC.Kind, FC.Checksum);
1026
62
  }
1027
56
  File.ModuleDBI->addDebugSubsection(std::move(NewChecksums));
1028
56
}
1029
1030
115
void PDBLinker::addObjFile(ObjFile *File) {
1031
115
  // Add a module descriptor for every object file. We need to put an absolute
1032
115
  // path to the object into the PDB. If this is a plain object, we make its
1033
115
  // path absolute. If it's an object in an archive, we make the archive path
1034
115
  // absolute.
1035
115
  bool InArchive = !File->ParentName.empty();
1036
115
  SmallString<128> Path = InArchive ? 
File->ParentName3
:
File->getName()112
;
1037
115
  pdbMakeAbsolute(Path);
1038
115
  StringRef Name = InArchive ? 
File->getName()3
:
StringRef(Path)112
;
1039
115
1040
115
  pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
1041
115
  File->ModuleDBI = &ExitOnErr(DbiBuilder.addModuleInfo(Name));
1042
115
  File->ModuleDBI->setObjFileName(Path);
1043
115
1044
115
  auto Chunks = File->getChunks();
1045
115
  uint32_t Modi = File->ModuleDBI->getModuleIndex();
1046
117
  for (Chunk *C : Chunks) {
1047
117
    auto *SecChunk = dyn_cast<SectionChunk>(C);
1048
117
    if (!SecChunk || !SecChunk->Live)
1049
2
      continue;
1050
115
    pdb::SectionContrib SC = createSectionContrib(SecChunk, Modi);
1051
115
    File->ModuleDBI->setFirstSectionContrib(SC);
1052
115
    break;
1053
115
  }
1054
115
1055
115
  // Before we can process symbol substreams from .debug$S, we need to process
1056
115
  // type information, file checksums, and the string table.  Add type info to
1057
115
  // the PDB first, so that we can get the map from object file type and item
1058
115
  // indices to PDB type and item indices.
1059
115
  CVIndexMap ObjectIndexMap;
1060
115
  auto IndexMapResult = mergeDebugT(File, ObjectIndexMap);
1061
115
1062
115
  // If the .debug$T sections fail to merge, assume there is no debug info.
1063
115
  if (!IndexMapResult) {
1064
4
    auto FileName = sys::path::filename(Path);
1065
4
    warn("Cannot use debug info for '" + FileName + "'\n" +
1066
4
         ">>> failed to load reference " +
1067
4
         StringRef(toString(IndexMapResult.takeError())));
1068
4
    return;
1069
4
  }
1070
111
1071
111
  ScopedTimer T(SymbolMergingTimer);
1072
111
1073
111
  DebugSHandler DSH(*this, *File, *IndexMapResult);
1074
111
  // Now do all live .debug$S and .debug$F sections.
1075
134
  for (SectionChunk *DebugChunk : File->getDebugChunks()) {
1076
134
    if (!DebugChunk->Live || DebugChunk->getSize() == 0)
1077
0
      continue;
1078
134
1079
134
    if (DebugChunk->getSectionName() == ".debug$S") {
1080
77
      DSH.handleDebugS(*DebugChunk);
1081
77
      continue;
1082
77
    }
1083
57
1084
57
    if (DebugChunk->getSectionName() == ".debug$F") {
1085
1
      ArrayRef<uint8_t> RelocatedDebugContents =
1086
1
          relocateDebugChunk(Alloc, *DebugChunk);
1087
1
1088
1
      FixedStreamArray<object::FpoData> FpoRecords;
1089
1
      BinaryStreamReader Reader(RelocatedDebugContents, support::little);
1090
1
      uint32_t Count = RelocatedDebugContents.size() / sizeof(object::FpoData);
1091
1
      ExitOnErr(Reader.readArray(FpoRecords, Count));
1092
1
1093
1
      // These are already relocated and don't refer to the string table, so we
1094
1
      // can just copy it.
1095
1
      for (const object::FpoData &FD : FpoRecords)
1096
1
        DbiBuilder.addOldFpoData(FD);
1097
1
      continue;
1098
1
    }
1099
57
  }
1100
111
1101
111
  // Do any post-processing now that all .debug$S sections have been processed.
1102
111
  DSH.finish();
1103
111
}
1104
1105
219
static PublicSym32 createPublic(Defined *Def) {
1106
219
  PublicSym32 Pub(SymbolKind::S_PUB32);
1107
219
  Pub.Name = Def->getName();
1108
219
  if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
1109
203
    if (D->getCOFFSymbol().isFunctionDefinition())
1110
138
      Pub.Flags = PublicSymFlags::Function;
1111
203
  } else 
if (16
isa<DefinedImportThunk>(Def)16
) {
1112
8
    Pub.Flags = PublicSymFlags::Function;
1113
8
  }
1114
219
1115
219
  OutputSection *OS = Def->getChunk()->getOutputSection();
1116
219
  assert(OS && "all publics should be in final image");
1117
219
  Pub.Offset = Def->getRVA() - OS->getRVA();
1118
219
  Pub.Segment = OS->SectionIndex;
1119
219
  return Pub;
1120
219
}
1121
1122
// Add all object files to the PDB. Merge .debug$T sections into IpiData and
1123
// TpiData.
1124
87
void PDBLinker::addObjectsToPDB() {
1125
87
  ScopedTimer T1(AddObjectsTimer);
1126
87
  for (ObjFile *File : ObjFile::Instances)
1127
115
    addObjFile(File);
1128
87
1129
87
  Builder.getStringTableBuilder().setStrings(PDBStrTab);
1130
87
  T1.stop();
1131
87
1132
87
  // Construct TPI and IPI stream contents.
1133
87
  ScopedTimer T2(TpiStreamLayoutTimer);
1134
87
  if (Config->DebugGHashes) {
1135
2
    addTypeInfo(Builder.getTpiBuilder(), GlobalTypeTable);
1136
2
    addTypeInfo(Builder.getIpiBuilder(), GlobalIDTable);
1137
85
  } else {
1138
85
    addTypeInfo(Builder.getTpiBuilder(), TypeTable);
1139
85
    addTypeInfo(Builder.getIpiBuilder(), IDTable);
1140
85
  }
1141
87
  T2.stop();
1142
87
1143
87
  ScopedTimer T3(GlobalsLayoutTimer);
1144
87
  // Compute the public and global symbols.
1145
87
  auto &GsiBuilder = Builder.getGsiBuilder();
1146
87
  std::vector<PublicSym32> Publics;
1147
1.08k
  Symtab->forEachSymbol([&Publics](Symbol *S) {
1148
1.08k
    // Only emit defined, live symbols that have a chunk.
1149
1.08k
    auto *Def = dyn_cast<Defined>(S);
1150
1.08k
    if (Def && 
Def->isLive()1.06k
&&
Def->getChunk()1.05k
)
1151
219
      Publics.push_back(createPublic(Def));
1152
1.08k
  });
1153
87
1154
87
  if (!Publics.empty()) {
1155
86
    // Sort the public symbols and add them to the stream.
1156
86
    std::sort(Publics.begin(), Publics.end(),
1157
227
              [](const PublicSym32 &L, const PublicSym32 &R) {
1158
227
                return L.Name < R.Name;
1159
227
              });
1160
86
    for (const PublicSym32 &Pub : Publics)
1161
219
      GsiBuilder.addPublicSymbol(Pub);
1162
86
  }
1163
87
}
1164
1165
87
void PDBLinker::addNatvisFiles() {
1166
87
  for (StringRef File : Config->NatvisFiles) {
1167
0
    ErrorOr<std::unique_ptr<MemoryBuffer>> DataOrErr =
1168
0
        MemoryBuffer::getFile(File);
1169
0
    if (!DataOrErr) {
1170
0
      warn("Cannot open input file: " + File);
1171
0
      continue;
1172
0
    }
1173
0
    Builder.addInjectedSource(File, std::move(*DataOrErr));
1174
0
  }
1175
87
}
1176
1177
87
static codeview::CPUType toCodeViewMachine(COFF::MachineTypes Machine) {
1178
87
  switch (Machine) {
1179
87
  case COFF::IMAGE_FILE_MACHINE_AMD64:
1180
61
    return codeview::CPUType::X64;
1181
87
  case COFF::IMAGE_FILE_MACHINE_ARM:
1182
0
    return codeview::CPUType::ARM7;
1183
87
  case COFF::IMAGE_FILE_MACHINE_ARM64:
1184
0
    return codeview::CPUType::ARM64;
1185
87
  case COFF::IMAGE_FILE_MACHINE_ARMNT:
1186
0
    return codeview::CPUType::ARMNT;
1187
87
  case COFF::IMAGE_FILE_MACHINE_I386:
1188
26
    return codeview::CPUType::Intel80386;
1189
87
  default:
1190
0
    llvm_unreachable("Unsupported CPU Type");
1191
87
  }
1192
87
}
1193
1194
static void addCommonLinkerModuleSymbols(StringRef Path,
1195
                                         pdb::DbiModuleDescriptorBuilder &Mod,
1196
87
                                         BumpPtrAllocator &Allocator) {
1197
87
  ObjNameSym ONS(SymbolRecordKind::ObjNameSym);
1198
87
  Compile3Sym CS(SymbolRecordKind::Compile3Sym);
1199
87
  EnvBlockSym EBS(SymbolRecordKind::EnvBlockSym);
1200
87
1201
87
  ONS.Name = "* Linker *";
1202
87
  ONS.Signature = 0;
1203
87
1204
87
  CS.Machine = toCodeViewMachine(Config->Machine);
1205
87
  // Interestingly, if we set the string to 0.0.0.0, then when trying to view
1206
87
  // local variables WinDbg emits an error that private symbols are not present.
1207
87
  // By setting this to a valid MSVC linker version string, local variables are
1208
87
  // displayed properly.   As such, even though it is not representative of
1209
87
  // LLVM's version information, we need this for compatibility.
1210
87
  CS.Flags = CompileSym3Flags::None;
1211
87
  CS.VersionBackendBuild = 25019;
1212
87
  CS.VersionBackendMajor = 14;
1213
87
  CS.VersionBackendMinor = 10;
1214
87
  CS.VersionBackendQFE = 0;
1215
87
1216
87
  // MSVC also sets the frontend to 0.0.0.0 since this is specifically for the
1217
87
  // linker module (which is by definition a backend), so we don't need to do
1218
87
  // anything here.  Also, it seems we can use "LLVM Linker" for the linker name
1219
87
  // without any problems.  Only the backend version has to be hardcoded to a
1220
87
  // magic number.
1221
87
  CS.VersionFrontendBuild = 0;
1222
87
  CS.VersionFrontendMajor = 0;
1223
87
  CS.VersionFrontendMinor = 0;
1224
87
  CS.VersionFrontendQFE = 0;
1225
87
  CS.Version = "LLVM Linker";
1226
87
  CS.setLanguage(SourceLanguage::Link);
1227
87
1228
87
  ArrayRef<StringRef> Args = makeArrayRef(Config->Argv).drop_front();
1229
87
  std::string ArgStr = llvm::join(Args, " ");
1230
87
  EBS.Fields.push_back("cwd");
1231
87
  SmallString<64> cwd;
1232
87
  if (Config->PDBSourcePath.empty()) 
1233
85
    sys::fs::current_path(cwd);
1234
2
  else
1235
2
    cwd = Config->PDBSourcePath;
1236
87
  EBS.Fields.push_back(cwd);
1237
87
  EBS.Fields.push_back("exe");
1238
87
  SmallString<64> exe = Config->Argv[0];
1239
87
  pdbMakeAbsolute(exe);
1240
87
  EBS.Fields.push_back(exe);
1241
87
  EBS.Fields.push_back("pdb");
1242
87
  EBS.Fields.push_back(Path);
1243
87
  EBS.Fields.push_back("cmd");
1244
87
  EBS.Fields.push_back(ArgStr);
1245
87
  Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1246
87
      ONS, Allocator, CodeViewContainer::Pdb));
1247
87
  Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1248
87
      CS, Allocator, CodeViewContainer::Pdb));
1249
87
  Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1250
87
      EBS, Allocator, CodeViewContainer::Pdb));
1251
87
}
1252
1253
static void addLinkerModuleSectionSymbol(pdb::DbiModuleDescriptorBuilder &Mod,
1254
                                         OutputSection &OS,
1255
220
                                         BumpPtrAllocator &Allocator) {
1256
220
  SectionSym Sym(SymbolRecordKind::SectionSym);
1257
220
  Sym.Alignment = 12; // 2^12 = 4KB
1258
220
  Sym.Characteristics = OS.Header.Characteristics;
1259
220
  Sym.Length = OS.getVirtualSize();
1260
220
  Sym.Name = OS.Name;
1261
220
  Sym.Rva = OS.getRVA();
1262
220
  Sym.SectionNumber = OS.SectionIndex;
1263
220
  Mod.addSymbol(codeview::SymbolSerializer::writeOneSymbol(
1264
220
      Sym, Allocator, CodeViewContainer::Pdb));
1265
220
}
1266
1267
// Creates a PDB file.
1268
void coff::createPDB(SymbolTable *Symtab,
1269
                     ArrayRef<OutputSection *> OutputSections,
1270
                     ArrayRef<uint8_t> SectionTable,
1271
87
                     llvm::codeview::DebugInfo *BuildId) {
1272
87
  ScopedTimer T1(TotalPdbLinkTimer);
1273
87
  PDBLinker PDB(Symtab);
1274
87
1275
87
  PDB.initialize(BuildId);
1276
87
  PDB.addObjectsToPDB();
1277
87
  PDB.addSections(OutputSections, SectionTable);
1278
87
  PDB.addNatvisFiles();
1279
87
1280
87
  ScopedTimer T2(DiskCommitTimer);
1281
87
  codeview::GUID Guid;
1282
87
  PDB.commit(&Guid);
1283
87
  memcpy(&BuildId->PDB70.Signature, &Guid, 16);
1284
87
}
1285
1286
87
void PDBLinker::initialize(llvm::codeview::DebugInfo *BuildId) {
1287
87
  ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
1288
87
1289
87
  BuildId->Signature.CVSignature = OMF::Signature::PDB70;
1290
87
  // Signature is set to a hash of the PDB contents when the PDB is done.
1291
87
  memset(BuildId->PDB70.Signature, 0, 16);
1292
87
  BuildId->PDB70.Age = 1;
1293
87
1294
87
  // Create streams in MSF for predefined streams, namely
1295
87
  // PDB, TPI, DBI and IPI.
1296
522
  for (int I = 0; I < (int)pdb::kSpecialStreamCount; 
++I435
)
1297
435
    ExitOnErr(Builder.getMsfBuilder().addStream(0));
1298
87
1299
87
  // Add an Info stream.
1300
87
  auto &InfoBuilder = Builder.getInfoBuilder();
1301
87
  InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
1302
87
  InfoBuilder.setHashPDBContentsToGUID(true);
1303
87
1304
87
  // Add an empty DBI stream.
1305
87
  pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
1306
87
  DbiBuilder.setAge(BuildId->PDB70.Age);
1307
87
  DbiBuilder.setVersionHeader(pdb::PdbDbiV70);
1308
87
  DbiBuilder.setMachineType(Config->Machine);
1309
87
  // Technically we are not link.exe 14.11, but there are known cases where
1310
87
  // debugging tools on Windows expect Microsoft-specific version numbers or
1311
87
  // they fail to work at all.  Since we know we produce PDBs that are
1312
87
  // compatible with LINK 14.11, we set that version number here.
1313
87
  DbiBuilder.setBuildNumber(14, 11);
1314
87
}
1315
1316
void PDBLinker::addSections(ArrayRef<OutputSection *> OutputSections,
1317
87
                            ArrayRef<uint8_t> SectionTable) {
1318
87
  // It's not entirely clear what this is, but the * Linker * module uses it.
1319
87
  pdb::DbiStreamBuilder &DbiBuilder = Builder.getDbiBuilder();
1320
87
  NativePath = Config->PDBPath;
1321
87
  pdbMakeAbsolute(NativePath);
1322
87
  uint32_t PdbFilePathNI = DbiBuilder.addECName(NativePath);
1323
87
  auto &LinkerModule = ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
1324
87
  LinkerModule.setPdbFilePathNI(PdbFilePathNI);
1325
87
  addCommonLinkerModuleSymbols(NativePath, LinkerModule, Alloc);
1326
87
1327
87
  // Add section contributions. They must be ordered by ascending RVA.
1328
220
  for (OutputSection *OS : OutputSections) {
1329
220
    addLinkerModuleSectionSymbol(LinkerModule, *OS, Alloc);
1330
542
    for (Chunk *C : OS->Chunks) {
1331
542
      pdb::SectionContrib SC =
1332
542
          createSectionContrib(C, LinkerModule.getModuleIndex());
1333
542
      Builder.getDbiBuilder().addSectionContrib(SC);
1334
542
    }
1335
220
  }
1336
87
1337
87
  // Add Section Map stream.
1338
87
  ArrayRef<object::coff_section> Sections = {
1339
87
      (const object::coff_section *)SectionTable.data(),
1340
87
      SectionTable.size() / sizeof(object::coff_section)};
1341
87
  SectionMap = pdb::DbiStreamBuilder::createSectionMap(Sections);
1342
87
  DbiBuilder.setSectionMap(SectionMap);
1343
87
1344
87
  // Add COFF section header stream.
1345
87
  ExitOnErr(
1346
87
      DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
1347
87
}
1348
1349
87
void PDBLinker::commit(codeview::GUID *Guid) {
1350
87
  // Write to a file.
1351
87
  ExitOnErr(Builder.commit(Config->PDBPath, Guid));
1352
87
}
1353
1354
static Expected<StringRef>
1355
getFileName(const DebugStringTableSubsectionRef &Strings,
1356
5
            const DebugChecksumsSubsectionRef &Checksums, uint32_t FileID) {
1357
5
  auto Iter = Checksums.getArray().at(FileID);
1358
5
  if (Iter == Checksums.getArray().end())
1359
0
    return make_error<CodeViewError>(cv_error_code::no_records);
1360
5
  uint32_t Offset = Iter->FileNameOffset;
1361
5
  return Strings.getString(Offset);
1362
5
}
1363
1364
19
static uint32_t getSecrelReloc() {
1365
19
  switch (Config->Machine) {
1366
19
  case AMD64:
1367
19
    return COFF::IMAGE_REL_AMD64_SECREL;
1368
19
  case I386:
1369
0
    return COFF::IMAGE_REL_I386_SECREL;
1370
19
  case ARMNT:
1371
0
    return COFF::IMAGE_REL_ARM_SECREL;
1372
19
  case ARM64:
1373
0
    return COFF::IMAGE_REL_ARM64_SECREL;
1374
19
  default:
1375
0
    llvm_unreachable("unknown machine type");
1376
19
  }
1377
19
}
1378
1379
// Try to find a line table for the given offset Addr into the given chunk C.
1380
// If a line table was found, the line table, the string and checksum tables
1381
// that are used to interpret the line table, and the offset of Addr in the line
1382
// table are stored in the output arguments. Returns whether a line table was
1383
// found.
1384
static bool findLineTable(const SectionChunk *C, uint32_t Addr,
1385
                          DebugStringTableSubsectionRef &CVStrTab,
1386
                          DebugChecksumsSubsectionRef &Checksums,
1387
                          DebugLinesSubsectionRef &Lines,
1388
19
                          uint32_t &OffsetInLinetable) {
1389
19
  ExitOnError ExitOnErr;
1390
19
  uint32_t SecrelReloc = getSecrelReloc();
1391
19
1392
19
  for (SectionChunk *DbgC : C->File->getDebugChunks()) {
1393
17
    if (DbgC->getSectionName() != ".debug$S")
1394
0
      continue;
1395
17
1396
17
    // Build a mapping of SECREL relocations in DbgC that refer to C.
1397
17
    DenseMap<uint32_t, uint32_t> Secrels;
1398
22
    for (const coff_relocation &R : DbgC->Relocs) {
1399
22
      if (R.Type != SecrelReloc)
1400
11
        continue;
1401
11
1402
11
      if (auto *S = dyn_cast_or_null<DefinedRegular>(
1403
11
              C->File->getSymbols()[R.SymbolTableIndex]))
1404
11
        if (S->getChunk() == C)
1405
9
          Secrels[R.VirtualAddress] = S->getValue();
1406
11
    }
1407
17
1408
17
    ArrayRef<uint8_t> Contents =
1409
17
        consumeDebugMagic(DbgC->getContents(), ".debug$S");
1410
17
    DebugSubsectionArray Subsections;
1411
17
    BinaryStreamReader Reader(Contents, support::little);
1412
17
    ExitOnErr(Reader.readArray(Subsections, Contents.size()));
1413
17
1414
24
    for (const DebugSubsectionRecord &SS : Subsections) {
1415
24
      switch (SS.kind()) {
1416
24
      case DebugSubsectionKind::StringTable: {
1417
5
        assert(!CVStrTab.valid() &&
1418
5
               "Encountered multiple string table subsections!");
1419
5
        ExitOnErr(CVStrTab.initialize(SS.getRecordData()));
1420
5
        break;
1421
24
      }
1422
24
      case DebugSubsectionKind::FileChecksums:
1423
5
        assert(!Checksums.valid() &&
1424
5
               "Encountered multiple checksum subsections!");
1425
5
        ExitOnErr(Checksums.initialize(SS.getRecordData()));
1426
5
        break;
1427
24
      case DebugSubsectionKind::Lines: {
1428
8
        ArrayRef<uint8_t> Bytes;
1429
8
        auto Ref = SS.getRecordData();
1430
8
        ExitOnErr(Ref.readLongestContiguousChunk(0, Bytes));
1431
8
        size_t OffsetInDbgC = Bytes.data() - DbgC->getContents().data();
1432
8
1433
8
        // Check whether this line table refers to C.
1434
8
        auto I = Secrels.find(OffsetInDbgC);
1435
8
        if (I == Secrels.end())
1436
2
          break;
1437
6
1438
6
        // Check whether this line table covers Addr in C.
1439
6
        DebugLinesSubsectionRef LinesTmp;
1440
6
        ExitOnErr(LinesTmp.initialize(BinaryStreamReader(Ref)));
1441
6
        uint32_t OffsetInC = I->second + LinesTmp.header()->RelocOffset;
1442
6
        if (Addr < OffsetInC || Addr >= OffsetInC + LinesTmp.header()->CodeSize)
1443
1
          break;
1444
5
1445
5
        assert(!Lines.header() &&
1446
5
               "Encountered multiple line tables for function!");
1447
5
        ExitOnErr(Lines.initialize(BinaryStreamReader(Ref)));
1448
5
        OffsetInLinetable = Addr - OffsetInC;
1449
5
        break;
1450
5
      }
1451
6
      default:
1452
6
        break;
1453
24
      }
1454
24
1455
24
      if (CVStrTab.valid() && 
Checksums.valid()13
&&
Lines.header()13
)
1456
5
        return true;
1457
24
    }
1458
17
  }
1459
19
1460
19
  
return false14
;
1461
19
}
1462
1463
// Use CodeView line tables to resolve a file and line number for the given
1464
// offset into the given chunk and return them, or {"", 0} if a line table was
1465
// not found.
1466
std::pair<StringRef, uint32_t> coff::getFileLine(const SectionChunk *C,
1467
19
                                                 uint32_t Addr) {
1468
19
  ExitOnError ExitOnErr;
1469
19
1470
19
  DebugStringTableSubsectionRef CVStrTab;
1471
19
  DebugChecksumsSubsectionRef Checksums;
1472
19
  DebugLinesSubsectionRef Lines;
1473
19
  uint32_t OffsetInLinetable;
1474
19
1475
19
  if (!findLineTable(C, Addr, CVStrTab, Checksums, Lines, OffsetInLinetable))
1476
14
    return {"", 0};
1477
5
1478
5
  uint32_t NameIndex;
1479
5
  uint32_t LineNumber;
1480
7
  for (LineColumnEntry &Entry : Lines) {
1481
10
    for (const LineNumberEntry &LN : Entry.LineNumbers) {
1482
10
      if (LN.Offset > OffsetInLinetable) {
1483
2
        StringRef Filename =
1484
2
            ExitOnErr(getFileName(CVStrTab, Checksums, NameIndex));
1485
2
        return {Filename, LineNumber};
1486
2
      }
1487
8
      LineInfo LI(LN.Flags);
1488
8
      NameIndex = Entry.NameIndex;
1489
8
      LineNumber = LI.getStartLine();
1490
8
    }
1491
7
  }
1492
5
  StringRef Filename = ExitOnErr(getFileName(CVStrTab, Checksums, NameIndex));
1493
3
  return {Filename, LineNumber};
1494
5
}