jit.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. // SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "core/arm/symbols.h"
  4. #include "core/core.h"
  5. #include "core/hle/ipc_helpers.h"
  6. #include "core/hle/kernel/k_code_memory.h"
  7. #include "core/hle/kernel/k_transfer_memory.h"
  8. #include "core/hle/result.h"
  9. #include "core/hle/service/jit/jit.h"
  10. #include "core/hle/service/jit/jit_context.h"
  11. #include "core/hle/service/server_manager.h"
  12. #include "core/hle/service/service.h"
  13. #include "core/memory.h"
  14. namespace Service::JIT {
  15. struct CodeRange {
  16. u64 offset;
  17. u64 size;
  18. };
  19. class IJitEnvironment final : public ServiceFramework<IJitEnvironment> {
  20. public:
  21. explicit IJitEnvironment(Core::System& system_, Kernel::KProcess& process_, CodeRange user_rx,
  22. CodeRange user_ro)
  23. : ServiceFramework{system_, "IJitEnvironment"}, process{&process_}, context{
  24. system_.Memory()} {
  25. // clang-format off
  26. static const FunctionInfo functions[] = {
  27. {0, &IJitEnvironment::GenerateCode, "GenerateCode"},
  28. {1, &IJitEnvironment::Control, "Control"},
  29. {1000, &IJitEnvironment::LoadPlugin, "LoadPlugin"},
  30. {1001, &IJitEnvironment::GetCodeAddress, "GetCodeAddress"},
  31. };
  32. // clang-format on
  33. RegisterHandlers(functions);
  34. // Identity map user code range into sysmodule context
  35. configuration.user_ro_memory = user_ro;
  36. configuration.user_rx_memory = user_rx;
  37. configuration.sys_ro_memory = user_ro;
  38. configuration.sys_rx_memory = user_rx;
  39. }
  40. void GenerateCode(Kernel::HLERequestContext& ctx) {
  41. LOG_DEBUG(Service_JIT, "called");
  42. struct InputParameters {
  43. u32 data_size;
  44. u64 command;
  45. std::array<CodeRange, 2> ranges;
  46. Struct32 data;
  47. };
  48. struct OutputParameters {
  49. s32 return_value;
  50. std::array<CodeRange, 2> ranges;
  51. };
  52. IPC::RequestParser rp{ctx};
  53. const auto parameters{rp.PopRaw<InputParameters>()};
  54. // Optional input/output buffers
  55. const auto input_buffer{ctx.CanReadBuffer() ? ctx.ReadBuffer() : std::span<const u8>()};
  56. std::vector<u8> output_buffer(ctx.CanWriteBuffer() ? ctx.GetWriteBufferSize() : 0);
  57. // Function call prototype:
  58. // void GenerateCode(s32* ret, CodeRange* c0_out, CodeRange* c1_out, JITConfiguration* cfg,
  59. // u64 cmd, u8* input_buf, size_t input_size, CodeRange* c0_in,
  60. // CodeRange* c1_in, Struct32* data, size_t data_size, u8* output_buf,
  61. // size_t output_size);
  62. //
  63. // The command argument is used to control the behavior of the plugin during code
  64. // generation. The configuration allows the plugin to access the output code ranges, and the
  65. // other arguments are used to transfer state between the game and the plugin.
  66. const VAddr ret_ptr{context.AddHeap(0u)};
  67. const VAddr c0_in_ptr{context.AddHeap(parameters.ranges[0])};
  68. const VAddr c1_in_ptr{context.AddHeap(parameters.ranges[1])};
  69. const VAddr c0_out_ptr{context.AddHeap(ClearSize(parameters.ranges[0]))};
  70. const VAddr c1_out_ptr{context.AddHeap(ClearSize(parameters.ranges[1]))};
  71. const VAddr input_ptr{context.AddHeap(input_buffer.data(), input_buffer.size())};
  72. const VAddr output_ptr{context.AddHeap(output_buffer.data(), output_buffer.size())};
  73. const VAddr data_ptr{context.AddHeap(parameters.data)};
  74. const VAddr configuration_ptr{context.AddHeap(configuration)};
  75. // The callback does not directly return a value, it only writes to the output pointer
  76. context.CallFunction(callbacks.GenerateCode, ret_ptr, c0_out_ptr, c1_out_ptr,
  77. configuration_ptr, parameters.command, input_ptr, input_buffer.size(),
  78. c0_in_ptr, c1_in_ptr, data_ptr, parameters.data_size, output_ptr,
  79. output_buffer.size());
  80. const s32 return_value{context.GetHeap<s32>(ret_ptr)};
  81. if (return_value == 0) {
  82. // The callback has written to the output executable code range,
  83. // requiring an instruction cache invalidation
  84. system.InvalidateCpuInstructionCacheRange(configuration.user_rx_memory.offset,
  85. configuration.user_rx_memory.size);
  86. // Write back to the IPC output buffer, if provided
  87. if (ctx.CanWriteBuffer()) {
  88. context.GetHeap(output_ptr, output_buffer.data(), output_buffer.size());
  89. ctx.WriteBuffer(output_buffer.data(), output_buffer.size());
  90. }
  91. const OutputParameters out{
  92. .return_value = return_value,
  93. .ranges =
  94. {
  95. context.GetHeap<CodeRange>(c0_out_ptr),
  96. context.GetHeap<CodeRange>(c1_out_ptr),
  97. },
  98. };
  99. IPC::ResponseBuilder rb{ctx, 8};
  100. rb.Push(ResultSuccess);
  101. rb.PushRaw(out);
  102. } else {
  103. LOG_WARNING(Service_JIT, "plugin GenerateCode callback failed");
  104. IPC::ResponseBuilder rb{ctx, 2};
  105. rb.Push(ResultUnknown);
  106. }
  107. };
  108. void Control(Kernel::HLERequestContext& ctx) {
  109. LOG_DEBUG(Service_JIT, "called");
  110. IPC::RequestParser rp{ctx};
  111. const auto command{rp.PopRaw<u64>()};
  112. // Optional input/output buffers
  113. const auto input_buffer{ctx.CanReadBuffer() ? ctx.ReadBuffer() : std::span<const u8>()};
  114. std::vector<u8> output_buffer(ctx.CanWriteBuffer() ? ctx.GetWriteBufferSize() : 0);
  115. // Function call prototype:
  116. // u64 Control(s32* ret, JITConfiguration* cfg, u64 cmd, u8* input_buf, size_t input_size,
  117. // u8* output_buf, size_t output_size);
  118. //
  119. // This function is used to set up the state of the plugin before code generation, generally
  120. // passing objects like pointers to VM state from the game. It is usually called once.
  121. const VAddr ret_ptr{context.AddHeap(0u)};
  122. const VAddr configuration_ptr{context.AddHeap(configuration)};
  123. const VAddr input_ptr{context.AddHeap(input_buffer.data(), input_buffer.size())};
  124. const VAddr output_ptr{context.AddHeap(output_buffer.data(), output_buffer.size())};
  125. const u64 wrapper_value{context.CallFunction(callbacks.Control, ret_ptr, configuration_ptr,
  126. command, input_ptr, input_buffer.size(),
  127. output_ptr, output_buffer.size())};
  128. const s32 return_value{context.GetHeap<s32>(ret_ptr)};
  129. if (wrapper_value == 0 && return_value == 0) {
  130. // Write back to the IPC output buffer, if provided
  131. if (ctx.CanWriteBuffer()) {
  132. context.GetHeap(output_ptr, output_buffer.data(), output_buffer.size());
  133. ctx.WriteBuffer(output_buffer.data(), output_buffer.size());
  134. }
  135. IPC::ResponseBuilder rb{ctx, 3};
  136. rb.Push(ResultSuccess);
  137. rb.Push(return_value);
  138. } else {
  139. LOG_WARNING(Service_JIT, "plugin Control callback failed");
  140. IPC::ResponseBuilder rb{ctx, 2};
  141. rb.Push(ResultUnknown);
  142. }
  143. }
  144. void LoadPlugin(Kernel::HLERequestContext& ctx) {
  145. LOG_DEBUG(Service_JIT, "called");
  146. IPC::RequestParser rp{ctx};
  147. const auto tmem_size{rp.PopRaw<u64>()};
  148. const auto tmem_handle{ctx.GetCopyHandle(0)};
  149. const auto nro_plugin{ctx.ReadBuffer(1)};
  150. if (tmem_size == 0) {
  151. LOG_ERROR(Service_JIT, "attempted to load plugin with empty transfer memory");
  152. IPC::ResponseBuilder rb{ctx, 2};
  153. rb.Push(ResultUnknown);
  154. return;
  155. }
  156. auto tmem{process->GetHandleTable().GetObject<Kernel::KTransferMemory>(tmem_handle)};
  157. if (tmem.IsNull()) {
  158. LOG_ERROR(Service_JIT, "attempted to load plugin with invalid transfer memory handle");
  159. IPC::ResponseBuilder rb{ctx, 2};
  160. rb.Push(ResultUnknown);
  161. return;
  162. }
  163. // Set up the configuration with the required TransferMemory address
  164. configuration.transfer_memory.offset = tmem->GetSourceAddress();
  165. configuration.transfer_memory.size = tmem_size;
  166. // Gather up all the callbacks from the loaded plugin
  167. auto symbols{Core::Symbols::GetSymbols(nro_plugin, true)};
  168. const auto GetSymbol{[&](const std::string& name) { return symbols[name].first; }};
  169. callbacks.rtld_fini = GetSymbol("_fini");
  170. callbacks.rtld_init = GetSymbol("_init");
  171. callbacks.Control = GetSymbol("nnjitpluginControl");
  172. callbacks.ResolveBasicSymbols = GetSymbol("nnjitpluginResolveBasicSymbols");
  173. callbacks.SetupDiagnostics = GetSymbol("nnjitpluginSetupDiagnostics");
  174. callbacks.Configure = GetSymbol("nnjitpluginConfigure");
  175. callbacks.GenerateCode = GetSymbol("nnjitpluginGenerateCode");
  176. callbacks.GetVersion = GetSymbol("nnjitpluginGetVersion");
  177. callbacks.OnPrepared = GetSymbol("nnjitpluginOnPrepared");
  178. callbacks.Keeper = GetSymbol("nnjitpluginKeeper");
  179. if (callbacks.GetVersion == 0 || callbacks.Configure == 0 || callbacks.GenerateCode == 0 ||
  180. callbacks.OnPrepared == 0) {
  181. LOG_ERROR(Service_JIT, "plugin does not implement all necessary functionality");
  182. IPC::ResponseBuilder rb{ctx, 2};
  183. rb.Push(ResultUnknown);
  184. return;
  185. }
  186. if (!context.LoadNRO(nro_plugin)) {
  187. LOG_ERROR(Service_JIT, "failed to load plugin");
  188. IPC::ResponseBuilder rb{ctx, 2};
  189. rb.Push(ResultUnknown);
  190. return;
  191. }
  192. context.MapProcessMemory(configuration.sys_ro_memory.offset,
  193. configuration.sys_ro_memory.size);
  194. context.MapProcessMemory(configuration.sys_rx_memory.offset,
  195. configuration.sys_rx_memory.size);
  196. context.MapProcessMemory(configuration.transfer_memory.offset,
  197. configuration.transfer_memory.size);
  198. // Run ELF constructors, if needed
  199. if (callbacks.rtld_init != 0) {
  200. context.CallFunction(callbacks.rtld_init);
  201. }
  202. // Function prototype:
  203. // u64 GetVersion();
  204. const auto version{context.CallFunction(callbacks.GetVersion)};
  205. if (version != 1) {
  206. LOG_ERROR(Service_JIT, "unknown plugin version {}", version);
  207. IPC::ResponseBuilder rb{ctx, 2};
  208. rb.Push(ResultUnknown);
  209. return;
  210. }
  211. // Function prototype:
  212. // void ResolveBasicSymbols(void (*resolver)(const char* name));
  213. const auto resolve{context.GetHelper("_resolve")};
  214. if (callbacks.ResolveBasicSymbols != 0) {
  215. context.CallFunction(callbacks.ResolveBasicSymbols, resolve);
  216. }
  217. // Function prototype:
  218. // void SetupDiagnostics(u32 enabled, void (**resolver)(const char* name));
  219. const auto resolve_ptr{context.AddHeap(resolve)};
  220. if (callbacks.SetupDiagnostics != 0) {
  221. context.CallFunction(callbacks.SetupDiagnostics, 0u, resolve_ptr);
  222. }
  223. // Function prototype:
  224. // void Configure(u32* memory_flags);
  225. context.CallFunction(callbacks.Configure, 0ull);
  226. // Function prototype:
  227. // void OnPrepared(JITConfiguration* cfg);
  228. const auto configuration_ptr{context.AddHeap(configuration)};
  229. context.CallFunction(callbacks.OnPrepared, configuration_ptr);
  230. IPC::ResponseBuilder rb{ctx, 2};
  231. rb.Push(ResultSuccess);
  232. }
  233. void GetCodeAddress(Kernel::HLERequestContext& ctx) {
  234. LOG_DEBUG(Service_JIT, "called");
  235. IPC::ResponseBuilder rb{ctx, 6};
  236. rb.Push(ResultSuccess);
  237. rb.Push(configuration.user_rx_memory.offset);
  238. rb.Push(configuration.user_ro_memory.offset);
  239. }
  240. private:
  241. using Struct32 = std::array<u8, 32>;
  242. struct GuestCallbacks {
  243. VAddr rtld_fini;
  244. VAddr rtld_init;
  245. VAddr Control;
  246. VAddr ResolveBasicSymbols;
  247. VAddr SetupDiagnostics;
  248. VAddr Configure;
  249. VAddr GenerateCode;
  250. VAddr GetVersion;
  251. VAddr Keeper;
  252. VAddr OnPrepared;
  253. };
  254. struct JITConfiguration {
  255. CodeRange user_rx_memory;
  256. CodeRange user_ro_memory;
  257. CodeRange transfer_memory;
  258. CodeRange sys_rx_memory;
  259. CodeRange sys_ro_memory;
  260. };
  261. static CodeRange ClearSize(CodeRange in) {
  262. in.size = 0;
  263. return in;
  264. }
  265. Kernel::KScopedAutoObject<Kernel::KProcess> process;
  266. GuestCallbacks callbacks;
  267. JITConfiguration configuration;
  268. JITContext context;
  269. };
  270. class JITU final : public ServiceFramework<JITU> {
  271. public:
  272. explicit JITU(Core::System& system_) : ServiceFramework{system_, "jit:u"} {
  273. // clang-format off
  274. static const FunctionInfo functions[] = {
  275. {0, &JITU::CreateJitEnvironment, "CreateJitEnvironment"},
  276. };
  277. // clang-format on
  278. RegisterHandlers(functions);
  279. }
  280. void CreateJitEnvironment(Kernel::HLERequestContext& ctx) {
  281. LOG_DEBUG(Service_JIT, "called");
  282. struct Parameters {
  283. u64 rx_size;
  284. u64 ro_size;
  285. };
  286. IPC::RequestParser rp{ctx};
  287. const auto parameters{rp.PopRaw<Parameters>()};
  288. const auto process_handle{ctx.GetCopyHandle(0)};
  289. const auto rx_mem_handle{ctx.GetCopyHandle(1)};
  290. const auto ro_mem_handle{ctx.GetCopyHandle(2)};
  291. if (parameters.rx_size == 0 || parameters.ro_size == 0) {
  292. LOG_ERROR(Service_JIT, "attempted to init with empty code regions");
  293. IPC::ResponseBuilder rb{ctx, 2};
  294. rb.Push(ResultUnknown);
  295. return;
  296. }
  297. // Fetch using the handle table for the application process here,
  298. // since we are not multiprocess yet.
  299. const auto& handle_table{system.ApplicationProcess()->GetHandleTable()};
  300. auto process{handle_table.GetObject<Kernel::KProcess>(process_handle)};
  301. if (process.IsNull()) {
  302. LOG_ERROR(Service_JIT, "process is null for handle=0x{:08X}", process_handle);
  303. IPC::ResponseBuilder rb{ctx, 2};
  304. rb.Push(ResultUnknown);
  305. return;
  306. }
  307. auto rx_mem{handle_table.GetObject<Kernel::KCodeMemory>(rx_mem_handle)};
  308. if (rx_mem.IsNull()) {
  309. LOG_ERROR(Service_JIT, "rx_mem is null for handle=0x{:08X}", rx_mem_handle);
  310. IPC::ResponseBuilder rb{ctx, 2};
  311. rb.Push(ResultUnknown);
  312. return;
  313. }
  314. auto ro_mem{handle_table.GetObject<Kernel::KCodeMemory>(ro_mem_handle)};
  315. if (ro_mem.IsNull()) {
  316. LOG_ERROR(Service_JIT, "ro_mem is null for handle=0x{:08X}", ro_mem_handle);
  317. IPC::ResponseBuilder rb{ctx, 2};
  318. rb.Push(ResultUnknown);
  319. return;
  320. }
  321. const CodeRange user_rx{
  322. .offset = rx_mem->GetSourceAddress(),
  323. .size = parameters.rx_size,
  324. };
  325. const CodeRange user_ro{
  326. .offset = ro_mem->GetSourceAddress(),
  327. .size = parameters.ro_size,
  328. };
  329. IPC::ResponseBuilder rb{ctx, 2, 0, 1};
  330. rb.Push(ResultSuccess);
  331. rb.PushIpcInterface<IJitEnvironment>(system, *process, user_rx, user_ro);
  332. }
  333. };
  334. void LoopProcess(Core::System& system) {
  335. auto server_manager = std::make_unique<ServerManager>(system);
  336. server_manager->RegisterNamedService("jit:u", std::make_shared<JITU>(system));
  337. ServerManager::RunServer(std::move(server_manager));
  338. }
  339. } // namespace Service::JIT