ipc_helpers.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. if (context.Session()->IsDomain() && context.HasDomainMessageHeader()) {
  97. IPC::DomainMessageHeader domain_header{};
  98. domain_header.num_objects = num_domain_objects;
  99. PushRaw(domain_header);
  100. }
  101. IPC::DataPayloadHeader data_payload_header{};
  102. data_payload_header.magic = Common::MakeMagic('S', 'F', 'C', 'O');
  103. PushRaw(data_payload_header);
  104. datapayload_index = index;
  105. }
  106. template <class T>
  107. void PushIpcInterface(std::shared_ptr<T> iface) {
  108. if (context->Session()->IsDomain()) {
  109. context->AddDomainObject(std::move(iface));
  110. } else {
  111. auto& kernel = Core::System::GetInstance().Kernel();
  112. auto sessions =
  113. Kernel::ServerSession::CreateSessionPair(kernel, iface->GetServiceName());
  114. auto server = std::get<Kernel::SharedPtr<Kernel::ServerSession>>(sessions);
  115. auto client = std::get<Kernel::SharedPtr<Kernel::ClientSession>>(sessions);
  116. iface->ClientConnected(server);
  117. context->AddMoveObject(std::move(client));
  118. }
  119. }
  120. template <class T, class... Args>
  121. void PushIpcInterface(Args&&... args) {
  122. PushIpcInterface<T>(std::make_shared<T>(std::forward<Args>(args)...));
  123. }
  124. void ValidateHeader() {
  125. const std::size_t num_domain_objects = context->NumDomainObjects();
  126. const std::size_t num_move_objects = context->NumMoveObjects();
  127. ASSERT_MSG(!num_domain_objects || !num_move_objects,
  128. "cannot move normal handles and domain objects");
  129. ASSERT_MSG((index - datapayload_index) == normal_params_size,
  130. "normal_params_size value is incorrect");
  131. ASSERT_MSG((num_domain_objects + num_move_objects) == num_objects_to_move,
  132. "num_objects_to_move value is incorrect");
  133. ASSERT_MSG(context->NumCopyObjects() == num_handles_to_copy,
  134. "num_handles_to_copy value is incorrect");
  135. }
  136. // Validate on destruction, as there shouldn't be any case where we don't want it
  137. ~ResponseBuilder() {
  138. ValidateHeader();
  139. }
  140. template <typename T>
  141. void Push(T value);
  142. template <typename First, typename... Other>
  143. void Push(const First& first_value, const Other&... other_values);
  144. /**
  145. * Helper function for pushing strongly-typed enumeration values.
  146. *
  147. * @tparam Enum The enumeration type to be pushed
  148. *
  149. * @param value The value to push.
  150. *
  151. * @note The underlying size of the enumeration type is the size of the
  152. * data that gets pushed. e.g. "enum class SomeEnum : u16" will
  153. * push a u16-sized amount of data.
  154. */
  155. template <typename Enum>
  156. void PushEnum(Enum value) {
  157. static_assert(std::is_enum_v<Enum>, "T must be an enum type within a PushEnum call.");
  158. static_assert(!std::is_convertible_v<Enum, int>,
  159. "enum type in PushEnum must be a strongly typed enum.");
  160. Push(static_cast<std::underlying_type_t<Enum>>(value));
  161. }
  162. /**
  163. * @brief Copies the content of the given trivially copyable class to the buffer as a normal
  164. * param
  165. * @note: The input class must be correctly packed/padded to fit hardware layout.
  166. */
  167. template <typename T>
  168. void PushRaw(const T& value);
  169. template <typename... O>
  170. void PushMoveObjects(Kernel::SharedPtr<O>... pointers);
  171. template <typename... O>
  172. void PushCopyObjects(Kernel::SharedPtr<O>... pointers);
  173. private:
  174. u32 normal_params_size{};
  175. u32 num_handles_to_copy{};
  176. u32 num_objects_to_move{}; ///< Domain objects or move handles, context dependent
  177. std::ptrdiff_t datapayload_index{};
  178. };
  179. /// Push ///
  180. template <>
  181. inline void ResponseBuilder::Push(u32 value) {
  182. cmdbuf[index++] = value;
  183. }
  184. template <typename T>
  185. void ResponseBuilder::PushRaw(const T& value) {
  186. std::memcpy(cmdbuf + index, &value, sizeof(T));
  187. index += (sizeof(T) + 3) / 4; // round up to word length
  188. }
  189. template <>
  190. inline void ResponseBuilder::Push(ResultCode value) {
  191. // Result codes are actually 64-bit in the IPC buffer, but only the high part is discarded.
  192. Push(value.raw);
  193. Push<u32>(0);
  194. }
  195. template <>
  196. inline void ResponseBuilder::Push(u8 value) {
  197. PushRaw(value);
  198. }
  199. template <>
  200. inline void ResponseBuilder::Push(u16 value) {
  201. PushRaw(value);
  202. }
  203. template <>
  204. inline void ResponseBuilder::Push(u64 value) {
  205. Push(static_cast<u32>(value));
  206. Push(static_cast<u32>(value >> 32));
  207. }
  208. template <>
  209. inline void ResponseBuilder::Push(bool value) {
  210. Push(static_cast<u8>(value));
  211. }
  212. template <typename First, typename... Other>
  213. void ResponseBuilder::Push(const First& first_value, const Other&... other_values) {
  214. Push(first_value);
  215. Push(other_values...);
  216. }
  217. template <typename... O>
  218. inline void ResponseBuilder::PushCopyObjects(Kernel::SharedPtr<O>... pointers) {
  219. auto objects = {pointers...};
  220. for (auto& object : objects) {
  221. context->AddCopyObject(std::move(object));
  222. }
  223. }
  224. template <typename... O>
  225. inline void ResponseBuilder::PushMoveObjects(Kernel::SharedPtr<O>... pointers) {
  226. auto objects = {pointers...};
  227. for (auto& object : objects) {
  228. context->AddMoveObject(std::move(object));
  229. }
  230. }
  231. class RequestParser : public RequestHelperBase {
  232. public:
  233. explicit RequestParser(u32* command_buffer) : RequestHelperBase(command_buffer) {}
  234. explicit RequestParser(Kernel::HLERequestContext& context) : RequestHelperBase(context) {
  235. ASSERT_MSG(context.GetDataPayloadOffset(), "context is incomplete");
  236. Skip(context.GetDataPayloadOffset(), false);
  237. // Skip the u64 command id, it's already stored in the context
  238. static constexpr u32 CommandIdSize = 2;
  239. Skip(CommandIdSize, false);
  240. }
  241. template <typename T>
  242. T Pop();
  243. template <typename T>
  244. void Pop(T& value);
  245. template <typename First, typename... Other>
  246. void Pop(First& first_value, Other&... other_values);
  247. template <typename T>
  248. T PopEnum() {
  249. static_assert(std::is_enum_v<T>, "T must be an enum type within a PopEnum call.");
  250. static_assert(!std::is_convertible_v<T, int>,
  251. "enum type in PopEnum must be a strongly typed enum.");
  252. return static_cast<T>(Pop<std::underlying_type_t<T>>());
  253. }
  254. /**
  255. * @brief Reads the next normal parameters as a struct, by copying it
  256. * @note: The output class must be correctly packed/padded to fit hardware layout.
  257. */
  258. template <typename T>
  259. void PopRaw(T& value);
  260. /**
  261. * @brief Reads the next normal parameters as a struct, by copying it into a new value
  262. * @note: The output class must be correctly packed/padded to fit hardware layout.
  263. */
  264. template <typename T>
  265. T PopRaw();
  266. template <typename T>
  267. Kernel::SharedPtr<T> GetMoveObject(std::size_t index);
  268. template <typename T>
  269. Kernel::SharedPtr<T> GetCopyObject(std::size_t index);
  270. template <class T>
  271. std::shared_ptr<T> PopIpcInterface() {
  272. ASSERT(context->Session()->IsDomain());
  273. ASSERT(context->GetDomainMessageHeader()->input_object_count > 0);
  274. return context->GetDomainRequestHandler<T>(Pop<u32>() - 1);
  275. }
  276. };
  277. /// Pop ///
  278. template <>
  279. inline u32 RequestParser::Pop() {
  280. return cmdbuf[index++];
  281. }
  282. template <typename T>
  283. void RequestParser::PopRaw(T& value) {
  284. std::memcpy(&value, cmdbuf + index, sizeof(T));
  285. index += (sizeof(T) + 3) / 4; // round up to word length
  286. }
  287. template <typename T>
  288. T RequestParser::PopRaw() {
  289. T value;
  290. PopRaw(value);
  291. return value;
  292. }
  293. template <>
  294. inline u8 RequestParser::Pop() {
  295. return PopRaw<u8>();
  296. }
  297. template <>
  298. inline u16 RequestParser::Pop() {
  299. return PopRaw<u16>();
  300. }
  301. template <>
  302. inline u64 RequestParser::Pop() {
  303. const u64 lsw = Pop<u32>();
  304. const u64 msw = Pop<u32>();
  305. return msw << 32 | lsw;
  306. }
  307. template <>
  308. inline s64 RequestParser::Pop() {
  309. return static_cast<s64>(Pop<u64>());
  310. }
  311. template <>
  312. inline bool RequestParser::Pop() {
  313. return Pop<u8>() != 0;
  314. }
  315. template <>
  316. inline ResultCode RequestParser::Pop() {
  317. return ResultCode{Pop<u32>()};
  318. }
  319. template <typename T>
  320. void RequestParser::Pop(T& value) {
  321. value = Pop<T>();
  322. }
  323. template <typename First, typename... Other>
  324. void RequestParser::Pop(First& first_value, Other&... other_values) {
  325. first_value = Pop<First>();
  326. Pop(other_values...);
  327. }
  328. template <typename T>
  329. Kernel::SharedPtr<T> RequestParser::GetMoveObject(std::size_t index) {
  330. return context->GetMoveObject<T>(index);
  331. }
  332. template <typename T>
  333. Kernel::SharedPtr<T> RequestParser::GetCopyObject(std::size_t index) {
  334. return context->GetCopyObject<T>(index);
  335. }
  336. } // namespace IPC