hle_ipc.h 12 KB

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