hle_ipc.h 11 KB

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