forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathELFDumper.cpp
7361 lines (6581 loc) · 264 KB
/
ELFDumper.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
//===- ELFDumper.cpp - ELF-specific dumper --------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements the ELF-specific dumper for llvm-readobj.
///
//===----------------------------------------------------------------------===//
#include "ARMEHABIPrinter.h"
#include "DwarfCFIEHPrinter.h"
#include "ObjDumper.h"
#include "StackMapPrinter.h"
#include "llvm-readobj.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/BinaryFormat/AMDGPUMetadataVerifier.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/BinaryFormat/MsgPackDocument.h"
#include "llvm/Demangle/Demangle.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/ELF.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Object/ELFTypes.h"
#include "llvm/Object/Error.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Object/RelocationResolver.h"
#include "llvm/Object/StackMapParser.h"
#include "llvm/Support/AMDGPUMetadata.h"
#include "llvm/Support/ARMAttributeParser.h"
#include "llvm/Support/ARMBuildAttributes.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/MSP430AttributeParser.h"
#include "llvm/Support/MSP430Attributes.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/MipsABIFlags.h"
#include "llvm/Support/RISCVAttributeParser.h"
#include "llvm/Support/RISCVAttributes.h"
#include "llvm/Support/ScopedPrinter.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cinttypes>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <iterator>
#include <memory>
#include <string>
#include <system_error>
#include <vector>
using namespace llvm;
using namespace llvm::object;
using namespace ELF;
#define LLVM_READOBJ_ENUM_CASE(ns, enum) \
case ns::enum: \
return #enum;
#define ENUM_ENT(enum, altName) \
{ #enum, altName, ELF::enum }
#define ENUM_ENT_1(enum) \
{ #enum, #enum, ELF::enum }
namespace {
template <class ELFT> struct RelSymbol {
RelSymbol(const typename ELFT::Sym *S, StringRef N)
: Sym(S), Name(N.str()) {}
const typename ELFT::Sym *Sym;
std::string Name;
};
/// Represents a contiguous uniform range in the file. We cannot just create a
/// range directly because when creating one of these from the .dynamic table
/// the size, entity size and virtual address are different entries in arbitrary
/// order (DT_REL, DT_RELSZ, DT_RELENT for example).
struct DynRegionInfo {
DynRegionInfo(const Binary &Owner, const ObjDumper &D)
: Obj(&Owner), Dumper(&D) {}
DynRegionInfo(const Binary &Owner, const ObjDumper &D, const uint8_t *A,
uint64_t S, uint64_t ES)
: Addr(A), Size(S), EntSize(ES), Obj(&Owner), Dumper(&D) {}
/// Address in current address space.
const uint8_t *Addr = nullptr;
/// Size in bytes of the region.
uint64_t Size = 0;
/// Size of each entity in the region.
uint64_t EntSize = 0;
/// Owner object. Used for error reporting.
const Binary *Obj;
/// Dumper used for error reporting.
const ObjDumper *Dumper;
/// Error prefix. Used for error reporting to provide more information.
std::string Context;
/// Region size name. Used for error reporting.
StringRef SizePrintName = "size";
/// Entry size name. Used for error reporting. If this field is empty, errors
/// will not mention the entry size.
StringRef EntSizePrintName = "entry size";
template <typename Type> ArrayRef<Type> getAsArrayRef() const {
const Type *Start = reinterpret_cast<const Type *>(Addr);
if (!Start)
return {Start, Start};
const uint64_t Offset =
Addr - (const uint8_t *)Obj->getMemoryBufferRef().getBufferStart();
const uint64_t ObjSize = Obj->getMemoryBufferRef().getBufferSize();
if (Size > ObjSize - Offset) {
Dumper->reportUniqueWarning(
"unable to read data at 0x" + Twine::utohexstr(Offset) +
" of size 0x" + Twine::utohexstr(Size) + " (" + SizePrintName +
"): it goes past the end of the file of size 0x" +
Twine::utohexstr(ObjSize));
return {Start, Start};
}
if (EntSize == sizeof(Type) && (Size % EntSize == 0))
return {Start, Start + (Size / EntSize)};
std::string Msg;
if (!Context.empty())
Msg += Context + " has ";
Msg += ("invalid " + SizePrintName + " (0x" + Twine::utohexstr(Size) + ")")
.str();
if (!EntSizePrintName.empty())
Msg +=
(" or " + EntSizePrintName + " (0x" + Twine::utohexstr(EntSize) + ")")
.str();
Dumper->reportUniqueWarning(Msg);
return {Start, Start};
}
};
struct GroupMember {
StringRef Name;
uint64_t Index;
};
struct GroupSection {
StringRef Name;
std::string Signature;
uint64_t ShName;
uint64_t Index;
uint32_t Link;
uint32_t Info;
uint32_t Type;
std::vector<GroupMember> Members;
};
namespace {
struct NoteType {
uint32_t ID;
StringRef Name;
};
} // namespace
template <class ELFT> class Relocation {
public:
Relocation(const typename ELFT::Rel &R, bool IsMips64EL)
: Type(R.getType(IsMips64EL)), Symbol(R.getSymbol(IsMips64EL)),
Offset(R.r_offset), Info(R.r_info) {}
Relocation(const typename ELFT::Rela &R, bool IsMips64EL)
: Relocation((const typename ELFT::Rel &)R, IsMips64EL) {
Addend = R.r_addend;
}
uint32_t Type;
uint32_t Symbol;
typename ELFT::uint Offset;
typename ELFT::uint Info;
Optional<int64_t> Addend;
};
template <class ELFT> class MipsGOTParser;
template <typename ELFT> class ELFDumper : public ObjDumper {
LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
public:
ELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer);
void printUnwindInfo() override;
void printNeededLibraries() override;
void printHashTable() override;
void printGnuHashTable() override;
void printLoadName() override;
void printVersionInfo() override;
void printArchSpecificInfo() override;
void printStackMap() const override;
const object::ELFObjectFile<ELFT> &getElfObject() const { return ObjF; };
std::string describe(const Elf_Shdr &Sec) const;
unsigned getHashTableEntSize() const {
// EM_S390 and ELF::EM_ALPHA platforms use 8-bytes entries in SHT_HASH
// sections. This violates the ELF specification.
if (Obj.getHeader().e_machine == ELF::EM_S390 ||
Obj.getHeader().e_machine == ELF::EM_ALPHA)
return 8;
return 4;
}
Elf_Dyn_Range dynamic_table() const {
// A valid .dynamic section contains an array of entries terminated
// with a DT_NULL entry. However, sometimes the section content may
// continue past the DT_NULL entry, so to dump the section correctly,
// we first find the end of the entries by iterating over them.
Elf_Dyn_Range Table = DynamicTable.template getAsArrayRef<Elf_Dyn>();
size_t Size = 0;
while (Size < Table.size())
if (Table[Size++].getTag() == DT_NULL)
break;
return Table.slice(0, Size);
}
Elf_Sym_Range dynamic_symbols() const {
if (!DynSymRegion)
return Elf_Sym_Range();
return DynSymRegion->template getAsArrayRef<Elf_Sym>();
}
const Elf_Shdr *findSectionByName(StringRef Name) const;
StringRef getDynamicStringTable() const { return DynamicStringTable; }
protected:
virtual void printVersionSymbolSection(const Elf_Shdr *Sec) = 0;
virtual void printVersionDefinitionSection(const Elf_Shdr *Sec) = 0;
virtual void printVersionDependencySection(const Elf_Shdr *Sec) = 0;
void
printDependentLibsHelper(function_ref<void(const Elf_Shdr &)> OnSectionStart,
function_ref<void(StringRef, uint64_t)> OnLibEntry);
virtual void printRelRelaReloc(const Relocation<ELFT> &R,
const RelSymbol<ELFT> &RelSym) = 0;
virtual void printRelrReloc(const Elf_Relr &R) = 0;
virtual void printDynamicRelocHeader(unsigned Type, StringRef Name,
const DynRegionInfo &Reg) {}
void printReloc(const Relocation<ELFT> &R, unsigned RelIndex,
const Elf_Shdr &Sec, const Elf_Shdr *SymTab);
void printDynamicReloc(const Relocation<ELFT> &R);
void printDynamicRelocationsHelper();
void printRelocationsHelper(const Elf_Shdr &Sec);
void forEachRelocationDo(
const Elf_Shdr &Sec, bool RawRelr,
llvm::function_ref<void(const Relocation<ELFT> &, unsigned,
const Elf_Shdr &, const Elf_Shdr *)>
RelRelaFn,
llvm::function_ref<void(const Elf_Relr &)> RelrFn);
virtual void printSymtabMessage(const Elf_Shdr *Symtab, size_t Offset,
bool NonVisibilityBitsUsed) const {};
virtual void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
DataRegion<Elf_Word> ShndxTable,
Optional<StringRef> StrTable, bool IsDynamic,
bool NonVisibilityBitsUsed) const = 0;
virtual void printMipsABIFlags() = 0;
virtual void printMipsGOT(const MipsGOTParser<ELFT> &Parser) = 0;
virtual void printMipsPLT(const MipsGOTParser<ELFT> &Parser) = 0;
Expected<ArrayRef<Elf_Versym>>
getVersionTable(const Elf_Shdr &Sec, ArrayRef<Elf_Sym> *SymTab,
StringRef *StrTab, const Elf_Shdr **SymTabSec) const;
StringRef getPrintableSectionName(const Elf_Shdr &Sec) const;
std::vector<GroupSection> getGroups();
// Returns the function symbol index for the given address. Matches the
// symbol's section with FunctionSec when specified.
// Returns None if no function symbol can be found for the address or in case
// it is not defined in the specified section.
SmallVector<uint32_t>
getSymbolIndexesForFunctionAddress(uint64_t SymValue,
Optional<const Elf_Shdr *> FunctionSec);
bool printFunctionStackSize(uint64_t SymValue,
Optional<const Elf_Shdr *> FunctionSec,
const Elf_Shdr &StackSizeSec, DataExtractor Data,
uint64_t *Offset);
void printStackSize(const Relocation<ELFT> &R, const Elf_Shdr &RelocSec,
unsigned Ndx, const Elf_Shdr *SymTab,
const Elf_Shdr *FunctionSec, const Elf_Shdr &StackSizeSec,
const RelocationResolver &Resolver, DataExtractor Data);
virtual void printStackSizeEntry(uint64_t Size,
ArrayRef<std::string> FuncNames) = 0;
void printRelocatableStackSizes(std::function<void()> PrintHeader);
void printNonRelocatableStackSizes(std::function<void()> PrintHeader);
/// Retrieves sections with corresponding relocation sections based on
/// IsMatch.
void getSectionAndRelocations(
std::function<bool(const Elf_Shdr &)> IsMatch,
llvm::MapVector<const Elf_Shdr *, const Elf_Shdr *> &SecToRelocMap);
const object::ELFObjectFile<ELFT> &ObjF;
const ELFFile<ELFT> &Obj;
StringRef FileName;
Expected<DynRegionInfo> createDRI(uint64_t Offset, uint64_t Size,
uint64_t EntSize) {
if (Offset + Size < Offset || Offset + Size > Obj.getBufSize())
return createError("offset (0x" + Twine::utohexstr(Offset) +
") + size (0x" + Twine::utohexstr(Size) +
") is greater than the file size (0x" +
Twine::utohexstr(Obj.getBufSize()) + ")");
return DynRegionInfo(ObjF, *this, Obj.base() + Offset, Size, EntSize);
}
void printAttributes(unsigned, std::unique_ptr<ELFAttributeParser>,
support::endianness);
void printMipsReginfo();
void printMipsOptions();
std::pair<const Elf_Phdr *, const Elf_Shdr *> findDynamic();
void loadDynamicTable();
void parseDynamicTable();
Expected<StringRef> getSymbolVersion(const Elf_Sym &Sym,
bool &IsDefault) const;
Expected<SmallVector<Optional<VersionEntry>, 0> *> getVersionMap() const;
DynRegionInfo DynRelRegion;
DynRegionInfo DynRelaRegion;
DynRegionInfo DynRelrRegion;
DynRegionInfo DynPLTRelRegion;
Optional<DynRegionInfo> DynSymRegion;
DynRegionInfo DynSymTabShndxRegion;
DynRegionInfo DynamicTable;
StringRef DynamicStringTable;
const Elf_Hash *HashTable = nullptr;
const Elf_GnuHash *GnuHashTable = nullptr;
const Elf_Shdr *DotSymtabSec = nullptr;
const Elf_Shdr *DotDynsymSec = nullptr;
const Elf_Shdr *DotAddrsigSec = nullptr;
DenseMap<const Elf_Shdr *, ArrayRef<Elf_Word>> ShndxTables;
Optional<uint64_t> SONameOffset;
Optional<DenseMap<uint64_t, std::vector<uint32_t>>> AddressToIndexMap;
const Elf_Shdr *SymbolVersionSection = nullptr; // .gnu.version
const Elf_Shdr *SymbolVersionNeedSection = nullptr; // .gnu.version_r
const Elf_Shdr *SymbolVersionDefSection = nullptr; // .gnu.version_d
std::string getFullSymbolName(const Elf_Sym &Symbol, unsigned SymIndex,
DataRegion<Elf_Word> ShndxTable,
Optional<StringRef> StrTable,
bool IsDynamic) const;
Expected<unsigned>
getSymbolSectionIndex(const Elf_Sym &Symbol, unsigned SymIndex,
DataRegion<Elf_Word> ShndxTable) const;
Expected<StringRef> getSymbolSectionName(const Elf_Sym &Symbol,
unsigned SectionIndex) const;
std::string getStaticSymbolName(uint32_t Index) const;
StringRef getDynamicString(uint64_t Value) const;
void printSymbolsHelper(bool IsDynamic) const;
std::string getDynamicEntry(uint64_t Type, uint64_t Value) const;
Expected<RelSymbol<ELFT>> getRelocationTarget(const Relocation<ELFT> &R,
const Elf_Shdr *SymTab) const;
ArrayRef<Elf_Word> getShndxTable(const Elf_Shdr *Symtab) const;
private:
mutable SmallVector<Optional<VersionEntry>, 0> VersionMap;
};
template <class ELFT>
std::string ELFDumper<ELFT>::describe(const Elf_Shdr &Sec) const {
return ::describe(Obj, Sec);
}
namespace {
template <class ELFT> struct SymtabLink {
typename ELFT::SymRange Symbols;
StringRef StringTable;
const typename ELFT::Shdr *SymTab;
};
// Returns the linked symbol table, symbols and associated string table for a
// given section.
template <class ELFT>
Expected<SymtabLink<ELFT>> getLinkAsSymtab(const ELFFile<ELFT> &Obj,
const typename ELFT::Shdr &Sec,
unsigned ExpectedType) {
Expected<const typename ELFT::Shdr *> SymtabOrErr =
Obj.getSection(Sec.sh_link);
if (!SymtabOrErr)
return createError("invalid section linked to " + describe(Obj, Sec) +
": " + toString(SymtabOrErr.takeError()));
if ((*SymtabOrErr)->sh_type != ExpectedType)
return createError(
"invalid section linked to " + describe(Obj, Sec) + ": expected " +
object::getELFSectionTypeName(Obj.getHeader().e_machine, ExpectedType) +
", but got " +
object::getELFSectionTypeName(Obj.getHeader().e_machine,
(*SymtabOrErr)->sh_type));
Expected<StringRef> StrTabOrErr = Obj.getLinkAsStrtab(**SymtabOrErr);
if (!StrTabOrErr)
return createError(
"can't get a string table for the symbol table linked to " +
describe(Obj, Sec) + ": " + toString(StrTabOrErr.takeError()));
Expected<typename ELFT::SymRange> SymsOrErr = Obj.symbols(*SymtabOrErr);
if (!SymsOrErr)
return createError("unable to read symbols from the " + describe(Obj, Sec) +
": " + toString(SymsOrErr.takeError()));
return SymtabLink<ELFT>{*SymsOrErr, *StrTabOrErr, *SymtabOrErr};
}
} // namespace
template <class ELFT>
Expected<ArrayRef<typename ELFT::Versym>>
ELFDumper<ELFT>::getVersionTable(const Elf_Shdr &Sec, ArrayRef<Elf_Sym> *SymTab,
StringRef *StrTab,
const Elf_Shdr **SymTabSec) const {
assert((!SymTab && !StrTab && !SymTabSec) || (SymTab && StrTab && SymTabSec));
if (reinterpret_cast<uintptr_t>(Obj.base() + Sec.sh_offset) %
sizeof(uint16_t) !=
0)
return createError("the " + describe(Sec) + " is misaligned");
Expected<ArrayRef<Elf_Versym>> VersionsOrErr =
Obj.template getSectionContentsAsArray<Elf_Versym>(Sec);
if (!VersionsOrErr)
return createError("cannot read content of " + describe(Sec) + ": " +
toString(VersionsOrErr.takeError()));
Expected<SymtabLink<ELFT>> SymTabOrErr =
getLinkAsSymtab(Obj, Sec, SHT_DYNSYM);
if (!SymTabOrErr) {
reportUniqueWarning(SymTabOrErr.takeError());
return *VersionsOrErr;
}
if (SymTabOrErr->Symbols.size() != VersionsOrErr->size())
reportUniqueWarning(describe(Sec) + ": the number of entries (" +
Twine(VersionsOrErr->size()) +
") does not match the number of symbols (" +
Twine(SymTabOrErr->Symbols.size()) +
") in the symbol table with index " +
Twine(Sec.sh_link));
if (SymTab) {
*SymTab = SymTabOrErr->Symbols;
*StrTab = SymTabOrErr->StringTable;
*SymTabSec = SymTabOrErr->SymTab;
}
return *VersionsOrErr;
}
template <class ELFT>
void ELFDumper<ELFT>::printSymbolsHelper(bool IsDynamic) const {
Optional<StringRef> StrTable;
size_t Entries = 0;
Elf_Sym_Range Syms(nullptr, nullptr);
const Elf_Shdr *SymtabSec = IsDynamic ? DotDynsymSec : DotSymtabSec;
if (IsDynamic) {
StrTable = DynamicStringTable;
Syms = dynamic_symbols();
Entries = Syms.size();
} else if (DotSymtabSec) {
if (Expected<StringRef> StrTableOrErr =
Obj.getStringTableForSymtab(*DotSymtabSec))
StrTable = *StrTableOrErr;
else
reportUniqueWarning(
"unable to get the string table for the SHT_SYMTAB section: " +
toString(StrTableOrErr.takeError()));
if (Expected<Elf_Sym_Range> SymsOrErr = Obj.symbols(DotSymtabSec))
Syms = *SymsOrErr;
else
reportUniqueWarning(
"unable to read symbols from the SHT_SYMTAB section: " +
toString(SymsOrErr.takeError()));
Entries = DotSymtabSec->getEntityCount();
}
if (Syms.empty())
return;
// The st_other field has 2 logical parts. The first two bits hold the symbol
// visibility (STV_*) and the remainder hold other platform-specific values.
bool NonVisibilityBitsUsed =
llvm::any_of(Syms, [](const Elf_Sym &S) { return S.st_other & ~0x3; });
DataRegion<Elf_Word> ShndxTable =
IsDynamic ? DataRegion<Elf_Word>(
(const Elf_Word *)this->DynSymTabShndxRegion.Addr,
this->getElfObject().getELFFile().end())
: DataRegion<Elf_Word>(this->getShndxTable(SymtabSec));
printSymtabMessage(SymtabSec, Entries, NonVisibilityBitsUsed);
for (const Elf_Sym &Sym : Syms)
printSymbol(Sym, &Sym - Syms.begin(), ShndxTable, StrTable, IsDynamic,
NonVisibilityBitsUsed);
}
template <typename ELFT> class GNUELFDumper : public ELFDumper<ELFT> {
formatted_raw_ostream &OS;
public:
LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
GNUELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
: ELFDumper<ELFT>(ObjF, Writer),
OS(static_cast<formatted_raw_ostream &>(Writer.getOStream())) {
assert(&this->W.getOStream() == &llvm::fouts());
}
void printFileSummary(StringRef FileStr, ObjectFile &Obj,
ArrayRef<std::string> InputFilenames,
const Archive *A) override;
void printFileHeaders() override;
void printGroupSections() override;
void printRelocations() override;
void printSectionHeaders() override;
void printSymbols(bool PrintSymbols, bool PrintDynamicSymbols) override;
void printHashSymbols() override;
void printSectionDetails() override;
void printDependentLibs() override;
void printDynamicTable() override;
void printDynamicRelocations() override;
void printSymtabMessage(const Elf_Shdr *Symtab, size_t Offset,
bool NonVisibilityBitsUsed) const override;
void printProgramHeaders(bool PrintProgramHeaders,
cl::boolOrDefault PrintSectionMapping) override;
void printVersionSymbolSection(const Elf_Shdr *Sec) override;
void printVersionDefinitionSection(const Elf_Shdr *Sec) override;
void printVersionDependencySection(const Elf_Shdr *Sec) override;
void printHashHistograms() override;
void printCGProfile() override;
void printBBAddrMaps() override;
void printAddrsig() override;
void printNotes() override;
void printELFLinkerOptions() override;
void printStackSizes() override;
private:
void printHashHistogram(const Elf_Hash &HashTable);
void printGnuHashHistogram(const Elf_GnuHash &GnuHashTable);
void printHashTableSymbols(const Elf_Hash &HashTable);
void printGnuHashTableSymbols(const Elf_GnuHash &GnuHashTable);
struct Field {
std::string Str;
unsigned Column;
Field(StringRef S, unsigned Col) : Str(std::string(S)), Column(Col) {}
Field(unsigned Col) : Column(Col) {}
};
template <typename T, typename TEnum>
std::string printFlags(T Value, ArrayRef<EnumEntry<TEnum>> EnumValues,
TEnum EnumMask1 = {}, TEnum EnumMask2 = {},
TEnum EnumMask3 = {}) const {
std::string Str;
for (const EnumEntry<TEnum> &Flag : EnumValues) {
if (Flag.Value == 0)
continue;
TEnum EnumMask{};
if (Flag.Value & EnumMask1)
EnumMask = EnumMask1;
else if (Flag.Value & EnumMask2)
EnumMask = EnumMask2;
else if (Flag.Value & EnumMask3)
EnumMask = EnumMask3;
bool IsEnum = (Flag.Value & EnumMask) != 0;
if ((!IsEnum && (Value & Flag.Value) == Flag.Value) ||
(IsEnum && (Value & EnumMask) == Flag.Value)) {
if (!Str.empty())
Str += ", ";
Str += Flag.AltName;
}
}
return Str;
}
formatted_raw_ostream &printField(struct Field F) const {
if (F.Column != 0)
OS.PadToColumn(F.Column);
OS << F.Str;
OS.flush();
return OS;
}
void printHashedSymbol(const Elf_Sym *Sym, unsigned SymIndex,
DataRegion<Elf_Word> ShndxTable, StringRef StrTable,
uint32_t Bucket);
void printRelrReloc(const Elf_Relr &R) override;
void printRelRelaReloc(const Relocation<ELFT> &R,
const RelSymbol<ELFT> &RelSym) override;
void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
DataRegion<Elf_Word> ShndxTable,
Optional<StringRef> StrTable, bool IsDynamic,
bool NonVisibilityBitsUsed) const override;
void printDynamicRelocHeader(unsigned Type, StringRef Name,
const DynRegionInfo &Reg) override;
std::string getSymbolSectionNdx(const Elf_Sym &Symbol, unsigned SymIndex,
DataRegion<Elf_Word> ShndxTable) const;
void printProgramHeaders() override;
void printSectionMapping() override;
void printGNUVersionSectionProlog(const typename ELFT::Shdr &Sec,
const Twine &Label, unsigned EntriesNum);
void printStackSizeEntry(uint64_t Size,
ArrayRef<std::string> FuncNames) override;
void printMipsGOT(const MipsGOTParser<ELFT> &Parser) override;
void printMipsPLT(const MipsGOTParser<ELFT> &Parser) override;
void printMipsABIFlags() override;
};
template <typename ELFT> class LLVMELFDumper : public ELFDumper<ELFT> {
public:
LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
LLVMELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
: ELFDumper<ELFT>(ObjF, Writer), W(Writer) {}
void printFileHeaders() override;
void printGroupSections() override;
void printRelocations() override;
void printSectionHeaders() override;
void printSymbols(bool PrintSymbols, bool PrintDynamicSymbols) override;
void printDependentLibs() override;
void printDynamicTable() override;
void printDynamicRelocations() override;
void printProgramHeaders(bool PrintProgramHeaders,
cl::boolOrDefault PrintSectionMapping) override;
void printVersionSymbolSection(const Elf_Shdr *Sec) override;
void printVersionDefinitionSection(const Elf_Shdr *Sec) override;
void printVersionDependencySection(const Elf_Shdr *Sec) override;
void printHashHistograms() override;
void printCGProfile() override;
void printBBAddrMaps() override;
void printAddrsig() override;
void printNotes() override;
void printELFLinkerOptions() override;
void printStackSizes() override;
private:
void printRelrReloc(const Elf_Relr &R) override;
void printRelRelaReloc(const Relocation<ELFT> &R,
const RelSymbol<ELFT> &RelSym) override;
void printSymbolSection(const Elf_Sym &Symbol, unsigned SymIndex,
DataRegion<Elf_Word> ShndxTable) const;
void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
DataRegion<Elf_Word> ShndxTable,
Optional<StringRef> StrTable, bool IsDynamic,
bool /*NonVisibilityBitsUsed*/) const override;
void printProgramHeaders() override;
void printSectionMapping() override {}
void printStackSizeEntry(uint64_t Size,
ArrayRef<std::string> FuncNames) override;
void printMipsGOT(const MipsGOTParser<ELFT> &Parser) override;
void printMipsPLT(const MipsGOTParser<ELFT> &Parser) override;
void printMipsABIFlags() override;
protected:
ScopedPrinter &W;
};
// JSONELFDumper shares most of the same implementation as LLVMELFDumper except
// it uses a JSONScopedPrinter.
template <typename ELFT> class JSONELFDumper : public LLVMELFDumper<ELFT> {
public:
LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
JSONELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
: LLVMELFDumper<ELFT>(ObjF, Writer) {}
void printFileSummary(StringRef FileStr, ObjectFile &Obj,
ArrayRef<std::string> InputFilenames,
const Archive *A) override;
private:
std::unique_ptr<DictScope> FileScope;
};
} // end anonymous namespace
namespace llvm {
template <class ELFT>
static std::unique_ptr<ObjDumper>
createELFDumper(const ELFObjectFile<ELFT> &Obj, ScopedPrinter &Writer) {
if (opts::Output == opts::GNU)
return std::make_unique<GNUELFDumper<ELFT>>(Obj, Writer);
else if (opts::Output == opts::JSON)
return std::make_unique<JSONELFDumper<ELFT>>(Obj, Writer);
return std::make_unique<LLVMELFDumper<ELFT>>(Obj, Writer);
}
std::unique_ptr<ObjDumper> createELFDumper(const object::ELFObjectFileBase &Obj,
ScopedPrinter &Writer) {
// Little-endian 32-bit
if (const ELF32LEObjectFile *ELFObj = dyn_cast<ELF32LEObjectFile>(&Obj))
return createELFDumper(*ELFObj, Writer);
// Big-endian 32-bit
if (const ELF32BEObjectFile *ELFObj = dyn_cast<ELF32BEObjectFile>(&Obj))
return createELFDumper(*ELFObj, Writer);
// Little-endian 64-bit
if (const ELF64LEObjectFile *ELFObj = dyn_cast<ELF64LEObjectFile>(&Obj))
return createELFDumper(*ELFObj, Writer);
// Big-endian 64-bit
return createELFDumper(*cast<ELF64BEObjectFile>(&Obj), Writer);
}
} // end namespace llvm
template <class ELFT>
Expected<SmallVector<Optional<VersionEntry>, 0> *>
ELFDumper<ELFT>::getVersionMap() const {
// If the VersionMap has already been loaded or if there is no dynamic symtab
// or version table, there is nothing to do.
if (!VersionMap.empty() || !DynSymRegion || !SymbolVersionSection)
return &VersionMap;
Expected<SmallVector<Optional<VersionEntry>, 0>> MapOrErr =
Obj.loadVersionMap(SymbolVersionNeedSection, SymbolVersionDefSection);
if (MapOrErr)
VersionMap = *MapOrErr;
else
return MapOrErr.takeError();
return &VersionMap;
}
template <typename ELFT>
Expected<StringRef> ELFDumper<ELFT>::getSymbolVersion(const Elf_Sym &Sym,
bool &IsDefault) const {
// This is a dynamic symbol. Look in the GNU symbol version table.
if (!SymbolVersionSection) {
// No version table.
IsDefault = false;
return "";
}
assert(DynSymRegion && "DynSymRegion has not been initialised");
// Determine the position in the symbol table of this entry.
size_t EntryIndex = (reinterpret_cast<uintptr_t>(&Sym) -
reinterpret_cast<uintptr_t>(DynSymRegion->Addr)) /
sizeof(Elf_Sym);
// Get the corresponding version index entry.
Expected<const Elf_Versym *> EntryOrErr =
Obj.template getEntry<Elf_Versym>(*SymbolVersionSection, EntryIndex);
if (!EntryOrErr)
return EntryOrErr.takeError();
unsigned Version = (*EntryOrErr)->vs_index;
if (Version == VER_NDX_LOCAL || Version == VER_NDX_GLOBAL) {
IsDefault = false;
return "";
}
Expected<SmallVector<Optional<VersionEntry>, 0> *> MapOrErr =
getVersionMap();
if (!MapOrErr)
return MapOrErr.takeError();
return Obj.getSymbolVersionByIndex(Version, IsDefault, **MapOrErr,
Sym.st_shndx == ELF::SHN_UNDEF);
}
template <typename ELFT>
Expected<RelSymbol<ELFT>>
ELFDumper<ELFT>::getRelocationTarget(const Relocation<ELFT> &R,
const Elf_Shdr *SymTab) const {
if (R.Symbol == 0)
return RelSymbol<ELFT>(nullptr, "");
Expected<const Elf_Sym *> SymOrErr =
Obj.template getEntry<Elf_Sym>(*SymTab, R.Symbol);
if (!SymOrErr)
return createError("unable to read an entry with index " + Twine(R.Symbol) +
" from " + describe(*SymTab) + ": " +
toString(SymOrErr.takeError()));
const Elf_Sym *Sym = *SymOrErr;
if (!Sym)
return RelSymbol<ELFT>(nullptr, "");
Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(*SymTab);
if (!StrTableOrErr)
return StrTableOrErr.takeError();
const Elf_Sym *FirstSym =
cantFail(Obj.template getEntry<Elf_Sym>(*SymTab, 0));
std::string SymbolName =
getFullSymbolName(*Sym, Sym - FirstSym, getShndxTable(SymTab),
*StrTableOrErr, SymTab->sh_type == SHT_DYNSYM);
return RelSymbol<ELFT>(Sym, SymbolName);
}
template <typename ELFT>
ArrayRef<typename ELFT::Word>
ELFDumper<ELFT>::getShndxTable(const Elf_Shdr *Symtab) const {
if (Symtab) {
auto It = ShndxTables.find(Symtab);
if (It != ShndxTables.end())
return It->second;
}
return {};
}
static std::string maybeDemangle(StringRef Name) {
return opts::Demangle ? demangle(std::string(Name)) : Name.str();
}
template <typename ELFT>
std::string ELFDumper<ELFT>::getStaticSymbolName(uint32_t Index) const {
auto Warn = [&](Error E) -> std::string {
reportUniqueWarning("unable to read the name of symbol with index " +
Twine(Index) + ": " + toString(std::move(E)));
return "<?>";
};
Expected<const typename ELFT::Sym *> SymOrErr =
Obj.getSymbol(DotSymtabSec, Index);
if (!SymOrErr)
return Warn(SymOrErr.takeError());
Expected<StringRef> StrTabOrErr = Obj.getStringTableForSymtab(*DotSymtabSec);
if (!StrTabOrErr)
return Warn(StrTabOrErr.takeError());
Expected<StringRef> NameOrErr = (*SymOrErr)->getName(*StrTabOrErr);
if (!NameOrErr)
return Warn(NameOrErr.takeError());
return maybeDemangle(*NameOrErr);
}
template <typename ELFT>
std::string ELFDumper<ELFT>::getFullSymbolName(const Elf_Sym &Symbol,
unsigned SymIndex,
DataRegion<Elf_Word> ShndxTable,
Optional<StringRef> StrTable,
bool IsDynamic) const {
if (!StrTable)
return "<?>";
std::string SymbolName;
if (Expected<StringRef> NameOrErr = Symbol.getName(*StrTable)) {
SymbolName = maybeDemangle(*NameOrErr);
} else {
reportUniqueWarning(NameOrErr.takeError());
return "<?>";
}
if (SymbolName.empty() && Symbol.getType() == ELF::STT_SECTION) {
Expected<unsigned> SectionIndex =
getSymbolSectionIndex(Symbol, SymIndex, ShndxTable);
if (!SectionIndex) {
reportUniqueWarning(SectionIndex.takeError());
return "<?>";
}
Expected<StringRef> NameOrErr = getSymbolSectionName(Symbol, *SectionIndex);
if (!NameOrErr) {
reportUniqueWarning(NameOrErr.takeError());
return ("<section " + Twine(*SectionIndex) + ">").str();
}
return std::string(*NameOrErr);
}
if (!IsDynamic)
return SymbolName;
bool IsDefault;
Expected<StringRef> VersionOrErr = getSymbolVersion(Symbol, IsDefault);
if (!VersionOrErr) {
reportUniqueWarning(VersionOrErr.takeError());
return SymbolName + "@<corrupt>";
}
if (!VersionOrErr->empty()) {
SymbolName += (IsDefault ? "@@" : "@");
SymbolName += *VersionOrErr;
}
return SymbolName;
}
template <typename ELFT>
Expected<unsigned>
ELFDumper<ELFT>::getSymbolSectionIndex(const Elf_Sym &Symbol, unsigned SymIndex,
DataRegion<Elf_Word> ShndxTable) const {
unsigned Ndx = Symbol.st_shndx;
if (Ndx == SHN_XINDEX)
return object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex,
ShndxTable);
if (Ndx != SHN_UNDEF && Ndx < SHN_LORESERVE)
return Ndx;
auto CreateErr = [&](const Twine &Name, Optional<unsigned> Offset = None) {
std::string Desc;
if (Offset)
Desc = (Name + "+0x" + Twine::utohexstr(*Offset)).str();
else
Desc = Name.str();
return createError(
"unable to get section index for symbol with st_shndx = 0x" +
Twine::utohexstr(Ndx) + " (" + Desc + ")");
};
if (Ndx >= ELF::SHN_LOPROC && Ndx <= ELF::SHN_HIPROC)
return CreateErr("SHN_LOPROC", Ndx - ELF::SHN_LOPROC);
if (Ndx >= ELF::SHN_LOOS && Ndx <= ELF::SHN_HIOS)
return CreateErr("SHN_LOOS", Ndx - ELF::SHN_LOOS);
if (Ndx == ELF::SHN_UNDEF)
return CreateErr("SHN_UNDEF");
if (Ndx == ELF::SHN_ABS)
return CreateErr("SHN_ABS");
if (Ndx == ELF::SHN_COMMON)
return CreateErr("SHN_COMMON");
return CreateErr("SHN_LORESERVE", Ndx - SHN_LORESERVE);
}
template <typename ELFT>
Expected<StringRef>
ELFDumper<ELFT>::getSymbolSectionName(const Elf_Sym &Symbol,
unsigned SectionIndex) const {
Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(SectionIndex);
if (!SecOrErr)
return SecOrErr.takeError();
return Obj.getSectionName(**SecOrErr);
}
template <class ELFO>
static const typename ELFO::Elf_Shdr *
findNotEmptySectionByAddress(const ELFO &Obj, StringRef FileName,
uint64_t Addr) {
for (const typename ELFO::Elf_Shdr &Shdr : cantFail(Obj.sections()))
if (Shdr.sh_addr == Addr && Shdr.sh_size > 0)
return &Shdr;
return nullptr;
}
const EnumEntry<unsigned> ElfClass[] = {
{"None", "none", ELF::ELFCLASSNONE},
{"32-bit", "ELF32", ELF::ELFCLASS32},
{"64-bit", "ELF64", ELF::ELFCLASS64},
};
const EnumEntry<unsigned> ElfDataEncoding[] = {
{"None", "none", ELF::ELFDATANONE},
{"LittleEndian", "2's complement, little endian", ELF::ELFDATA2LSB},
{"BigEndian", "2's complement, big endian", ELF::ELFDATA2MSB},
};
const EnumEntry<unsigned> ElfObjectFileType[] = {
{"None", "NONE (none)", ELF::ET_NONE},