hle_ipc.h 11 KB

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