hle_ipc.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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/kernel.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 HandleTable;
  23. class HLERequestContext;
  24. class Process;
  25. class Event;
  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. void ParseCommandBuffer(u32_le* src_cmdbuf, bool incoming);
  114. /// Populates this context with data from the requesting process/thread.
  115. ResultCode PopulateFromIncomingCommandBuffer(u32_le* src_cmdbuf, Process& src_process,
  116. HandleTable& src_table);
  117. /// Writes data from this context back to the requesting process/thread.
  118. ResultCode WriteToOutgoingCommandBuffer(Thread& thread);
  119. u32_le GetCommand() const {
  120. return command;
  121. }
  122. IPC::CommandType GetCommandType() const {
  123. return command_header->type;
  124. }
  125. unsigned GetDataPayloadOffset() const {
  126. return data_payload_offset;
  127. }
  128. const std::vector<IPC::BufferDescriptorX>& BufferDescriptorX() const {
  129. return buffer_x_desciptors;
  130. }
  131. const std::vector<IPC::BufferDescriptorABW>& BufferDescriptorA() const {
  132. return buffer_a_desciptors;
  133. }
  134. const std::vector<IPC::BufferDescriptorABW>& BufferDescriptorB() const {
  135. return buffer_b_desciptors;
  136. }
  137. const std::vector<IPC::BufferDescriptorC>& BufferDescriptorC() const {
  138. return buffer_c_desciptors;
  139. }
  140. const std::shared_ptr<IPC::DomainMessageHeader>& GetDomainMessageHeader() const {
  141. return domain_message_header;
  142. }
  143. /// Helper function to read a buffer using the appropriate buffer descriptor
  144. std::vector<u8> ReadBuffer(int buffer_index = 0) const;
  145. /// Helper function to write a buffer using the appropriate buffer descriptor
  146. size_t WriteBuffer(const void* buffer, size_t size, int buffer_index = 0) const;
  147. /* Helper function to write a buffer using the appropriate buffer descriptor
  148. *
  149. * @tparam ContiguousContainer an arbitrary container that satisfies the
  150. * ContiguousContainer concept in the C++ standard library.
  151. *
  152. * @param container The container to write the data of into a buffer.
  153. * @param buffer_index The buffer in particular to write to.
  154. */
  155. template <typename ContiguousContainer,
  156. typename = std::enable_if_t<!std::is_pointer_v<ContiguousContainer>>>
  157. size_t WriteBuffer(const ContiguousContainer& container, int buffer_index = 0) const {
  158. using ContiguousType = typename ContiguousContainer::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(container), std::size(container) * sizeof(ContiguousType),
  162. buffer_index);
  163. }
  164. /// Helper function to get the size of the input buffer
  165. size_t GetReadBufferSize(int buffer_index = 0) const;
  166. /// Helper function to get the size of the output buffer
  167. size_t GetWriteBufferSize(int buffer_index = 0) const;
  168. template <typename T>
  169. SharedPtr<T> GetCopyObject(size_t index) {
  170. ASSERT(index < copy_objects.size());
  171. return DynamicObjectCast<T>(copy_objects[index]);
  172. }
  173. template <typename T>
  174. SharedPtr<T> GetMoveObject(size_t index) {
  175. ASSERT(index < move_objects.size());
  176. return DynamicObjectCast<T>(move_objects[index]);
  177. }
  178. void AddMoveObject(SharedPtr<Object> object) {
  179. move_objects.emplace_back(std::move(object));
  180. }
  181. void AddCopyObject(SharedPtr<Object> object) {
  182. copy_objects.emplace_back(std::move(object));
  183. }
  184. void AddDomainObject(std::shared_ptr<SessionRequestHandler> object) {
  185. domain_objects.emplace_back(std::move(object));
  186. }
  187. template <typename T>
  188. std::shared_ptr<T> GetDomainRequestHandler(size_t index) const {
  189. return std::static_pointer_cast<T>(domain_request_handlers[index]);
  190. }
  191. void SetDomainRequestHandlers(
  192. const std::vector<std::shared_ptr<SessionRequestHandler>>& handlers) {
  193. domain_request_handlers = handlers;
  194. }
  195. /// Clears the list of objects so that no lingering objects are written accidentally to the
  196. /// response buffer.
  197. void ClearIncomingObjects() {
  198. move_objects.clear();
  199. copy_objects.clear();
  200. domain_objects.clear();
  201. }
  202. size_t NumMoveObjects() const {
  203. return move_objects.size();
  204. }
  205. size_t NumCopyObjects() const {
  206. return copy_objects.size();
  207. }
  208. size_t NumDomainObjects() const {
  209. return domain_objects.size();
  210. }
  211. std::string Description() const;
  212. private:
  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