ipc_helpers.h 14 KB

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