hle_ipc.h 13 KB

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