ipc_helpers.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. // SPDX-FileCopyrightText: 2016 Citra Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include <cstring>
  5. #include <memory>
  6. #include <type_traits>
  7. #include <utility>
  8. #include "common/assert.h"
  9. #include "common/common_types.h"
  10. #include "core/hle/ipc.h"
  11. #include "core/hle/kernel/hle_ipc.h"
  12. #include "core/hle/kernel/k_process.h"
  13. #include "core/hle/kernel/k_resource_limit.h"
  14. #include "core/hle/kernel/k_session.h"
  15. #include "core/hle/result.h"
  16. namespace IPC {
  17. constexpr Result ERR_REMOTE_PROCESS_DEAD{ErrorModule::HIPC, 301};
  18. class RequestHelperBase {
  19. protected:
  20. Kernel::HLERequestContext* context = nullptr;
  21. u32* cmdbuf;
  22. u32 index = 0;
  23. public:
  24. explicit RequestHelperBase(u32* command_buffer) : cmdbuf(command_buffer) {}
  25. explicit RequestHelperBase(Kernel::HLERequestContext& ctx)
  26. : context(&ctx), cmdbuf(ctx.CommandBuffer()) {}
  27. void Skip(u32 size_in_words, bool set_to_null) {
  28. if (set_to_null) {
  29. memset(cmdbuf + index, 0, size_in_words * sizeof(u32));
  30. }
  31. index += size_in_words;
  32. }
  33. /**
  34. * Aligns the current position forward to a 16-byte boundary, padding with zeros.
  35. */
  36. void AlignWithPadding() {
  37. if (index & 3) {
  38. Skip(static_cast<u32>(4 - (index & 3)), true);
  39. }
  40. }
  41. u32 GetCurrentOffset() const {
  42. return index;
  43. }
  44. void SetCurrentOffset(u32 offset) {
  45. index = offset;
  46. }
  47. };
  48. class ResponseBuilder : public RequestHelperBase {
  49. public:
  50. /// Flags used for customizing the behavior of ResponseBuilder
  51. enum class Flags : u32 {
  52. None = 0,
  53. /// Uses move handles to move objects in the response, even when in a domain. This is
  54. /// required when PushMoveObjects is used.
  55. AlwaysMoveHandles = 1,
  56. };
  57. explicit ResponseBuilder(Kernel::HLERequestContext& ctx, u32 normal_params_size_,
  58. u32 num_handles_to_copy_ = 0, u32 num_objects_to_move_ = 0,
  59. Flags flags = Flags::None)
  60. : RequestHelperBase(ctx), normal_params_size(normal_params_size_),
  61. num_handles_to_copy(num_handles_to_copy_),
  62. num_objects_to_move(num_objects_to_move_), kernel{ctx.kernel} {
  63. memset(cmdbuf, 0, sizeof(u32) * IPC::COMMAND_BUFFER_LENGTH);
  64. IPC::CommandHeader header{};
  65. // The entire size of the raw data section in u32 units, including the 16 bytes of mandatory
  66. // padding.
  67. u32 raw_data_size = ctx.write_size =
  68. ctx.IsTipc() ? normal_params_size - 1 : normal_params_size;
  69. u32 num_handles_to_move{};
  70. u32 num_domain_objects{};
  71. const bool always_move_handles{
  72. (static_cast<u32>(flags) & static_cast<u32>(Flags::AlwaysMoveHandles)) != 0};
  73. if (!ctx.Session()->IsDomain() || always_move_handles) {
  74. num_handles_to_move = num_objects_to_move;
  75. } else {
  76. num_domain_objects = num_objects_to_move;
  77. }
  78. if (ctx.Session()->IsDomain()) {
  79. raw_data_size +=
  80. static_cast<u32>(sizeof(DomainMessageHeader) / sizeof(u32) + num_domain_objects);
  81. ctx.write_size += num_domain_objects;
  82. }
  83. if (ctx.IsTipc()) {
  84. header.type.Assign(ctx.GetCommandType());
  85. } else {
  86. raw_data_size += static_cast<u32>(sizeof(IPC::DataPayloadHeader) / sizeof(u32) + 4 +
  87. normal_params_size);
  88. }
  89. header.data_size.Assign(raw_data_size);
  90. if (num_handles_to_copy || num_handles_to_move) {
  91. header.enable_handle_descriptor.Assign(1);
  92. }
  93. PushRaw(header);
  94. if (header.enable_handle_descriptor) {
  95. IPC::HandleDescriptorHeader handle_descriptor_header{};
  96. handle_descriptor_header.num_handles_to_copy.Assign(num_handles_to_copy_);
  97. handle_descriptor_header.num_handles_to_move.Assign(num_handles_to_move);
  98. PushRaw(handle_descriptor_header);
  99. ctx.handles_offset = index;
  100. Skip(num_handles_to_copy + num_handles_to_move, true);
  101. }
  102. if (!ctx.IsTipc()) {
  103. AlignWithPadding();
  104. if (ctx.Session()->IsDomain() && ctx.HasDomainMessageHeader()) {
  105. IPC::DomainMessageHeader domain_header{};
  106. domain_header.num_objects = num_domain_objects;
  107. PushRaw(domain_header);
  108. }
  109. IPC::DataPayloadHeader data_payload_header{};
  110. data_payload_header.magic = Common::MakeMagic('S', 'F', 'C', 'O');
  111. PushRaw(data_payload_header);
  112. }
  113. data_payload_index = index;
  114. ctx.data_payload_offset = index;
  115. ctx.write_size += index;
  116. ctx.domain_offset = static_cast<u32>(index + raw_data_size / sizeof(u32));
  117. }
  118. template <class T>
  119. void PushIpcInterface(std::shared_ptr<T> iface) {
  120. if (context->Session()->IsDomain()) {
  121. context->AddDomainObject(std::move(iface));
  122. } else {
  123. kernel.CurrentProcess()->GetResourceLimit()->Reserve(
  124. Kernel::LimitableResource::Sessions, 1);
  125. auto* session = Kernel::KSession::Create(kernel);
  126. session->Initialize(nullptr, iface->GetServiceName());
  127. context->AddMoveObject(&session->GetClientSession());
  128. iface->ClientConnected(&session->GetServerSession());
  129. }
  130. }
  131. template <class T, class... Args>
  132. void PushIpcInterface(Args&&... args) {
  133. PushIpcInterface<T>(std::make_shared<T>(std::forward<Args>(args)...));
  134. }
  135. void PushImpl(s8 value);
  136. void PushImpl(s16 value);
  137. void PushImpl(s32 value);
  138. void PushImpl(s64 value);
  139. void PushImpl(u8 value);
  140. void PushImpl(u16 value);
  141. void PushImpl(u32 value);
  142. void PushImpl(u64 value);
  143. void PushImpl(float value);
  144. void PushImpl(double value);
  145. void PushImpl(bool value);
  146. void PushImpl(Result value);
  147. template <typename T>
  148. void Push(T value) {
  149. return PushImpl(value);
  150. }
  151. template <typename First, typename... Other>
  152. void Push(const First& first_value, const Other&... other_values);
  153. /**
  154. * Helper function for pushing strongly-typed enumeration values.
  155. *
  156. * @tparam Enum The enumeration type to be pushed
  157. *
  158. * @param value The value to push.
  159. *
  160. * @note The underlying size of the enumeration type is the size of the
  161. * data that gets pushed. e.g. "enum class SomeEnum : u16" will
  162. * push a u16-sized amount of data.
  163. */
  164. template <typename Enum>
  165. void PushEnum(Enum value) {
  166. static_assert(std::is_enum_v<Enum>, "T must be an enum type within a PushEnum call.");
  167. static_assert(!std::is_convertible_v<Enum, int>,
  168. "enum type in PushEnum must be a strongly typed enum.");
  169. Push(static_cast<std::underlying_type_t<Enum>>(value));
  170. }
  171. /**
  172. * @brief Copies the content of the given trivially copyable class to the buffer as a normal
  173. * param
  174. * @note: The input class must be correctly packed/padded to fit hardware layout.
  175. */
  176. template <typename T>
  177. void PushRaw(const T& value);
  178. template <typename... O>
  179. void PushMoveObjects(O*... pointers);
  180. template <typename... O>
  181. void PushMoveObjects(O&... pointers);
  182. template <typename... O>
  183. void PushCopyObjects(O*... pointers);
  184. template <typename... O>
  185. void PushCopyObjects(O&... pointers);
  186. private:
  187. u32 normal_params_size{};
  188. u32 num_handles_to_copy{};
  189. u32 num_objects_to_move{}; ///< Domain objects or move handles, context dependent
  190. u32 data_payload_index{};
  191. Kernel::KernelCore& kernel;
  192. };
  193. /// Push ///
  194. inline void ResponseBuilder::PushImpl(s32 value) {
  195. cmdbuf[index++] = value;
  196. }
  197. inline void ResponseBuilder::PushImpl(u32 value) {
  198. cmdbuf[index++] = value;
  199. }
  200. template <typename T>
  201. void ResponseBuilder::PushRaw(const T& value) {
  202. static_assert(std::is_trivially_copyable_v<T>,
  203. "It's undefined behavior to use memcpy with non-trivially copyable objects");
  204. std::memcpy(cmdbuf + index, &value, sizeof(T));
  205. index += (sizeof(T) + 3) / 4; // round up to word length
  206. }
  207. inline void ResponseBuilder::PushImpl(Result value) {
  208. // Result codes are actually 64-bit in the IPC buffer, but only the high part is discarded.
  209. Push(value.raw);
  210. Push<u32>(0);
  211. }
  212. inline void ResponseBuilder::PushImpl(s8 value) {
  213. PushRaw(value);
  214. }
  215. inline void ResponseBuilder::PushImpl(s16 value) {
  216. PushRaw(value);
  217. }
  218. inline void ResponseBuilder::PushImpl(s64 value) {
  219. PushImpl(static_cast<u32>(value));
  220. PushImpl(static_cast<u32>(value >> 32));
  221. }
  222. inline void ResponseBuilder::PushImpl(u8 value) {
  223. PushRaw(value);
  224. }
  225. inline void ResponseBuilder::PushImpl(u16 value) {
  226. PushRaw(value);
  227. }
  228. inline void ResponseBuilder::PushImpl(u64 value) {
  229. PushImpl(static_cast<u32>(value));
  230. PushImpl(static_cast<u32>(value >> 32));
  231. }
  232. inline void ResponseBuilder::PushImpl(float value) {
  233. u32 integral;
  234. std::memcpy(&integral, &value, sizeof(u32));
  235. PushImpl(integral);
  236. }
  237. inline void ResponseBuilder::PushImpl(double value) {
  238. u64 integral;
  239. std::memcpy(&integral, &value, sizeof(u64));
  240. PushImpl(integral);
  241. }
  242. inline void ResponseBuilder::PushImpl(bool value) {
  243. PushImpl(static_cast<u8>(value));
  244. }
  245. template <typename First, typename... Other>
  246. void ResponseBuilder::Push(const First& first_value, const Other&... other_values) {
  247. Push(first_value);
  248. Push(other_values...);
  249. }
  250. template <typename... O>
  251. inline void ResponseBuilder::PushCopyObjects(O*... pointers) {
  252. auto objects = {pointers...};
  253. for (auto& object : objects) {
  254. context->AddCopyObject(object);
  255. }
  256. }
  257. template <typename... O>
  258. inline void ResponseBuilder::PushCopyObjects(O&... pointers) {
  259. auto objects = {&pointers...};
  260. for (auto& object : objects) {
  261. context->AddCopyObject(object);
  262. }
  263. }
  264. template <typename... O>
  265. inline void ResponseBuilder::PushMoveObjects(O*... pointers) {
  266. auto objects = {pointers...};
  267. for (auto& object : objects) {
  268. context->AddMoveObject(object);
  269. }
  270. }
  271. template <typename... O>
  272. inline void ResponseBuilder::PushMoveObjects(O&... pointers) {
  273. auto objects = {&pointers...};
  274. for (auto& object : objects) {
  275. context->AddMoveObject(object);
  276. }
  277. }
  278. class RequestParser : public RequestHelperBase {
  279. public:
  280. explicit RequestParser(u32* command_buffer) : RequestHelperBase(command_buffer) {}
  281. explicit RequestParser(Kernel::HLERequestContext& ctx) : RequestHelperBase(ctx) {
  282. // TIPC does not have data payload offset
  283. if (!ctx.IsTipc()) {
  284. ASSERT_MSG(ctx.GetDataPayloadOffset(), "context is incomplete");
  285. Skip(ctx.GetDataPayloadOffset(), false);
  286. }
  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 <class T>
  317. std::weak_ptr<T> PopIpcInterface() {
  318. ASSERT(context->Session()->IsDomain());
  319. ASSERT(context->GetDomainMessageHeader().input_object_count > 0);
  320. return context->GetDomainHandler<T>(Pop<u32>() - 1);
  321. }
  322. };
  323. /// Pop ///
  324. template <>
  325. inline u32 RequestParser::Pop() {
  326. return cmdbuf[index++];
  327. }
  328. template <>
  329. inline s32 RequestParser::Pop() {
  330. return static_cast<s32>(Pop<u32>());
  331. }
  332. // Ignore the -Wclass-memaccess warning on memcpy for non-trivially default constructible objects.
  333. #if defined(__GNUC__)
  334. #pragma GCC diagnostic push
  335. #pragma GCC diagnostic ignored "-Wclass-memaccess"
  336. #endif
  337. template <typename T>
  338. void RequestParser::PopRaw(T& value) {
  339. static_assert(std::is_trivially_copyable_v<T>,
  340. "It's undefined behavior to use memcpy with non-trivially copyable objects");
  341. std::memcpy(&value, cmdbuf + index, sizeof(T));
  342. index += (sizeof(T) + 3) / 4; // round up to word length
  343. }
  344. #if defined(__GNUC__)
  345. #pragma GCC diagnostic pop
  346. #endif
  347. template <typename T>
  348. T RequestParser::PopRaw() {
  349. T value;
  350. PopRaw(value);
  351. return value;
  352. }
  353. template <>
  354. inline u8 RequestParser::Pop() {
  355. return PopRaw<u8>();
  356. }
  357. template <>
  358. inline u16 RequestParser::Pop() {
  359. return PopRaw<u16>();
  360. }
  361. template <>
  362. inline u64 RequestParser::Pop() {
  363. const u64 lsw = Pop<u32>();
  364. const u64 msw = Pop<u32>();
  365. return msw << 32 | lsw;
  366. }
  367. template <>
  368. inline s8 RequestParser::Pop() {
  369. return static_cast<s8>(Pop<u8>());
  370. }
  371. template <>
  372. inline s16 RequestParser::Pop() {
  373. return static_cast<s16>(Pop<u16>());
  374. }
  375. template <>
  376. inline s64 RequestParser::Pop() {
  377. return static_cast<s64>(Pop<u64>());
  378. }
  379. template <>
  380. inline float RequestParser::Pop() {
  381. const u32 value = Pop<u32>();
  382. float real;
  383. std::memcpy(&real, &value, sizeof(real));
  384. return real;
  385. }
  386. template <>
  387. inline double RequestParser::Pop() {
  388. const u64 value = Pop<u64>();
  389. double real;
  390. std::memcpy(&real, &value, sizeof(real));
  391. return real;
  392. }
  393. template <>
  394. inline bool RequestParser::Pop() {
  395. return Pop<u8>() != 0;
  396. }
  397. template <>
  398. inline Result RequestParser::Pop() {
  399. return Result{Pop<u32>()};
  400. }
  401. template <typename T>
  402. void RequestParser::Pop(T& value) {
  403. value = Pop<T>();
  404. }
  405. template <typename First, typename... Other>
  406. void RequestParser::Pop(First& first_value, Other&... other_values) {
  407. first_value = Pop<First>();
  408. Pop(other_values...);
  409. }
  410. } // namespace IPC