hle_ipc.h 14 KB

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