hle_ipc.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <array>
  5. #include <sstream>
  6. #include <boost/range/algorithm_ext/erase.hpp>
  7. #include "common/assert.h"
  8. #include "common/common_funcs.h"
  9. #include "common/common_types.h"
  10. #include "common/logging/log.h"
  11. #include "core/hle/ipc_helpers.h"
  12. #include "core/hle/kernel/hle_ipc.h"
  13. #include "core/hle/kernel/k_auto_object.h"
  14. #include "core/hle/kernel/k_handle_table.h"
  15. #include "core/hle/kernel/k_process.h"
  16. #include "core/hle/kernel/k_server_session.h"
  17. #include "core/hle/kernel/k_thread.h"
  18. #include "core/hle/kernel/kernel.h"
  19. #include "core/hle/kernel/service_thread.h"
  20. #include "core/memory.h"
  21. namespace Kernel {
  22. SessionRequestHandler::SessionRequestHandler(KernelCore& kernel_, const char* service_name_,
  23. ServiceThreadType thread_type)
  24. : kernel{kernel_} {
  25. if (thread_type == ServiceThreadType::CreateNew) {
  26. service_thread = kernel.CreateServiceThread(service_name_);
  27. } else {
  28. service_thread = kernel.GetDefaultServiceThread();
  29. }
  30. }
  31. SessionRequestHandler::~SessionRequestHandler() {
  32. kernel.ReleaseServiceThread(service_thread);
  33. }
  34. SessionRequestManager::SessionRequestManager(KernelCore& kernel_) : kernel{kernel_} {}
  35. SessionRequestManager::~SessionRequestManager() = default;
  36. bool SessionRequestManager::HasSessionRequestHandler(const HLERequestContext& context) const {
  37. if (IsDomain() && context.HasDomainMessageHeader()) {
  38. const auto& message_header = context.GetDomainMessageHeader();
  39. const auto object_id = message_header.object_id;
  40. if (object_id > DomainHandlerCount()) {
  41. LOG_CRITICAL(IPC, "object_id {} is too big!", object_id);
  42. return false;
  43. }
  44. return !DomainHandler(object_id - 1).expired();
  45. } else {
  46. return session_handler != nullptr;
  47. }
  48. }
  49. Result SessionRequestManager::CompleteSyncRequest(KServerSession* server_session,
  50. HLERequestContext& context) {
  51. Result result = ResultSuccess;
  52. // If the session has been converted to a domain, handle the domain request
  53. if (this->HasSessionRequestHandler(context)) {
  54. if (IsDomain() && context.HasDomainMessageHeader()) {
  55. result = HandleDomainSyncRequest(server_session, context);
  56. // If there is no domain header, the regular session handler is used
  57. } else if (this->HasSessionHandler()) {
  58. // If this manager has an associated HLE handler, forward the request to it.
  59. result = this->SessionHandler().HandleSyncRequest(*server_session, context);
  60. }
  61. } else {
  62. ASSERT_MSG(false, "Session handler is invalid, stubbing response!");
  63. IPC::ResponseBuilder rb(context, 2);
  64. rb.Push(ResultSuccess);
  65. }
  66. if (convert_to_domain) {
  67. ASSERT_MSG(!IsDomain(), "ServerSession is already a domain instance.");
  68. this->ConvertToDomain();
  69. convert_to_domain = false;
  70. }
  71. return result;
  72. }
  73. Result SessionRequestManager::HandleDomainSyncRequest(KServerSession* server_session,
  74. HLERequestContext& context) {
  75. if (!context.HasDomainMessageHeader()) {
  76. return ResultSuccess;
  77. }
  78. // Set domain handlers in HLE context, used for domain objects (IPC interfaces) as inputs
  79. context.SetSessionRequestManager(server_session->GetSessionRequestManager());
  80. // If there is a DomainMessageHeader, then this is CommandType "Request"
  81. const auto& domain_message_header = context.GetDomainMessageHeader();
  82. const u32 object_id{domain_message_header.object_id};
  83. switch (domain_message_header.command) {
  84. case IPC::DomainMessageHeader::CommandType::SendMessage:
  85. if (object_id > this->DomainHandlerCount()) {
  86. LOG_CRITICAL(IPC,
  87. "object_id {} is too big! This probably means a recent service call "
  88. "needed to return a new interface!",
  89. object_id);
  90. ASSERT(false);
  91. return ResultSuccess; // Ignore error if asserts are off
  92. }
  93. if (auto strong_ptr = this->DomainHandler(object_id - 1).lock()) {
  94. return strong_ptr->HandleSyncRequest(*server_session, context);
  95. } else {
  96. ASSERT(false);
  97. return ResultSuccess;
  98. }
  99. case IPC::DomainMessageHeader::CommandType::CloseVirtualHandle: {
  100. LOG_DEBUG(IPC, "CloseVirtualHandle, object_id=0x{:08X}", object_id);
  101. this->CloseDomainHandler(object_id - 1);
  102. IPC::ResponseBuilder rb{context, 2};
  103. rb.Push(ResultSuccess);
  104. return ResultSuccess;
  105. }
  106. }
  107. LOG_CRITICAL(IPC, "Unknown domain command={}", domain_message_header.command.Value());
  108. ASSERT(false);
  109. return ResultSuccess;
  110. }
  111. Result SessionRequestManager::QueueSyncRequest(KSession* parent,
  112. std::shared_ptr<HLERequestContext>&& context) {
  113. // Ensure we have a session request handler
  114. if (this->HasSessionRequestHandler(*context)) {
  115. if (auto strong_ptr = this->GetServiceThread().lock()) {
  116. strong_ptr->QueueSyncRequest(*parent, std::move(context));
  117. } else {
  118. ASSERT_MSG(false, "strong_ptr is nullptr!");
  119. }
  120. } else {
  121. ASSERT_MSG(false, "handler is invalid!");
  122. }
  123. return ResultSuccess;
  124. }
  125. void SessionRequestHandler::ClientConnected(KServerSession* session) {
  126. session->GetSessionRequestManager()->SetSessionHandler(shared_from_this());
  127. // Ensure our server session is tracked globally.
  128. kernel.RegisterServerObject(session);
  129. }
  130. void SessionRequestHandler::ClientDisconnected(KServerSession* session) {}
  131. HLERequestContext::HLERequestContext(KernelCore& kernel_, Core::Memory::Memory& memory_,
  132. KServerSession* server_session_, KThread* thread_)
  133. : server_session(server_session_), thread(thread_), kernel{kernel_}, memory{memory_} {
  134. cmd_buf[0] = 0;
  135. }
  136. HLERequestContext::~HLERequestContext() = default;
  137. void HLERequestContext::ParseCommandBuffer(const KHandleTable& handle_table, u32_le* src_cmdbuf,
  138. bool incoming) {
  139. IPC::RequestParser rp(src_cmdbuf);
  140. command_header = rp.PopRaw<IPC::CommandHeader>();
  141. if (command_header->IsCloseCommand()) {
  142. // Close does not populate the rest of the IPC header
  143. return;
  144. }
  145. // If handle descriptor is present, add size of it
  146. if (command_header->enable_handle_descriptor) {
  147. handle_descriptor_header = rp.PopRaw<IPC::HandleDescriptorHeader>();
  148. if (handle_descriptor_header->send_current_pid) {
  149. pid = rp.Pop<u64>();
  150. }
  151. if (incoming) {
  152. // Populate the object lists with the data in the IPC request.
  153. for (u32 handle = 0; handle < handle_descriptor_header->num_handles_to_copy; ++handle) {
  154. incoming_copy_handles.push_back(rp.Pop<Handle>());
  155. }
  156. for (u32 handle = 0; handle < handle_descriptor_header->num_handles_to_move; ++handle) {
  157. incoming_move_handles.push_back(rp.Pop<Handle>());
  158. }
  159. } else {
  160. // For responses we just ignore the handles, they're empty and will be populated when
  161. // translating the response.
  162. rp.Skip(handle_descriptor_header->num_handles_to_copy, false);
  163. rp.Skip(handle_descriptor_header->num_handles_to_move, false);
  164. }
  165. }
  166. for (u32 i = 0; i < command_header->num_buf_x_descriptors; ++i) {
  167. buffer_x_desciptors.push_back(rp.PopRaw<IPC::BufferDescriptorX>());
  168. }
  169. for (u32 i = 0; i < command_header->num_buf_a_descriptors; ++i) {
  170. buffer_a_desciptors.push_back(rp.PopRaw<IPC::BufferDescriptorABW>());
  171. }
  172. for (u32 i = 0; i < command_header->num_buf_b_descriptors; ++i) {
  173. buffer_b_desciptors.push_back(rp.PopRaw<IPC::BufferDescriptorABW>());
  174. }
  175. for (u32 i = 0; i < command_header->num_buf_w_descriptors; ++i) {
  176. buffer_w_desciptors.push_back(rp.PopRaw<IPC::BufferDescriptorABW>());
  177. }
  178. const auto buffer_c_offset = rp.GetCurrentOffset() + command_header->data_size;
  179. if (!command_header->IsTipc()) {
  180. // Padding to align to 16 bytes
  181. rp.AlignWithPadding();
  182. if (Session()->GetSessionRequestManager()->IsDomain() &&
  183. ((command_header->type == IPC::CommandType::Request ||
  184. command_header->type == IPC::CommandType::RequestWithContext) ||
  185. !incoming)) {
  186. // If this is an incoming message, only CommandType "Request" has a domain header
  187. // All outgoing domain messages have the domain header, if only incoming has it
  188. if (incoming || domain_message_header) {
  189. domain_message_header = rp.PopRaw<IPC::DomainMessageHeader>();
  190. } else {
  191. if (Session()->GetSessionRequestManager()->IsDomain()) {
  192. LOG_WARNING(IPC, "Domain request has no DomainMessageHeader!");
  193. }
  194. }
  195. }
  196. data_payload_header = rp.PopRaw<IPC::DataPayloadHeader>();
  197. data_payload_offset = rp.GetCurrentOffset();
  198. if (domain_message_header &&
  199. domain_message_header->command ==
  200. IPC::DomainMessageHeader::CommandType::CloseVirtualHandle) {
  201. // CloseVirtualHandle command does not have SFC* or any data
  202. return;
  203. }
  204. if (incoming) {
  205. ASSERT(data_payload_header->magic == Common::MakeMagic('S', 'F', 'C', 'I'));
  206. } else {
  207. ASSERT(data_payload_header->magic == Common::MakeMagic('S', 'F', 'C', 'O'));
  208. }
  209. }
  210. rp.SetCurrentOffset(buffer_c_offset);
  211. // For Inline buffers, the response data is written directly to buffer_c_offset
  212. // and in this case we don't have any BufferDescriptorC on the request.
  213. if (command_header->buf_c_descriptor_flags >
  214. IPC::CommandHeader::BufferDescriptorCFlag::InlineDescriptor) {
  215. if (command_header->buf_c_descriptor_flags ==
  216. IPC::CommandHeader::BufferDescriptorCFlag::OneDescriptor) {
  217. buffer_c_desciptors.push_back(rp.PopRaw<IPC::BufferDescriptorC>());
  218. } else {
  219. u32 num_buf_c_descriptors =
  220. static_cast<u32>(command_header->buf_c_descriptor_flags.Value()) - 2;
  221. // This is used to detect possible underflows, in case something is broken
  222. // with the two ifs above and the flags value is == 0 || == 1.
  223. ASSERT(num_buf_c_descriptors < 14);
  224. for (u32 i = 0; i < num_buf_c_descriptors; ++i) {
  225. buffer_c_desciptors.push_back(rp.PopRaw<IPC::BufferDescriptorC>());
  226. }
  227. }
  228. }
  229. rp.SetCurrentOffset(data_payload_offset);
  230. command = rp.Pop<u32_le>();
  231. rp.Skip(1, false); // The command is actually an u64, but we don't use the high part.
  232. }
  233. Result HLERequestContext::PopulateFromIncomingCommandBuffer(const KHandleTable& handle_table,
  234. u32_le* src_cmdbuf) {
  235. ParseCommandBuffer(handle_table, src_cmdbuf, true);
  236. if (command_header->IsCloseCommand()) {
  237. // Close does not populate the rest of the IPC header
  238. return ResultSuccess;
  239. }
  240. std::copy_n(src_cmdbuf, IPC::COMMAND_BUFFER_LENGTH, cmd_buf.begin());
  241. return ResultSuccess;
  242. }
  243. Result HLERequestContext::WriteToOutgoingCommandBuffer(KThread& requesting_thread) {
  244. auto current_offset = handles_offset;
  245. auto& owner_process = *requesting_thread.GetOwnerProcess();
  246. auto& handle_table = owner_process.GetHandleTable();
  247. for (auto& object : outgoing_copy_objects) {
  248. Handle handle{};
  249. if (object) {
  250. R_TRY(handle_table.Add(&handle, object));
  251. }
  252. cmd_buf[current_offset++] = handle;
  253. }
  254. for (auto& object : outgoing_move_objects) {
  255. Handle handle{};
  256. if (object) {
  257. R_TRY(handle_table.Add(&handle, object));
  258. // Close our reference to the object, as it is being moved to the caller.
  259. object->Close();
  260. }
  261. cmd_buf[current_offset++] = handle;
  262. }
  263. // Write the domain objects to the command buffer, these go after the raw untranslated data.
  264. // TODO(Subv): This completely ignores C buffers.
  265. if (server_session->GetSessionRequestManager()->IsDomain()) {
  266. current_offset = domain_offset - static_cast<u32>(outgoing_domain_objects.size());
  267. for (auto& object : outgoing_domain_objects) {
  268. server_session->GetSessionRequestManager()->AppendDomainHandler(std::move(object));
  269. cmd_buf[current_offset++] = static_cast<u32_le>(
  270. server_session->GetSessionRequestManager()->DomainHandlerCount());
  271. }
  272. }
  273. // Copy the translated command buffer back into the thread's command buffer area.
  274. memory.WriteBlock(owner_process, requesting_thread.GetTLSAddress(), cmd_buf.data(),
  275. write_size * sizeof(u32));
  276. return ResultSuccess;
  277. }
  278. std::vector<u8> HLERequestContext::ReadBuffer(std::size_t buffer_index) const {
  279. std::vector<u8> buffer{};
  280. const bool is_buffer_a{BufferDescriptorA().size() > buffer_index &&
  281. BufferDescriptorA()[buffer_index].Size()};
  282. if (is_buffer_a) {
  283. ASSERT_OR_EXECUTE_MSG(
  284. BufferDescriptorA().size() > buffer_index, { return buffer; },
  285. "BufferDescriptorA invalid buffer_index {}", buffer_index);
  286. buffer.resize(BufferDescriptorA()[buffer_index].Size());
  287. memory.ReadBlock(BufferDescriptorA()[buffer_index].Address(), buffer.data(), buffer.size());
  288. } else {
  289. ASSERT_OR_EXECUTE_MSG(
  290. BufferDescriptorX().size() > buffer_index, { return buffer; },
  291. "BufferDescriptorX invalid buffer_index {}", buffer_index);
  292. buffer.resize(BufferDescriptorX()[buffer_index].Size());
  293. memory.ReadBlock(BufferDescriptorX()[buffer_index].Address(), buffer.data(), buffer.size());
  294. }
  295. return buffer;
  296. }
  297. std::size_t HLERequestContext::WriteBuffer(const void* buffer, std::size_t size,
  298. std::size_t buffer_index) const {
  299. if (size == 0) {
  300. LOG_WARNING(Core, "skip empty buffer write");
  301. return 0;
  302. }
  303. const bool is_buffer_b{BufferDescriptorB().size() > buffer_index &&
  304. BufferDescriptorB()[buffer_index].Size()};
  305. const std::size_t buffer_size{GetWriteBufferSize(buffer_index)};
  306. if (size > buffer_size) {
  307. LOG_CRITICAL(Core, "size ({:016X}) is greater than buffer_size ({:016X})", size,
  308. buffer_size);
  309. size = buffer_size; // TODO(bunnei): This needs to be HW tested
  310. }
  311. if (is_buffer_b) {
  312. ASSERT_OR_EXECUTE_MSG(
  313. BufferDescriptorB().size() > buffer_index &&
  314. BufferDescriptorB()[buffer_index].Size() >= size,
  315. { return 0; }, "BufferDescriptorB is invalid, index={}, size={}", buffer_index, size);
  316. WriteBufferB(buffer, size, buffer_index);
  317. } else {
  318. ASSERT_OR_EXECUTE_MSG(
  319. BufferDescriptorC().size() > buffer_index &&
  320. BufferDescriptorC()[buffer_index].Size() >= size,
  321. { return 0; }, "BufferDescriptorC is invalid, index={}, size={}", buffer_index, size);
  322. WriteBufferC(buffer, size, buffer_index);
  323. }
  324. return size;
  325. }
  326. std::size_t HLERequestContext::WriteBufferB(const void* buffer, std::size_t size,
  327. std::size_t buffer_index) const {
  328. if (buffer_index >= BufferDescriptorB().size() || size == 0) {
  329. return 0;
  330. }
  331. const auto buffer_size{BufferDescriptorB()[buffer_index].Size()};
  332. if (size > buffer_size) {
  333. LOG_CRITICAL(Core, "size ({:016X}) is greater than buffer_size ({:016X})", size,
  334. buffer_size);
  335. size = buffer_size; // TODO(bunnei): This needs to be HW tested
  336. }
  337. memory.WriteBlock(BufferDescriptorB()[buffer_index].Address(), buffer, size);
  338. return size;
  339. }
  340. std::size_t HLERequestContext::WriteBufferC(const void* buffer, std::size_t size,
  341. std::size_t buffer_index) const {
  342. if (buffer_index >= BufferDescriptorC().size() || size == 0) {
  343. return 0;
  344. }
  345. const auto buffer_size{BufferDescriptorC()[buffer_index].Size()};
  346. if (size > buffer_size) {
  347. LOG_CRITICAL(Core, "size ({:016X}) is greater than buffer_size ({:016X})", size,
  348. buffer_size);
  349. size = buffer_size; // TODO(bunnei): This needs to be HW tested
  350. }
  351. memory.WriteBlock(BufferDescriptorC()[buffer_index].Address(), buffer, size);
  352. return size;
  353. }
  354. std::size_t HLERequestContext::GetReadBufferSize(std::size_t buffer_index) const {
  355. const bool is_buffer_a{BufferDescriptorA().size() > buffer_index &&
  356. BufferDescriptorA()[buffer_index].Size()};
  357. if (is_buffer_a) {
  358. ASSERT_OR_EXECUTE_MSG(
  359. BufferDescriptorA().size() > buffer_index, { return 0; },
  360. "BufferDescriptorA invalid buffer_index {}", buffer_index);
  361. return BufferDescriptorA()[buffer_index].Size();
  362. } else {
  363. ASSERT_OR_EXECUTE_MSG(
  364. BufferDescriptorX().size() > buffer_index, { return 0; },
  365. "BufferDescriptorX invalid buffer_index {}", buffer_index);
  366. return BufferDescriptorX()[buffer_index].Size();
  367. }
  368. }
  369. std::size_t HLERequestContext::GetWriteBufferSize(std::size_t buffer_index) const {
  370. const bool is_buffer_b{BufferDescriptorB().size() > buffer_index &&
  371. BufferDescriptorB()[buffer_index].Size()};
  372. if (is_buffer_b) {
  373. ASSERT_OR_EXECUTE_MSG(
  374. BufferDescriptorB().size() > buffer_index, { return 0; },
  375. "BufferDescriptorB invalid buffer_index {}", buffer_index);
  376. return BufferDescriptorB()[buffer_index].Size();
  377. } else {
  378. ASSERT_OR_EXECUTE_MSG(
  379. BufferDescriptorC().size() > buffer_index, { return 0; },
  380. "BufferDescriptorC invalid buffer_index {}", buffer_index);
  381. return BufferDescriptorC()[buffer_index].Size();
  382. }
  383. return 0;
  384. }
  385. bool HLERequestContext::CanReadBuffer(std::size_t buffer_index) const {
  386. const bool is_buffer_a{BufferDescriptorA().size() > buffer_index &&
  387. BufferDescriptorA()[buffer_index].Size()};
  388. if (is_buffer_a) {
  389. return BufferDescriptorA().size() > buffer_index;
  390. } else {
  391. return BufferDescriptorX().size() > buffer_index;
  392. }
  393. }
  394. bool HLERequestContext::CanWriteBuffer(std::size_t buffer_index) const {
  395. const bool is_buffer_b{BufferDescriptorB().size() > buffer_index &&
  396. BufferDescriptorB()[buffer_index].Size()};
  397. if (is_buffer_b) {
  398. return BufferDescriptorB().size() > buffer_index;
  399. } else {
  400. return BufferDescriptorC().size() > buffer_index;
  401. }
  402. }
  403. std::string HLERequestContext::Description() const {
  404. if (!command_header) {
  405. return "No command header available";
  406. }
  407. std::ostringstream s;
  408. s << "IPC::CommandHeader: Type:" << static_cast<u32>(command_header->type.Value());
  409. s << ", X(Pointer):" << command_header->num_buf_x_descriptors;
  410. if (command_header->num_buf_x_descriptors) {
  411. s << '[';
  412. for (u64 i = 0; i < command_header->num_buf_x_descriptors; ++i) {
  413. s << "0x" << std::hex << BufferDescriptorX()[i].Size();
  414. if (i < command_header->num_buf_x_descriptors - 1)
  415. s << ", ";
  416. }
  417. s << ']';
  418. }
  419. s << ", A(Send):" << command_header->num_buf_a_descriptors;
  420. if (command_header->num_buf_a_descriptors) {
  421. s << '[';
  422. for (u64 i = 0; i < command_header->num_buf_a_descriptors; ++i) {
  423. s << "0x" << std::hex << BufferDescriptorA()[i].Size();
  424. if (i < command_header->num_buf_a_descriptors - 1)
  425. s << ", ";
  426. }
  427. s << ']';
  428. }
  429. s << ", B(Receive):" << command_header->num_buf_b_descriptors;
  430. if (command_header->num_buf_b_descriptors) {
  431. s << '[';
  432. for (u64 i = 0; i < command_header->num_buf_b_descriptors; ++i) {
  433. s << "0x" << std::hex << BufferDescriptorB()[i].Size();
  434. if (i < command_header->num_buf_b_descriptors - 1)
  435. s << ", ";
  436. }
  437. s << ']';
  438. }
  439. s << ", C(ReceiveList):" << BufferDescriptorC().size();
  440. if (!BufferDescriptorC().empty()) {
  441. s << '[';
  442. for (u64 i = 0; i < BufferDescriptorC().size(); ++i) {
  443. s << "0x" << std::hex << BufferDescriptorC()[i].Size();
  444. if (i < BufferDescriptorC().size() - 1)
  445. s << ", ";
  446. }
  447. s << ']';
  448. }
  449. s << ", data_size:" << command_header->data_size.Value();
  450. return s.str();
  451. }
  452. } // namespace Kernel