ipc_helpers.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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_session.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(s32 value) {
  182. cmdbuf[index++] = static_cast<u32>(value);
  183. }
  184. template <>
  185. inline void ResponseBuilder::Push(u32 value) {
  186. cmdbuf[index++] = value;
  187. }
  188. template <typename T>
  189. void ResponseBuilder::PushRaw(const T& value) {
  190. std::memcpy(cmdbuf + index, &value, sizeof(T));
  191. index += (sizeof(T) + 3) / 4; // round up to word length
  192. }
  193. template <>
  194. inline void ResponseBuilder::Push(ResultCode value) {
  195. // Result codes are actually 64-bit in the IPC buffer, but only the high part is discarded.
  196. Push(value.raw);
  197. Push<u32>(0);
  198. }
  199. template <>
  200. inline void ResponseBuilder::Push(s8 value) {
  201. PushRaw(value);
  202. }
  203. template <>
  204. inline void ResponseBuilder::Push(s16 value) {
  205. PushRaw(value);
  206. }
  207. template <>
  208. inline void ResponseBuilder::Push(s64 value) {
  209. Push(static_cast<u32>(value));
  210. Push(static_cast<u32>(value >> 32));
  211. }
  212. template <>
  213. inline void ResponseBuilder::Push(u8 value) {
  214. PushRaw(value);
  215. }
  216. template <>
  217. inline void ResponseBuilder::Push(u16 value) {
  218. PushRaw(value);
  219. }
  220. template <>
  221. inline void ResponseBuilder::Push(u64 value) {
  222. Push(static_cast<u32>(value));
  223. Push(static_cast<u32>(value >> 32));
  224. }
  225. template <>
  226. inline void ResponseBuilder::Push(bool value) {
  227. Push(static_cast<u8>(value));
  228. }
  229. template <typename First, typename... Other>
  230. void ResponseBuilder::Push(const First& first_value, const Other&... other_values) {
  231. Push(first_value);
  232. Push(other_values...);
  233. }
  234. template <typename... O>
  235. inline void ResponseBuilder::PushCopyObjects(Kernel::SharedPtr<O>... pointers) {
  236. auto objects = {pointers...};
  237. for (auto& object : objects) {
  238. context->AddCopyObject(std::move(object));
  239. }
  240. }
  241. template <typename... O>
  242. inline void ResponseBuilder::PushMoveObjects(Kernel::SharedPtr<O>... pointers) {
  243. auto objects = {pointers...};
  244. for (auto& object : objects) {
  245. context->AddMoveObject(std::move(object));
  246. }
  247. }
  248. class RequestParser : public RequestHelperBase {
  249. public:
  250. explicit RequestParser(u32* command_buffer) : RequestHelperBase(command_buffer) {}
  251. explicit RequestParser(Kernel::HLERequestContext& context) : RequestHelperBase(context) {
  252. ASSERT_MSG(context.GetDataPayloadOffset(), "context is incomplete");
  253. Skip(context.GetDataPayloadOffset(), false);
  254. // Skip the u64 command id, it's already stored in the context
  255. static constexpr u32 CommandIdSize = 2;
  256. Skip(CommandIdSize, false);
  257. }
  258. template <typename T>
  259. T Pop();
  260. template <typename T>
  261. void Pop(T& value);
  262. template <typename First, typename... Other>
  263. void Pop(First& first_value, Other&... other_values);
  264. template <typename T>
  265. T PopEnum() {
  266. static_assert(std::is_enum_v<T>, "T must be an enum type within a PopEnum call.");
  267. static_assert(!std::is_convertible_v<T, int>,
  268. "enum type in PopEnum must be a strongly typed enum.");
  269. return static_cast<T>(Pop<std::underlying_type_t<T>>());
  270. }
  271. /**
  272. * @brief Reads the next normal parameters as a struct, by copying it
  273. * @note: The output class must be correctly packed/padded to fit hardware layout.
  274. */
  275. template <typename T>
  276. void PopRaw(T& value);
  277. /**
  278. * @brief Reads the next normal parameters as a struct, by copying it into a new value
  279. * @note: The output class must be correctly packed/padded to fit hardware layout.
  280. */
  281. template <typename T>
  282. T PopRaw();
  283. template <typename T>
  284. Kernel::SharedPtr<T> GetMoveObject(std::size_t index);
  285. template <typename T>
  286. Kernel::SharedPtr<T> GetCopyObject(std::size_t index);
  287. template <class T>
  288. std::shared_ptr<T> PopIpcInterface() {
  289. ASSERT(context->Session()->IsDomain());
  290. ASSERT(context->GetDomainMessageHeader().input_object_count > 0);
  291. return context->GetDomainRequestHandler<T>(Pop<u32>() - 1);
  292. }
  293. };
  294. /// Pop ///
  295. template <>
  296. inline u32 RequestParser::Pop() {
  297. return cmdbuf[index++];
  298. }
  299. template <typename T>
  300. void RequestParser::PopRaw(T& value) {
  301. std::memcpy(&value, cmdbuf + index, sizeof(T));
  302. index += (sizeof(T) + 3) / 4; // round up to word length
  303. }
  304. template <typename T>
  305. T RequestParser::PopRaw() {
  306. T value;
  307. PopRaw(value);
  308. return value;
  309. }
  310. template <>
  311. inline u8 RequestParser::Pop() {
  312. return PopRaw<u8>();
  313. }
  314. template <>
  315. inline u16 RequestParser::Pop() {
  316. return PopRaw<u16>();
  317. }
  318. template <>
  319. inline u64 RequestParser::Pop() {
  320. const u64 lsw = Pop<u32>();
  321. const u64 msw = Pop<u32>();
  322. return msw << 32 | lsw;
  323. }
  324. template <>
  325. inline s64 RequestParser::Pop() {
  326. return static_cast<s64>(Pop<u64>());
  327. }
  328. template <>
  329. inline bool RequestParser::Pop() {
  330. return Pop<u8>() != 0;
  331. }
  332. template <>
  333. inline ResultCode RequestParser::Pop() {
  334. return ResultCode{Pop<u32>()};
  335. }
  336. template <typename T>
  337. void RequestParser::Pop(T& value) {
  338. value = Pop<T>();
  339. }
  340. template <typename First, typename... Other>
  341. void RequestParser::Pop(First& first_value, Other&... other_values) {
  342. first_value = Pop<First>();
  343. Pop(other_values...);
  344. }
  345. template <typename T>
  346. Kernel::SharedPtr<T> RequestParser::GetMoveObject(std::size_t index) {
  347. return context->GetMoveObject<T>(index);
  348. }
  349. template <typename T>
  350. Kernel::SharedPtr<T> RequestParser::GetCopyObject(std::size_t index) {
  351. return context->GetCopyObject<T>(index);
  352. }
  353. } // namespace IPC