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