forked from jeremyhu/llvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DwarfLinker.cpp
3537 lines (3081 loc) · 136 KB
/
DwarfLinker.cpp
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
//===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "DebugMap.h"
#include "BinaryHolder.h"
#include "DebugMap.h"
#include "dsymutil.h"
#include "MachOUtils.h"
#include "NonRelocatableStringpool.h"
#include "llvm/ADT/IntervalMap.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/DIE.h"
#include "llvm/Config/config.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCTargetOptionsCommandFlags.h"
#include "llvm/Object/MachO.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include <string>
#include <tuple>
namespace llvm {
namespace dsymutil {
namespace {
template <typename KeyT, typename ValT>
using HalfOpenIntervalMap =
IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
IntervalMapHalfOpenInfo<KeyT>>;
typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
// FIXME: Delete this structure.
struct PatchLocation {
DIE::value_iterator I;
PatchLocation() = default;
PatchLocation(DIE::value_iterator I) : I(I) {}
void set(uint64_t New) const {
assert(I);
const auto &Old = *I;
assert(Old.getType() == DIEValue::isInteger);
*I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
}
uint64_t get() const {
assert(I);
return I->getDIEInteger().getValue();
}
};
class CompileUnit;
struct DeclMapInfo;
/// A DeclContext is a named program scope that is used for ODR
/// uniquing of types.
/// The set of DeclContext for the ODR-subject parts of a Dwarf link
/// is expanded (and uniqued) with each new object file processed. We
/// need to determine the context of each DIE in an linked object file
/// to see if the corresponding type has already been emitted.
///
/// The contexts are conceptually organised as a tree (eg. a function
/// scope is contained in a namespace scope that contains other
/// scopes), but storing/accessing them in an actual tree is too
/// inefficient: we need to be able to very quickly query a context
/// for a given child context by name. Storing a StringMap in each
/// DeclContext would be too space inefficient.
/// The solution here is to give each DeclContext a link to its parent
/// (this allows to walk up the tree), but to query the existance of a
/// specific DeclContext using a separate DenseMap keyed on the hash
/// of the fully qualified name of the context.
class DeclContext {
unsigned QualifiedNameHash;
uint32_t Line;
uint32_t ByteSize;
uint16_t Tag;
StringRef Name;
StringRef File;
const DeclContext &Parent;
const DWARFDebugInfoEntryMinimal *LastSeenDIE;
uint32_t LastSeenCompileUnitID;
uint32_t CanonicalDIEOffset;
friend DeclMapInfo;
public:
typedef DenseSet<DeclContext *, DeclMapInfo> Map;
DeclContext()
: QualifiedNameHash(0), Line(0), ByteSize(0),
Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
LastSeenDIE(nullptr), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
StringRef Name, StringRef File, const DeclContext &Parent,
const DWARFDebugInfoEntryMinimal *LastSeenDIE = nullptr,
unsigned CUId = 0)
: QualifiedNameHash(Hash), Line(Line), ByteSize(ByteSize), Tag(Tag),
Name(Name), File(File), Parent(Parent), LastSeenDIE(LastSeenDIE),
LastSeenCompileUnitID(CUId), CanonicalDIEOffset(0) {}
uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
bool setLastSeenDIE(CompileUnit &U, const DWARFDebugInfoEntryMinimal *Die);
uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
uint16_t getTag() const { return Tag; }
StringRef getName() const { return Name; }
};
/// Info type for the DenseMap storing the DeclContext pointers.
struct DeclMapInfo : private DenseMapInfo<DeclContext *> {
using DenseMapInfo<DeclContext *>::getEmptyKey;
using DenseMapInfo<DeclContext *>::getTombstoneKey;
static unsigned getHashValue(const DeclContext *Ctxt) {
return Ctxt->QualifiedNameHash;
}
static bool isEqual(const DeclContext *LHS, const DeclContext *RHS) {
if (RHS == getEmptyKey() || RHS == getTombstoneKey())
return RHS == LHS;
return LHS->QualifiedNameHash == RHS->QualifiedNameHash &&
LHS->Line == RHS->Line && LHS->ByteSize == RHS->ByteSize &&
LHS->Name.data() == RHS->Name.data() &&
LHS->File.data() == RHS->File.data() &&
LHS->Parent.QualifiedNameHash == RHS->Parent.QualifiedNameHash;
}
};
/// This class gives a tree-like API to the DenseMap that stores the
/// DeclContext objects. It also holds the BumpPtrAllocator where
/// these objects will be allocated.
class DeclContextTree {
BumpPtrAllocator Allocator;
DeclContext Root;
DeclContext::Map Contexts;
public:
/// Get the child of \a Context described by \a DIE in \a Unit. The
/// required strings will be interned in \a StringPool.
/// \returns The child DeclContext along with one bit that is set if
/// this context is invalid.
/// An invalid context means it shouldn't be considered for uniquing, but its
/// not returning null, because some children of that context might be
/// uniquing candidates. FIXME: The invalid bit along the return value is to
/// emulate some dsymutil-classic functionality.
PointerIntPair<DeclContext *, 1>
getChildDeclContext(DeclContext &Context,
const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &Unit,
NonRelocatableStringpool &StringPool, bool InClangModule);
DeclContext &getRoot() { return Root; }
};
/// \brief Stores all information relating to a compile unit, be it in
/// its original instance in the object file to its brand new cloned
/// and linked DIE tree.
class CompileUnit {
public:
/// \brief Information gathered about a DIE in the object file.
struct DIEInfo {
int64_t AddrAdjust; ///< Address offset to apply to the described entity.
DeclContext *Ctxt; ///< ODR Declaration context.
DIE *Clone; ///< Cloned version of that DIE.
uint32_t ParentIdx; ///< The index of this DIE's parent.
bool Keep : 1; ///< Is the DIE part of the linked output?
bool InDebugMap : 1;///< Was this DIE's entity found in the map?
bool Prune : 1; ///< Is this a pure forward declaration we can strip?
};
CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR,
StringRef ClangModuleName)
: OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Ranges(RangeAlloc), ClangModuleName(ClangModuleName) {
Info.resize(OrigUnit.getNumDIEs());
const auto *CUDie = OrigUnit.getUnitDIE(false);
unsigned Lang = CUDie->getAttributeValueAsUnsignedConstant(
&OrigUnit, dwarf::DW_AT_language, 0);
HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
Lang == dwarf::DW_LANG_C_plus_plus_03 ||
Lang == dwarf::DW_LANG_C_plus_plus_11 ||
Lang == dwarf::DW_LANG_C_plus_plus_14 ||
Lang == dwarf::DW_LANG_ObjC_plus_plus);
}
CompileUnit(CompileUnit &&RHS)
: OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
// The CompileUnit container has been 'reserve()'d with the right
// size. We cannot move the IntervalMap anyway.
llvm_unreachable("CompileUnits should not be moved.");
}
DWARFUnit &getOrigUnit() const { return OrigUnit; }
unsigned getUniqueID() const { return ID; }
DIE *getOutputUnitDIE() const { return CUDie; }
void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
bool hasODR() const { return HasODR; }
bool isClangModule() const { return !ClangModuleName.empty(); }
const std::string &getClangModuleName() const { return ClangModuleName; }
DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
uint64_t getStartOffset() const { return StartOffset; }
uint64_t getNextUnitOffset() const { return NextUnitOffset; }
void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
uint64_t getLowPc() const { return LowPc; }
uint64_t getHighPc() const { return HighPc; }
Optional<PatchLocation> getUnitRangesAttribute() const {
return UnitRangeAttribute;
}
const FunctionIntervals &getFunctionRanges() const { return Ranges; }
const std::vector<PatchLocation> &getRangesAttributes() const {
return RangeAttributes;
}
const std::vector<std::pair<PatchLocation, int64_t>> &
getLocationAttributes() const {
return LocationAttributes;
}
void setHasInterestingContent() { HasInterestingContent = true; }
bool hasInterestingContent() { return HasInterestingContent; }
/// Mark every DIE in this unit as kept. This function also
/// marks variables as InDebugMap so that they appear in the
/// reconstructed accelerator tables.
void markEverythingAsKept();
/// \brief Compute the end offset for this unit. Must be
/// called after the CU's DIEs have been cloned.
/// \returns the next unit offset (which is also the current
/// debug_info section size).
uint64_t computeNextUnitOffset();
/// \brief Keep track of a forward reference to DIE \p Die in \p
/// RefUnit by \p Attr. The attribute should be fixed up later to
/// point to the absolute offset of \p Die in the debug_info section
/// or to the canonical offset of \p Ctxt if it is non-null.
void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
DeclContext *Ctxt, PatchLocation Attr);
/// \brief Apply all fixups recored by noteForwardReference().
void fixupForwardReferences();
/// \brief Add a function range [\p LowPC, \p HighPC) that is
/// relocatad by applying offset \p PCOffset.
void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
/// \brief Keep track of a DW_AT_range attribute that we will need to
/// patch up later.
void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
/// \brief Keep track of a location attribute pointing to a location
/// list in the debug_loc section.
void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
/// \brief Add a name accelerator entry for \p Die with \p Name
/// which is stored in the string table at \p Offset.
void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
bool SkipPubnamesSection = false);
/// \brief Add a type accelerator entry for \p Die with \p Name
/// which is stored in the string table at \p Offset.
void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
struct AccelInfo {
StringRef Name; ///< Name of the entry.
const DIE *Die; ///< DIE this entry describes.
uint32_t NameOffset; ///< Offset of Name in the string pool.
bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
bool SkipPubSection = false)
: Name(Name), Die(Die), NameOffset(NameOffset),
SkipPubSection(SkipPubSection) {}
};
const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
/// Get the full path for file \a FileNum in the line table
const char *getResolvedPath(unsigned FileNum) {
if (FileNum >= ResolvedPaths.size())
return nullptr;
return ResolvedPaths[FileNum].size() ? ResolvedPaths[FileNum].c_str()
: nullptr;
}
/// Set the fully resolved path for the line-table's file \a FileNum
/// to \a Path.
void setResolvedPath(unsigned FileNum, const std::string &Path) {
if (ResolvedPaths.size() <= FileNum)
ResolvedPaths.resize(FileNum + 1);
ResolvedPaths[FileNum] = Path;
}
private:
DWARFUnit &OrigUnit;
unsigned ID;
std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
DIE *CUDie; ///< Root of the linked DIE tree.
uint64_t StartOffset;
uint64_t NextUnitOffset;
uint64_t LowPc;
uint64_t HighPc;
/// \brief A list of attributes to fixup with the absolute offset of
/// a DIE in the debug_info section.
///
/// The offsets for the attributes in this array couldn't be set while
/// cloning because for cross-cu forward refences the target DIE's
/// offset isn't known you emit the reference attribute.
std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
PatchLocation>> ForwardDIEReferences;
FunctionIntervals::Allocator RangeAlloc;
/// \brief The ranges in that interval map are the PC ranges for
/// functions in this unit, associated with the PC offset to apply
/// to the addresses to get the linked address.
FunctionIntervals Ranges;
/// \brief DW_AT_ranges attributes to patch after we have gathered
/// all the unit's function addresses.
/// @{
std::vector<PatchLocation> RangeAttributes;
Optional<PatchLocation> UnitRangeAttribute;
/// @}
/// \brief Location attributes that need to be transfered from th
/// original debug_loc section to the liked one. They are stored
/// along with the PC offset that is to be applied to their
/// function's address.
std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
/// \brief Accelerator entries for the unit, both for the pub*
/// sections and the apple* ones.
/// @{
std::vector<AccelInfo> Pubnames;
std::vector<AccelInfo> Pubtypes;
/// @}
/// Cached resolved paths from the line table.
std::vector<std::string> ResolvedPaths;
/// Is this unit subject to the ODR rule?
bool HasODR;
/// Did a DIE actually contain a valid reloc?
bool HasInterestingContent;
/// If this is a Clang module, this holds the module's name.
std::string ClangModuleName;
};
void CompileUnit::markEverythingAsKept() {
for (auto &I : Info)
// Mark everything that wasn't explicity marked for pruning.
I.Keep = !I.Prune;
}
uint64_t CompileUnit::computeNextUnitOffset() {
NextUnitOffset = StartOffset + 11 /* Header size */;
// The root DIE might be null, meaning that the Unit had nothing to
// contribute to the linked output. In that case, we will emit the
// unit header without any actual DIE.
if (CUDie)
NextUnitOffset += CUDie->getSize();
return NextUnitOffset;
}
/// \brief Keep track of a forward cross-cu reference from this unit
/// to \p Die that lives in \p RefUnit.
void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
DeclContext *Ctxt, PatchLocation Attr) {
ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
}
/// \brief Apply all fixups recorded by noteForwardReference().
void CompileUnit::fixupForwardReferences() {
for (const auto &Ref : ForwardDIEReferences) {
DIE *RefDie;
const CompileUnit *RefUnit;
PatchLocation Attr;
DeclContext *Ctxt;
std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
if (Ctxt && Ctxt->getCanonicalDIEOffset())
Attr.set(Ctxt->getCanonicalDIEOffset());
else
Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
}
}
void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
int64_t PcOffset) {
Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
}
void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
if (Die.getTag() != dwarf::DW_TAG_compile_unit)
RangeAttributes.push_back(Attr);
else
UnitRangeAttribute = Attr;
}
void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
LocationAttributes.emplace_back(Attr, PcOffset);
}
/// \brief Add a name accelerator entry for \p Die with \p Name
/// which is stored in the string table at \p Offset.
void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
uint32_t Offset, bool SkipPubSection) {
Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
}
/// \brief Add a type accelerator entry for \p Die with \p Name
/// which is stored in the string table at \p Offset.
void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
uint32_t Offset) {
Pubtypes.emplace_back(Name, Die, Offset, false);
}
/// \brief The Dwarf streaming logic
///
/// All interactions with the MC layer that is used to build the debug
/// information binary representation are handled in this class.
class DwarfStreamer {
/// \defgroup MCObjects MC layer objects constructed by the streamer
/// @{
std::unique_ptr<MCRegisterInfo> MRI;
std::unique_ptr<MCAsmInfo> MAI;
std::unique_ptr<MCObjectFileInfo> MOFI;
std::unique_ptr<MCContext> MC;
MCAsmBackend *MAB; // Owned by MCStreamer
std::unique_ptr<MCInstrInfo> MII;
std::unique_ptr<MCSubtargetInfo> MSTI;
MCCodeEmitter *MCE; // Owned by MCStreamer
MCStreamer *MS; // Owned by AsmPrinter
std::unique_ptr<TargetMachine> TM;
std::unique_ptr<AsmPrinter> Asm;
/// @}
/// \brief the file we stream the linked Dwarf to.
std::unique_ptr<raw_fd_ostream> OutFile;
uint32_t RangesSectionSize;
uint32_t LocSectionSize;
uint32_t LineSectionSize;
uint32_t FrameSectionSize;
/// \brief Emit the pubnames or pubtypes section contribution for \p
/// Unit into \p Sec. The data is provided in \p Names.
void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
const CompileUnit &Unit,
const std::vector<CompileUnit::AccelInfo> &Names);
public:
/// \brief Actually create the streamer and the ouptut file.
///
/// This could be done directly in the constructor, but it feels
/// more natural to handle errors through return value.
bool init(Triple TheTriple, StringRef OutputFilename);
/// \brief Dump the file to the disk.
bool finish(const DebugMap &);
AsmPrinter &getAsmPrinter() const { return *Asm; }
/// \brief Set the current output section to debug_info and change
/// the MC Dwarf version to \p DwarfVersion.
void switchToDebugInfoSection(unsigned DwarfVersion);
/// \brief Emit the compilation unit header for \p Unit in the
/// debug_info section.
///
/// As a side effect, this also switches the current Dwarf version
/// of the MC layer to the one of U.getOrigUnit().
void emitCompileUnitHeader(CompileUnit &Unit);
/// \brief Recursively emit the DIE tree rooted at \p Die.
void emitDIE(DIE &Die);
/// \brief Emit the abbreviation table \p Abbrevs to the
/// debug_abbrev section.
void emitAbbrevs(const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs);
/// \brief Emit the string table described by \p Pool.
void emitStrings(const NonRelocatableStringpool &Pool);
/// \brief Emit debug_ranges for \p FuncRange by translating the
/// original \p Entries.
void emitRangesEntries(
int64_t UnitPcOffset, uint64_t OrigLowPc,
FunctionIntervals::const_iterator FuncRange,
const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
unsigned AddressSize);
/// \brief Emit debug_aranges entries for \p Unit and if \p
/// DoRangesSection is true, also emit the debug_ranges entries for
/// the DW_TAG_compile_unit's DW_AT_ranges attribute.
void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
uint32_t getRangesSectionSize() const { return RangesSectionSize; }
/// \brief Emit the debug_loc contribution for \p Unit by copying
/// the entries from \p Dwarf and offseting them. Update the
/// location attributes to point to the new entries.
void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
/// \brief Emit the line table described in \p Rows into the
/// debug_line section.
void emitLineTableForUnit(MCDwarfLineTableParams Params,
StringRef PrologueBytes, unsigned MinInstLength,
std::vector<DWARFDebugLine::Row> &Rows,
unsigned AdddressSize);
uint32_t getLineSectionSize() const { return LineSectionSize; }
/// \brief Emit the .debug_pubnames contribution for \p Unit.
void emitPubNamesForUnit(const CompileUnit &Unit);
/// \brief Emit the .debug_pubtypes contribution for \p Unit.
void emitPubTypesForUnit(const CompileUnit &Unit);
/// \brief Emit a CIE.
void emitCIE(StringRef CIEBytes);
/// \brief Emit an FDE with data \p Bytes.
void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
StringRef Bytes);
uint32_t getFrameSectionSize() const { return FrameSectionSize; }
};
bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
std::string ErrorStr;
std::string TripleName;
StringRef Context = "dwarf streamer init";
// Get the target.
const Target *TheTarget =
TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
if (!TheTarget)
return error(ErrorStr, Context);
TripleName = TheTriple.getTriple();
// Create all the MC Objects.
MRI.reset(TheTarget->createMCRegInfo(TripleName));
if (!MRI)
return error(Twine("no register info for target ") + TripleName, Context);
MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
if (!MAI)
return error("no asm info for target " + TripleName, Context);
MOFI.reset(new MCObjectFileInfo);
MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
*MC);
MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
if (!MAB)
return error("no asm backend for target " + TripleName, Context);
MII.reset(TheTarget->createMCInstrInfo());
if (!MII)
return error("no instr info info for target " + TripleName, Context);
MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
if (!MSTI)
return error("no subtarget info for target " + TripleName, Context);
MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
if (!MCE)
return error("no code emitter for target " + TripleName, Context);
// Create the output file.
std::error_code EC;
OutFile =
llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
if (EC)
return error(Twine(OutputFilename) + ": " + EC.message(), Context);
MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
MS = TheTarget->createMCObjectStreamer(
TheTriple, *MC, *MAB, *OutFile, MCE, *MSTI, MCOptions.MCRelaxAll,
MCOptions.MCIncrementalLinkerCompatible,
/*DWARFMustBeAtTheEnd*/ false);
if (!MS)
return error("no object streamer for target " + TripleName, Context);
// Finally create the AsmPrinter we'll use to emit the DIEs.
TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
if (!TM)
return error("no target machine for target " + TripleName, Context);
Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
if (!Asm)
return error("no asm printer for target " + TripleName, Context);
RangesSectionSize = 0;
LocSectionSize = 0;
LineSectionSize = 0;
FrameSectionSize = 0;
return true;
}
bool DwarfStreamer::finish(const DebugMap &DM) {
if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty())
return MachOUtils::generateDsymCompanion(DM, *MS, *OutFile);
MS->Finish();
return true;
}
/// \brief Set the current output section to debug_info and change
/// the MC Dwarf version to \p DwarfVersion.
void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
MS->SwitchSection(MOFI->getDwarfInfoSection());
MC->setDwarfVersion(DwarfVersion);
}
/// \brief Emit the compilation unit header for \p Unit in the
/// debug_info section.
///
/// A Dwarf scetion header is encoded as:
/// uint32_t Unit length (omiting this field)
/// uint16_t Version
/// uint32_t Abbreviation table offset
/// uint8_t Address size
///
/// Leading to a total of 11 bytes.
void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
unsigned Version = Unit.getOrigUnit().getVersion();
switchToDebugInfoSection(Version);
// Emit size of content not including length itself. The size has
// already been computed in CompileUnit::computeOffsets(). Substract
// 4 to that size to account for the length field.
Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
Asm->EmitInt16(Version);
// We share one abbreviations table across all units so it's always at the
// start of the section.
Asm->EmitInt32(0);
Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
}
/// \brief Emit the \p Abbrevs array as the shared abbreviation table
/// for the linked Dwarf file.
void DwarfStreamer::emitAbbrevs(
const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs) {
MS->SwitchSection(MOFI->getDwarfAbbrevSection());
Asm->emitDwarfAbbrevs(Abbrevs);
}
/// \brief Recursively emit the DIE tree rooted at \p Die.
void DwarfStreamer::emitDIE(DIE &Die) {
MS->SwitchSection(MOFI->getDwarfInfoSection());
Asm->emitDwarfDIE(Die);
}
/// \brief Emit the debug_str section stored in \p Pool.
void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
for (auto *Entry = Pool.getFirstEntry(); Entry;
Entry = Pool.getNextEntry(Entry))
Asm->OutStreamer->EmitBytes(
StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
}
/// \brief Emit the debug_range section contents for \p FuncRange by
/// translating the original \p Entries. The debug_range section
/// format is totally trivial, consisting just of pairs of address
/// sized addresses describing the ranges.
void DwarfStreamer::emitRangesEntries(
int64_t UnitPcOffset, uint64_t OrigLowPc,
FunctionIntervals::const_iterator FuncRange,
const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
unsigned AddressSize) {
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
// Offset each range by the right amount.
int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
for (const auto &Range : Entries) {
if (Range.isBaseAddressSelectionEntry(AddressSize)) {
warn("unsupported base address selection operation",
"emitting debug_ranges");
break;
}
// Do not emit empty ranges.
if (Range.StartAddress == Range.EndAddress)
continue;
// All range entries should lie in the function range.
if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
Range.EndAddress + OrigLowPc <= FuncRange.stop()))
warn("inconsistent range data.", "emitting debug_ranges");
MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
RangesSectionSize += 2 * AddressSize;
}
// Add the terminator entry.
MS->EmitIntValue(0, AddressSize);
MS->EmitIntValue(0, AddressSize);
RangesSectionSize += 2 * AddressSize;
}
/// \brief Emit the debug_aranges contribution of a unit and
/// if \p DoDebugRanges is true the debug_range contents for a
/// compile_unit level DW_AT_ranges attribute (Which are basically the
/// same thing with a different base address).
/// Just aggregate all the ranges gathered inside that unit.
void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
bool DoDebugRanges) {
unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
// Gather the ranges in a vector, so that we can simplify them. The
// IntervalMap will have coalesced the non-linked ranges, but here
// we want to coalesce the linked addresses.
std::vector<std::pair<uint64_t, uint64_t>> Ranges;
const auto &FunctionRanges = Unit.getFunctionRanges();
for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
Range != End; ++Range)
Ranges.push_back(std::make_pair(Range.start() + Range.value(),
Range.stop() + Range.value()));
// The object addresses where sorted, but again, the linked
// addresses might end up in a different order.
std::sort(Ranges.begin(), Ranges.end());
if (!Ranges.empty()) {
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
unsigned HeaderSize =
sizeof(int32_t) + // Size of contents (w/o this field
sizeof(int16_t) + // DWARF ARange version number
sizeof(int32_t) + // Offset of CU in the .debug_info section
sizeof(int8_t) + // Pointer Size (in bytes)
sizeof(int8_t); // Segment Size (in bytes)
unsigned TupleSize = AddressSize * 2;
unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Asm->OutStreamer->EmitLabel(BeginLabel);
Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
Asm->EmitInt8(AddressSize); // Address size
Asm->EmitInt8(0); // Segment size
Asm->OutStreamer->EmitFill(Padding, 0x0);
for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
++Range) {
uint64_t RangeStart = Range->first;
MS->EmitIntValue(RangeStart, AddressSize);
while ((Range + 1) != End && Range->second == (Range + 1)->first)
++Range;
MS->EmitIntValue(Range->second - RangeStart, AddressSize);
}
// Emit terminator
Asm->OutStreamer->EmitIntValue(0, AddressSize);
Asm->OutStreamer->EmitIntValue(0, AddressSize);
Asm->OutStreamer->EmitLabel(EndLabel);
}
if (!DoDebugRanges)
return;
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
// Offset each range by the right amount.
int64_t PcOffset = -Unit.getLowPc();
// Emit coalesced ranges.
for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
MS->EmitIntValue(Range->first + PcOffset, AddressSize);
while (Range + 1 != End && Range->second == (Range + 1)->first)
++Range;
MS->EmitIntValue(Range->second + PcOffset, AddressSize);
RangesSectionSize += 2 * AddressSize;
}
// Add the terminator entry.
MS->EmitIntValue(0, AddressSize);
MS->EmitIntValue(0, AddressSize);
RangesSectionSize += 2 * AddressSize;
}
/// \brief Emit location lists for \p Unit and update attribtues to
/// point to the new entries.
void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
DWARFContext &Dwarf) {
const auto &Attributes = Unit.getLocationAttributes();
if (Attributes.empty())
return;
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
const DWARFSection &InputSec = Dwarf.getLocSection();
DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
DWARFUnit &OrigUnit = Unit.getOrigUnit();
const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
int64_t UnitPcOffset = 0;
uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
if (OrigLowPc != -1ULL)
UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
for (const auto &Attr : Attributes) {
uint32_t Offset = Attr.first.get();
Attr.first.set(LocSectionSize);
// This is the quantity to add to the old location address to get
// the correct address for the new one.
int64_t LocPcOffset = Attr.second + UnitPcOffset;
while (Data.isValidOffset(Offset)) {
uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
uint64_t High = Data.getUnsigned(&Offset, AddressSize);
LocSectionSize += 2 * AddressSize;
if (Low == 0 && High == 0) {
Asm->OutStreamer->EmitIntValue(0, AddressSize);
Asm->OutStreamer->EmitIntValue(0, AddressSize);
break;
}
Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
uint64_t Length = Data.getU16(&Offset);
Asm->OutStreamer->EmitIntValue(Length, 2);
// Just copy the bytes over.
Asm->OutStreamer->EmitBytes(
StringRef(InputSec.Data.substr(Offset, Length)));
Offset += Length;
LocSectionSize += Length + 2;
}
}
}
void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
StringRef PrologueBytes,
unsigned MinInstLength,
std::vector<DWARFDebugLine::Row> &Rows,
unsigned PointerSize) {
// Switch to the section where the table will be emitted into.
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
MCSymbol *LineStartSym = MC->createTempSymbol();
MCSymbol *LineEndSym = MC->createTempSymbol();
// The first 4 bytes is the total length of the information for this
// compilation unit (not including these 4 bytes for the length).
Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Asm->OutStreamer->EmitLabel(LineStartSym);
// Copy Prologue.
MS->EmitBytes(PrologueBytes);
LineSectionSize += PrologueBytes.size() + 4;
SmallString<128> EncodingBuffer;
raw_svector_ostream EncodingOS(EncodingBuffer);
if (Rows.empty()) {
// We only have the dummy entry, dsymutil emits an entry with a 0
// address in that case.
MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
MS->EmitBytes(EncodingOS.str());
LineSectionSize += EncodingBuffer.size();
MS->EmitLabel(LineEndSym);
return;
}
// Line table state machine fields
unsigned FileNum = 1;
unsigned LastLine = 1;
unsigned Column = 0;
unsigned IsStatement = 1;
unsigned Isa = 0;
uint64_t Address = -1ULL;
unsigned RowsSinceLastSequence = 0;
for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
auto &Row = Rows[Idx];
int64_t AddressDelta;
if (Address == -1ULL) {
MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
MS->EmitULEB128IntValue(PointerSize + 1);
MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
MS->EmitIntValue(Row.Address, PointerSize);
LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
AddressDelta = 0;
} else {
AddressDelta = (Row.Address - Address) / MinInstLength;
}
// FIXME: code copied and transfromed from
// MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
// this code, but the current compatibility requirement with
// classic dsymutil makes it hard. Revisit that once this
// requirement is dropped.
if (FileNum != Row.File) {
FileNum = Row.File;
MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
MS->EmitULEB128IntValue(FileNum);
LineSectionSize += 1 + getULEB128Size(FileNum);
}
if (Column != Row.Column) {
Column = Row.Column;
MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
MS->EmitULEB128IntValue(Column);
LineSectionSize += 1 + getULEB128Size(Column);
}
// FIXME: We should handle the discriminator here, but dsymutil
// doesn' consider it, thus ignore it for now.
if (Isa != Row.Isa) {
Isa = Row.Isa;
MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
MS->EmitULEB128IntValue(Isa);
LineSectionSize += 1 + getULEB128Size(Isa);
}
if (IsStatement != Row.IsStmt) {
IsStatement = Row.IsStmt;
MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
LineSectionSize += 1;
}
if (Row.BasicBlock) {
MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
LineSectionSize += 1;
}
if (Row.PrologueEnd) {
MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
LineSectionSize += 1;
}
if (Row.EpilogueBegin) {
MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
LineSectionSize += 1;
}
int64_t LineDelta = int64_t(Row.Line) - LastLine;
if (!Row.EndSequence) {
MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
MS->EmitBytes(EncodingOS.str());
LineSectionSize += EncodingBuffer.size();
EncodingBuffer.resize(0);
Address = Row.Address;
LastLine = Row.Line;
RowsSinceLastSequence++;
} else {
if (LineDelta) {
MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
MS->EmitSLEB128IntValue(LineDelta);
LineSectionSize += 1 + getSLEB128Size(LineDelta);
}
if (AddressDelta) {