-
Notifications
You must be signed in to change notification settings - Fork 17k
Expand file tree
/
Copy pathPDB.cpp
More file actions
1879 lines (1642 loc) · 70.4 KB
/
PDB.cpp
File metadata and controls
1879 lines (1642 loc) · 70.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- PDB.cpp ------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "PDB.h"
#include "COFFLinkerContext.h"
#include "Chunks.h"
#include "Config.h"
#include "DebugTypes.h"
#include "Driver.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "TypeMerger.h"
#include "Writer.h"
#include "lld/Common/Timer.h"
#include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
#include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
#include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"
#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
#include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
#include "llvm/DebugInfo/CodeView/RecordName.h"
#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
#include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h"
#include "llvm/DebugInfo/CodeView/SymbolSerializer.h"
#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
#include "llvm/DebugInfo/MSF/MSFBuilder.h"
#include "llvm/DebugInfo/MSF/MSFCommon.h"
#include "llvm/DebugInfo/MSF/MSFError.h"
#include "llvm/DebugInfo/PDB/GenericError.h"
#include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
#include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
#include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h"
#include "llvm/DebugInfo/PDB/Native/InfoStream.h"
#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
#include "llvm/DebugInfo/PDB/Native/NativeSession.h"
#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
#include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
#include "llvm/DebugInfo/PDB/PDB.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/CVDebugRecord.h"
#include "llvm/Support/BinaryByteStream.h"
#include "llvm/Support/CRC.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/FormatAdapters.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/ScopedPrinter.h"
#include "llvm/Support/TimeProfiler.h"
#include <memory>
#include <optional>
using namespace llvm;
using namespace llvm::codeview;
using namespace lld;
using namespace lld::coff;
using llvm::object::coff_section;
using llvm::pdb::StringTableFixup;
namespace {
class DebugSHandler;
class PDBLinker {
friend DebugSHandler;
public:
PDBLinker(COFFLinkerContext &ctx)
: builder(bAlloc()), tMerger(ctx, bAlloc()), ctx(ctx) {
// This isn't strictly necessary, but link.exe usually puts an empty string
// as the first "valid" string in the string table, so we do the same in
// order to maintain as much byte-for-byte compatibility as possible.
pdbStrTab.insert("");
}
/// Emit the basic PDB structure: initial streams, headers, etc.
void initialize(llvm::codeview::DebugInfo *buildId);
/// Add natvis files specified on the command line.
void addNatvisFiles();
/// Add named streams specified on the command line.
void addNamedStreams();
/// Link CodeView from each object file in the symbol table into the PDB.
void addObjectsToPDB();
/// Add every live, defined public symbol to the PDB.
void addPublicsToPDB();
/// Link info for each import file in the symbol table into the PDB.
void addImportFilesToPDB();
void createModuleDBI(ObjFile *file);
/// Link CodeView from a single object file into the target (output) PDB.
/// When a precompiled headers object is linked, its TPI map might be provided
/// externally.
void addDebug(TpiSource *source);
void addDebugSymbols(TpiSource *source);
// Analyze the symbol records to separate module symbols from global symbols,
// find string references, and calculate how large the symbol stream will be
// in the PDB.
void analyzeSymbolSubsection(SectionChunk *debugChunk,
uint32_t &moduleSymOffset,
uint32_t &nextRelocIndex,
std::vector<StringTableFixup> &stringTableFixups,
BinaryStreamRef symData);
// Write all module symbols from all live debug symbol subsections of the
// given object file into the given stream writer.
Error writeAllModuleSymbolRecords(ObjFile *file, BinaryStreamWriter &writer);
// Callback to copy and relocate debug symbols during PDB file writing.
static Error commitSymbolsForObject(void *ctx, void *obj,
BinaryStreamWriter &writer);
// Copy the symbol record, relocate it, and fix the alignment if necessary.
// Rewrite type indices in the record. Replace unrecognized symbol records
// with S_SKIP records.
void writeSymbolRecord(SectionChunk *debugChunk,
ArrayRef<uint8_t> sectionContents, CVSymbol sym,
size_t alignedSize, uint32_t &nextRelocIndex,
std::vector<uint8_t> &storage);
/// Add the section map and section contributions to the PDB.
void addSections(ArrayRef<uint8_t> sectionTable);
/// Write the PDB to disk and store the Guid generated for it in *Guid.
void commit(codeview::GUID *guid);
// Print statistics regarding the final PDB
void printStats();
private:
void pdbMakeAbsolute(SmallVectorImpl<char> &fileName);
void translateIdSymbols(MutableArrayRef<uint8_t> &recordData,
TpiSource *source);
void addCommonLinkerModuleSymbols(StringRef path,
pdb::DbiModuleDescriptorBuilder &mod);
pdb::PDBFileBuilder builder;
TypeMerger tMerger;
COFFLinkerContext &ctx;
/// PDBs use a single global string table for filenames in the file checksum
/// table.
DebugStringTableSubsection pdbStrTab;
llvm::SmallString<128> nativePath;
// For statistics
uint64_t globalSymbols = 0;
uint64_t moduleSymbols = 0;
uint64_t publicSymbols = 0;
uint64_t nbTypeRecords = 0;
uint64_t nbTypeRecordsBytes = 0;
};
/// Represents an unrelocated DEBUG_S_FRAMEDATA subsection.
struct UnrelocatedFpoData {
SectionChunk *debugChunk = nullptr;
ArrayRef<uint8_t> subsecData;
uint32_t relocIndex = 0;
};
/// The size of the magic bytes at the beginning of a symbol section or stream.
enum : uint32_t { kSymbolStreamMagicSize = 4 };
class DebugSHandler {
COFFLinkerContext &ctx;
PDBLinker &linker;
/// The object file whose .debug$S sections we're processing.
ObjFile &file;
/// The DEBUG_S_STRINGTABLE subsection. These strings are referred to by
/// index from other records in the .debug$S section. All of these strings
/// need to be added to the global PDB string table, and all references to
/// these strings need to have their indices re-written to refer to the
/// global PDB string table.
DebugStringTableSubsectionRef cvStrTab;
/// The DEBUG_S_FILECHKSMS subsection. As above, these are referred to
/// by other records in the .debug$S section and need to be merged into the
/// PDB.
DebugChecksumsSubsectionRef checksums;
/// The DEBUG_S_FRAMEDATA subsection(s). There can be more than one of
/// these and they need not appear in any specific order. However, they
/// contain string table references which need to be re-written, so we
/// collect them all here and re-write them after all subsections have been
/// discovered and processed.
std::vector<UnrelocatedFpoData> frameDataSubsecs;
/// List of string table references in symbol records. Later they will be
/// applied to the symbols during PDB writing.
std::vector<StringTableFixup> stringTableFixups;
/// Sum of the size of all module symbol records across all .debug$S sections.
/// Includes record realignment and the size of the symbol stream magic
/// prefix.
uint32_t moduleStreamSize = kSymbolStreamMagicSize;
/// Next relocation index in the current .debug$S section. Resets every
/// handleDebugS call.
uint32_t nextRelocIndex = 0;
void advanceRelocIndex(SectionChunk *debugChunk, ArrayRef<uint8_t> subsec);
void addUnrelocatedSubsection(SectionChunk *debugChunk,
const DebugSubsectionRecord &ss);
void addFrameDataSubsection(SectionChunk *debugChunk,
const DebugSubsectionRecord &ss);
public:
DebugSHandler(COFFLinkerContext &ctx, PDBLinker &linker, ObjFile &file)
: ctx(ctx), linker(linker), file(file) {}
void handleDebugS(SectionChunk *debugChunk);
void finish();
};
}
// Visual Studio's debugger requires absolute paths in various places in the
// PDB to work without additional configuration:
// https://docs.microsoft.com/en-us/visualstudio/debugger/debug-source-files-common-properties-solution-property-pages-dialog-box
void PDBLinker::pdbMakeAbsolute(SmallVectorImpl<char> &fileName) {
// The default behavior is to produce paths that are valid within the context
// of the machine that you perform the link on. If the linker is running on
// a POSIX system, we will output absolute POSIX paths. If the linker is
// running on a Windows system, we will output absolute Windows paths. If the
// user desires any other kind of behavior, they should explicitly pass
// /pdbsourcepath, in which case we will treat the exact string the user
// passed in as the gospel and not normalize, canonicalize it.
if (sys::path::is_absolute(fileName, sys::path::Style::windows) ||
sys::path::is_absolute(fileName, sys::path::Style::posix))
return;
// It's not absolute in any path syntax. Relative paths necessarily refer to
// the local file system, so we can make it native without ending up with a
// nonsensical path.
if (ctx.config.pdbSourcePath.empty()) {
sys::path::native(fileName);
sys::fs::make_absolute(fileName);
sys::path::remove_dots(fileName, true);
return;
}
// Try to guess whether /PDBSOURCEPATH is a unix path or a windows path.
// Since PDB's are more of a Windows thing, we make this conservative and only
// decide that it's a unix path if we're fairly certain. Specifically, if
// it starts with a forward slash.
SmallString<128> absoluteFileName = ctx.config.pdbSourcePath;
sys::path::Style guessedStyle = absoluteFileName.starts_with("/")
? sys::path::Style::posix
: sys::path::Style::windows;
sys::path::append(absoluteFileName, guessedStyle, fileName);
sys::path::native(absoluteFileName, guessedStyle);
sys::path::remove_dots(absoluteFileName, true, guessedStyle);
fileName = std::move(absoluteFileName);
}
static void addTypeInfo(pdb::TpiStreamBuilder &tpiBuilder,
TypeCollection &typeTable) {
// Start the TPI or IPI stream header.
tpiBuilder.setVersionHeader(pdb::PdbTpiV80);
// Flatten the in memory type table and hash each type.
typeTable.ForEachRecord([&](TypeIndex ti, const CVType &type) {
auto hash = pdb::hashTypeRecord(type);
if (auto e = hash.takeError())
fatal("type hashing error");
tpiBuilder.addTypeRecord(type.RecordData, *hash);
});
}
static void addGHashTypeInfo(COFFLinkerContext &ctx,
pdb::PDBFileBuilder &builder) {
// Start the TPI or IPI stream header.
builder.getTpiBuilder().setVersionHeader(pdb::PdbTpiV80);
builder.getIpiBuilder().setVersionHeader(pdb::PdbTpiV80);
for (TpiSource *source : ctx.tpiSourceList) {
builder.getTpiBuilder().addTypeRecords(source->mergedTpi.recs,
source->mergedTpi.recSizes,
source->mergedTpi.recHashes);
builder.getIpiBuilder().addTypeRecords(source->mergedIpi.recs,
source->mergedIpi.recSizes,
source->mergedIpi.recHashes);
}
}
static void
recordStringTableReferences(CVSymbol sym, uint32_t symOffset,
std::vector<StringTableFixup> &stringTableFixups) {
// For now we only handle S_FILESTATIC, but we may need the same logic for
// S_DEFRANGE and S_DEFRANGE_SUBFIELD. However, I cannot seem to generate any
// PDBs that contain these types of records, so because of the uncertainty
// they are omitted here until we can prove that it's necessary.
switch (sym.kind()) {
case SymbolKind::S_FILESTATIC: {
// FileStaticSym::ModFileOffset
uint32_t ref = *reinterpret_cast<const ulittle32_t *>(&sym.data()[8]);
stringTableFixups.push_back({ref, symOffset + 8});
break;
}
case SymbolKind::S_DEFRANGE:
case SymbolKind::S_DEFRANGE_SUBFIELD:
log("Not fixing up string table reference in S_DEFRANGE / "
"S_DEFRANGE_SUBFIELD record");
break;
default:
break;
}
}
static SymbolKind symbolKind(ArrayRef<uint8_t> recordData) {
const RecordPrefix *prefix =
reinterpret_cast<const RecordPrefix *>(recordData.data());
return static_cast<SymbolKind>(uint16_t(prefix->RecordKind));
}
/// MSVC translates S_PROC_ID_END to S_END, and S_[LG]PROC32_ID to S_[LG]PROC32
void PDBLinker::translateIdSymbols(MutableArrayRef<uint8_t> &recordData,
TpiSource *source) {
RecordPrefix *prefix = reinterpret_cast<RecordPrefix *>(recordData.data());
SymbolKind kind = symbolKind(recordData);
if (kind == SymbolKind::S_PROC_ID_END) {
prefix->RecordKind = SymbolKind::S_END;
return;
}
// In an object file, GPROC32_ID has an embedded reference which refers to the
// single object file type index namespace. This has already been translated
// to the PDB file's ID stream index space, but we need to convert this to a
// symbol that refers to the type stream index space. So we remap again from
// ID index space to type index space.
if (kind == SymbolKind::S_GPROC32_ID || kind == SymbolKind::S_LPROC32_ID) {
SmallVector<TiReference, 1> refs;
auto content = recordData.drop_front(sizeof(RecordPrefix));
CVSymbol sym(recordData);
discoverTypeIndicesInSymbol(sym, refs);
assert(refs.size() == 1);
assert(refs.front().Count == 1);
TypeIndex *ti =
reinterpret_cast<TypeIndex *>(content.data() + refs[0].Offset);
// `ti` is the index of a FuncIdRecord or MemberFuncIdRecord which lives in
// the IPI stream, whose `FunctionType` member refers to the TPI stream.
// Note that LF_FUNC_ID and LF_MFUNC_ID have the same record layout, and
// in both cases we just need the second type index.
if (!ti->isSimple() && !ti->isNoneType()) {
TypeIndex newType = TypeIndex(SimpleTypeKind::NotTranslated);
if (ctx.config.debugGHashes) {
auto idToType = tMerger.funcIdToType.find(*ti);
if (idToType != tMerger.funcIdToType.end())
newType = idToType->second;
} else {
if (tMerger.getIDTable().contains(*ti)) {
CVType funcIdData = tMerger.getIDTable().getType(*ti);
if (funcIdData.length() >= 8 && (funcIdData.kind() == LF_FUNC_ID ||
funcIdData.kind() == LF_MFUNC_ID)) {
newType = *reinterpret_cast<const TypeIndex *>(&funcIdData.data()[8]);
}
}
}
if (newType == TypeIndex(SimpleTypeKind::NotTranslated)) {
Warn(ctx) << formatv(
"procedure symbol record for `{0}` in {1} refers to PDB "
"item index {2:X} which is not a valid function ID record",
getSymbolName(CVSymbol(recordData)), source->file->getName(),
ti->getIndex());
}
*ti = newType;
}
kind = (kind == SymbolKind::S_GPROC32_ID) ? SymbolKind::S_GPROC32
: SymbolKind::S_LPROC32;
prefix->RecordKind = uint16_t(kind);
}
}
namespace {
struct ScopeRecord {
ulittle32_t ptrParent;
ulittle32_t ptrEnd;
};
} // namespace
/// Given a pointer to a symbol record that opens a scope, return a pointer to
/// the scope fields.
static ScopeRecord *getSymbolScopeFields(void *sym) {
return reinterpret_cast<ScopeRecord *>(reinterpret_cast<char *>(sym) +
sizeof(RecordPrefix));
}
// To open a scope, push the offset of the current symbol record onto the
// stack.
static void scopeStackOpen(SmallVectorImpl<uint32_t> &stack,
std::vector<uint8_t> &storage) {
stack.push_back(storage.size());
}
// To close a scope, update the record that opened the scope.
static void scopeStackClose(COFFLinkerContext &ctx,
SmallVectorImpl<uint32_t> &stack,
std::vector<uint8_t> &storage,
uint32_t storageBaseOffset, ObjFile *file) {
if (stack.empty()) {
Warn(ctx) << "symbol scopes are not balanced in " << file->getName();
return;
}
// Update ptrEnd of the record that opened the scope to point to the
// current record, if we are writing into the module symbol stream.
uint32_t offOpen = stack.pop_back_val();
uint32_t offEnd = storageBaseOffset + storage.size();
uint32_t offParent = stack.empty() ? 0 : (stack.back() + storageBaseOffset);
ScopeRecord *scopeRec = getSymbolScopeFields(&(storage)[offOpen]);
scopeRec->ptrParent = offParent;
scopeRec->ptrEnd = offEnd;
}
static bool symbolGoesInModuleStream(const CVSymbol &sym,
unsigned symbolScopeDepth) {
switch (sym.kind()) {
case SymbolKind::S_GDATA32:
case SymbolKind::S_GTHREAD32:
// We really should not be seeing S_PROCREF and S_LPROCREF in the first place
// since they are synthesized by the linker in response to S_GPROC32 and
// S_LPROC32, but if we do see them, don't put them in the module stream I
// guess.
case SymbolKind::S_PROCREF:
case SymbolKind::S_LPROCREF:
return false;
// S_UDT and S_CONSTANT records go in the module stream if it is not a global record.
case SymbolKind::S_UDT:
case SymbolKind::S_CONSTANT:
return symbolScopeDepth > 0;
// S_GDATA32 does not go in the module stream, but S_LDATA32 does.
case SymbolKind::S_LDATA32:
case SymbolKind::S_LTHREAD32:
default:
return true;
}
}
static bool symbolGoesInGlobalsStream(const CVSymbol &sym,
unsigned symbolScopeDepth) {
switch (sym.kind()) {
case SymbolKind::S_GDATA32:
case SymbolKind::S_GTHREAD32:
case SymbolKind::S_GPROC32:
case SymbolKind::S_LPROC32:
case SymbolKind::S_GPROC32_ID:
case SymbolKind::S_LPROC32_ID:
// We really should not be seeing S_PROCREF and S_LPROCREF in the first place
// since they are synthesized by the linker in response to S_GPROC32 and
// S_LPROC32, but if we do see them, copy them straight through.
case SymbolKind::S_PROCREF:
case SymbolKind::S_LPROCREF:
return true;
// Records that go in the globals stream, unless they are function-local.
case SymbolKind::S_UDT:
case SymbolKind::S_LDATA32:
case SymbolKind::S_LTHREAD32:
case SymbolKind::S_CONSTANT:
return symbolScopeDepth == 0;
default:
return false;
}
}
static void addGlobalSymbol(pdb::GSIStreamBuilder &builder, uint16_t modIndex,
unsigned symOffset,
std::vector<uint8_t> &symStorage) {
CVSymbol sym{ArrayRef(symStorage)};
switch (sym.kind()) {
case SymbolKind::S_CONSTANT:
case SymbolKind::S_UDT:
case SymbolKind::S_GDATA32:
case SymbolKind::S_GTHREAD32:
case SymbolKind::S_LTHREAD32:
case SymbolKind::S_LDATA32:
case SymbolKind::S_PROCREF:
case SymbolKind::S_LPROCREF: {
// sym is a temporary object, so we have to copy and reallocate the record
// to stabilize it.
uint8_t *mem = bAlloc().Allocate<uint8_t>(sym.length());
memcpy(mem, sym.data().data(), sym.length());
builder.addGlobalSymbol(CVSymbol(ArrayRef(mem, sym.length())));
break;
}
case SymbolKind::S_GPROC32:
case SymbolKind::S_LPROC32: {
SymbolRecordKind k = SymbolRecordKind::ProcRefSym;
if (sym.kind() == SymbolKind::S_LPROC32)
k = SymbolRecordKind::LocalProcRef;
ProcRefSym ps(k);
ps.Module = modIndex;
// For some reason, MSVC seems to add one to this value.
++ps.Module;
ps.Name = getSymbolName(sym);
ps.SumName = 0;
ps.SymOffset = symOffset;
builder.addGlobalSymbol(ps);
break;
}
default:
llvm_unreachable("Invalid symbol kind!");
}
}
// Check if the given symbol record was padded for alignment. If so, zero out
// the padding bytes and update the record prefix with the new size.
static void fixRecordAlignment(MutableArrayRef<uint8_t> recordBytes,
size_t oldSize) {
size_t alignedSize = recordBytes.size();
if (oldSize == alignedSize)
return;
reinterpret_cast<RecordPrefix *>(recordBytes.data())->RecordLen =
alignedSize - 2;
memset(recordBytes.data() + oldSize, 0, alignedSize - oldSize);
}
// Replace any record with a skip record of the same size. This is useful when
// we have reserved size for a symbol record, but type index remapping fails.
static void replaceWithSkipRecord(MutableArrayRef<uint8_t> recordBytes) {
memset(recordBytes.data(), 0, recordBytes.size());
auto *prefix = reinterpret_cast<RecordPrefix *>(recordBytes.data());
prefix->RecordKind = SymbolKind::S_SKIP;
prefix->RecordLen = recordBytes.size() - 2;
}
// Copy the symbol record, relocate it, and fix the alignment if necessary.
// Rewrite type indices in the record. Replace unrecognized symbol records with
// S_SKIP records.
void PDBLinker::writeSymbolRecord(SectionChunk *debugChunk,
ArrayRef<uint8_t> sectionContents,
CVSymbol sym, size_t alignedSize,
uint32_t &nextRelocIndex,
std::vector<uint8_t> &storage) {
// Allocate space for the new record at the end of the storage.
storage.resize(storage.size() + alignedSize);
auto recordBytes = MutableArrayRef<uint8_t>(storage).take_back(alignedSize);
// Copy the symbol record and relocate it.
debugChunk->writeAndRelocateSubsection(sectionContents, sym.data(),
nextRelocIndex, recordBytes.data());
fixRecordAlignment(recordBytes, sym.length());
// Re-map all the type index references.
TpiSource *source = debugChunk->file->debugTypesObj;
if (!source->remapTypesInSymbolRecord(recordBytes)) {
Log(ctx) << "ignoring unknown symbol record with kind 0x"
<< utohexstr(sym.kind());
replaceWithSkipRecord(recordBytes);
}
// An object file may have S_xxx_ID symbols, but these get converted to
// "real" symbols in a PDB.
translateIdSymbols(recordBytes, source);
}
void PDBLinker::analyzeSymbolSubsection(
SectionChunk *debugChunk, uint32_t &moduleSymOffset,
uint32_t &nextRelocIndex, std::vector<StringTableFixup> &stringTableFixups,
BinaryStreamRef symData) {
ObjFile *file = debugChunk->file;
uint32_t moduleSymStart = moduleSymOffset;
uint32_t scopeLevel = 0;
std::vector<uint8_t> storage;
ArrayRef<uint8_t> sectionContents = debugChunk->getContents();
ArrayRef<uint8_t> symsBuffer;
cantFail(symData.readBytes(0, symData.getLength(), symsBuffer));
if (symsBuffer.empty())
Warn(ctx) << "empty symbols subsection in " << file->getName();
Error ec = forEachCodeViewRecord<CVSymbol>(
symsBuffer, [&](CVSymbol sym) -> llvm::Error {
// Track the current scope.
if (symbolOpensScope(sym.kind()))
++scopeLevel;
else if (symbolEndsScope(sym.kind()))
--scopeLevel;
uint32_t alignedSize =
alignTo(sym.length(), alignOf(CodeViewContainer::Pdb));
// Copy global records. Some global records (mainly procedures)
// reference the current offset into the module stream.
if (symbolGoesInGlobalsStream(sym, scopeLevel)) {
storage.clear();
writeSymbolRecord(debugChunk, sectionContents, sym, alignedSize,
nextRelocIndex, storage);
addGlobalSymbol(builder.getGsiBuilder(),
file->moduleDBI->getModuleIndex(), moduleSymOffset,
storage);
++globalSymbols;
}
// Update the module stream offset and record any string table index
// references. There are very few of these and they will be rewritten
// later during PDB writing.
if (symbolGoesInModuleStream(sym, scopeLevel)) {
recordStringTableReferences(sym, moduleSymOffset, stringTableFixups);
moduleSymOffset += alignedSize;
++moduleSymbols;
}
return Error::success();
});
// If we encountered corrupt records, ignore the whole subsection. If we wrote
// any partial records, undo that. For globals, we just keep what we have and
// continue.
if (ec) {
Warn(ctx) << "corrupt symbol records in " << file->getName();
moduleSymOffset = moduleSymStart;
consumeError(std::move(ec));
}
}
Error PDBLinker::writeAllModuleSymbolRecords(ObjFile *file,
BinaryStreamWriter &writer) {
ExitOnError exitOnErr;
std::vector<uint8_t> storage;
SmallVector<uint32_t, 4> scopes;
// Visit all live .debug$S sections a second time, and write them to the PDB.
for (SectionChunk *debugChunk : file->getDebugChunks()) {
if (!debugChunk->live || debugChunk->getSize() == 0 ||
debugChunk->getSectionName() != ".debug$S")
continue;
ArrayRef<uint8_t> sectionContents = debugChunk->getContents();
auto contents =
SectionChunk::consumeDebugMagic(sectionContents, ".debug$S");
DebugSubsectionArray subsections;
BinaryStreamReader reader(contents, llvm::endianness::little);
exitOnErr(reader.readArray(subsections, contents.size()));
uint32_t nextRelocIndex = 0;
for (const DebugSubsectionRecord &ss : subsections) {
if (ss.kind() != DebugSubsectionKind::Symbols)
continue;
uint32_t moduleSymStart = writer.getOffset();
scopes.clear();
storage.clear();
ArrayRef<uint8_t> symsBuffer;
BinaryStreamRef sr = ss.getRecordData();
cantFail(sr.readBytes(0, sr.getLength(), symsBuffer));
auto ec = forEachCodeViewRecord<CVSymbol>(
symsBuffer, [&](CVSymbol sym) -> llvm::Error {
// Track the current scope. Only update records in the postmerge
// pass.
if (symbolOpensScope(sym.kind()))
scopeStackOpen(scopes, storage);
else if (symbolEndsScope(sym.kind()))
scopeStackClose(ctx, scopes, storage, moduleSymStart, file);
// Copy, relocate, and rewrite each module symbol.
if (symbolGoesInModuleStream(sym, scopes.size())) {
uint32_t alignedSize =
alignTo(sym.length(), alignOf(CodeViewContainer::Pdb));
writeSymbolRecord(debugChunk, sectionContents, sym, alignedSize,
nextRelocIndex, storage);
}
return Error::success();
});
// If we encounter corrupt records in the second pass, ignore them. We
// already warned about them in the first analysis pass.
if (ec) {
consumeError(std::move(ec));
storage.clear();
}
// Writing bytes has a very high overhead, so write the entire subsection
// at once.
// TODO: Consider buffering symbols for the entire object file to reduce
// overhead even further.
if (Error e = writer.writeBytes(storage))
return e;
}
}
return Error::success();
}
Error PDBLinker::commitSymbolsForObject(void *ctx, void *obj,
BinaryStreamWriter &writer) {
return static_cast<PDBLinker *>(ctx)->writeAllModuleSymbolRecords(
static_cast<ObjFile *>(obj), writer);
}
static pdb::SectionContrib createSectionContrib(COFFLinkerContext &ctx,
const Chunk *c, uint32_t modi) {
OutputSection *os = c ? ctx.getOutputSection(c) : nullptr;
pdb::SectionContrib sc;
memset(&sc, 0, sizeof(sc));
sc.ISect = os ? os->sectionIndex : llvm::pdb::kInvalidStreamIndex;
sc.Off = c && os ? c->getRVA() - os->getRVA() : 0;
sc.Size = c ? c->getSize() : -1;
if (auto *secChunk = dyn_cast_or_null<SectionChunk>(c)) {
sc.Characteristics = secChunk->header->Characteristics;
sc.Imod = secChunk->file->moduleDBI->getModuleIndex();
ArrayRef<uint8_t> contents = secChunk->getContents();
JamCRC crc(0);
crc.update(contents);
sc.DataCrc = crc.getCRC();
} else {
sc.Characteristics = os ? os->header.Characteristics : 0;
sc.Imod = modi;
}
sc.RelocCrc = 0; // FIXME
return sc;
}
static uint32_t
translateStringTableIndex(COFFLinkerContext &ctx, uint32_t objIndex,
const DebugStringTableSubsectionRef &objStrTable,
DebugStringTableSubsection &pdbStrTable) {
auto expectedString = objStrTable.getString(objIndex);
if (!expectedString) {
Warn(ctx) << "Invalid string table reference";
consumeError(expectedString.takeError());
return 0;
}
return pdbStrTable.insert(*expectedString);
}
void DebugSHandler::handleDebugS(SectionChunk *debugChunk) {
// Note that we are processing the *unrelocated* section contents. They will
// be relocated later during PDB writing.
ArrayRef<uint8_t> contents = debugChunk->getContents();
contents = SectionChunk::consumeDebugMagic(contents, ".debug$S");
DebugSubsectionArray subsections;
BinaryStreamReader reader(contents, llvm::endianness::little);
ExitOnError exitOnErr;
exitOnErr(reader.readArray(subsections, contents.size()));
debugChunk->sortRelocations();
// Reset the relocation index, since this is a new section.
nextRelocIndex = 0;
for (const DebugSubsectionRecord &ss : subsections) {
// Ignore subsections with the 'ignore' bit. Some versions of the Visual C++
// runtime have subsections with this bit set.
if (uint32_t(ss.kind()) & codeview::SubsectionIgnoreFlag)
continue;
switch (ss.kind()) {
case DebugSubsectionKind::StringTable: {
assert(!cvStrTab.valid() &&
"Encountered multiple string table subsections!");
exitOnErr(cvStrTab.initialize(ss.getRecordData()));
break;
}
case DebugSubsectionKind::FileChecksums:
assert(!checksums.valid() &&
"Encountered multiple checksum subsections!");
exitOnErr(checksums.initialize(ss.getRecordData()));
break;
case DebugSubsectionKind::Lines:
case DebugSubsectionKind::InlineeLines:
addUnrelocatedSubsection(debugChunk, ss);
break;
case DebugSubsectionKind::FrameData:
addFrameDataSubsection(debugChunk, ss);
break;
case DebugSubsectionKind::Symbols:
linker.analyzeSymbolSubsection(debugChunk, moduleStreamSize,
nextRelocIndex, stringTableFixups,
ss.getRecordData());
break;
case DebugSubsectionKind::CrossScopeImports:
case DebugSubsectionKind::CrossScopeExports:
// These appear to relate to cross-module optimization, so we might use
// these for ThinLTO.
break;
case DebugSubsectionKind::ILLines:
case DebugSubsectionKind::FuncMDTokenMap:
case DebugSubsectionKind::TypeMDTokenMap:
case DebugSubsectionKind::MergedAssemblyInput:
// These appear to relate to .Net assembly info.
break;
case DebugSubsectionKind::CoffSymbolRVA:
// Unclear what this is for.
break;
case DebugSubsectionKind::XfgHashType:
case DebugSubsectionKind::XfgHashVirtual:
break;
default:
Warn(ctx) << "ignoring unknown debug$S subsection kind 0x"
<< utohexstr(uint32_t(ss.kind())) << " in file "
<< toString(&file);
break;
}
}
}
void DebugSHandler::advanceRelocIndex(SectionChunk *sc,
ArrayRef<uint8_t> subsec) {
ptrdiff_t vaBegin = subsec.data() - sc->getContents().data();
assert(vaBegin > 0);
auto relocs = sc->getRelocs();
for (; nextRelocIndex < relocs.size(); ++nextRelocIndex) {
if (relocs[nextRelocIndex].VirtualAddress >= (uint32_t)vaBegin)
break;
}
}
namespace {
/// Wrapper class for unrelocated line and inlinee line subsections, which
/// require only relocation and type index remapping to add to the PDB.
class UnrelocatedDebugSubsection : public DebugSubsection {
public:
UnrelocatedDebugSubsection(DebugSubsectionKind k, SectionChunk *debugChunk,
ArrayRef<uint8_t> subsec, uint32_t relocIndex)
: DebugSubsection(k), debugChunk(debugChunk), subsec(subsec),
relocIndex(relocIndex) {}
Error commit(BinaryStreamWriter &writer) const override;
uint32_t calculateSerializedSize() const override { return subsec.size(); }
SectionChunk *debugChunk;
ArrayRef<uint8_t> subsec;
uint32_t relocIndex;
};
} // namespace
Error UnrelocatedDebugSubsection::commit(BinaryStreamWriter &writer) const {
std::vector<uint8_t> relocatedBytes(subsec.size());
uint32_t tmpRelocIndex = relocIndex;
debugChunk->writeAndRelocateSubsection(debugChunk->getContents(), subsec,
tmpRelocIndex, relocatedBytes.data());
// Remap type indices in inlinee line records in place. Skip the remapping if
// there is no type source info.
if (kind() == DebugSubsectionKind::InlineeLines &&
debugChunk->file->debugTypesObj) {
TpiSource *source = debugChunk->file->debugTypesObj;
DebugInlineeLinesSubsectionRef inlineeLines;
BinaryStreamReader storageReader(relocatedBytes, llvm::endianness::little);
ExitOnError exitOnErr;
exitOnErr(inlineeLines.initialize(storageReader));
for (const InlineeSourceLine &line : inlineeLines) {
TypeIndex &inlinee = *const_cast<TypeIndex *>(&line.Header->Inlinee);
if (!source->remapTypeIndex(inlinee, TiRefKind::IndexRef)) {
log("bad inlinee line record in " + debugChunk->file->getName() +
" with bad inlinee index 0x" + utohexstr(inlinee.getIndex()));
}
}
}
return writer.writeBytes(relocatedBytes);
}
void DebugSHandler::addUnrelocatedSubsection(SectionChunk *debugChunk,
const DebugSubsectionRecord &ss) {
ArrayRef<uint8_t> subsec;
BinaryStreamRef sr = ss.getRecordData();
cantFail(sr.readBytes(0, sr.getLength(), subsec));
advanceRelocIndex(debugChunk, subsec);
file.moduleDBI->addDebugSubsection(
std::make_shared<UnrelocatedDebugSubsection>(ss.kind(), debugChunk,
subsec, nextRelocIndex));
}
void DebugSHandler::addFrameDataSubsection(SectionChunk *debugChunk,
const DebugSubsectionRecord &ss) {
// We need to re-write string table indices here, so save off all
// frame data subsections until we've processed the entire list of
// subsections so that we can be sure we have the string table.
ArrayRef<uint8_t> subsec;
BinaryStreamRef sr = ss.getRecordData();
cantFail(sr.readBytes(0, sr.getLength(), subsec));
advanceRelocIndex(debugChunk, subsec);
frameDataSubsecs.push_back({debugChunk, subsec, nextRelocIndex});
}
static Expected<StringRef>
getFileName(const DebugStringTableSubsectionRef &strings,
const DebugChecksumsSubsectionRef &checksums, uint32_t fileID) {
auto iter = checksums.getArray().at(fileID);
if (iter == checksums.getArray().end())
return make_error<CodeViewError>(cv_error_code::no_records);
uint32_t offset = iter->FileNameOffset;
return strings.getString(offset);
}
void DebugSHandler::finish() {
pdb::DbiStreamBuilder &dbiBuilder = linker.builder.getDbiBuilder();
// If we found any symbol records for the module symbol stream, defer them.
if (moduleStreamSize > kSymbolStreamMagicSize)
file.moduleDBI->addUnmergedSymbols(&file, moduleStreamSize -
kSymbolStreamMagicSize);
// We should have seen all debug subsections across the entire object file now
// which means that if a StringTable subsection and Checksums subsection were
// present, now is the time to handle them.
if (!cvStrTab.valid()) {
if (checksums.valid())
fatal(".debug$S sections with a checksums subsection must also contain a "
"string table subsection");
if (!stringTableFixups.empty())
Warn(ctx)
<< "No StringTable subsection was encountered, but there are string "
"table references";
return;
}
ExitOnError exitOnErr;
// Handle FPO data. Each subsection begins with a single image base
// relocation, which is then added to the RvaStart of each frame data record
// when it is added to the PDB. The string table indices for the FPO program
// must also be rewritten to use the PDB string table.
for (const UnrelocatedFpoData &subsec : frameDataSubsecs) {
// Relocate the first four bytes of the subection and reinterpret them as a
// 32 bit little-endian integer.
SectionChunk *debugChunk = subsec.debugChunk;
ArrayRef<uint8_t> subsecData = subsec.subsecData;
uint32_t relocIndex = subsec.relocIndex;
auto unrelocatedRvaStart = subsecData.take_front(sizeof(uint32_t));
uint8_t relocatedRvaStart[sizeof(uint32_t)];
debugChunk->writeAndRelocateSubsection(debugChunk->getContents(),
unrelocatedRvaStart, relocIndex,
&relocatedRvaStart[0]);
// Use of memcpy here avoids violating type-based aliasing rules.
support::ulittle32_t rvaStart;
memcpy(&rvaStart, &relocatedRvaStart[0], sizeof(support::ulittle32_t));
// Copy each frame data record, add in rvaStart, translate string table
// indices, and add the record to the PDB.
DebugFrameDataSubsectionRef fds;
BinaryStreamReader reader(subsecData, llvm::endianness::little);
exitOnErr(fds.initialize(reader));
for (codeview::FrameData fd : fds) {
fd.RvaStart += rvaStart;
fd.FrameFunc = translateStringTableIndex(ctx, fd.FrameFunc, cvStrTab,
linker.pdbStrTab);
dbiBuilder.addNewFpoData(fd);
}
}
// Translate the fixups and pass them off to the module builder so they will
// be applied during writing.
for (StringTableFixup &ref : stringTableFixups) {
ref.StrTabOffset = translateStringTableIndex(ctx, ref.StrTabOffset,
cvStrTab, linker.pdbStrTab);
}
file.moduleDBI->setStringTableFixups(std::move(stringTableFixups));
// Make a new file checksum table that refers to offsets in the PDB-wide
// string table. Generally the string table subsection appears after the
// checksum table, so we have to do this after looping over all the
// subsections. The new checksum table must have the exact same layout and
// size as the original. Otherwise, the file references in the line and
// inlinee line tables will be incorrect.
auto newChecksums = std::make_unique<DebugChecksumsSubsection>(linker.pdbStrTab);
for (const FileChecksumEntry &fc : checksums) {
SmallString<128> filename =
exitOnErr(cvStrTab.getString(fc.FileNameOffset));
linker.pdbMakeAbsolute(filename);
exitOnErr(dbiBuilder.addModuleSourceFile(*file.moduleDBI, filename));