hle_ipc.cpp 18 KB

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