hle_ipc.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <array>
  6. #include <sstream>
  7. #include <utility>
  8. #include <boost/range/algorithm_ext/erase.hpp>
  9. #include "common/assert.h"
  10. #include "common/common_funcs.h"
  11. #include "common/common_types.h"
  12. #include "common/logging/log.h"
  13. #include "core/core.h"
  14. #include "core/hle/ipc_helpers.h"
  15. #include "core/hle/kernel/handle_table.h"
  16. #include "core/hle/kernel/hle_ipc.h"
  17. #include "core/hle/kernel/kernel.h"
  18. #include "core/hle/kernel/object.h"
  19. #include "core/hle/kernel/process.h"
  20. #include "core/hle/kernel/readable_event.h"
  21. #include "core/hle/kernel/server_session.h"
  22. #include "core/hle/kernel/writable_event.h"
  23. #include "core/memory.h"
  24. namespace Kernel {
  25. void SessionRequestHandler::ClientConnected(SharedPtr<ServerSession> server_session) {
  26. server_session->SetHleHandler(shared_from_this());
  27. connected_sessions.push_back(std::move(server_session));
  28. }
  29. void SessionRequestHandler::ClientDisconnected(const SharedPtr<ServerSession>& server_session) {
  30. server_session->SetHleHandler(nullptr);
  31. boost::range::remove_erase(connected_sessions, server_session);
  32. }
  33. SharedPtr<WritableEvent> HLERequestContext::SleepClientThread(
  34. SharedPtr<Thread> thread, const std::string& reason, u64 timeout, WakeupCallback&& callback,
  35. SharedPtr<WritableEvent> writable_event) {
  36. // Put the client thread to sleep until the wait event is signaled or the timeout expires.
  37. thread->SetWakeupCallback([context = *this, callback](
  38. ThreadWakeupReason reason, SharedPtr<Thread> thread,
  39. SharedPtr<WaitObject> object, std::size_t index) mutable -> bool {
  40. ASSERT(thread->GetStatus() == ThreadStatus::WaitHLEEvent);
  41. callback(thread, context, reason);
  42. context.WriteToOutgoingCommandBuffer(*thread);
  43. return true;
  44. });
  45. auto& kernel = Core::System::GetInstance().Kernel();
  46. if (!writable_event) {
  47. // Create event if not provided
  48. const auto pair = WritableEvent::CreateEventPair(kernel, Kernel::ResetType::OneShot,
  49. "HLE Pause Event: " + reason);
  50. writable_event = pair.writable;
  51. }
  52. const auto readable_event{writable_event->GetReadableEvent()};
  53. writable_event->Clear();
  54. thread->SetStatus(ThreadStatus::WaitHLEEvent);
  55. thread->SetWaitObjects({readable_event});
  56. readable_event->AddWaitingThread(thread);
  57. if (timeout > 0) {
  58. thread->WakeAfterDelay(timeout);
  59. }
  60. return writable_event;
  61. }
  62. HLERequestContext::HLERequestContext(SharedPtr<Kernel::ServerSession> server_session)
  63. : server_session(std::move(server_session)) {
  64. cmd_buf[0] = 0;
  65. }
  66. HLERequestContext::~HLERequestContext() = default;
  67. void HLERequestContext::ParseCommandBuffer(const HandleTable& handle_table, u32_le* src_cmdbuf,
  68. bool incoming) {
  69. IPC::RequestParser rp(src_cmdbuf);
  70. command_header = std::make_shared<IPC::CommandHeader>(rp.PopRaw<IPC::CommandHeader>());
  71. if (command_header->type == IPC::CommandType::Close) {
  72. // Close does not populate the rest of the IPC header
  73. return;
  74. }
  75. // If handle descriptor is present, add size of it
  76. if (command_header->enable_handle_descriptor) {
  77. handle_descriptor_header =
  78. std::make_shared<IPC::HandleDescriptorHeader>(rp.PopRaw<IPC::HandleDescriptorHeader>());
  79. if (handle_descriptor_header->send_current_pid) {
  80. rp.Skip(2, false);
  81. }
  82. if (incoming) {
  83. // Populate the object lists with the data in the IPC request.
  84. for (u32 handle = 0; handle < handle_descriptor_header->num_handles_to_copy; ++handle) {
  85. copy_objects.push_back(handle_table.GetGeneric(rp.Pop<Handle>()));
  86. }
  87. for (u32 handle = 0; handle < handle_descriptor_header->num_handles_to_move; ++handle) {
  88. move_objects.push_back(handle_table.GetGeneric(rp.Pop<Handle>()));
  89. }
  90. } else {
  91. // For responses we just ignore the handles, they're empty and will be populated when
  92. // translating the response.
  93. rp.Skip(handle_descriptor_header->num_handles_to_copy, false);
  94. rp.Skip(handle_descriptor_header->num_handles_to_move, false);
  95. }
  96. }
  97. for (unsigned i = 0; i < command_header->num_buf_x_descriptors; ++i) {
  98. buffer_x_desciptors.push_back(rp.PopRaw<IPC::BufferDescriptorX>());
  99. }
  100. for (unsigned i = 0; i < command_header->num_buf_a_descriptors; ++i) {
  101. buffer_a_desciptors.push_back(rp.PopRaw<IPC::BufferDescriptorABW>());
  102. }
  103. for (unsigned i = 0; i < command_header->num_buf_b_descriptors; ++i) {
  104. buffer_b_desciptors.push_back(rp.PopRaw<IPC::BufferDescriptorABW>());
  105. }
  106. for (unsigned i = 0; i < command_header->num_buf_w_descriptors; ++i) {
  107. buffer_w_desciptors.push_back(rp.PopRaw<IPC::BufferDescriptorABW>());
  108. }
  109. buffer_c_offset = rp.GetCurrentOffset() + command_header->data_size;
  110. // Padding to align to 16 bytes
  111. rp.AlignWithPadding();
  112. if (Session()->IsDomain() && ((command_header->type == IPC::CommandType::Request ||
  113. command_header->type == IPC::CommandType::RequestWithContext) ||
  114. !incoming)) {
  115. // If this is an incoming message, only CommandType "Request" has a domain header
  116. // All outgoing domain messages have the domain header, if only incoming has it
  117. if (incoming || domain_message_header) {
  118. domain_message_header =
  119. std::make_shared<IPC::DomainMessageHeader>(rp.PopRaw<IPC::DomainMessageHeader>());
  120. } else {
  121. if (Session()->IsDomain())
  122. LOG_WARNING(IPC, "Domain request has no DomainMessageHeader!");
  123. }
  124. }
  125. data_payload_header =
  126. std::make_shared<IPC::DataPayloadHeader>(rp.PopRaw<IPC::DataPayloadHeader>());
  127. data_payload_offset = rp.GetCurrentOffset();
  128. if (domain_message_header && domain_message_header->command ==
  129. IPC::DomainMessageHeader::CommandType::CloseVirtualHandle) {
  130. // CloseVirtualHandle command does not have SFC* or any data
  131. return;
  132. }
  133. if (incoming) {
  134. ASSERT(data_payload_header->magic == Common::MakeMagic('S', 'F', 'C', 'I'));
  135. } else {
  136. ASSERT(data_payload_header->magic == Common::MakeMagic('S', 'F', 'C', 'O'));
  137. }
  138. rp.SetCurrentOffset(buffer_c_offset);
  139. // For Inline buffers, the response data is written directly to buffer_c_offset
  140. // and in this case we don't have any BufferDescriptorC on the request.
  141. if (command_header->buf_c_descriptor_flags >
  142. IPC::CommandHeader::BufferDescriptorCFlag::InlineDescriptor) {
  143. if (command_header->buf_c_descriptor_flags ==
  144. IPC::CommandHeader::BufferDescriptorCFlag::OneDescriptor) {
  145. buffer_c_desciptors.push_back(rp.PopRaw<IPC::BufferDescriptorC>());
  146. } else {
  147. unsigned num_buf_c_descriptors =
  148. static_cast<unsigned>(command_header->buf_c_descriptor_flags.Value()) - 2;
  149. // This is used to detect possible underflows, in case something is broken
  150. // with the two ifs above and the flags value is == 0 || == 1.
  151. ASSERT(num_buf_c_descriptors < 14);
  152. for (unsigned i = 0; i < num_buf_c_descriptors; ++i) {
  153. buffer_c_desciptors.push_back(rp.PopRaw<IPC::BufferDescriptorC>());
  154. }
  155. }
  156. }
  157. rp.SetCurrentOffset(data_payload_offset);
  158. command = rp.Pop<u32_le>();
  159. rp.Skip(1, false); // The command is actually an u64, but we don't use the high part.
  160. }
  161. ResultCode HLERequestContext::PopulateFromIncomingCommandBuffer(const HandleTable& handle_table,
  162. u32_le* src_cmdbuf) {
  163. ParseCommandBuffer(handle_table, src_cmdbuf, true);
  164. if (command_header->type == IPC::CommandType::Close) {
  165. // Close does not populate the rest of the IPC header
  166. return RESULT_SUCCESS;
  167. }
  168. // The data_size already includes the payload header, the padding and the domain header.
  169. std::size_t size = data_payload_offset + command_header->data_size -
  170. sizeof(IPC::DataPayloadHeader) / sizeof(u32) - 4;
  171. if (domain_message_header)
  172. size -= sizeof(IPC::DomainMessageHeader) / sizeof(u32);
  173. std::copy_n(src_cmdbuf, size, cmd_buf.begin());
  174. return RESULT_SUCCESS;
  175. }
  176. ResultCode HLERequestContext::WriteToOutgoingCommandBuffer(Thread& thread) {
  177. auto& owner_process = *thread.GetOwnerProcess();
  178. auto& handle_table = owner_process.GetHandleTable();
  179. std::array<u32, IPC::COMMAND_BUFFER_LENGTH> dst_cmdbuf;
  180. Memory::ReadBlock(owner_process, thread.GetTLSAddress(), dst_cmdbuf.data(),
  181. dst_cmdbuf.size() * sizeof(u32));
  182. // The header was already built in the internal command buffer. Attempt to parse it to verify
  183. // the integrity and then copy it over to the target command buffer.
  184. ParseCommandBuffer(handle_table, cmd_buf.data(), false);
  185. // The data_size already includes the payload header, the padding and the domain header.
  186. std::size_t size = data_payload_offset + command_header->data_size -
  187. sizeof(IPC::DataPayloadHeader) / sizeof(u32) - 4;
  188. if (domain_message_header)
  189. size -= sizeof(IPC::DomainMessageHeader) / sizeof(u32);
  190. std::copy_n(cmd_buf.begin(), size, dst_cmdbuf.data());
  191. if (command_header->enable_handle_descriptor) {
  192. ASSERT_MSG(!move_objects.empty() || !copy_objects.empty(),
  193. "Handle descriptor bit set but no handles to translate");
  194. // We write the translated handles at a specific offset in the command buffer, this space
  195. // was already reserved when writing the header.
  196. std::size_t current_offset =
  197. (sizeof(IPC::CommandHeader) + sizeof(IPC::HandleDescriptorHeader)) / sizeof(u32);
  198. ASSERT_MSG(!handle_descriptor_header->send_current_pid, "Sending PID is not implemented");
  199. ASSERT(copy_objects.size() == handle_descriptor_header->num_handles_to_copy);
  200. ASSERT(move_objects.size() == handle_descriptor_header->num_handles_to_move);
  201. // We don't make a distinction between copy and move handles when translating since HLE
  202. // services don't deal with handles directly. However, the guest applications might check
  203. // for specific values in each of these descriptors.
  204. for (auto& object : copy_objects) {
  205. ASSERT(object != nullptr);
  206. dst_cmdbuf[current_offset++] = handle_table.Create(object).Unwrap();
  207. }
  208. for (auto& object : move_objects) {
  209. ASSERT(object != nullptr);
  210. dst_cmdbuf[current_offset++] = handle_table.Create(object).Unwrap();
  211. }
  212. }
  213. // TODO(Subv): Translate the X/A/B/W buffers.
  214. if (Session()->IsDomain() && domain_message_header) {
  215. ASSERT(domain_message_header->num_objects == domain_objects.size());
  216. // Write the domain objects to the command buffer, these go after the raw untranslated data.
  217. // TODO(Subv): This completely ignores C buffers.
  218. std::size_t domain_offset = size - domain_message_header->num_objects;
  219. auto& request_handlers = server_session->domain_request_handlers;
  220. for (auto& object : domain_objects) {
  221. request_handlers.emplace_back(object);
  222. dst_cmdbuf[domain_offset++] = static_cast<u32_le>(request_handlers.size());
  223. }
  224. }
  225. // Copy the translated command buffer back into the thread's command buffer area.
  226. Memory::WriteBlock(owner_process, thread.GetTLSAddress(), dst_cmdbuf.data(),
  227. dst_cmdbuf.size() * sizeof(u32));
  228. return RESULT_SUCCESS;
  229. }
  230. std::vector<u8> HLERequestContext::ReadBuffer(int buffer_index) const {
  231. std::vector<u8> buffer;
  232. const bool is_buffer_a{BufferDescriptorA().size() && BufferDescriptorA()[buffer_index].Size()};
  233. if (is_buffer_a) {
  234. buffer.resize(BufferDescriptorA()[buffer_index].Size());
  235. Memory::ReadBlock(BufferDescriptorA()[buffer_index].Address(), buffer.data(),
  236. buffer.size());
  237. } else {
  238. buffer.resize(BufferDescriptorX()[buffer_index].Size());
  239. Memory::ReadBlock(BufferDescriptorX()[buffer_index].Address(), buffer.data(),
  240. buffer.size());
  241. }
  242. return buffer;
  243. }
  244. std::size_t HLERequestContext::WriteBuffer(const void* buffer, std::size_t size,
  245. int buffer_index) const {
  246. if (size == 0) {
  247. LOG_WARNING(Core, "skip empty buffer write");
  248. return 0;
  249. }
  250. const bool is_buffer_b{BufferDescriptorB().size() && BufferDescriptorB()[buffer_index].Size()};
  251. const std::size_t buffer_size{GetWriteBufferSize(buffer_index)};
  252. if (size > buffer_size) {
  253. LOG_CRITICAL(Core, "size ({:016X}) is greater than buffer_size ({:016X})", size,
  254. buffer_size);
  255. size = buffer_size; // TODO(bunnei): This needs to be HW tested
  256. }
  257. if (is_buffer_b) {
  258. Memory::WriteBlock(BufferDescriptorB()[buffer_index].Address(), buffer, size);
  259. } else {
  260. Memory::WriteBlock(BufferDescriptorC()[buffer_index].Address(), buffer, size);
  261. }
  262. return size;
  263. }
  264. std::size_t HLERequestContext::GetReadBufferSize(int buffer_index) const {
  265. const bool is_buffer_a{BufferDescriptorA().size() && BufferDescriptorA()[buffer_index].Size()};
  266. return is_buffer_a ? BufferDescriptorA()[buffer_index].Size()
  267. : BufferDescriptorX()[buffer_index].Size();
  268. }
  269. std::size_t HLERequestContext::GetWriteBufferSize(int buffer_index) const {
  270. const bool is_buffer_b{BufferDescriptorB().size() && BufferDescriptorB()[buffer_index].Size()};
  271. return is_buffer_b ? BufferDescriptorB()[buffer_index].Size()
  272. : BufferDescriptorC()[buffer_index].Size();
  273. }
  274. std::string HLERequestContext::Description() const {
  275. if (!command_header) {
  276. return "No command header available";
  277. }
  278. std::ostringstream s;
  279. s << "IPC::CommandHeader: Type:" << static_cast<u32>(command_header->type.Value());
  280. s << ", X(Pointer):" << command_header->num_buf_x_descriptors;
  281. if (command_header->num_buf_x_descriptors) {
  282. s << '[';
  283. for (u64 i = 0; i < command_header->num_buf_x_descriptors; ++i) {
  284. s << "0x" << std::hex << BufferDescriptorX()[i].Size();
  285. if (i < command_header->num_buf_x_descriptors - 1)
  286. s << ", ";
  287. }
  288. s << ']';
  289. }
  290. s << ", A(Send):" << command_header->num_buf_a_descriptors;
  291. if (command_header->num_buf_a_descriptors) {
  292. s << '[';
  293. for (u64 i = 0; i < command_header->num_buf_a_descriptors; ++i) {
  294. s << "0x" << std::hex << BufferDescriptorA()[i].Size();
  295. if (i < command_header->num_buf_a_descriptors - 1)
  296. s << ", ";
  297. }
  298. s << ']';
  299. }
  300. s << ", B(Receive):" << command_header->num_buf_b_descriptors;
  301. if (command_header->num_buf_b_descriptors) {
  302. s << '[';
  303. for (u64 i = 0; i < command_header->num_buf_b_descriptors; ++i) {
  304. s << "0x" << std::hex << BufferDescriptorB()[i].Size();
  305. if (i < command_header->num_buf_b_descriptors - 1)
  306. s << ", ";
  307. }
  308. s << ']';
  309. }
  310. s << ", C(ReceiveList):" << BufferDescriptorC().size();
  311. if (!BufferDescriptorC().empty()) {
  312. s << '[';
  313. for (u64 i = 0; i < BufferDescriptorC().size(); ++i) {
  314. s << "0x" << std::hex << BufferDescriptorC()[i].Size();
  315. if (i < BufferDescriptorC().size() - 1)
  316. s << ", ";
  317. }
  318. s << ']';
  319. }
  320. s << ", data_size:" << command_header->data_size.Value();
  321. return s.str();
  322. }
  323. } // namespace Kernel