hle_ipc.h 11 KB

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