ipc_helpers.h 14 KB

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