hle_ipc.h 13 KB

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