ipc_helpers.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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/k_process.h"
  12. #include "core/hle/kernel/k_resource_limit.h"
  13. #include "core/hle/kernel/k_session.h"
  14. #include "core/hle/result.h"
  15. #include "core/hle/service/hle_ipc.h"
  16. #include "core/hle/service/server_manager.h"
  17. namespace IPC {
  18. constexpr Result ERR_REMOTE_PROCESS_DEAD{ErrorModule::HIPC, 301};
  19. class RequestHelperBase {
  20. protected:
  21. Service::HLERequestContext* context = nullptr;
  22. u32* cmdbuf;
  23. u32 index = 0;
  24. public:
  25. explicit RequestHelperBase(u32* command_buffer) : cmdbuf(command_buffer) {}
  26. explicit RequestHelperBase(Service::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(Service::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.GetManager()->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.GetManager()->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.GetManager()->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. auto manager{context->GetManager()};
  122. if (manager->IsDomain()) {
  123. context->AddDomainObject(std::move(iface));
  124. } else {
  125. kernel.ApplicationProcess()->GetResourceLimit()->Reserve(
  126. Kernel::LimitableResource::SessionCountMax, 1);
  127. auto* session = Kernel::KSession::Create(kernel);
  128. session->Initialize(nullptr, iface->GetServiceName());
  129. auto next_manager = std::make_shared<Service::SessionRequestManager>(
  130. kernel, manager->GetServerManager());
  131. next_manager->SetSessionHandler(iface);
  132. manager->GetServerManager().RegisterSession(&session->GetServerSession(), next_manager);
  133. context->AddMoveObject(&session->GetClientSession());
  134. }
  135. }
  136. template <class T, class... Args>
  137. void PushIpcInterface(Args&&... args) {
  138. PushIpcInterface<T>(std::make_shared<T>(std::forward<Args>(args)...));
  139. }
  140. void PushImpl(s8 value);
  141. void PushImpl(s16 value);
  142. void PushImpl(s32 value);
  143. void PushImpl(s64 value);
  144. void PushImpl(u8 value);
  145. void PushImpl(u16 value);
  146. void PushImpl(u32 value);
  147. void PushImpl(u64 value);
  148. void PushImpl(float value);
  149. void PushImpl(double value);
  150. void PushImpl(bool value);
  151. void PushImpl(Result value);
  152. template <typename T>
  153. void Push(T value) {
  154. return PushImpl(value);
  155. }
  156. template <typename First, typename... Other>
  157. void Push(const First& first_value, const Other&... other_values);
  158. /**
  159. * Helper function for pushing strongly-typed enumeration values.
  160. *
  161. * @tparam Enum The enumeration type to be pushed
  162. *
  163. * @param value The value to push.
  164. *
  165. * @note The underlying size of the enumeration type is the size of the
  166. * data that gets pushed. e.g. "enum class SomeEnum : u16" will
  167. * push a u16-sized amount of data.
  168. */
  169. template <typename Enum>
  170. void PushEnum(Enum value) {
  171. static_assert(std::is_enum_v<Enum>, "T must be an enum type within a PushEnum call.");
  172. static_assert(!std::is_convertible_v<Enum, int>,
  173. "enum type in PushEnum must be a strongly typed enum.");
  174. Push(static_cast<std::underlying_type_t<Enum>>(value));
  175. }
  176. /**
  177. * @brief Copies the content of the given trivially copyable class to the buffer as a normal
  178. * param
  179. * @note: The input class must be correctly packed/padded to fit hardware layout.
  180. */
  181. template <typename T>
  182. void PushRaw(const T& value);
  183. template <typename... O>
  184. void PushMoveObjects(O*... pointers);
  185. template <typename... O>
  186. void PushMoveObjects(O&... pointers);
  187. template <typename... O>
  188. void PushCopyObjects(O*... pointers);
  189. template <typename... O>
  190. void PushCopyObjects(O&... pointers);
  191. private:
  192. u32 normal_params_size{};
  193. u32 num_handles_to_copy{};
  194. u32 num_objects_to_move{}; ///< Domain objects or move handles, context dependent
  195. u32 data_payload_index{};
  196. Kernel::KernelCore& kernel;
  197. };
  198. /// Push ///
  199. inline void ResponseBuilder::PushImpl(s32 value) {
  200. cmdbuf[index++] = value;
  201. }
  202. inline void ResponseBuilder::PushImpl(u32 value) {
  203. cmdbuf[index++] = value;
  204. }
  205. template <typename T>
  206. void ResponseBuilder::PushRaw(const T& value) {
  207. static_assert(std::is_trivially_copyable_v<T>,
  208. "It's undefined behavior to use memcpy with non-trivially copyable objects");
  209. std::memcpy(cmdbuf + index, &value, sizeof(T));
  210. index += (sizeof(T) + 3) / 4; // round up to word length
  211. }
  212. inline void ResponseBuilder::PushImpl(Result value) {
  213. // Result codes are actually 64-bit in the IPC buffer, but only the high part is discarded.
  214. Push(value.raw);
  215. Push<u32>(0);
  216. }
  217. inline void ResponseBuilder::PushImpl(s8 value) {
  218. PushRaw(value);
  219. }
  220. inline void ResponseBuilder::PushImpl(s16 value) {
  221. PushRaw(value);
  222. }
  223. inline void ResponseBuilder::PushImpl(s64 value) {
  224. PushImpl(static_cast<u32>(value));
  225. PushImpl(static_cast<u32>(value >> 32));
  226. }
  227. inline void ResponseBuilder::PushImpl(u8 value) {
  228. PushRaw(value);
  229. }
  230. inline void ResponseBuilder::PushImpl(u16 value) {
  231. PushRaw(value);
  232. }
  233. inline void ResponseBuilder::PushImpl(u64 value) {
  234. PushImpl(static_cast<u32>(value));
  235. PushImpl(static_cast<u32>(value >> 32));
  236. }
  237. inline void ResponseBuilder::PushImpl(float value) {
  238. u32 integral;
  239. std::memcpy(&integral, &value, sizeof(u32));
  240. PushImpl(integral);
  241. }
  242. inline void ResponseBuilder::PushImpl(double value) {
  243. u64 integral;
  244. std::memcpy(&integral, &value, sizeof(u64));
  245. PushImpl(integral);
  246. }
  247. inline void ResponseBuilder::PushImpl(bool value) {
  248. PushImpl(static_cast<u8>(value));
  249. }
  250. template <typename First, typename... Other>
  251. void ResponseBuilder::Push(const First& first_value, const Other&... other_values) {
  252. Push(first_value);
  253. Push(other_values...);
  254. }
  255. template <typename... O>
  256. inline void ResponseBuilder::PushCopyObjects(O*... pointers) {
  257. auto objects = {pointers...};
  258. for (auto& object : objects) {
  259. context->AddCopyObject(object);
  260. }
  261. }
  262. template <typename... O>
  263. inline void ResponseBuilder::PushCopyObjects(O&... pointers) {
  264. auto objects = {&pointers...};
  265. for (auto& object : objects) {
  266. context->AddCopyObject(object);
  267. }
  268. }
  269. template <typename... O>
  270. inline void ResponseBuilder::PushMoveObjects(O*... pointers) {
  271. auto objects = {pointers...};
  272. for (auto& object : objects) {
  273. context->AddMoveObject(object);
  274. }
  275. }
  276. template <typename... O>
  277. inline void ResponseBuilder::PushMoveObjects(O&... pointers) {
  278. auto objects = {&pointers...};
  279. for (auto& object : objects) {
  280. context->AddMoveObject(object);
  281. }
  282. }
  283. class RequestParser : public RequestHelperBase {
  284. public:
  285. explicit RequestParser(u32* command_buffer) : RequestHelperBase(command_buffer) {}
  286. explicit RequestParser(Service::HLERequestContext& ctx) : RequestHelperBase(ctx) {
  287. // TIPC does not have data payload offset
  288. if (!ctx.IsTipc()) {
  289. ASSERT_MSG(ctx.GetDataPayloadOffset(), "context is incomplete");
  290. Skip(ctx.GetDataPayloadOffset(), false);
  291. }
  292. // Skip the u64 command id, it's already stored in the context
  293. static constexpr u32 CommandIdSize = 2;
  294. Skip(CommandIdSize, false);
  295. }
  296. template <typename T>
  297. T Pop();
  298. template <typename T>
  299. void Pop(T& value);
  300. template <typename First, typename... Other>
  301. void Pop(First& first_value, Other&... other_values);
  302. template <typename T>
  303. T PopEnum() {
  304. static_assert(std::is_enum_v<T>, "T must be an enum type within a PopEnum call.");
  305. static_assert(!std::is_convertible_v<T, int>,
  306. "enum type in PopEnum must be a strongly typed enum.");
  307. return static_cast<T>(Pop<std::underlying_type_t<T>>());
  308. }
  309. /**
  310. * @brief Reads the next normal parameters as a struct, by copying it
  311. * @note: The output class must be correctly packed/padded to fit hardware layout.
  312. */
  313. template <typename T>
  314. void PopRaw(T& value);
  315. /**
  316. * @brief Reads the next normal parameters as a struct, by copying it into a new value
  317. * @note: The output class must be correctly packed/padded to fit hardware layout.
  318. */
  319. template <typename T>
  320. T PopRaw();
  321. template <class T>
  322. std::weak_ptr<T> PopIpcInterface() {
  323. ASSERT(context->GetManager()->IsDomain());
  324. ASSERT(context->GetDomainMessageHeader().input_object_count > 0);
  325. return context->GetDomainHandler<T>(Pop<u32>() - 1);
  326. }
  327. };
  328. /// Pop ///
  329. template <>
  330. inline u32 RequestParser::Pop() {
  331. return cmdbuf[index++];
  332. }
  333. template <>
  334. inline s32 RequestParser::Pop() {
  335. return static_cast<s32>(Pop<u32>());
  336. }
  337. // Ignore the -Wclass-memaccess warning on memcpy for non-trivially default constructible objects.
  338. #if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
  339. #pragma GCC diagnostic push
  340. #pragma GCC diagnostic ignored "-Wclass-memaccess"
  341. #endif
  342. template <typename T>
  343. void RequestParser::PopRaw(T& value) {
  344. static_assert(std::is_trivially_copyable_v<T>,
  345. "It's undefined behavior to use memcpy with non-trivially copyable objects");
  346. std::memcpy(&value, cmdbuf + index, sizeof(T));
  347. index += (sizeof(T) + 3) / 4; // round up to word length
  348. }
  349. #if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
  350. #pragma GCC diagnostic pop
  351. #endif
  352. template <typename T>
  353. T RequestParser::PopRaw() {
  354. T value;
  355. PopRaw(value);
  356. return value;
  357. }
  358. template <>
  359. inline u8 RequestParser::Pop() {
  360. return PopRaw<u8>();
  361. }
  362. template <>
  363. inline u16 RequestParser::Pop() {
  364. return PopRaw<u16>();
  365. }
  366. template <>
  367. inline u64 RequestParser::Pop() {
  368. const u64 lsw = Pop<u32>();
  369. const u64 msw = Pop<u32>();
  370. return msw << 32 | lsw;
  371. }
  372. template <>
  373. inline s8 RequestParser::Pop() {
  374. return static_cast<s8>(Pop<u8>());
  375. }
  376. template <>
  377. inline s16 RequestParser::Pop() {
  378. return static_cast<s16>(Pop<u16>());
  379. }
  380. template <>
  381. inline s64 RequestParser::Pop() {
  382. return static_cast<s64>(Pop<u64>());
  383. }
  384. template <>
  385. inline float RequestParser::Pop() {
  386. const u32 value = Pop<u32>();
  387. float real;
  388. std::memcpy(&real, &value, sizeof(real));
  389. return real;
  390. }
  391. template <>
  392. inline double RequestParser::Pop() {
  393. const u64 value = Pop<u64>();
  394. double real;
  395. std::memcpy(&real, &value, sizeof(real));
  396. return real;
  397. }
  398. template <>
  399. inline bool RequestParser::Pop() {
  400. return Pop<u8>() != 0;
  401. }
  402. template <>
  403. inline Result RequestParser::Pop() {
  404. return Result{Pop<u32>()};
  405. }
  406. template <typename T>
  407. void RequestParser::Pop(T& value) {
  408. value = Pop<T>();
  409. }
  410. template <typename First, typename... Other>
  411. void RequestParser::Pop(First& first_value, Other&... other_values) {
  412. first_value = Pop<First>();
  413. Pop(other_values...);
  414. }
  415. } // namespace IPC