-
Notifications
You must be signed in to change notification settings - Fork 123
/
llvm-mctoll.cpp
1594 lines (1420 loc) · 55.6 KB
/
llvm-mctoll.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
//===-- llvm-mctoll.cpp -----------------------------------------*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This program is a utility that converts a binary to LLVM IR (.ll file)
//
//===----------------------------------------------------------------------===//
#include "llvm-mctoll.h"
#include "EmitRaisedOutputPass.h"
#include "PeepholeOptimizationPass.h"
#include "Raiser/IncludedFileInfo.h"
#include "Raiser/MCInstOrData.h"
#include "Raiser/MachineFunctionRaiser.h"
#include "Raiser/ModuleRaiser.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "llvm/Bitcode/BitcodeWriterPass.h"
#include "llvm/CodeGen/FaultMaps.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/Symbolize/Symbolize.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRPrintingPasses.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDisassembler/MCDisassembler.h"
#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/MC/MCInstrAnalysis.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCTargetOptions.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/COFFImportFile.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Object/MachO.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Object/Wasm.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include <algorithm>
#include <cctype>
#include <cstring>
#include <fstream>
#include <set>
#include <system_error>
#include <unordered_map>
#include <utility>
#include <vector>
using namespace llvm;
using namespace llvm::mctoll;
using namespace object;
namespace {
using namespace llvm::opt; // for HelpHidden in Opts.inc
// custom Flag for opt::DriverFlag defined in the llvm/Option/Option.h
enum MyFlag { HelpSkipped = (1 << 4) };
enum ID {
OPT_INVALID = 0, // This is not an option ID.
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES) \
OPT_##ID,
#include "Opts.inc"
#undef OPTION
};
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "Opts.inc"
#undef PREFIX
const opt::OptTable::Info InfoTable[] = {
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES) \
{ \
PREFIX, NAME, HELPTEXT, \
METAVAR, OPT_##ID, opt::Option::KIND##Class, \
PARAM, FLAGS, OPT_##GROUP, \
OPT_##ALIAS, ALIASARGS, VALUES},
#include "Opts.inc"
#undef OPTION
};
class MctollOptTable : public opt::OptTable {
public:
MctollOptTable(const char *Usage, const char *Description)
: OptTable(InfoTable), Usage(Usage), Description(Description) {
setGroupedShortOptions(true);
}
void printHelp(StringRef Argv0, bool ShowHidden = false) const {
Argv0 = sys::path::filename(Argv0);
unsigned FlagsToExclude = HelpSkipped | (ShowHidden ? 0 : HelpHidden);
opt::OptTable::printHelp(outs(), (Argv0 + Usage).str().c_str(), Description,
0, FlagsToExclude, ShowHidden);
// TODO Replace this with OptTable API once it adds extrahelp support.
outs() << "\nPass @FILE as argument to read options from FILE.\n";
}
private:
const char *Usage;
const char *Description;
};
enum OutputFormatTy { OF_LL, OF_BC, OF_Null, OF_Unknown };
} // namespace
#define DEBUG_TYPE "mctoll"
static std::vector<std::string> InputFileNames;
static std::string OutputFilename;
std::string MCPU;
std::vector<std::string> MAttrs;
OutputFormatTy OutputFormat; // Output file type. Default is binary bitcode.
bool mctoll::Disassemble;
static bool MachOOpt;
static bool NoVerify;
std::string mctoll::TargetName;
std::string mctoll::TripleName;
std::string mctoll::SysRoot;
std::string mctoll::ArchName;
static std::string FilterConfigFileName;
std::vector<std::string> mctoll::FilterSections;
static uint64_t StartAddress;
static bool HasStartAddressFlag;
static uint64_t StopAddress = UINT64_MAX;
static bool HasStopAddressFlag;
/// String vector of include files to parse for external definitions
std::vector<std::string> mctoll::IncludeFileNames;
std::string mctoll::CompilationDBDir;
static bool PrintImmHex;
namespace {
static ManagedStatic<std::vector<std::string>> RunPassNames;
struct RunPassOption {
// NOLINTNEXTLINE(misc-unconventional-assign-operator)
auto operator=(const std::string &Val) const {
if (Val.empty())
return;
SmallVector<StringRef, 8> PassNames;
StringRef(Val).split(PassNames, ',', -1, false);
for (auto PassName : PassNames)
RunPassNames->push_back(std::string(PassName));
}
};
} // namespace
namespace {
typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
class SectionFilterIterator {
public:
SectionFilterIterator(FilterPredicate P,
llvm::object::section_iterator const &I,
llvm::object::section_iterator const &E)
: Predicate(std::move(P)), Iterator(I), End(E) {
scanPredicate();
}
const llvm::object::SectionRef &operator*() const { return *Iterator; }
SectionFilterIterator &operator++() {
++Iterator;
scanPredicate();
return *this;
}
bool operator!=(SectionFilterIterator const &Other) const {
return Iterator != Other.Iterator;
}
private:
void scanPredicate() {
while (Iterator != End && !Predicate(*Iterator)) {
++Iterator;
}
}
FilterPredicate Predicate;
llvm::object::section_iterator Iterator;
llvm::object::section_iterator End;
};
class SectionFilter {
public:
SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
: Predicate(std::move(P)), Object(O) {}
SectionFilterIterator begin() {
return SectionFilterIterator(Predicate, Object.section_begin(),
Object.section_end());
}
SectionFilterIterator end() {
return SectionFilterIterator(Predicate, Object.section_end(),
Object.section_end());
}
private:
FilterPredicate Predicate;
llvm::object::ObjectFile const &Object;
};
SectionFilter toolSectionFilter(llvm::object::ObjectFile const &O) {
return SectionFilter(
[](llvm::object::SectionRef const &S) {
if (FilterSections.empty())
return true;
llvm::StringRef String;
if (auto NameOrErr = S.getName())
String = *NameOrErr;
else {
consumeError(NameOrErr.takeError());
return false;
}
return is_contained(FilterSections, String);
},
O);
}
} // namespace
static const Target *getTarget(const ObjectFile *Obj = nullptr) {
// Figure out the target triple.
llvm::Triple TheTriple("unknown-unknown-unknown");
if (TripleName.empty()) {
if (Obj) {
auto Arch = Obj->getArch();
TheTriple.setArch(Triple::ArchType(Arch));
// For ARM targets, try to use the build attributes to build determine
// the build target. Target features are also added, but later during
// disassembly.
if (Arch == Triple::arm || Arch == Triple::armeb) {
Obj->setARMSubArch(TheTriple);
}
// TheTriple defaults to ELF, and COFF doesn't have an environment:
// the best we can do here is indicate that it is mach-o.
if (Obj->isMachO())
TheTriple.setObjectFormat(Triple::MachO);
if (Obj->isCOFF()) {
const auto *const COFFObj = dyn_cast<COFFObjectFile>(Obj);
if (COFFObj->getArch() == Triple::thumb)
TheTriple.setTriple("thumbv7-windows");
}
}
} else {
TheTriple.setTriple(Triple::normalize(TripleName));
// Use the triple, but also try to combine with ARM build attributes.
if (Obj) {
auto Arch = Obj->getArch();
if (Arch == Triple::arm || Arch == Triple::armeb) {
Obj->setARMSubArch(TheTriple);
}
}
}
// Get the target specific parser.
std::string Error;
const Target *TheTarget =
TargetRegistry::lookupTarget(mctoll::ArchName, TheTriple, Error);
if (!TheTarget) {
if (Obj)
reportError(Obj->getFileName(), "Support for raising " +
TheTriple.getArchName() +
" not included");
else
error("Unsupported target " + TheTriple.getArchName());
}
// A few of opcodes in ARMv4 or ARMv5 are identified as ARMv6 opcodes,
// so unify the triple Archs lower than ARMv6 to ARMv6 temporarily.
if (TheTriple.getArchName() == "armv4t" ||
TheTriple.getArchName() == "armv5te" ||
TheTriple.getArchName() == "armv5" || TheTriple.getArchName() == "armv5t")
TheTriple.setArchName("armv6");
// Update the triple name and return the found target.
TripleName = TheTriple.getTriple();
return TheTarget;
}
static std::unique_ptr<ToolOutputFile> getOutputStream(StringRef InfileName) {
// If output file name is not explicitly specified construct a name based on
// the input file name.
if (OutputFilename.empty()) {
// If InputFilename ends in .o, remove it.
if (InfileName.endswith(".o"))
OutputFilename = std::string(InfileName.drop_back(2));
else if (InfileName.endswith(".so"))
OutputFilename = std::string(InfileName.drop_back(3));
else
OutputFilename = std::string(InfileName);
switch (OutputFormat) {
case OF_LL:
OutputFilename += "-dis.ll";
break;
// Just uses enum CGFT_ObjectFile represent llvm bitcode file type
// provisionally.
case OF_BC:
OutputFilename += "-dis.bc";
break;
default:
OutputFilename += ".null";
break;
}
}
// Decide if we need "binary" output.
bool Binary = OutputFormat != OF_LL;
// Open the file.
std::error_code EC;
sys::fs::OpenFlags OpenFlags = sys::fs::OF_None;
if (!Binary)
OpenFlags |= sys::fs::OF_Text;
auto FDOut = std::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);
if (EC) {
errs() << EC.message() << '\n';
return nullptr;
}
return FDOut;
}
static bool addPass(PassManagerBase &PM, StringRef Argv0, StringRef PassName,
TargetPassConfig &TPC) {
if (PassName == "none")
return false;
const PassRegistry *PR = PassRegistry::getPassRegistry();
const PassInfo *PI = PR->getPassInfo(PassName);
if (!PI) {
errs() << Argv0 << ": run-pass " << PassName << " is not registered.\n";
return true;
}
Pass *P;
if (PI->getNormalCtor())
P = PI->getNormalCtor()();
else {
errs() << Argv0 << ": cannot create pass: " << PI->getPassName() << "\n";
return true;
}
std::string Banner = std::string("After ") + std::string(P->getPassName());
PM.add(P);
TPC.printAndVerify(Banner);
return false;
}
bool mctoll::RelocAddressLess(RelocationRef A, RelocationRef B) {
return A.getOffset() < B.getOffset();
}
namespace {
static bool isArmElf(const ObjectFile *Obj) {
return (Obj->isELF() &&
(Obj->getArch() == Triple::aarch64 ||
Obj->getArch() == Triple::aarch64_be ||
Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
Obj->getArch() == Triple::thumb ||
Obj->getArch() == Triple::thumbeb));
}
class PrettyPrinter {
public:
virtual ~PrettyPrinter() {}
virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
ArrayRef<uint8_t> Bytes, uint64_t Address,
raw_ostream &OS, StringRef Annot,
MCSubtargetInfo const &STI) {
OS << format("%8" PRIx64 ":", Address);
OS << "\t";
dumpBytes(Bytes, OS);
if (MI)
IP.printInst(MI, 0, "", STI, OS);
else
OS << " <unknown>";
}
};
PrettyPrinter PrettyPrinterInst;
PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
return PrettyPrinterInst;
}
} // namespace
bool mctoll::isRelocAddressLess(RelocationRef A, RelocationRef B) {
return A.getOffset() < B.getOffset();
}
template <class ELFT>
static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
const RelocationRef &RelRef,
SmallVectorImpl<char> &Result) {
DataRefImpl Rel = RelRef.getRawDataRefImpl();
typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
const ELFFile<ELFT> &EF = *Obj->getELFFile();
auto SecOrErr = EF.getSection(Rel.d.a);
if (!SecOrErr)
return errorToErrorCode(SecOrErr.takeError());
const Elf_Shdr *Sec = *SecOrErr;
auto SymTabOrErr = EF.getSection(Sec->sh_link);
if (!SymTabOrErr)
return errorToErrorCode(SymTabOrErr.takeError());
const Elf_Shdr *SymTab = *SymTabOrErr;
assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
SymTab->sh_type == ELF::SHT_DYNSYM);
auto StrTabSec = EF.getSection(SymTab->sh_link);
if (!StrTabSec)
return errorToErrorCode(StrTabSec.takeError());
auto StrTabOrErr = EF.getStringTable(*StrTabSec);
if (!StrTabOrErr)
return errorToErrorCode(StrTabOrErr.takeError());
StringRef StrTab = *StrTabOrErr;
uint8_t RefType = RelRef.getType();
StringRef Res;
int64_t Addend = 0;
switch (Sec->sh_type) {
default:
return object_error::parse_failed;
case ELF::SHT_REL: {
// TODO: Read implicit addend from section data.
break;
}
case ELF::SHT_RELA: {
const Elf_Rela *ERela = Obj->getRela(Rel);
Addend = ERela->r_addend;
break;
}
}
symbol_iterator SI = RelRef.getSymbol();
const Elf_Sym *Symb = Obj->getSymbol(SI->getRawDataRefImpl());
StringRef Target;
if (Symb->getType() == ELF::STT_SECTION) {
Expected<section_iterator> SymSI = SI->getSection();
if (!SymSI)
return errorToErrorCode(SymSI.takeError());
const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
auto SecName = EF.getSectionName(SymSec);
if (!SecName)
return errorToErrorCode(SecName.takeError());
Target = *SecName;
} else {
Expected<StringRef> SymName = Symb->getName(StrTab);
if (!SymName)
return errorToErrorCode(SymName.takeError());
Target = *SymName;
}
switch (EF.getHeader()->e_machine) {
case ELF::EM_X86_64:
switch (RefType) {
case ELF::R_X86_64_PC8:
case ELF::R_X86_64_PC16:
case ELF::R_X86_64_PC32: {
std::string FmtBuf;
raw_string_ostream Fmt(FmtBuf);
Fmt << Target << (Addend < 0 ? "" : "+") << Addend << "-P";
Fmt.flush();
Result.append(FmtBuf.begin(), FmtBuf.end());
} break;
case ELF::R_X86_64_8:
case ELF::R_X86_64_16:
case ELF::R_X86_64_32:
case ELF::R_X86_64_32S:
case ELF::R_X86_64_64: {
std::string FmtBuf;
raw_string_ostream Fmt(FmtBuf);
Fmt << Target << (Addend < 0 ? "" : "+") << Addend;
Fmt.flush();
Result.append(FmtBuf.begin(), FmtBuf.end());
} break;
default:
Res = "Unknown";
}
break;
case ELF::EM_LANAI:
case ELF::EM_AVR:
case ELF::EM_AARCH64: {
std::string FmtBuf;
raw_string_ostream Fmt(FmtBuf);
Fmt << Target;
if (Addend != 0)
Fmt << (Addend < 0 ? "" : "+") << Addend;
Fmt.flush();
Result.append(FmtBuf.begin(), FmtBuf.end());
break;
}
case ELF::EM_386:
case ELF::EM_IAMCU:
case ELF::EM_ARM:
case ELF::EM_HEXAGON:
case ELF::EM_MIPS:
case ELF::EM_BPF:
case ELF::EM_RISCV:
Res = Target;
break;
default:
Res = "Unknown";
}
if (Result.empty())
Result.append(Res.begin(), Res.end());
return std::error_code();
}
static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
assert(Obj->isELF());
auto SymbImpl = Sym.getRawDataRefImpl();
if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj)) {
auto SymbOrErr = Elf32LEObj->getSymbol(SymbImpl);
if (!SymbOrErr)
reportError(SymbOrErr.takeError(), "ELF32 symbol not found");
return SymbOrErr.get()->getType();
}
if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj)) {
auto SymbOrErr = Elf64LEObj->getSymbol(SymbImpl);
if (!SymbOrErr)
reportError(SymbOrErr.takeError(), "ELF32 symbol not found");
return SymbOrErr.get()->getType();
}
if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj)) {
auto SymbOrErr = Elf32BEObj->getSymbol(SymbImpl);
if (!SymbOrErr)
reportError(SymbOrErr.takeError(), "ELF32 symbol not found");
return SymbOrErr.get()->getType();
}
if (auto *Elf64BEObj = dyn_cast<ELF64BEObjectFile>(Obj)) {
auto SymbOrErr = Elf64BEObj->getSymbol(SymbImpl);
if (!SymbOrErr)
reportError(SymbOrErr.takeError(), "ELF32 symbol not found");
return SymbOrErr.get()->getType();
}
llvm_unreachable("Unsupported binary format");
// Keep the code analyzer happy
return ELF::STT_NOTYPE;
}
template <class ELFT>
static void
addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
for (auto Symbol : Obj->getDynamicSymbolIterators()) {
uint8_t SymbolType = Symbol.getELFType();
if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
continue;
Expected<uint64_t> AddressOrErr = Symbol.getAddress();
if (!AddressOrErr)
reportError(AddressOrErr.takeError(), Obj->getFileName());
uint64_t Address = *AddressOrErr;
Expected<StringRef> Name = Symbol.getName();
if (!Name)
reportError(Name.takeError(), Obj->getFileName());
if (Name->empty())
continue;
Expected<section_iterator> SectionOrErr = Symbol.getSection();
if (!SectionOrErr)
reportError(SectionOrErr.takeError(), Obj->getFileName());
section_iterator SecI = *SectionOrErr;
if (SecI == Obj->section_end())
continue;
AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
}
}
static void
addDynamicElfSymbols(const ObjectFile *Obj,
std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
assert(Obj->isELF());
if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
addDynamicElfSymbols(Elf32LEObj, AllSymbols);
else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
addDynamicElfSymbols(Elf64LEObj, AllSymbols);
else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
addDynamicElfSymbols(Elf32BEObj, AllSymbols);
else if (auto *Elf64BEObj = dyn_cast<ELF64BEObjectFile>(Obj))
addDynamicElfSymbols(Elf64BEObj, AllSymbols);
else
llvm_unreachable("Unsupported binary format");
}
/*
A list of symbol entries corresponding to CRT functions added by
the linker while creating an ELF executable. It is not necessary to
disassemble and translate these functions.
*/
static std::set<StringRef> ELFCRTSymbols = {
"call_weak_fn",
"deregister_tm_clones",
"__do_global_dtors_aux",
"__do_global_dtors_aux_fini_array_entry",
"_fini",
"frame_dummy",
"__frame_dummy_init_array_entry",
"_init",
"__init_array_end",
"__init_array_start",
"__libc_csu_fini",
"__libc_csu_init",
"register_tm_clones",
"_start",
"_dl_relocate_static_pie"};
/*
A list of symbol entries corresponding to CRT functions added by
the linker while creating an MachO executable. It is not necessary
to disassemble and translate these functions.
*/
static std::set<StringRef> MachOCRTSymbols = {"__mh_execute_header",
"dyld_stub_binder", "__text",
"__stubs", "__stub_helper"};
/*
A list of sections whose contents are to be disassembled as code
*/
static std::set<StringRef> ELFSectionsToDisassemble = {".text"};
static std::set<StringRef> MachOSectionsToDisassemble = {};
/* TODO : If it is a C++ binary object symbol, look at the
signature of the symbol to deduce the return value and return
type. If the symbol does not include the function signature,
just create a function that takes no arguments */
/* A non vararg function type with no arguments */
/* TODO: Figure out the symbol linkage type from the symbol
table. For now assuming global linkage
*/
static bool isAFunctionSymbol(const ObjectFile *Obj, SymbolInfoTy &Symbol) {
if (Obj->isELF()) {
return (Symbol.Type == ELF::STT_FUNC);
}
if (Obj->isMachO()) {
// If Symbol is not in the MachOCRTSymbol list return true indicating that
// this is a symbol of a function we are interested in disassembling and
// raising.
return (MachOCRTSymbols.find(Symbol.Name) == MachOCRTSymbols.end());
}
return false;
}
#define MODULE_RAISER(TargetName) \
extern "C" void register##TargetName##ModuleRaiser();
#include "Raisers.def"
static void initializeAllModuleRaisers() {
#define MODULE_RAISER(TargetName) register##TargetName##ModuleRaiser();
#include "Raisers.def"
}
static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
if (StartAddress > StopAddress)
error("Start address should be less than stop address");
const Target *TheTarget = getTarget(Obj);
// Package up features to be passed to target/subtarget
SubtargetFeatures Features = Obj->getFeatures();
if (MAttrs.size()) {
for (unsigned Idx = 0; Idx != MAttrs.size(); ++Idx)
Features.AddFeature(MAttrs[Idx]);
}
std::unique_ptr<const MCRegisterInfo> MRI(
TheTarget->createMCRegInfo(TripleName));
if (!MRI)
reportError(Obj->getFileName(),
"no register info for target " + TripleName);
MCTargetOptions MCOptions;
// Set up disassembler.
std::unique_ptr<const MCAsmInfo> AsmInfo(
TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
if (!AsmInfo)
reportError(Obj->getFileName(),
"no assembly info for target " + TripleName);
std::unique_ptr<const MCSubtargetInfo> STI(
TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
if (!STI)
reportError(Obj->getFileName(),
"no subtarget info for target " + TripleName);
std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
if (!MII)
reportError(Obj->getFileName(),
"no instruction info for target " + TripleName);
MCContext Ctx(Triple(TripleName), AsmInfo.get(), MRI.get(), STI.get());
std::unique_ptr<MCDisassembler> DisAsm(
TheTarget->createMCDisassembler(*STI, Ctx));
if (!DisAsm)
reportError(Obj->getFileName(), "no disassembler for target " + TripleName);
std::unique_ptr<const MCInstrAnalysis> MIA(
TheTarget->createMCInstrAnalysis(MII.get()));
int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
if (!IP)
reportError(Obj->getFileName(),
"no instruction printer for target " + TripleName);
IP->setPrintImmHex(PrintImmHex);
PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
LLVMContext LlvmCtx;
std::unique_ptr<TargetMachine> Target(
TheTarget->createTargetMachine(TripleName, MCPU, Features.getString(),
TargetOptions(), /* RelocModel */ None));
assert(Target && "Could not allocate target machine!");
LLVMTargetMachine &LlvmTgtMach = static_cast<LLVMTargetMachine &>(*Target);
MachineModuleInfoWrapperPass *MachineModuleInfo =
new MachineModuleInfoWrapperPass(&LlvmTgtMach);
/* New Module instance with file name */
Module M(Obj->getFileName(), LlvmCtx);
/* Set datalayout of the module to be the same as LLVMTargetMachine */
M.setDataLayout(Target->createDataLayout());
MachineModuleInfo->doInitialization(M);
// Initialize all module raisers that are supported and are part of current
// LLVM build.
initializeAllModuleRaisers();
// Get the module raiser for Target of the binary being raised
ModuleRaiser *MR = mctoll::getModuleRaiser(Target.get());
assert((MR != nullptr) && "Failed to build module raiser");
// Set data of module raiser
MR->setModuleRaiserInfo(&M, Target.get(), &MachineModuleInfo->getMMI(),
MIA.get(), MII.get(), MRI.get(), IP.get(), Obj,
DisAsm.get());
// Collect dynamic relocations.
MR->collectDynamicRelocations();
// Create a mapping, RelocSecs = SectionRelocMap[S], where sections
// in RelocSecs contain the relocations for section S.
std::error_code EC;
std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
for (const SectionRef &Section : toolSectionFilter(*Obj)) {
Expected<section_iterator> SecOrErr = Section.getRelocatedSection();
if (!SecOrErr) {
break;
}
section_iterator Sec2 = *SecOrErr;
if (Sec2 != Obj->section_end())
SectionRelocMap[*Sec2].push_back(Section);
}
// Create a mapping from virtual address to symbol name. This is used to
// pretty print the symbols while disassembling.
std::map<SectionRef, SectionSymbolsTy> AllSymbols;
for (const SymbolRef &Symbol : Obj->symbols()) {
Expected<uint64_t> AddressOrErr = Symbol.getAddress();
if (!AddressOrErr)
reportError(AddressOrErr.takeError(), Obj->getFileName());
uint64_t Address = *AddressOrErr;
Expected<StringRef> Name = Symbol.getName();
if (!Name)
reportError(Name.takeError(), Obj->getFileName());
if (Name->empty())
continue;
Expected<section_iterator> SectionOrErr = Symbol.getSection();
if (!SectionOrErr)
reportError(SectionOrErr.takeError(), Obj->getFileName());
section_iterator SecI = *SectionOrErr;
if (SecI == Obj->section_end())
continue;
uint8_t SymbolType = ELF::STT_NOTYPE;
if (Obj->isELF())
SymbolType = getElfSymbolType(Obj, Symbol);
AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
}
if (AllSymbols.empty() && Obj->isELF())
addDynamicElfSymbols(Obj, AllSymbols);
// Create a mapping from virtual address to section.
std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
for (SectionRef Sec : Obj->sections())
SectionAddresses.emplace_back(Sec.getAddress(), Sec);
array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
// Linked executables (.exe and .dll files) typically don't include a real
// symbol table, but they might contain an export table.
if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
for (const auto &ExportEntry : COFFObj->export_directories()) {
StringRef Name;
error(ExportEntry.getSymbolName(Name));
if (Name.empty())
continue;
uint32_t RVA;
error(ExportEntry.getExportRVA(RVA));
uint64_t VA = COFFObj->getImageBase() + RVA;
auto Sec = std::upper_bound(
SectionAddresses.begin(), SectionAddresses.end(), VA,
[](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
return LHS < RHS.first;
});
if (Sec != SectionAddresses.begin())
--Sec;
else
Sec = SectionAddresses.end();
if (Sec != SectionAddresses.end())
AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
}
}
// Sort all the symbols, this allows us to use a simple binary search to find
// a symbol near an address.
for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
for (const SectionRef &Section : toolSectionFilter(*Obj)) {
if ((!Section.isText() || Section.isVirtual()))
continue;
StringRef SectionName;
if (auto NameOrErr = Section.getName())
SectionName = *NameOrErr;
else
consumeError(NameOrErr.takeError());
uint64_t SectionAddr = Section.getAddress();
uint64_t SectSize = Section.getSize();
if (!SectSize)
continue;
// Get the list of all the symbols in this section.
SectionSymbolsTy &Symbols = AllSymbols[Section];
std::vector<uint64_t> DataMappingSymsAddr;
std::vector<uint64_t> TextMappingSymsAddr;
if (isArmElf(Obj)) {
for (const auto &Symb : Symbols) {
uint64_t Address = Symb.Addr;
StringRef Name = Symb.Name;
if (Name.startswith("$d"))
DataMappingSymsAddr.push_back(Address - SectionAddr);
if (Name.startswith("$x"))
TextMappingSymsAddr.push_back(Address - SectionAddr);
if (Name.startswith("$a"))
TextMappingSymsAddr.push_back(Address - SectionAddr);
if (Name.startswith("$t"))
TextMappingSymsAddr.push_back(Address - SectionAddr);
}
}
std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
// If the section has no symbol at the start, just insert a dummy one.
StringRef DummyName;
if (Symbols.empty() || Symbols[0].Addr != 0) {
Symbols.insert(
Symbols.begin(),
SymbolInfoTy(SectionAddr, DummyName,
Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
}
SmallString<40> Comments;
raw_svector_ostream CommentStream(Comments);
StringRef BytesStr =
unwrapOrError(Section.getContents(), Obj->getFileName());
ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
BytesStr.size());
uint64_t Size;
uint64_t Index;
FunctionFilter *FuncFilter = MR->getFunctionFilter();
if (!FilterConfigFileName.empty()) {
if (!FuncFilter->readFilterFunctionConfigFile(FilterConfigFileName)) {
dbgs() << "Unable to read function filter configuration file "
<< FilterConfigFileName << ". Ignoring\n";
}
}
// Build a map of relocations (if they exist in the binary) of text
// section whose instructions are being raised.
MR->collectTextSectionRelocs(Section);
// Set used to record all branch targets of a function.
std::set<uint64_t> BranchTargetSet;
MachineFunctionRaiser *CurMFRaiser = nullptr;
// Disassemble symbol by symbol and fill MR->MFRaiserVector by
// MachineFunctionRaiser for each function
LLVM_DEBUG(dbgs() << "BEGIN Disassembly of Functions in Section : "
<< SectionName.data() << "\n");
for (unsigned SI = 0, SSize = Symbols.size(); SI != SSize; ++SI) {
uint64_t Start = Symbols[SI].Addr - SectionAddr;
// The end is either the section end or the beginning of the next
// symbol.
uint64_t End =
(SI == SSize - 1) ? SectSize : Symbols[SI + 1].Addr - SectionAddr;
// Don't try to disassemble beyond the end of section contents.
if (End > SectSize)
End = SectSize;
// If this symbol has the same address as the next symbol, then skip it.
if (Start >= End)
continue;
// Check if we need to skip symbol
// Skip if the symbol's data is not between StartAddress and StopAddress
if (End + SectionAddr < StartAddress ||
Start + SectionAddr > StopAddress) {
continue;
}
// Stop disassembly at the stop address specified
if (End + SectionAddr > StopAddress)
End = StopAddress - SectionAddr;
if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
// make size 4 bytes folded
End = Start + ((End - Start) & ~0x3ull);
if (Symbols[SI].Type == ELF::STT_AMDGPU_HSA_KERNEL) {
// skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
Start += 256;
}
if (SI == SSize - 1 ||
Symbols[SI + 1].Type == ELF::STT_AMDGPU_HSA_KERNEL) {
// cut trailing zeroes at the end of kernel
// cut up to 256 bytes
const uint64_t EndAlign = 256;
const auto Limit = End - (std::min)(EndAlign, End - Start);
while (End > Limit && *reinterpret_cast<const support::ulittle32_t *>(
&Bytes[End - 4]) == 0)
End -= 4;
}
}
if (isAFunctionSymbol(Obj, Symbols[SI])) {
auto &SymStr = Symbols[SI].Name;
bool RaiseFuncSymbol = true;
if ((!FilterConfigFileName.empty())) {
// Check the symbol name whether it should be excluded or not.
// Check in a non-empty exclude list
if (!FuncFilter->isFilterSetEmpty(FunctionFilter::FILTER_EXCLUDE)) {
FunctionFilter::FuncInfo *FI = FuncFilter->findFuncInfoBySymbol(
SymStr, FunctionFilter::FILTER_EXCLUDE);
if (FI != nullptr) {