hle_ipc.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 <boost/container/small_vector.hpp>
  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/object.h"
  18. union ResultCode;
  19. namespace Core::Memory {
  20. class Memory;
  21. }
  22. namespace IPC {
  23. class ResponseBuilder;
  24. }
  25. namespace Service {
  26. class ServiceFrameworkBase;
  27. }
  28. namespace Kernel {
  29. class Domain;
  30. class HandleTable;
  31. class HLERequestContext;
  32. class KernelCore;
  33. class Process;
  34. class ServerSession;
  35. class KThread;
  36. class KReadableEvent;
  37. class KWritableEvent;
  38. enum class ThreadWakeupReason;
  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();
  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 ResultCode the result code of the translate operation.
  55. */
  56. virtual ResultCode HandleSyncRequest(Kernel::HLERequestContext& context) = 0;
  57. /**
  58. * Signals that a client has just connected to this HLE handler and keeps the
  59. * associated ServerSession alive for the duration of the connection.
  60. * @param server_session Owning pointer to the ServerSession associated with the connection.
  61. */
  62. void ClientConnected(std::shared_ptr<ServerSession> server_session);
  63. /**
  64. * Signals that a client has just disconnected from this HLE handler and releases the
  65. * associated ServerSession.
  66. * @param server_session ServerSession associated with the connection.
  67. */
  68. void ClientDisconnected(const std::shared_ptr<ServerSession>& server_session);
  69. protected:
  70. /// List of sessions that are connected to this handler.
  71. /// A ServerSession whose server endpoint is an HLE implementation is kept alive by this list
  72. /// for the duration of the connection.
  73. std::vector<std::shared_ptr<ServerSession>> connected_sessions;
  74. };
  75. /**
  76. * Class containing information about an in-flight IPC request being handled by an HLE service
  77. * implementation. Services should avoid using old global APIs (e.g. Kernel::GetCommandBuffer()) and
  78. * when possible use the APIs in this class to service the request.
  79. *
  80. * HLE handle protocol
  81. * ===================
  82. *
  83. * To avoid needing HLE services to keep a separate handle table, or having to directly modify the
  84. * requester's table, a tweaked protocol is used to receive and send handles in requests. The kernel
  85. * will decode the incoming handles into object pointers and insert a id in the buffer where the
  86. * handle would normally be. The service then calls GetIncomingHandle() with that id to get the
  87. * pointer to the object. Similarly, instead of inserting a handle into the command buffer, the
  88. * service calls AddOutgoingHandle() and stores the returned id where the handle would normally go.
  89. *
  90. * The end result is similar to just giving services their own real handle tables, but since these
  91. * ids are local to a specific context, it avoids requiring services to manage handles for objects
  92. * across multiple calls and ensuring that unneeded handles are cleaned up.
  93. */
  94. class HLERequestContext {
  95. public:
  96. explicit HLERequestContext(KernelCore& kernel, Core::Memory::Memory& memory,
  97. std::shared_ptr<ServerSession> session, KThread* thread);
  98. ~HLERequestContext();
  99. /// Returns a pointer to the IPC command buffer for this request.
  100. u32* CommandBuffer() {
  101. return cmd_buf.data();
  102. }
  103. /**
  104. * Returns the session through which this request was made. This can be used as a map key to
  105. * access per-client data on services.
  106. */
  107. const std::shared_ptr<Kernel::ServerSession>& Session() const {
  108. return server_session;
  109. }
  110. /// Populates this context with data from the requesting process/thread.
  111. ResultCode PopulateFromIncomingCommandBuffer(const HandleTable& handle_table,
  112. u32_le* src_cmdbuf);
  113. /// Writes data from this context back to the requesting process/thread.
  114. ResultCode WriteToOutgoingCommandBuffer(KThread& thread);
  115. u32_le GetCommand() const {
  116. return command;
  117. }
  118. IPC::CommandType GetCommandType() const {
  119. return command_header->type;
  120. }
  121. unsigned GetDataPayloadOffset() const {
  122. return data_payload_offset;
  123. }
  124. const std::vector<IPC::BufferDescriptorX>& BufferDescriptorX() const {
  125. return buffer_x_desciptors;
  126. }
  127. const std::vector<IPC::BufferDescriptorABW>& BufferDescriptorA() const {
  128. return buffer_a_desciptors;
  129. }
  130. const std::vector<IPC::BufferDescriptorABW>& BufferDescriptorB() const {
  131. return buffer_b_desciptors;
  132. }
  133. const std::vector<IPC::BufferDescriptorC>& BufferDescriptorC() const {
  134. return buffer_c_desciptors;
  135. }
  136. const IPC::DomainMessageHeader& GetDomainMessageHeader() const {
  137. return domain_message_header.value();
  138. }
  139. bool HasDomainMessageHeader() const {
  140. return domain_message_header.has_value();
  141. }
  142. /// Helper function to read a buffer using the appropriate buffer descriptor
  143. std::vector<u8> ReadBuffer(std::size_t buffer_index = 0) const;
  144. /// Helper function to write a buffer using the appropriate buffer descriptor
  145. std::size_t WriteBuffer(const void* buffer, std::size_t size,
  146. std::size_t buffer_index = 0) const;
  147. /* Helper function to write a buffer using the appropriate buffer descriptor
  148. *
  149. * @tparam T an arbitrary container that satisfies the
  150. * ContiguousContainer concept in the C++ standard library or a trivially copyable type.
  151. *
  152. * @param data The container/data to write into a buffer.
  153. * @param buffer_index The buffer in particular to write to.
  154. */
  155. template <typename T, typename = std::enable_if_t<!std::is_pointer_v<T>>>
  156. std::size_t WriteBuffer(const T& data, std::size_t buffer_index = 0) const {
  157. if constexpr (Common::IsSTLContainer<T>) {
  158. using ContiguousType = typename T::value_type;
  159. static_assert(std::is_trivially_copyable_v<ContiguousType>,
  160. "Container to WriteBuffer must contain trivially copyable objects");
  161. return WriteBuffer(std::data(data), std::size(data) * sizeof(ContiguousType),
  162. buffer_index);
  163. } else {
  164. static_assert(std::is_trivially_copyable_v<T>, "T must be trivially copyable");
  165. return WriteBuffer(&data, sizeof(T), buffer_index);
  166. }
  167. }
  168. /// Helper function to get the size of the input buffer
  169. std::size_t GetReadBufferSize(std::size_t buffer_index = 0) const;
  170. /// Helper function to get the size of the output buffer
  171. std::size_t GetWriteBufferSize(std::size_t buffer_index = 0) const;
  172. /// Helper function to test whether the input buffer at buffer_index can be read
  173. bool CanReadBuffer(std::size_t buffer_index = 0) const;
  174. /// Helper function to test whether the output buffer at buffer_index can be written
  175. bool CanWriteBuffer(std::size_t buffer_index = 0) const;
  176. Handle GetCopyHandle(std::size_t index) const {
  177. return copy_handles.at(index);
  178. }
  179. Handle GetMoveHandle(std::size_t index) const {
  180. return move_handles.at(index);
  181. }
  182. template <typename T>
  183. std::shared_ptr<T> GetCopyObject(std::size_t index) {
  184. return DynamicObjectCast<T>(copy_objects.at(index));
  185. }
  186. template <typename T>
  187. std::shared_ptr<T> GetMoveObject(std::size_t index) {
  188. return DynamicObjectCast<T>(move_objects.at(index));
  189. }
  190. void AddMoveObject(std::shared_ptr<Object> object) {
  191. move_objects.emplace_back(std::move(object));
  192. }
  193. void AddCopyObject(std::shared_ptr<Object> object) {
  194. copy_objects.emplace_back(std::move(object));
  195. }
  196. void AddDomainObject(std::shared_ptr<SessionRequestHandler> object) {
  197. domain_objects.emplace_back(std::move(object));
  198. }
  199. template <typename T>
  200. std::shared_ptr<T> GetDomainRequestHandler(std::size_t index) const {
  201. return std::static_pointer_cast<T>(domain_request_handlers.at(index));
  202. }
  203. void SetDomainRequestHandlers(
  204. const std::vector<std::shared_ptr<SessionRequestHandler>>& handlers) {
  205. domain_request_handlers = handlers;
  206. }
  207. /// Clears the list of objects so that no lingering objects are written accidentally to the
  208. /// response buffer.
  209. void ClearIncomingObjects() {
  210. move_objects.clear();
  211. copy_objects.clear();
  212. domain_objects.clear();
  213. }
  214. std::size_t NumMoveObjects() const {
  215. return move_objects.size();
  216. }
  217. std::size_t NumCopyObjects() const {
  218. return copy_objects.size();
  219. }
  220. std::size_t NumDomainObjects() const {
  221. return domain_objects.size();
  222. }
  223. std::string Description() const;
  224. KThread& GetThread() {
  225. return *thread;
  226. }
  227. bool IsThreadWaiting() const {
  228. return is_thread_waiting;
  229. }
  230. private:
  231. friend class IPC::ResponseBuilder;
  232. void ParseCommandBuffer(const HandleTable& handle_table, u32_le* src_cmdbuf, bool incoming);
  233. std::array<u32, IPC::COMMAND_BUFFER_LENGTH> cmd_buf;
  234. std::shared_ptr<Kernel::ServerSession> server_session;
  235. KThread* thread;
  236. // TODO(yuriks): Check common usage of this and optimize size accordingly
  237. boost::container::small_vector<Handle, 8> move_handles;
  238. boost::container::small_vector<Handle, 8> copy_handles;
  239. boost::container::small_vector<std::shared_ptr<Object>, 8> move_objects;
  240. boost::container::small_vector<std::shared_ptr<Object>, 8> copy_objects;
  241. boost::container::small_vector<std::shared_ptr<SessionRequestHandler>, 8> domain_objects;
  242. std::optional<IPC::CommandHeader> command_header;
  243. std::optional<IPC::HandleDescriptorHeader> handle_descriptor_header;
  244. std::optional<IPC::DataPayloadHeader> data_payload_header;
  245. std::optional<IPC::DomainMessageHeader> domain_message_header;
  246. std::vector<IPC::BufferDescriptorX> buffer_x_desciptors;
  247. std::vector<IPC::BufferDescriptorABW> buffer_a_desciptors;
  248. std::vector<IPC::BufferDescriptorABW> buffer_b_desciptors;
  249. std::vector<IPC::BufferDescriptorABW> buffer_w_desciptors;
  250. std::vector<IPC::BufferDescriptorC> buffer_c_desciptors;
  251. unsigned data_payload_offset{};
  252. unsigned buffer_c_offset{};
  253. u32_le command{};
  254. std::vector<std::shared_ptr<SessionRequestHandler>> domain_request_handlers;
  255. bool is_thread_waiting{};
  256. KernelCore& kernel;
  257. Core::Memory::Memory& memory;
  258. };
  259. } // namespace Kernel