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