forked from microsoft/llvm-mctoll
-
Notifications
You must be signed in to change notification settings - Fork 0
/
llvm-mctoll.cpp
1833 lines (1608 loc) · 63.8 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 "MCInstOrData.h"
#include "MachineFunctionRaiser.h"
#include "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/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/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/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/WithColor.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 object;
static cl::OptionCategory LLVMMCToLLCategory("llvm-mctoll options");
static cl::list<std::string> InputFilenames(cl::Positional,
cl::desc("<input object files>"),
cl::ZeroOrMore);
static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
cl::value_desc("filename"),
cl::cat(LLVMMCToLLCategory),
cl::NotHidden);
cl::opt<std::string>
MCPU("mcpu",
cl::desc("Target a specific cpu type (-mcpu=help for details)"),
cl::value_desc("cpu-name"), cl::init(""));
cl::list<std::string>
MAttrs("mattr", cl::CommaSeparated,
cl::desc("Target specific attributes (-mattr=help for details)"),
cl::value_desc("a1,+a2,-a3,..."));
// Output file type. Default is binary bitcode.
cl::opt<CodeGenFileType> OutputFormat(
"output-format", cl::init(CGFT_AssemblyFile),
cl::desc("Output format (default: binary bitcode):"),
cl::values(clEnumValN(CGFT_AssemblyFile, "ll",
"Emit llvm text bitcode ('.ll') file"),
clEnumValN(CGFT_ObjectFile, "bc",
"Emit llvm binary bitcode ('.bc') file"),
clEnumValN(CGFT_Null, "null",
"Emit nothing, for performance testing")),
cl::cat(LLVMMCToLLCategory), cl::NotHidden);
cl::opt<bool> llvm::Disassemble("raise", cl::desc("Raise machine instruction"),
cl::cat(LLVMMCToLLCategory), cl::NotHidden);
cl::alias Disassembled("d", cl::desc("Alias for -raise"),
cl::aliasopt(Disassemble), cl::cat(LLVMMCToLLCategory),
cl::NotHidden);
static cl::opt<bool>
MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
static cl::alias MachOm("m", cl::desc("Alias for --macho"),
cl::aliasopt(MachOOpt));
static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
cl::desc("Do not verify input module"));
cl::opt<std::string>
llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
"see -version for available targets"));
cl::opt<std::string>
llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
"see -version for available targets"));
cl::opt<std::string> llvm::FilterFunctionSet(
"filter-functions-file",
cl::desc("Specify which functions to raise via a configuration file."),
cl::cat(LLVMMCToLLCategory), cl::NotHidden);
cl::alias static FilterFunctionSetF(
"f", cl::desc("Alias for --filter-functions-file"),
cl::aliasopt(llvm::FilterFunctionSet), cl::cat(LLVMMCToLLCategory),
cl::NotHidden);
cl::opt<bool> llvm::SectionHeaders("section-headers",
cl::desc("Display summaries of the "
"headers for each section."));
static cl::alias SectionHeadersShort("headers",
cl::desc("Alias for --section-headers"),
cl::aliasopt(SectionHeaders));
static cl::alias SectionHeadersShorter("h",
cl::desc("Alias for --section-headers"),
cl::aliasopt(SectionHeaders));
cl::list<std::string>
llvm::FilterSections("section",
cl::desc("Operate on the specified sections only. "
"With -macho dump segment,section"));
cl::alias static FilterSectionsj("j", cl::desc("Alias for --section"),
cl::aliasopt(llvm::FilterSections));
cl::opt<bool> llvm::NoShowRawInsn("no-show-raw-insn",
cl::desc("When disassembling "
"instructions, do not print "
"the instruction bytes."));
cl::opt<bool> llvm::NoLeadingAddr("no-leading-addr",
cl::desc("Print no leading address"));
cl::opt<bool> llvm::UnwindInfo("unwind-info",
cl::desc("Display unwind information"));
static cl::alias UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
cl::aliasopt(UnwindInfo));
cl::opt<bool>
llvm::PrivateHeaders("private-headers",
cl::desc("Display format specific file headers"));
cl::opt<bool> llvm::FirstPrivateHeader(
"private-header", cl::desc("Display only the first format specific file "
"header"));
static cl::alias PrivateHeadersShort("p",
cl::desc("Alias for --private-headers"),
cl::aliasopt(PrivateHeaders));
cl::opt<bool>
llvm::PrintImmHex("print-imm-hex",
cl::desc("Use hex format for immediate values"));
cl::opt<bool> PrintFaultMaps("fault-map-section",
cl::desc("Display contents of faultmap section"));
cl::opt<unsigned long long>
StartAddress("start-address", cl::desc("Disassemble beginning at address"),
cl::value_desc("address"), cl::init(0));
cl::opt<unsigned long long> StopAddress("stop-address",
cl::desc("Stop disassembly at address"),
cl::value_desc("address"),
cl::init(UINT64_MAX));
namespace {
static ManagedStatic<std::vector<std::string>> RunPassNames;
struct RunPassOption {
void 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(PassName);
}
};
} // namespace
static RunPassOption RunPassOpt;
static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
"run-pass",
cl::desc("Run compiler only for specified passes (comma separated list)"),
cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
static StringRef ToolName;
typedef std::tuple<uint64_t, StringRef, uint8_t> SectionSymbolInfo;
typedef std::vector<SectionSymbolInfo> SectionSymbolsTy;
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
void llvm::error(std::error_code EC) {
if (!EC)
return;
errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
errs().flush();
exit(1);
}
void llvm::error(Error E) {
if (!E)
return;
WithColor::error(errs(), ToolName) << toString(std::move(E));
exit(1);
}
LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
errs() << ToolName << ": " << Message << ".\n";
errs().flush();
exit(1);
}
LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File, Twine Message) {
WithColor::error(errs(), ToolName)
<< "'" << File << "': " << Message << ".\n";
exit(1);
}
LLVM_ATTRIBUTE_NORETURN void llvm::report_error(Error E, StringRef File) {
assert(E);
std::string Buf;
raw_string_ostream OS(Buf);
logAllUnhandledErrors(std::move(E), OS);
OS.flush();
WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
exit(1);
}
LLVM_ATTRIBUTE_NORETURN void llvm::report_error(Error E, StringRef ArchiveName,
StringRef FileName,
StringRef ArchitectureName) {
assert(E);
WithColor::error(errs(), ToolName);
if (ArchiveName != "")
errs() << ArchiveName << "(" << FileName << ")";
else
errs() << "'" << FileName << "'";
if (!ArchitectureName.empty())
errs() << " (for architecture " << ArchitectureName << ")";
std::string Buf;
raw_string_ostream OS(Buf);
logAllUnhandledErrors(std::move(E), OS);
OS.flush();
errs() << ": " << Buf;
exit(1);
}
LLVM_ATTRIBUTE_NORETURN void llvm::report_error(Error E, StringRef ArchiveName,
const object::Archive::Child &C,
StringRef ArchitectureName) {
Expected<StringRef> NameOrErr = C.getName();
// TODO: if we have a error getting the name then it would be nice to print
// the index of which archive member this is and or its offset in the
// archive instead of "???" as the name.
if (!NameOrErr) {
consumeError(NameOrErr.takeError());
report_error(std::move(E), ArchiveName, "???", ArchitectureName);
} else
report_error(std::move(E), ArchiveName, NameOrErr.get(), ArchitectureName);
}
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 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(ArchName, TheTriple, Error);
if (!TheTarget) {
if (Obj)
report_error(Obj->getFileName(), "Support for raising " +
TheTriple.getArchName() +
" not included");
else
error("Unsupported target " + TheTriple.getArchName());
}
// Update the triple name and return the found target.
TripleName = TheTriple.getTriple();
return TheTarget;
}
static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName,
Triple::OSType OS,
const char *ProgName) {
// If we don't yet have an output filename, make one.
if (OutputFilename.empty()) {
// If InputFilename ends in .o, remove it.
StringRef IFN = InputFilenames[0];
if (IFN.endswith(".o"))
OutputFilename = IFN.drop_back(2);
else if (IFN.endswith(".so"))
OutputFilename = IFN.drop_back(3);
else
OutputFilename = IFN;
switch (OutputFormat) {
case CGFT_AssemblyFile:
OutputFilename += "-dis.ll";
break;
// Just uses enum CGFT_ObjectFile represent llvm bitcode file type
// provisionally.
case CGFT_ObjectFile:
OutputFilename += "-dis.bc";
break;
case CGFT_Null:
OutputFilename += ".null";
break;
}
}
// Decide if we need "binary" output.
bool Binary = false;
switch (OutputFormat) {
case CGFT_AssemblyFile:
break;
case CGFT_ObjectFile:
case CGFT_Null:
Binary = true;
break;
}
// Open the file.
std::error_code EC;
sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
if (!Binary)
OpenFlags |= sys::fs::F_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 toolname, StringRef PassName,
TargetPassConfig &TPC) {
if (PassName == "none")
return false;
const PassRegistry *PR = PassRegistry::getPassRegistry();
const PassInfo *PI = PR->getPassInfo(PassName);
if (!PI) {
errs() << toolname << ": run-pass " << PassName << " is not registered.\n";
return true;
}
Pass *P;
if (PI->getNormalCtor())
P = PI->getNormalCtor()();
else {
errs() << toolname << ": 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 llvm::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) {
if (!NoLeadingAddr)
OS << format("%8" PRIx64 ":", Address);
if (!NoShowRawInsn) {
OS << "\t";
dumpBytes(Bytes, OS);
}
if (MI)
IP.printInst(MI, OS, "", STI);
else
OS << " <unknown>";
}
};
PrettyPrinter PrettyPrinterInst;
PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
return PrettyPrinterInst;
}
} // namespace
bool llvm::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 type = 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 (type) {
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());
if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->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)
report_error(AddressOrErr.takeError(), Obj->getFileName());
uint64_t Address = *AddressOrErr;
Expected<StringRef> Name = Symbol.getName();
if (!Name)
report_error(Name.takeError(), Obj->getFileName());
if (Name->empty())
continue;
Expected<section_iterator> SectionOrErr = Symbol.getSection();
if (!SectionOrErr)
report_error(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 = 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 = {
"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,
SectionSymbolInfo &Symbol) {
if (Obj->isELF()) {
return (std::get<2>(Symbol) == 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(std::get<1>(Symbol)) == MachOCRTSymbols.end());
}
return false;
}
namespace RaiserContext {
SmallVector<ModuleRaiser *, 4> ModuleRaiserRegistry;
bool isSupportedArch(Triple::ArchType arch) {
for (auto m : ModuleRaiserRegistry)
if (m->getArchType() == arch)
return true;
return false;
}
ModuleRaiser *getModuleRaiser(const TargetMachine *tm) {
ModuleRaiser *mr = nullptr;
auto arch = tm->getTargetTriple().getArch();
for (auto m : ModuleRaiserRegistry)
if (m->getArchType() == arch) {
mr = m;
break;
}
assert(nullptr != mr && "This arch has not yet supported for raising!\n");
return mr;
}
} // namespace RaiserContext
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 i = 0; i != MAttrs.size(); ++i)
Features.AddFeature(MAttrs[i]);
}
std::unique_ptr<const MCRegisterInfo> MRI(
TheTarget->createMCRegInfo(TripleName));
if (!MRI)
report_error(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)
report_error(Obj->getFileName(),
"no assembly info for target " + TripleName);
std::unique_ptr<const MCSubtargetInfo> STI(
TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
if (!STI)
report_error(Obj->getFileName(),
"no subtarget info for target " + TripleName);
std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
if (!MII)
report_error(Obj->getFileName(),
"no instruction info for target " + TripleName);
MCObjectFileInfo MOFI;
MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
// FIXME: for now initialize MCObjectFileInfo with default values
MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
std::unique_ptr<MCDisassembler> DisAsm(
TheTarget->createMCDisassembler(*STI, Ctx));
if (!DisAsm)
report_error(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)
report_error(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 module(Obj->getFileName(), llvmCtx);
/* Set datalayout of the module to be the same as LLVMTargetMachine */
module.setDataLayout(Target->createDataLayout());
machineModuleInfo->doInitialization(module);
// Initialize all module raisers that are supported and are part of current
// LLVM build.
ModuleRaiser::InitializeAllModuleRaisers();
// Get the module raiser for Target of the binary being raised
ModuleRaiser *moduleRaiser = RaiserContext::getModuleRaiser(Target.get());
assert((moduleRaiser != nullptr) && "Failed to build module raiser");
// Set data of module raiser
moduleRaiser->setModuleRaiserInfo(&module, Target.get(),
&machineModuleInfo->getMMI(), MIA.get(),
MII.get(), Obj, DisAsm.get());
// Collect dynamic relocations.
moduleRaiser->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)
report_error(AddressOrErr.takeError(), Obj->getFileName());
uint64_t Address = *AddressOrErr;
Expected<StringRef> Name = Symbol.getName();
if (!Name)
report_error(Name.takeError(), Obj->getFileName());
if (Name->empty())
continue;
Expected<section_iterator> SectionOrErr = Symbol.getSection();
if (!SectionOrErr)
report_error(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;