hle_ipc.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include <array>
  5. #include <functional>
  6. #include <memory>
  7. #include <optional>
  8. #include <string>
  9. #include <type_traits>
  10. #include <vector>
  11. #include "common/assert.h"
  12. #include "common/common_types.h"
  13. #include "common/concepts.h"
  14. #include "common/swap.h"
  15. #include "core/hle/ipc.h"
  16. #include "core/hle/kernel/svc_common.h"
  17. union ResultCode;
  18. namespace Core::Memory {
  19. class Memory;
  20. }
  21. namespace IPC {
  22. class ResponseBuilder;
  23. }
  24. namespace Service {
  25. class ServiceFrameworkBase;
  26. }
  27. enum class ServiceThreadType {
  28. Default,
  29. CreateNew,
  30. };
  31. namespace Kernel {
  32. class Domain;
  33. class HLERequestContext;
  34. class KAutoObject;
  35. class KernelCore;
  36. class KHandleTable;
  37. class KProcess;
  38. class KServerSession;
  39. class KThread;
  40. class KReadableEvent;
  41. class KSession;
  42. class KWritableEvent;
  43. class ServiceThread;
  44. enum class ThreadWakeupReason;
  45. /**
  46. * Interface implemented by HLE Session handlers.
  47. * This can be provided to a ServerSession in order to hook into several relevant events
  48. * (such as a new connection or a SyncRequest) so they can be implemented in the emulator.
  49. */
  50. class SessionRequestHandler : public std::enable_shared_from_this<SessionRequestHandler> {
  51. public:
  52. SessionRequestHandler(KernelCore& kernel_, const char* service_name_,
  53. ServiceThreadType thread_type);
  54. virtual ~SessionRequestHandler();
  55. /**
  56. * Handles a sync request from the emulated application.
  57. * @param server_session The ServerSession that was triggered for this sync request,
  58. * it should be used to differentiate which client (As in ClientSession) we're answering to.
  59. * TODO(Subv): Use a wrapper structure to hold all the information relevant to
  60. * this request (ServerSession, Originator thread, Translated command buffer, etc).
  61. * @returns ResultCode the result code of the translate operation.
  62. */
  63. virtual ResultCode HandleSyncRequest(Kernel::KServerSession& session,
  64. Kernel::HLERequestContext& context) = 0;
  65. /**
  66. * Signals that a client has just connected to this HLE handler and keeps the
  67. * associated ServerSession alive for the duration of the connection.
  68. * @param server_session Owning pointer to the ServerSession associated with the connection.
  69. */
  70. void ClientConnected(KServerSession* session);
  71. /**
  72. * Signals that a client has just disconnected from this HLE handler and releases the
  73. * associated ServerSession.
  74. * @param server_session ServerSession associated with the connection.
  75. */
  76. void ClientDisconnected(KServerSession* session);
  77. std::weak_ptr<ServiceThread> GetServiceThread() const {
  78. return service_thread;
  79. }
  80. protected:
  81. KernelCore& kernel;
  82. std::weak_ptr<ServiceThread> service_thread;
  83. };
  84. using SessionRequestHandlerWeakPtr = std::weak_ptr<SessionRequestHandler>;
  85. using SessionRequestHandlerPtr = std::shared_ptr<SessionRequestHandler>;
  86. /**
  87. * Manages the underlying HLE requests for a session, and whether (or not) the session should be
  88. * treated as a domain. This is managed separately from server sessions, as this state is shared
  89. * when objects are cloned.
  90. */
  91. class SessionRequestManager final {
  92. public:
  93. explicit SessionRequestManager(KernelCore& kernel);
  94. ~SessionRequestManager();
  95. bool IsDomain() const {
  96. return is_domain;
  97. }
  98. void ConvertToDomain() {
  99. domain_handlers = {session_handler};
  100. is_domain = true;
  101. }
  102. std::size_t DomainHandlerCount() const {
  103. return domain_handlers.size();
  104. }
  105. bool HasSessionHandler() const {
  106. return session_handler != nullptr;
  107. }
  108. SessionRequestHandler& SessionHandler() {
  109. return *session_handler;
  110. }
  111. const SessionRequestHandler& SessionHandler() const {
  112. return *session_handler;
  113. }
  114. void CloseDomainHandler(std::size_t index) {
  115. if (index < DomainHandlerCount()) {
  116. domain_handlers[index] = nullptr;
  117. } else {
  118. ASSERT_MSG(false, "Unexpected handler index {}", index);
  119. }
  120. }
  121. SessionRequestHandlerWeakPtr DomainHandler(std::size_t index) const {
  122. ASSERT_MSG(index < DomainHandlerCount(), "Unexpected handler index {}", index);
  123. return domain_handlers.at(index);
  124. }
  125. void AppendDomainHandler(SessionRequestHandlerPtr&& handler) {
  126. domain_handlers.emplace_back(std::move(handler));
  127. }
  128. void SetSessionHandler(SessionRequestHandlerPtr&& handler) {
  129. session_handler = std::move(handler);
  130. }
  131. std::weak_ptr<ServiceThread> GetServiceThread() const {
  132. return session_handler->GetServiceThread();
  133. }
  134. bool HasSessionRequestHandler(const HLERequestContext& context) const;
  135. private:
  136. bool is_domain{};
  137. SessionRequestHandlerPtr session_handler;
  138. std::vector<SessionRequestHandlerPtr> domain_handlers;
  139. private:
  140. KernelCore& kernel;
  141. };
  142. /**
  143. * Class containing information about an in-flight IPC request being handled by an HLE service
  144. * implementation. Services should avoid using old global APIs (e.g. Kernel::GetCommandBuffer()) and
  145. * when possible use the APIs in this class to service the request.
  146. *
  147. * HLE handle protocol
  148. * ===================
  149. *
  150. * To avoid needing HLE services to keep a separate handle table, or having to directly modify the
  151. * requester's table, a tweaked protocol is used to receive and send handles in requests. The kernel
  152. * will decode the incoming handles into object pointers and insert a id in the buffer where the
  153. * handle would normally be. The service then calls GetIncomingHandle() with that id to get the
  154. * pointer to the object. Similarly, instead of inserting a handle into the command buffer, the
  155. * service calls AddOutgoingHandle() and stores the returned id where the handle would normally go.
  156. *
  157. * The end result is similar to just giving services their own real handle tables, but since these
  158. * ids are local to a specific context, it avoids requiring services to manage handles for objects
  159. * across multiple calls and ensuring that unneeded handles are cleaned up.
  160. */
  161. class HLERequestContext {
  162. public:
  163. explicit HLERequestContext(KernelCore& kernel, Core::Memory::Memory& memory,
  164. KServerSession* session, KThread* thread);
  165. ~HLERequestContext();
  166. /// Returns a pointer to the IPC command buffer for this request.
  167. u32* CommandBuffer() {
  168. return cmd_buf.data();
  169. }
  170. /**
  171. * Returns the session through which this request was made. This can be used as a map key to
  172. * access per-client data on services.
  173. */
  174. Kernel::KServerSession* Session() {
  175. return server_session;
  176. }
  177. /// Populates this context with data from the requesting process/thread.
  178. ResultCode PopulateFromIncomingCommandBuffer(const KHandleTable& handle_table,
  179. u32_le* src_cmdbuf);
  180. /// Writes data from this context back to the requesting process/thread.
  181. ResultCode WriteToOutgoingCommandBuffer(KThread& requesting_thread);
  182. u32_le GetHipcCommand() const {
  183. return command;
  184. }
  185. u32_le GetTipcCommand() const {
  186. return static_cast<u32_le>(command_header->type.Value()) -
  187. static_cast<u32_le>(IPC::CommandType::TIPC_CommandRegion);
  188. }
  189. u32_le GetCommand() const {
  190. return command_header->IsTipc() ? GetTipcCommand() : GetHipcCommand();
  191. }
  192. bool IsTipc() const {
  193. return command_header->IsTipc();
  194. }
  195. IPC::CommandType GetCommandType() const {
  196. return command_header->type;
  197. }
  198. u64 GetPID() const {
  199. return pid;
  200. }
  201. u32 GetDataPayloadOffset() const {
  202. return data_payload_offset;
  203. }
  204. const std::vector<IPC::BufferDescriptorX>& BufferDescriptorX() const {
  205. return buffer_x_desciptors;
  206. }
  207. const std::vector<IPC::BufferDescriptorABW>& BufferDescriptorA() const {
  208. return buffer_a_desciptors;
  209. }
  210. const std::vector<IPC::BufferDescriptorABW>& BufferDescriptorB() const {
  211. return buffer_b_desciptors;
  212. }
  213. const std::vector<IPC::BufferDescriptorC>& BufferDescriptorC() const {
  214. return buffer_c_desciptors;
  215. }
  216. const IPC::DomainMessageHeader& GetDomainMessageHeader() const {
  217. return domain_message_header.value();
  218. }
  219. bool HasDomainMessageHeader() const {
  220. return domain_message_header.has_value();
  221. }
  222. /// Helper function to read a buffer using the appropriate buffer descriptor
  223. std::vector<u8> ReadBuffer(std::size_t buffer_index = 0) const;
  224. /// Helper function to write a buffer using the appropriate buffer descriptor
  225. std::size_t WriteBuffer(const void* buffer, std::size_t size,
  226. std::size_t buffer_index = 0) const;
  227. /* Helper function to write a buffer using the appropriate buffer descriptor
  228. *
  229. * @tparam T an arbitrary container that satisfies the
  230. * ContiguousContainer concept in the C++ standard library or a trivially copyable type.
  231. *
  232. * @param data The container/data to write into a buffer.
  233. * @param buffer_index The buffer in particular to write to.
  234. */
  235. template <typename T, typename = std::enable_if_t<!std::is_pointer_v<T>>>
  236. std::size_t WriteBuffer(const T& data, std::size_t buffer_index = 0) const {
  237. if constexpr (Common::IsSTLContainer<T>) {
  238. using ContiguousType = typename T::value_type;
  239. static_assert(std::is_trivially_copyable_v<ContiguousType>,
  240. "Container to WriteBuffer must contain trivially copyable objects");
  241. return WriteBuffer(std::data(data), std::size(data) * sizeof(ContiguousType),
  242. buffer_index);
  243. } else {
  244. static_assert(std::is_trivially_copyable_v<T>, "T must be trivially copyable");
  245. return WriteBuffer(&data, sizeof(T), buffer_index);
  246. }
  247. }
  248. /// Helper function to get the size of the input buffer
  249. std::size_t GetReadBufferSize(std::size_t buffer_index = 0) const;
  250. /// Helper function to get the size of the output buffer
  251. std::size_t GetWriteBufferSize(std::size_t buffer_index = 0) const;
  252. /// Helper function to test whether the input buffer at buffer_index can be read
  253. bool CanReadBuffer(std::size_t buffer_index = 0) const;
  254. /// Helper function to test whether the output buffer at buffer_index can be written
  255. bool CanWriteBuffer(std::size_t buffer_index = 0) const;
  256. Handle GetCopyHandle(std::size_t index) const {
  257. return incoming_copy_handles.at(index);
  258. }
  259. Handle GetMoveHandle(std::size_t index) const {
  260. return incoming_move_handles.at(index);
  261. }
  262. void AddMoveObject(KAutoObject* object) {
  263. outgoing_move_objects.emplace_back(object);
  264. }
  265. void AddCopyObject(KAutoObject* object) {
  266. outgoing_copy_objects.emplace_back(object);
  267. }
  268. void AddDomainObject(SessionRequestHandlerPtr object) {
  269. outgoing_domain_objects.emplace_back(std::move(object));
  270. }
  271. template <typename T>
  272. std::shared_ptr<T> GetDomainHandler(std::size_t index) const {
  273. return std::static_pointer_cast<T>(manager.lock()->DomainHandler(index).lock());
  274. }
  275. void SetSessionRequestManager(std::weak_ptr<SessionRequestManager> manager_) {
  276. manager = std::move(manager_);
  277. }
  278. std::string Description() const;
  279. KThread& GetThread() {
  280. return *thread;
  281. }
  282. private:
  283. friend class IPC::ResponseBuilder;
  284. void ParseCommandBuffer(const KHandleTable& handle_table, u32_le* src_cmdbuf, bool incoming);
  285. std::array<u32, IPC::COMMAND_BUFFER_LENGTH> cmd_buf;
  286. Kernel::KServerSession* server_session{};
  287. KThread* thread;
  288. std::vector<Handle> incoming_move_handles;
  289. std::vector<Handle> incoming_copy_handles;
  290. std::vector<KAutoObject*> outgoing_move_objects;
  291. std::vector<KAutoObject*> outgoing_copy_objects;
  292. std::vector<SessionRequestHandlerPtr> outgoing_domain_objects;
  293. std::optional<IPC::CommandHeader> command_header;
  294. std::optional<IPC::HandleDescriptorHeader> handle_descriptor_header;
  295. std::optional<IPC::DataPayloadHeader> data_payload_header;
  296. std::optional<IPC::DomainMessageHeader> domain_message_header;
  297. std::vector<IPC::BufferDescriptorX> buffer_x_desciptors;
  298. std::vector<IPC::BufferDescriptorABW> buffer_a_desciptors;
  299. std::vector<IPC::BufferDescriptorABW> buffer_b_desciptors;
  300. std::vector<IPC::BufferDescriptorABW> buffer_w_desciptors;
  301. std::vector<IPC::BufferDescriptorC> buffer_c_desciptors;
  302. u32_le command{};
  303. u64 pid{};
  304. u32 write_size{};
  305. u32 data_payload_offset{};
  306. u32 handles_offset{};
  307. u32 domain_offset{};
  308. std::weak_ptr<SessionRequestManager> manager;
  309. KernelCore& kernel;
  310. Core::Memory::Memory& memory;
  311. };
  312. } // namespace Kernel