ipc_helpers.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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/hle/ipc.h"
  14. #include "core/hle/kernel/hle_ipc.h"
  15. #include "core/hle/kernel/k_client_port.h"
  16. #include "core/hle/kernel/k_session.h"
  17. #include "core/hle/kernel/object.h"
  18. #include "core/hle/result.h"
  19. namespace IPC {
  20. constexpr ResultCode ERR_REMOTE_PROCESS_DEAD{ErrorModule::HIPC, 301};
  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(u32 size_in_words, bool set_to_null) {
  31. if (set_to_null) {
  32. memset(cmdbuf + index, 0, size_in_words * sizeof(u32));
  33. }
  34. index += static_cast<ptrdiff_t>(size_in_words);
  35. }
  36. /**
  37. * Aligns the current position forward to a 16-byte boundary, padding with zeros.
  38. */
  39. void AlignWithPadding() {
  40. if (index & 3) {
  41. Skip(static_cast<u32>(4 - (index & 3)), true);
  42. }
  43. }
  44. u32 GetCurrentOffset() const {
  45. return static_cast<u32>(index);
  46. }
  47. void SetCurrentOffset(u32 offset) {
  48. index = static_cast<ptrdiff_t>(offset);
  49. }
  50. };
  51. class ResponseBuilder : public RequestHelperBase {
  52. public:
  53. /// Flags used for customizing the behavior of ResponseBuilder
  54. enum class Flags : u32 {
  55. None = 0,
  56. /// Uses move handles to move objects in the response, even when in a domain. This is
  57. /// required when PushMoveObjects is used.
  58. AlwaysMoveHandles = 1,
  59. };
  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),
  65. num_objects_to_move(num_objects_to_move), kernel{context.kernel} {
  66. memset(cmdbuf, 0, sizeof(u32) * IPC::COMMAND_BUFFER_LENGTH);
  67. context.ClearIncomingObjects();
  68. IPC::CommandHeader header{};
  69. // The entire size of the raw data section in u32 units, including the 16 bytes of mandatory
  70. // padding.
  71. u64 raw_data_size = sizeof(IPC::DataPayloadHeader) / 4 + 4 + normal_params_size;
  72. u32 num_handles_to_move{};
  73. u32 num_domain_objects{};
  74. const bool always_move_handles{
  75. (static_cast<u32>(flags) & static_cast<u32>(Flags::AlwaysMoveHandles)) != 0};
  76. if (!context.Session()->IsDomain() || always_move_handles) {
  77. num_handles_to_move = num_objects_to_move;
  78. } else {
  79. num_domain_objects = num_objects_to_move;
  80. }
  81. if (context.Session()->IsDomain()) {
  82. raw_data_size += sizeof(DomainMessageHeader) / 4 + num_domain_objects;
  83. }
  84. header.data_size.Assign(static_cast<u32>(raw_data_size));
  85. if (num_handles_to_copy || num_handles_to_move) {
  86. header.enable_handle_descriptor.Assign(1);
  87. }
  88. PushRaw(header);
  89. if (header.enable_handle_descriptor) {
  90. IPC::HandleDescriptorHeader handle_descriptor_header{};
  91. handle_descriptor_header.num_handles_to_copy.Assign(num_handles_to_copy);
  92. handle_descriptor_header.num_handles_to_move.Assign(num_handles_to_move);
  93. PushRaw(handle_descriptor_header);
  94. Skip(num_handles_to_copy + num_handles_to_move, true);
  95. }
  96. AlignWithPadding();
  97. if (context.Session()->IsDomain() && context.HasDomainMessageHeader()) {
  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* session = Kernel::KSession::Create(kernel);
  113. session->Initialize(iface->GetServiceName());
  114. context->AddMoveObject(&session->GetClientSession());
  115. iface->ClientConnected(session);
  116. }
  117. }
  118. template <class T, class... Args>
  119. void PushIpcInterface(Args&&... args) {
  120. PushIpcInterface<T>(std::make_shared<T>(std::forward<Args>(args)...));
  121. }
  122. void ValidateHeader() {
  123. const std::size_t num_domain_objects = context->NumDomainObjects();
  124. const std::size_t num_move_objects = context->NumMoveObjects();
  125. ASSERT_MSG(!num_domain_objects || !num_move_objects,
  126. "cannot move normal handles and domain objects");
  127. ASSERT_MSG((index - datapayload_index) == normal_params_size,
  128. "normal_params_size value is incorrect");
  129. ASSERT_MSG((num_domain_objects + num_move_objects) == num_objects_to_move,
  130. "num_objects_to_move value is incorrect");
  131. ASSERT_MSG(context->NumCopyObjects() == num_handles_to_copy,
  132. "num_handles_to_copy value is incorrect");
  133. }
  134. // Validate on destruction, as there shouldn't be any case where we don't want it
  135. ~ResponseBuilder() {
  136. ValidateHeader();
  137. }
  138. void PushImpl(s8 value);
  139. void PushImpl(s16 value);
  140. void PushImpl(s32 value);
  141. void PushImpl(s64 value);
  142. void PushImpl(u8 value);
  143. void PushImpl(u16 value);
  144. void PushImpl(u32 value);
  145. void PushImpl(u64 value);
  146. void PushImpl(float value);
  147. void PushImpl(double value);
  148. void PushImpl(bool value);
  149. void PushImpl(ResultCode value);
  150. template <typename T>
  151. void Push(T value) {
  152. return PushImpl(value);
  153. }
  154. template <typename First, typename... Other>
  155. void Push(const First& first_value, const Other&... other_values);
  156. /**
  157. * Helper function for pushing strongly-typed enumeration values.
  158. *
  159. * @tparam Enum The enumeration type to be pushed
  160. *
  161. * @param value The value to push.
  162. *
  163. * @note The underlying size of the enumeration type is the size of the
  164. * data that gets pushed. e.g. "enum class SomeEnum : u16" will
  165. * push a u16-sized amount of data.
  166. */
  167. template <typename Enum>
  168. void PushEnum(Enum value) {
  169. static_assert(std::is_enum_v<Enum>, "T must be an enum type within a PushEnum call.");
  170. static_assert(!std::is_convertible_v<Enum, int>,
  171. "enum type in PushEnum must be a strongly typed enum.");
  172. Push(static_cast<std::underlying_type_t<Enum>>(value));
  173. }
  174. /**
  175. * @brief Copies the content of the given trivially copyable class to the buffer as a normal
  176. * param
  177. * @note: The input class must be correctly packed/padded to fit hardware layout.
  178. */
  179. template <typename T>
  180. void PushRaw(const T& value);
  181. template <typename... O>
  182. void PushMoveObjects(O*... pointers);
  183. template <typename... O>
  184. void PushMoveObjects(O&... pointers);
  185. template <typename... O>
  186. void PushCopyObjects(O*... pointers);
  187. template <typename... O>
  188. void PushCopyObjects(O&... pointers);
  189. private:
  190. u32 normal_params_size{};
  191. u32 num_handles_to_copy{};
  192. u32 num_objects_to_move{}; ///< Domain objects or move handles, context dependent
  193. std::ptrdiff_t datapayload_index{};
  194. Kernel::KernelCore& kernel;
  195. };
  196. /// Push ///
  197. inline void ResponseBuilder::PushImpl(s32 value) {
  198. cmdbuf[index++] = static_cast<u32>(value);
  199. }
  200. inline void ResponseBuilder::PushImpl(u32 value) {
  201. cmdbuf[index++] = value;
  202. }
  203. template <typename T>
  204. void ResponseBuilder::PushRaw(const T& value) {
  205. static_assert(std::is_trivially_copyable_v<T>,
  206. "It's undefined behavior to use memcpy with non-trivially copyable objects");
  207. std::memcpy(cmdbuf + index, &value, sizeof(T));
  208. index += (sizeof(T) + 3) / 4; // round up to word length
  209. }
  210. inline void ResponseBuilder::PushImpl(ResultCode value) {
  211. // Result codes are actually 64-bit in the IPC buffer, but only the high part is discarded.
  212. Push(value.raw);
  213. Push<u32>(0);
  214. }
  215. inline void ResponseBuilder::PushImpl(s8 value) {
  216. PushRaw(value);
  217. }
  218. inline void ResponseBuilder::PushImpl(s16 value) {
  219. PushRaw(value);
  220. }
  221. inline void ResponseBuilder::PushImpl(s64 value) {
  222. PushImpl(static_cast<u32>(value));
  223. PushImpl(static_cast<u32>(value >> 32));
  224. }
  225. inline void ResponseBuilder::PushImpl(u8 value) {
  226. PushRaw(value);
  227. }
  228. inline void ResponseBuilder::PushImpl(u16 value) {
  229. PushRaw(value);
  230. }
  231. inline void ResponseBuilder::PushImpl(u64 value) {
  232. PushImpl(static_cast<u32>(value));
  233. PushImpl(static_cast<u32>(value >> 32));
  234. }
  235. inline void ResponseBuilder::PushImpl(float value) {
  236. u32 integral;
  237. std::memcpy(&integral, &value, sizeof(u32));
  238. PushImpl(integral);
  239. }
  240. inline void ResponseBuilder::PushImpl(double value) {
  241. u64 integral;
  242. std::memcpy(&integral, &value, sizeof(u64));
  243. PushImpl(integral);
  244. }
  245. inline void ResponseBuilder::PushImpl(bool value) {
  246. PushImpl(static_cast<u8>(value));
  247. }
  248. template <typename First, typename... Other>
  249. void ResponseBuilder::Push(const First& first_value, const Other&... other_values) {
  250. Push(first_value);
  251. Push(other_values...);
  252. }
  253. template <typename... O>
  254. inline void ResponseBuilder::PushCopyObjects(O*... pointers) {
  255. auto objects = {pointers...};
  256. for (auto& object : objects) {
  257. context->AddCopyObject(object);
  258. }
  259. }
  260. template <typename... O>
  261. inline void ResponseBuilder::PushCopyObjects(O&... pointers) {
  262. auto objects = {&pointers...};
  263. for (auto& object : objects) {
  264. context->AddCopyObject(object);
  265. }
  266. }
  267. template <typename... O>
  268. inline void ResponseBuilder::PushMoveObjects(O*... pointers) {
  269. auto objects = {pointers...};
  270. for (auto& object : objects) {
  271. context->AddMoveObject(object);
  272. }
  273. }
  274. template <typename... O>
  275. inline void ResponseBuilder::PushMoveObjects(O&... pointers) {
  276. auto objects = {&pointers...};
  277. for (auto& object : objects) {
  278. context->AddMoveObject(object);
  279. }
  280. }
  281. class RequestParser : public RequestHelperBase {
  282. public:
  283. explicit RequestParser(u32* command_buffer) : RequestHelperBase(command_buffer) {}
  284. explicit RequestParser(Kernel::HLERequestContext& context) : RequestHelperBase(context) {
  285. ASSERT_MSG(context.GetDataPayloadOffset(), "context is incomplete");
  286. Skip(context.GetDataPayloadOffset(), false);
  287. // Skip the u64 command id, it's already stored in the context
  288. static constexpr u32 CommandIdSize = 2;
  289. Skip(CommandIdSize, false);
  290. }
  291. template <typename T>
  292. T Pop();
  293. template <typename T>
  294. void Pop(T& value);
  295. template <typename First, typename... Other>
  296. void Pop(First& first_value, Other&... other_values);
  297. template <typename T>
  298. T PopEnum() {
  299. static_assert(std::is_enum_v<T>, "T must be an enum type within a PopEnum call.");
  300. static_assert(!std::is_convertible_v<T, int>,
  301. "enum type in PopEnum must be a strongly typed enum.");
  302. return static_cast<T>(Pop<std::underlying_type_t<T>>());
  303. }
  304. /**
  305. * @brief Reads the next normal parameters as a struct, by copying it
  306. * @note: The output class must be correctly packed/padded to fit hardware layout.
  307. */
  308. template <typename T>
  309. void PopRaw(T& value);
  310. /**
  311. * @brief Reads the next normal parameters as a struct, by copying it into a new value
  312. * @note: The output class must be correctly packed/padded to fit hardware layout.
  313. */
  314. template <typename T>
  315. T PopRaw();
  316. template <typename T>
  317. T* GetMoveObject(std::size_t index);
  318. template <typename T>
  319. T* GetCopyObject(std::size_t index);
  320. template <class T>
  321. std::shared_ptr<T> PopIpcInterface() {
  322. ASSERT(context->Session()->IsDomain());
  323. ASSERT(context->GetDomainMessageHeader().input_object_count > 0);
  324. return context->GetDomainRequestHandler<T>(Pop<u32>() - 1);
  325. }
  326. };
  327. /// Pop ///
  328. template <>
  329. inline u32 RequestParser::Pop() {
  330. return cmdbuf[index++];
  331. }
  332. template <>
  333. inline s32 RequestParser::Pop() {
  334. return static_cast<s32>(Pop<u32>());
  335. }
  336. template <typename T>
  337. void RequestParser::PopRaw(T& value) {
  338. static_assert(std::is_trivially_copyable_v<T>,
  339. "It's undefined behavior to use memcpy with non-trivially copyable objects");
  340. std::memcpy(&value, cmdbuf + index, sizeof(T));
  341. index += (sizeof(T) + 3) / 4; // round up to word length
  342. }
  343. template <typename T>
  344. T RequestParser::PopRaw() {
  345. T value;
  346. PopRaw(value);
  347. return value;
  348. }
  349. template <>
  350. inline u8 RequestParser::Pop() {
  351. return PopRaw<u8>();
  352. }
  353. template <>
  354. inline u16 RequestParser::Pop() {
  355. return PopRaw<u16>();
  356. }
  357. template <>
  358. inline u64 RequestParser::Pop() {
  359. const u64 lsw = Pop<u32>();
  360. const u64 msw = Pop<u32>();
  361. return msw << 32 | lsw;
  362. }
  363. template <>
  364. inline s8 RequestParser::Pop() {
  365. return static_cast<s8>(Pop<u8>());
  366. }
  367. template <>
  368. inline s16 RequestParser::Pop() {
  369. return static_cast<s16>(Pop<u16>());
  370. }
  371. template <>
  372. inline s64 RequestParser::Pop() {
  373. return static_cast<s64>(Pop<u64>());
  374. }
  375. template <>
  376. inline float RequestParser::Pop() {
  377. const u32 value = Pop<u32>();
  378. float real;
  379. std::memcpy(&real, &value, sizeof(real));
  380. return real;
  381. }
  382. template <>
  383. inline double RequestParser::Pop() {
  384. const u64 value = Pop<u64>();
  385. double real;
  386. std::memcpy(&real, &value, sizeof(real));
  387. return real;
  388. }
  389. template <>
  390. inline bool RequestParser::Pop() {
  391. return Pop<u8>() != 0;
  392. }
  393. template <>
  394. inline ResultCode RequestParser::Pop() {
  395. return ResultCode{Pop<u32>()};
  396. }
  397. template <typename T>
  398. void RequestParser::Pop(T& value) {
  399. value = Pop<T>();
  400. }
  401. template <typename First, typename... Other>
  402. void RequestParser::Pop(First& first_value, Other&... other_values) {
  403. first_value = Pop<First>();
  404. Pop(other_values...);
  405. }
  406. template <typename T>
  407. T* RequestParser::GetMoveObject(std::size_t index) {
  408. return context->GetMoveObject<T>(index);
  409. }
  410. template <typename T>
  411. T* RequestParser::GetCopyObject(std::size_t index) {
  412. return context->GetCopyObject<T>(index);
  413. }
  414. } // namespace IPC