Coverage Report

Created: 2019-07-24 05:18

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