-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
203 lines (173 loc) · 7.27 KB
/
main.cpp
File metadata and controls
203 lines (173 loc) · 7.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#include <format>
#include <iomanip>
#include "disassembly/A64Decoder.h"
#include "emulation/AArch64Cpu.h"
#include "loaders/elf/ElfLoader.h"
#include "emulation/executors/all_executors.h"
#include "emulation/libraries/libc/LibCStartMain.h"
#include "emulation/libraries/libc/Puts.h"
#include "emulation/libraries/libc/FOpen.h"
#include "emulation/filesystem/EmulatedFile.h"
#include "emulation/libraries/libc/FScanF.h"
#include "logging/LoggerBase.h"
#include "logging/LoggerFactory.h"
#include "cli/Options.h"
#include "cli/parser.h"
#include "cli/InteractiveMenu.h"
#include "emulation/systemv_abi.h"
#include "logging/LoggerContainer.h"
#include "cli/debugger.h"
namespace {
std::unique_ptr<Logging::LoggerBase> logger = Logging::createLogger("main");
}
std::map<InstructionType, std::unique_ptr<ExecutorBase>> map_all_executors(const std::shared_ptr<Emulation::Libraries::Mapper>& mapper) {
std::map<InstructionType, std::unique_ptr<ExecutorBase>> e;
e[InstructionType::AddOrSubImmediate] =
std::make_unique<Executors::DataProcImm::AddSubImmediateExecutor>();
e[InstructionType::PcRelativeAddressing] =
std::make_unique<Executors::DataProcImm::FormPcRelAddressExecutor>();
e[InstructionType::LogicalImmediate] =
std::make_unique<Executors::DataProcImm::LogicalImmediateExecutor>();
e[InstructionType::MoveWideImmediate] =
std::make_unique<Executors::DataProcImm::MoveWideImmediateExecutor>();
e[InstructionType::CompareAndBranchImmediate] =
std::make_unique<Executors::Begsi::CompareAndBranchImmediateExecutor>();
e[InstructionType::ConditionalBranchImmediate] =
std::make_unique<Executors::Begsi::ConditionalBranchImmediateExecutor>();
e[InstructionType::UnconditionalBranchImmediate] =
std::make_unique<Executors::Begsi::UnconditionalBranchImmediateExecutor>();
e[InstructionType::UnconditionalBranchRegister] =
std::make_unique<Executors::Begsi::UnconditionalBranchRegisterExecutor>();
e[InstructionType::Hint] =
std::make_unique<Executors::Begsi::HintExecutor>();
e[InstructionType::LoadStoreRegisterPair] =
std::make_unique<Executors::LoadsAndStores::LoadStoreRegPairExecutor>();
e[InstructionType::LoadStoreRegister] =
std::make_unique<Executors::LoadsAndStores::LoadStoreRegExecutor>();
e[InstructionType::LoadStoreRegisterUnsignedImm] =
std::make_unique<Executors::LoadsAndStores::LoadStoreRegUnsignedImm>();
e[InstructionType::ReservedCall] =
std::make_unique<Executors::Reserved::ReservedCallExecutor>(mapper);
e[InstructionType::AddSubExtendedRegister] =
std::make_unique<Executors::DataProcReg::AddSubExtendedRegisterExecutor>();
e[InstructionType::LogicalShiftedRegister] =
std::make_unique<Executors::DataProcReg::LogicalShiftedRegisterExecutor>();
return e;
}
void register_library_implementations(Emulation::Libraries::Mapper& mapper) {
// Register emulated functions
mapper.registerLibraryImplementation(
"__libc_start_main",
std::make_unique<Emulation::Libraries::LibC::LibCStartMain>());
mapper.registerLibraryImplementation(
"puts",
std::make_unique<Emulation::Libraries::LibC::Puts>());
mapper.registerLibraryImplementation(
"fopen",
std::make_unique<Emulation::Libraries::LibC::FOpen>());
mapper.registerLibraryImplementation(
"__isoc23_fscanf",
std::make_unique<Emulation::Libraries::LibC::FScanF>());
}
int read_elf_main(const Cli::Options& options) {
Loaders::ElfLoader loader(options.emulationTarget);
loader.loadEntireFile();
loader.parse();
AArch64Cpu cpu{};
// Initialize the System V stack
Emulation::SystemVStackInitInfo initInfo {
{"/hello_world"}, // program args
{
{"PWD", "/home/bonk"} // environment variables (e.g. PWD=/home/bonk)
}
};
Emulation::initialize_system_v_stack(*cpu.getMemory().getStack(AARCH64_MAIN_THREAD_ID), initInfo);
// Allocate ELF sections
loader.allocateSections(cpu.getMemory());
const auto mapper = std::make_shared<Emulation::Libraries::Mapper>();
register_library_implementations(*mapper);
// Dynamic link
mapper->allocateLinkingSegment(cpu.getMemory());
loader.linkSymbols(*mapper, cpu.getMemory());
// Allocate clean exit instruction
const virtual_address_t cleanExitAddr = cpu.getMemory().allocateSegment(sizeof(uint32_t));
const InstructionDefs::Reserved::ReservedCall reservedCall(
InstructionDefs::Reserved::ReservedCalls::Exit,
InstructionDefs::Reserved::IMM_EXIT_CLEAN_EXIT);
cpu.getMemory().write(cleanExitAddr, reservedCall.encode());
cpu.setCleanExitAddress(cleanExitAddr);
logger->info() << "Entry point: " << std::hex << std::showbase << loader.getEntryPoint() << std::endl;
cpu.setProgramCounter(loader.getEntryPoint());
auto executors = map_all_executors(mapper);
A64Decoder dec{};
// Add test file
cpu.getFs().addFile("/tmp/test2.txt", std::make_shared<Filesystem::EmulatedFile>("asd"));
logger->info() << std::endl << "============ Setup done. Starting the execution ============" << std::endl << std::endl;
virtual_address_t pc = cpu.getProgramCounter();
auto encodedInstruction = cpu.getMemory().read<uint32_t>(pc);
InstructionType type = dec.decodeNextType(encodedInstruction);
bool manualStepping = false;
while (type != InstructionType::Undefined) {
logger->info() << std::hex << std::noshowbase << (manualStepping ? "next: " : "") << "0x" << std::setfill('0') << std::setw(16) << pc << ": ";
const auto& executor = executors.find(type);
if (executor == executors.end()) {
throw std::runtime_error(std::format("Instruction type \"{}\" does not have a valid executor!",
static_cast<int>(type)));
}
if (!manualStepping && std::find(
options.breakpoints.begin(), options.breakpoints.end(), pc) != options.breakpoints.end()) {
manualStepping = true;
logger->error(false) << std::endl << "============= Breakpoint hit =============" << std::endl;
logger->error(false) << "Next instruction: ";
}
if (manualStepping) {
manualStepping = Cli::handle_manual_stepping_mode(*executor->second, dec.getRawInstruction(), cpu);
}
executor->second->decodeAndExecute(dec.getRawInstruction(), cpu);
if (cpu.isHalted()) {
break;
}
virtual_address_t newPc = cpu.getProgramCounter();
if (newPc == pc) {
// if the program counter wasn't changed by an executor, increment it
pc += sizeof(uint32_t);
cpu.setProgramCounter(pc);
}
else {
pc = newPc;
}
encodedInstruction = cpu.getMemory().read<uint32_t>(pc);
type = dec.decodeNextType(encodedInstruction);
}
if (!cpu.isHalted()) {
logger->error() << "Undefined instruction: " << std::hex << std::showbase << encodedInstruction << std::endl;
}
else {
logger->info() << "CPU halted. Exit code: " << cpu.getExitCode() << std::endl;
}
return 0;
}
int main(int argc, char** argv) {
std::string parseError;
Cli::Options opt = Cli::parseOptions(argc, argv, parseError);
if (!parseError.empty()) {
logger->error() << "An error has occurred while parsing cli options: " << std::endl << parseError << std::endl;
return 1;
}
if (opt.showHelp) {
Cli::printUsage(*logger);
return 0;
}
if (opt.interactive) {
Cli::InteractiveMenu menu(opt);
while (menu.menuLoop()) {}
if (menu.getState() == Cli::MenuState::Exit) {
logger->error() << "Exiting" << std::endl;
return 0;
}
opt = menu.getOptions();
}
Logging::setGlobalLogLevel(opt.logLevel);
logger->verbose() << "Loading ELF from " << opt.emulationTarget << std::endl;
return read_elf_main(opt);
}