ipc_helpers.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. // Copyright 2016 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <array>
  6. #include <cstring>
  7. #include <memory>
  8. #include <tuple>
  9. #include <type_traits>
  10. #include <utility>
  11. #include "common/assert.h"
  12. #include "common/common_types.h"
  13. #include "core/core.h"
  14. #include "core/hle/ipc.h"
  15. #include "core/hle/kernel/client_port.h"
  16. #include "core/hle/kernel/client_session.h"
  17. #include "core/hle/kernel/hle_ipc.h"
  18. #include "core/hle/kernel/object.h"
  19. #include "core/hle/kernel/server_port.h"
  20. namespace IPC {
  21. class RequestHelperBase {
  22. protected:
  23. Kernel::HLERequestContext* context = nullptr;
  24. u32* cmdbuf;
  25. ptrdiff_t index = 0;
  26. public:
  27. explicit RequestHelperBase(u32* command_buffer) : cmdbuf(command_buffer) {}
  28. explicit RequestHelperBase(Kernel::HLERequestContext& context)
  29. : context(&context), cmdbuf(context.CommandBuffer()) {}
  30. void Skip(unsigned size_in_words, bool set_to_null) {
  31. if (set_to_null)
  32. memset(cmdbuf + index, 0, size_in_words * sizeof(u32));
  33. index += size_in_words;
  34. }
  35. /**
  36. * Aligns the current position forward to a 16-byte boundary, padding with zeros.
  37. */
  38. void AlignWithPadding() {
  39. if (index & 3) {
  40. Skip(4 - (index & 3), true);
  41. }
  42. }
  43. unsigned GetCurrentOffset() const {
  44. return static_cast<unsigned>(index);
  45. }
  46. void SetCurrentOffset(unsigned offset) {
  47. index = static_cast<ptrdiff_t>(offset);
  48. }
  49. };
  50. class ResponseBuilder : public RequestHelperBase {
  51. public:
  52. /// Flags used for customizing the behavior of ResponseBuilder
  53. enum class Flags : u32 {
  54. None = 0,
  55. /// Uses move handles to move objects in the response, even when in a domain. This is
  56. /// required when PushMoveObjects is used.
  57. AlwaysMoveHandles = 1,
  58. };
  59. explicit ResponseBuilder(u32* command_buffer) : RequestHelperBase(command_buffer) {}
  60. explicit ResponseBuilder(Kernel::HLERequestContext& context, u32 normal_params_size,
  61. u32 num_handles_to_copy = 0, u32 num_objects_to_move = 0,
  62. Flags flags = Flags::None)
  63. : RequestHelperBase(context), normal_params_size(normal_params_size),
  64. num_handles_to_copy(num_handles_to_copy), num_objects_to_move(num_objects_to_move) {
  65. memset(cmdbuf, 0, sizeof(u32) * IPC::COMMAND_BUFFER_LENGTH);
  66. context.ClearIncomingObjects();
  67. IPC::CommandHeader header{};
  68. // The entire size of the raw data section in u32 units, including the 16 bytes of mandatory
  69. // padding.
  70. u32 raw_data_size = sizeof(IPC::DataPayloadHeader) / 4 + 4 + normal_params_size;
  71. u32 num_handles_to_move{};
  72. u32 num_domain_objects{};
  73. const bool always_move_handles{
  74. (static_cast<u32>(flags) & static_cast<u32>(Flags::AlwaysMoveHandles)) != 0};
  75. if (!context.Session()->IsDomain() || always_move_handles) {
  76. num_handles_to_move = num_objects_to_move;
  77. } else {
  78. num_domain_objects = num_objects_to_move;
  79. }
  80. if (context.Session()->IsDomain()) {
  81. raw_data_size += sizeof(DomainMessageHeader) / 4 + num_domain_objects;
  82. }
  83. header.data_size.Assign(raw_data_size);
  84. if (num_handles_to_copy || num_handles_to_move) {
  85. header.enable_handle_descriptor.Assign(1);
  86. }
  87. PushRaw(header);
  88. if (header.enable_handle_descriptor) {
  89. IPC::HandleDescriptorHeader handle_descriptor_header{};
  90. handle_descriptor_header.num_handles_to_copy.Assign(num_handles_to_copy);
  91. handle_descriptor_header.num_handles_to_move.Assign(num_handles_to_move);
  92. PushRaw(handle_descriptor_header);
  93. Skip(num_handles_to_copy + num_handles_to_move, true);
  94. }
  95. AlignWithPadding();
  96. const bool request_has_domain_header{context.GetDomainMessageHeader() != nullptr};
  97. if (context.Session()->IsDomain() && request_has_domain_header) {
  98. IPC::DomainMessageHeader domain_header{};
  99. domain_header.num_objects = num_domain_objects;
  100. PushRaw(domain_header);
  101. }
  102. IPC::DataPayloadHeader data_payload_header{};
  103. data_payload_header.magic = Common::MakeMagic('S', 'F', 'C', 'O');
  104. PushRaw(data_payload_header);
  105. datapayload_index = index;
  106. }
  107. template <class T>
  108. void PushIpcInterface(std::shared_ptr<T> iface) {
  109. if (context->Session()->IsDomain()) {
  110. context->AddDomainObject(std::move(iface));
  111. } else {
  112. auto& kernel = Core::System::GetInstance().Kernel();
  113. auto sessions =
  114. Kernel::ServerSession::CreateSessionPair(kernel, iface->GetServiceName());
  115. auto server = std::get<Kernel::SharedPtr<Kernel::ServerSession>>(sessions);
  116. auto client = std::get<Kernel::SharedPtr<Kernel::ClientSession>>(sessions);
  117. iface->ClientConnected(server);
  118. context->AddMoveObject(std::move(client));
  119. }
  120. }
  121. template <class T, class... Args>
  122. void PushIpcInterface(Args&&... args) {
  123. PushIpcInterface<T>(std::make_shared<T>(std::forward<Args>(args)...));
  124. }
  125. void ValidateHeader() {
  126. const std::size_t num_domain_objects = context->NumDomainObjects();
  127. const std::size_t num_move_objects = context->NumMoveObjects();
  128. ASSERT_MSG(!num_domain_objects || !num_move_objects,
  129. "cannot move normal handles and domain objects");
  130. ASSERT_MSG((index - datapayload_index) == normal_params_size,
  131. "normal_params_size value is incorrect");
  132. ASSERT_MSG((num_domain_objects + num_move_objects) == num_objects_to_move,
  133. "num_objects_to_move value is incorrect");
  134. ASSERT_MSG(context->NumCopyObjects() == num_handles_to_copy,
  135. "num_handles_to_copy value is incorrect");
  136. }
  137. // Validate on destruction, as there shouldn't be any case where we don't want it
  138. ~ResponseBuilder() {
  139. ValidateHeader();
  140. }
  141. template <typename T>
  142. void Push(T value);
  143. template <typename First, typename... Other>
  144. void Push(const First& first_value, const Other&... other_values);
  145. /**
  146. * Helper function for pushing strongly-typed enumeration values.
  147. *
  148. * @tparam Enum The enumeration type to be pushed
  149. *
  150. * @param value The value to push.
  151. *
  152. * @note The underlying size of the enumeration type is the size of the
  153. * data that gets pushed. e.g. "enum class SomeEnum : u16" will
  154. * push a u16-sized amount of data.
  155. */
  156. template <typename Enum>
  157. void PushEnum(Enum value) {
  158. static_assert(std::is_enum_v<Enum>, "T must be an enum type within a PushEnum call.");
  159. static_assert(!std::is_convertible_v<Enum, int>,
  160. "enum type in PushEnum must be a strongly typed enum.");
  161. Push(static_cast<std::underlying_type_t<Enum>>(value));
  162. }
  163. /**
  164. * @brief Copies the content of the given trivially copyable class to the buffer as a normal
  165. * param
  166. * @note: The input class must be correctly packed/padded to fit hardware layout.
  167. */
  168. template <typename T>
  169. void PushRaw(const T& value);
  170. template <typename... O>
  171. void PushMoveObjects(Kernel::SharedPtr<O>... pointers);
  172. template <typename... O>
  173. void PushCopyObjects(Kernel::SharedPtr<O>... pointers);
  174. private:
  175. u32 normal_params_size{};
  176. u32 num_handles_to_copy{};
  177. u32 num_objects_to_move{}; ///< Domain objects or move handles, context dependent
  178. std::ptrdiff_t datapayload_index{};
  179. };
  180. /// Push ///
  181. template <>
  182. inline void ResponseBuilder::Push(u32 value) {
  183. cmdbuf[index++] = value;
  184. }
  185. template <typename T>
  186. void ResponseBuilder::PushRaw(const T& value) {
  187. std::memcpy(cmdbuf + index, &value, sizeof(T));
  188. index += (sizeof(T) + 3) / 4; // round up to word length
  189. }
  190. template <>
  191. inline void ResponseBuilder::Push(ResultCode value) {
  192. // Result codes are actually 64-bit in the IPC buffer, but only the high part is discarded.
  193. Push(value.raw);
  194. Push<u32>(0);
  195. }
  196. template <>
  197. inline void ResponseBuilder::Push(u8 value) {
  198. PushRaw(value);
  199. }
  200. template <>
  201. inline void ResponseBuilder::Push(u16 value) {
  202. PushRaw(value);
  203. }
  204. template <>
  205. inline void ResponseBuilder::Push(u64 value) {
  206. Push(static_cast<u32>(value));
  207. Push(static_cast<u32>(value >> 32));
  208. }
  209. template <>
  210. inline void ResponseBuilder::Push(bool value) {
  211. Push(static_cast<u8>(value));
  212. }
  213. template <typename First, typename... Other>
  214. void ResponseBuilder::Push(const First& first_value, const Other&... other_values) {
  215. Push(first_value);
  216. Push(other_values...);
  217. }
  218. template <typename... O>
  219. inline void ResponseBuilder::PushCopyObjects(Kernel::SharedPtr<O>... pointers) {
  220. auto objects = {pointers...};
  221. for (auto& object : objects) {
  222. context->AddCopyObject(std::move(object));
  223. }
  224. }
  225. template <typename... O>
  226. inline void ResponseBuilder::PushMoveObjects(Kernel::SharedPtr<O>... pointers) {
  227. auto objects = {pointers...};
  228. for (auto& object : objects) {
  229. context->AddMoveObject(std::move(object));
  230. }
  231. }
  232. class RequestParser : public RequestHelperBase {
  233. public:
  234. explicit RequestParser(u32* command_buffer) : RequestHelperBase(command_buffer) {}
  235. explicit RequestParser(Kernel::HLERequestContext& context) : RequestHelperBase(context) {
  236. ASSERT_MSG(context.GetDataPayloadOffset(), "context is incomplete");
  237. Skip(context.GetDataPayloadOffset(), false);
  238. // Skip the u64 command id, it's already stored in the context
  239. static constexpr u32 CommandIdSize = 2;
  240. Skip(CommandIdSize, false);
  241. }
  242. ResponseBuilder MakeBuilder(u32 normal_params_size, u32 num_handles_to_copy,
  243. u32 num_handles_to_move,
  244. ResponseBuilder::Flags flags = ResponseBuilder::Flags::None) const {
  245. return ResponseBuilder{*context, normal_params_size, num_handles_to_copy,
  246. num_handles_to_move, flags};
  247. }
  248. template <typename T>
  249. T Pop();
  250. template <typename T>
  251. void Pop(T& value);
  252. template <typename First, typename... Other>
  253. void Pop(First& first_value, Other&... other_values);
  254. template <typename T>
  255. T PopEnum() {
  256. static_assert(std::is_enum_v<T>, "T must be an enum type within a PopEnum call.");
  257. static_assert(!std::is_convertible_v<T, int>,
  258. "enum type in PopEnum must be a strongly typed enum.");
  259. return static_cast<T>(Pop<std::underlying_type_t<T>>());
  260. }
  261. /**
  262. * @brief Reads the next normal parameters as a struct, by copying it
  263. * @note: The output class must be correctly packed/padded to fit hardware layout.
  264. */
  265. template <typename T>
  266. void PopRaw(T& value);
  267. /**
  268. * @brief Reads the next normal parameters as a struct, by copying it into a new value
  269. * @note: The output class must be correctly packed/padded to fit hardware layout.
  270. */
  271. template <typename T>
  272. T PopRaw();
  273. template <typename T>
  274. Kernel::SharedPtr<T> GetMoveObject(std::size_t index);
  275. template <typename T>
  276. Kernel::SharedPtr<T> GetCopyObject(std::size_t index);
  277. template <class T>
  278. std::shared_ptr<T> PopIpcInterface() {
  279. ASSERT(context->Session()->IsDomain());
  280. ASSERT(context->GetDomainMessageHeader()->input_object_count > 0);
  281. return context->GetDomainRequestHandler<T>(Pop<u32>() - 1);
  282. }
  283. };
  284. /// Pop ///
  285. template <>
  286. inline u32 RequestParser::Pop() {
  287. return cmdbuf[index++];
  288. }
  289. template <typename T>
  290. void RequestParser::PopRaw(T& value) {
  291. std::memcpy(&value, cmdbuf + index, sizeof(T));
  292. index += (sizeof(T) + 3) / 4; // round up to word length
  293. }
  294. template <typename T>
  295. T RequestParser::PopRaw() {
  296. T value;
  297. PopRaw(value);
  298. return value;
  299. }
  300. template <>
  301. inline u8 RequestParser::Pop() {
  302. return PopRaw<u8>();
  303. }
  304. template <>
  305. inline u16 RequestParser::Pop() {
  306. return PopRaw<u16>();
  307. }
  308. template <>
  309. inline u64 RequestParser::Pop() {
  310. const u64 lsw = Pop<u32>();
  311. const u64 msw = Pop<u32>();
  312. return msw << 32 | lsw;
  313. }
  314. template <>
  315. inline s64 RequestParser::Pop() {
  316. return static_cast<s64>(Pop<u64>());
  317. }
  318. template <>
  319. inline bool RequestParser::Pop() {
  320. return Pop<u8>() != 0;
  321. }
  322. template <>
  323. inline ResultCode RequestParser::Pop() {
  324. return ResultCode{Pop<u32>()};
  325. }
  326. template <typename T>
  327. void RequestParser::Pop(T& value) {
  328. value = Pop<T>();
  329. }
  330. template <typename First, typename... Other>
  331. void RequestParser::Pop(First& first_value, Other&... other_values) {
  332. first_value = Pop<First>();
  333. Pop(other_values...);
  334. }
  335. template <typename T>
  336. Kernel::SharedPtr<T> RequestParser::GetMoveObject(std::size_t index) {
  337. return context->GetMoveObject<T>(index);
  338. }
  339. template <typename T>
  340. Kernel::SharedPtr<T> RequestParser::GetCopyObject(std::size_t index) {
  341. return context->GetCopyObject<T>(index);
  342. }
  343. } // namespace IPC