ipc_helpers.h 15 KB

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