jit_context.cpp 15 KB

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