jit_context.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. // SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <array>
  4. #include <map>
  5. #include <span>
  6. #include <boost/icl/interval_set.hpp>
  7. #include <dynarmic/interface/A64/a64.h>
  8. #include <dynarmic/interface/A64/config.h>
  9. #include "common/alignment.h"
  10. #include "common/common_funcs.h"
  11. #include "common/div_ceil.h"
  12. #include "common/elf.h"
  13. #include "common/logging/log.h"
  14. #include "core/hle/service/jit/jit_context.h"
  15. #include "core/memory.h"
  16. using namespace Common::ELF;
  17. namespace Service::JIT {
  18. constexpr std::array<u8, 8> SVC0_ARM64 = {
  19. 0x01, 0x00, 0x00, 0xd4, // svc #0
  20. 0xc0, 0x03, 0x5f, 0xd6, // ret
  21. };
  22. constexpr std::array HELPER_FUNCTIONS{
  23. "_stop", "_resolve", "_panic", "memcpy", "memmove", "memset",
  24. };
  25. constexpr size_t STACK_ALIGN = 16;
  26. class JITContextImpl;
  27. using IntervalSet = boost::icl::interval_set<VAddr>::type;
  28. using IntervalType = boost::icl::interval_set<VAddr>::interval_type;
  29. class DynarmicCallbacks64 : public Dynarmic::A64::UserCallbacks {
  30. public:
  31. explicit DynarmicCallbacks64(Core::Memory::Memory& memory_, std::vector<u8>& local_memory_,
  32. IntervalSet& mapped_ranges_, JITContextImpl& parent_)
  33. : memory{memory_}, local_memory{local_memory_},
  34. mapped_ranges{mapped_ranges_}, parent{parent_} {}
  35. u8 MemoryRead8(u64 vaddr) override {
  36. return ReadMemory<u8>(vaddr);
  37. }
  38. u16 MemoryRead16(u64 vaddr) override {
  39. return ReadMemory<u16>(vaddr);
  40. }
  41. u32 MemoryRead32(u64 vaddr) override {
  42. return ReadMemory<u32>(vaddr);
  43. }
  44. u64 MemoryRead64(u64 vaddr) override {
  45. return ReadMemory<u64>(vaddr);
  46. }
  47. u128 MemoryRead128(u64 vaddr) override {
  48. return ReadMemory<u128>(vaddr);
  49. }
  50. std::string MemoryReadCString(u64 vaddr) {
  51. std::string result;
  52. u8 next;
  53. while ((next = MemoryRead8(vaddr++)) != 0) {
  54. result += next;
  55. }
  56. return result;
  57. }
  58. void MemoryWrite8(u64 vaddr, u8 value) override {
  59. WriteMemory<u8>(vaddr, value);
  60. }
  61. void MemoryWrite16(u64 vaddr, u16 value) override {
  62. WriteMemory<u16>(vaddr, value);
  63. }
  64. void MemoryWrite32(u64 vaddr, u32 value) override {
  65. WriteMemory<u32>(vaddr, value);
  66. }
  67. void MemoryWrite64(u64 vaddr, u64 value) override {
  68. WriteMemory<u64>(vaddr, value);
  69. }
  70. void MemoryWrite128(u64 vaddr, u128 value) override {
  71. WriteMemory<u128>(vaddr, value);
  72. }
  73. bool MemoryWriteExclusive8(u64 vaddr, u8 value, u8) override {
  74. return WriteMemory<u8>(vaddr, value);
  75. }
  76. bool MemoryWriteExclusive16(u64 vaddr, u16 value, u16) override {
  77. return WriteMemory<u16>(vaddr, value);
  78. }
  79. bool MemoryWriteExclusive32(u64 vaddr, u32 value, u32) override {
  80. return WriteMemory<u32>(vaddr, value);
  81. }
  82. bool MemoryWriteExclusive64(u64 vaddr, u64 value, u64) override {
  83. return WriteMemory<u64>(vaddr, value);
  84. }
  85. bool MemoryWriteExclusive128(u64 vaddr, u128 value, u128) override {
  86. return WriteMemory<u128>(vaddr, value);
  87. }
  88. void CallSVC(u32 swi) override;
  89. void ExceptionRaised(u64 pc, Dynarmic::A64::Exception exception) override;
  90. void InterpreterFallback(u64 pc, size_t num_instructions) override;
  91. void AddTicks(u64 ticks) override {}
  92. u64 GetTicksRemaining() override {
  93. return std::numeric_limits<u32>::max();
  94. }
  95. u64 GetCNTPCT() override {
  96. return 0;
  97. }
  98. template <class T>
  99. T ReadMemory(u64 vaddr) {
  100. T ret{};
  101. if (boost::icl::contains(mapped_ranges, vaddr)) {
  102. memory.ReadBlock(vaddr, &ret, sizeof(T));
  103. } else if (vaddr + sizeof(T) > local_memory.size()) {
  104. LOG_CRITICAL(Service_JIT, "plugin: unmapped read @ 0x{:016x}", vaddr);
  105. } else {
  106. std::memcpy(&ret, local_memory.data() + vaddr, sizeof(T));
  107. }
  108. return ret;
  109. }
  110. template <class T>
  111. bool WriteMemory(u64 vaddr, const T value) {
  112. if (boost::icl::contains(mapped_ranges, vaddr)) {
  113. memory.WriteBlock(vaddr, &value, sizeof(T));
  114. } else if (vaddr + sizeof(T) > local_memory.size()) {
  115. LOG_CRITICAL(Service_JIT, "plugin: unmapped write @ 0x{:016x}", vaddr);
  116. } else {
  117. std::memcpy(local_memory.data() + vaddr, &value, sizeof(T));
  118. }
  119. return true;
  120. }
  121. private:
  122. Core::Memory::Memory& memory;
  123. std::vector<u8>& local_memory;
  124. IntervalSet& mapped_ranges;
  125. JITContextImpl& parent;
  126. };
  127. class JITContextImpl {
  128. public:
  129. explicit JITContextImpl(Core::Memory::Memory& memory_) : memory{memory_} {
  130. callbacks =
  131. std::make_unique<DynarmicCallbacks64>(memory, local_memory, mapped_ranges, *this);
  132. user_config.callbacks = callbacks.get();
  133. jit = std::make_unique<Dynarmic::A64::Jit>(user_config);
  134. }
  135. bool LoadNRO(std::span<const u8> data) {
  136. local_memory.clear();
  137. relocbase = local_memory.size();
  138. local_memory.insert(local_memory.end(), data.begin(), data.end());
  139. if (FixupRelocations()) {
  140. InsertHelperFunctions();
  141. InsertStack();
  142. return true;
  143. }
  144. return false;
  145. }
  146. bool FixupRelocations() {
  147. // The loaded NRO file has ELF relocations that must be processed before it can run.
  148. // Normally this would be processed by RTLD, but in HLE context, we don't have
  149. // the linker available, so we have to do it ourselves.
  150. const VAddr mod_offset{callbacks->MemoryRead32(4)};
  151. if (callbacks->MemoryRead32(mod_offset) != Common::MakeMagic('M', 'O', 'D', '0')) {
  152. return false;
  153. }
  154. // For more info about dynamic entries, see the ELF ABI specification:
  155. // https://refspecs.linuxbase.org/elf/gabi4+/ch5.dynamic.html
  156. // https://refspecs.linuxbase.org/elf/gabi4+/ch4.reloc.html
  157. VAddr dynamic_offset{mod_offset + callbacks->MemoryRead32(mod_offset + 4)};
  158. VAddr rela_dyn = 0, relr_dyn = 0;
  159. size_t num_rela = 0, num_relr = 0;
  160. while (true) {
  161. const auto dyn{callbacks->ReadMemory<Elf64_Dyn>(dynamic_offset)};
  162. dynamic_offset += sizeof(Elf64_Dyn);
  163. if (!dyn.d_tag) {
  164. break;
  165. }
  166. if (dyn.d_tag == ElfDtRela) {
  167. rela_dyn = dyn.d_un.d_ptr;
  168. }
  169. if (dyn.d_tag == ElfDtRelasz) {
  170. num_rela = dyn.d_un.d_val / sizeof(Elf64_Rela);
  171. }
  172. if (dyn.d_tag == ElfDtRelr) {
  173. relr_dyn = dyn.d_un.d_ptr;
  174. }
  175. if (dyn.d_tag == ElfDtRelrsz) {
  176. num_relr = dyn.d_un.d_val / sizeof(Elf64_Relr);
  177. }
  178. }
  179. for (size_t i = 0; i < num_rela; i++) {
  180. const auto rela{callbacks->ReadMemory<Elf64_Rela>(rela_dyn + i * sizeof(Elf64_Rela))};
  181. if (Elf64RelType(rela.r_info) != ElfAArch64Relative) {
  182. continue;
  183. }
  184. const VAddr contents{callbacks->MemoryRead64(rela.r_offset)};
  185. callbacks->MemoryWrite64(rela.r_offset, contents + rela.r_addend);
  186. }
  187. VAddr relr_where = 0;
  188. for (size_t i = 0; i < num_relr; i++) {
  189. const auto relr{callbacks->ReadMemory<Elf64_Relr>(relr_dyn + i * sizeof(Elf64_Relr))};
  190. const auto incr{[&](VAddr where) {
  191. callbacks->MemoryWrite64(where, callbacks->MemoryRead64(where) + relocbase);
  192. }};
  193. if ((relr & 1) == 0) {
  194. // where pointer
  195. relr_where = relocbase + relr;
  196. incr(relr_where);
  197. relr_where += sizeof(Elf64_Addr);
  198. } else {
  199. // bitmap
  200. for (int bit = 1; bit < 64; bit++) {
  201. if ((relr & (1ULL << bit)) != 0) {
  202. incr(relr_where + i * sizeof(Elf64_Addr));
  203. }
  204. }
  205. relr_where += 63 * sizeof(Elf64_Addr);
  206. }
  207. }
  208. return true;
  209. }
  210. void InsertHelperFunctions() {
  211. for (const auto& name : HELPER_FUNCTIONS) {
  212. helpers[name] = local_memory.size();
  213. local_memory.insert(local_memory.end(), SVC0_ARM64.begin(), SVC0_ARM64.end());
  214. }
  215. }
  216. void InsertStack() {
  217. // Allocate enough space to avoid any reasonable risk of
  218. // overflowing the stack during plugin execution
  219. const u64 pad_amount{Common::AlignUp(local_memory.size(), STACK_ALIGN) -
  220. local_memory.size()};
  221. local_memory.insert(local_memory.end(), 0x10000 + pad_amount, 0);
  222. top_of_stack = local_memory.size();
  223. heap_pointer = top_of_stack;
  224. }
  225. void MapProcessMemory(VAddr dest_address, std::size_t size) {
  226. mapped_ranges.add(IntervalType{dest_address, dest_address + size});
  227. }
  228. void PushArgument(const void* data, size_t size) {
  229. const size_t num_words = Common::DivCeil(size, sizeof(u64));
  230. const size_t current_pos = argument_stack.size();
  231. argument_stack.insert(argument_stack.end(), num_words, 0);
  232. std::memcpy(argument_stack.data() + current_pos, data, size);
  233. }
  234. void SetupArguments() {
  235. // The first 8 integer registers are used for the first 8 integer
  236. // arguments. Floating-point arguments are not handled at this time.
  237. //
  238. // If a function takes more than 8 arguments, then stack space is reserved
  239. // for the remaining arguments, and the remaining arguments are inserted in
  240. // ascending memory order, each argument aligned to an 8-byte boundary. The
  241. // stack pointer must remain aligned to 16 bytes.
  242. //
  243. // For more info, see the AArch64 ABI PCS:
  244. // https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst
  245. for (size_t i = 0; i < 8 && i < argument_stack.size(); i++) {
  246. jit->SetRegister(i, argument_stack[i]);
  247. }
  248. if (argument_stack.size() > 8) {
  249. const VAddr new_sp = Common::AlignDown(
  250. top_of_stack - (argument_stack.size() - 8) * sizeof(u64), STACK_ALIGN);
  251. for (size_t i = 8; i < argument_stack.size(); i++) {
  252. callbacks->MemoryWrite64(new_sp + (i - 8) * sizeof(u64), argument_stack[i]);
  253. }
  254. jit->SetSP(new_sp);
  255. }
  256. // Reset the call state for the next invocation
  257. argument_stack.clear();
  258. heap_pointer = top_of_stack;
  259. }
  260. u64 CallFunction(VAddr func) {
  261. jit->SetRegister(30, helpers["_stop"]);
  262. jit->SetSP(top_of_stack);
  263. SetupArguments();
  264. jit->SetPC(func);
  265. jit->Run();
  266. return jit->GetRegister(0);
  267. }
  268. VAddr GetHelper(const std::string& name) {
  269. return helpers[name];
  270. }
  271. VAddr AddHeap(const void* data, size_t size) {
  272. // Require all heap data types to have the same alignment as the
  273. // stack pointer, for compatibility
  274. const size_t num_bytes{Common::AlignUp(size, STACK_ALIGN)};
  275. // Make additional memory space if required
  276. if (heap_pointer + num_bytes > local_memory.size()) {
  277. local_memory.insert(local_memory.end(),
  278. (heap_pointer + num_bytes) - local_memory.size(), 0);
  279. }
  280. const VAddr location{heap_pointer};
  281. std::memcpy(local_memory.data() + location, data, size);
  282. heap_pointer += num_bytes;
  283. return location;
  284. }
  285. void GetHeap(VAddr location, void* data, size_t size) {
  286. std::memcpy(data, local_memory.data() + location, size);
  287. }
  288. std::unique_ptr<DynarmicCallbacks64> callbacks;
  289. std::vector<u8> local_memory;
  290. std::vector<u64> argument_stack;
  291. IntervalSet mapped_ranges;
  292. Dynarmic::A64::UserConfig user_config;
  293. std::unique_ptr<Dynarmic::A64::Jit> jit;
  294. std::map<std::string, VAddr, std::less<>> helpers;
  295. Core::Memory::Memory& memory;
  296. VAddr top_of_stack;
  297. VAddr heap_pointer;
  298. VAddr relocbase;
  299. };
  300. void DynarmicCallbacks64::CallSVC(u32 swi) {
  301. // Service calls are used to implement helper functionality.
  302. //
  303. // The most important of these is the _stop helper, which transfers control
  304. // from the plugin back to HLE context to return a value. However, a few more
  305. // are also implemented to reduce the need for direct ARM implementations of
  306. // basic functionality, like memory operations.
  307. //
  308. // When we receive a helper request, the swi number will be zero, and the call
  309. // will have originated from an address we know is a helper function. Otherwise,
  310. // the plugin may be trying to issue a service call, which we shouldn't handle.
  311. if (swi != 0) {
  312. LOG_CRITICAL(Service_JIT, "plugin issued unknown service call {}", swi);
  313. parent.jit->HaltExecution();
  314. return;
  315. }
  316. u64 pc{parent.jit->GetPC() - 4};
  317. auto& helpers{parent.helpers};
  318. if (pc == helpers["memcpy"] || pc == helpers["memmove"]) {
  319. const VAddr dest{parent.jit->GetRegister(0)};
  320. const VAddr src{parent.jit->GetRegister(1)};
  321. const size_t n{parent.jit->GetRegister(2)};
  322. if (dest < src) {
  323. for (size_t i = 0; i < n; i++) {
  324. MemoryWrite8(dest + i, MemoryRead8(src + i));
  325. }
  326. } else {
  327. for (size_t i = n; i > 0; i--) {
  328. MemoryWrite8(dest + i - 1, MemoryRead8(src + i - 1));
  329. }
  330. }
  331. } else if (pc == helpers["memset"]) {
  332. const VAddr dest{parent.jit->GetRegister(0)};
  333. const u64 c{parent.jit->GetRegister(1)};
  334. const size_t n{parent.jit->GetRegister(2)};
  335. for (size_t i = 0; i < n; i++) {
  336. MemoryWrite8(dest + i, static_cast<u8>(c));
  337. }
  338. } else if (pc == helpers["_resolve"]) {
  339. // X0 contains a char* for a symbol to resolve
  340. const auto name{MemoryReadCString(parent.jit->GetRegister(0))};
  341. const auto helper{helpers[name]};
  342. if (helper != 0) {
  343. parent.jit->SetRegister(0, helper);
  344. } else {
  345. LOG_WARNING(Service_JIT, "plugin requested unknown function {}", name);
  346. parent.jit->SetRegister(0, helpers["_panic"]);
  347. }
  348. } else if (pc == helpers["_stop"]) {
  349. parent.jit->HaltExecution();
  350. } else if (pc == helpers["_panic"]) {
  351. LOG_CRITICAL(Service_JIT, "plugin panicked!");
  352. parent.jit->HaltExecution();
  353. } else {
  354. LOG_CRITICAL(Service_JIT, "plugin issued syscall at unknown address 0x{:x}", pc);
  355. parent.jit->HaltExecution();
  356. }
  357. }
  358. void DynarmicCallbacks64::ExceptionRaised(u64 pc, Dynarmic::A64::Exception exception) {
  359. LOG_CRITICAL(Service_JIT, "Illegal operation PC @ {:08x}", pc);
  360. parent.jit->HaltExecution();
  361. }
  362. void DynarmicCallbacks64::InterpreterFallback(u64 pc, size_t num_instructions) {
  363. LOG_CRITICAL(Service_JIT, "Unimplemented instruction PC @ {:08x}", pc);
  364. parent.jit->HaltExecution();
  365. }
  366. JITContext::JITContext(Core::Memory::Memory& memory)
  367. : impl{std::make_unique<JITContextImpl>(memory)} {}
  368. JITContext::~JITContext() {}
  369. bool JITContext::LoadNRO(std::span<const u8> data) {
  370. return impl->LoadNRO(data);
  371. }
  372. void JITContext::MapProcessMemory(VAddr dest_address, std::size_t size) {
  373. impl->MapProcessMemory(dest_address, size);
  374. }
  375. u64 JITContext::CallFunction(VAddr func) {
  376. return impl->CallFunction(func);
  377. }
  378. void JITContext::PushArgument(const void* data, size_t size) {
  379. impl->PushArgument(data, size);
  380. }
  381. VAddr JITContext::GetHelper(const std::string& name) {
  382. return impl->GetHelper(name);
  383. }
  384. VAddr JITContext::AddHeap(const void* data, size_t size) {
  385. return impl->AddHeap(data, size);
  386. }
  387. void JITContext::GetHeap(VAddr location, void* data, size_t size) {
  388. impl->GetHeap(location, data, size);
  389. }
  390. } // namespace Service::JIT