ipc_helpers.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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/client_port.h"
  15. #include "core/hle/kernel/client_session.h"
  16. #include "core/hle/kernel/hle_ipc.h"
  17. #include "core/hle/kernel/object.h"
  18. #include "core/hle/kernel/server_session.h"
  19. #include "core/hle/kernel/session.h"
  20. #include "core/hle/result.h"
  21. namespace IPC {
  22. constexpr ResultCode ERR_REMOTE_PROCESS_DEAD{ErrorModule::HIPC, 301};
  23. class RequestHelperBase {
  24. protected:
  25. Kernel::HLERequestContext* context = nullptr;
  26. u32* cmdbuf;
  27. ptrdiff_t index = 0;
  28. public:
  29. explicit RequestHelperBase(u32* command_buffer) : cmdbuf(command_buffer) {}
  30. explicit RequestHelperBase(Kernel::HLERequestContext& context)
  31. : context(&context), cmdbuf(context.CommandBuffer()) {}
  32. void Skip(u32 size_in_words, bool set_to_null) {
  33. if (set_to_null) {
  34. memset(cmdbuf + index, 0, size_in_words * sizeof(u32));
  35. }
  36. index += static_cast<ptrdiff_t>(size_in_words);
  37. }
  38. /**
  39. * Aligns the current position forward to a 16-byte boundary, padding with zeros.
  40. */
  41. void AlignWithPadding() {
  42. if (index & 3) {
  43. Skip(static_cast<u32>(4 - (index & 3)), true);
  44. }
  45. }
  46. u32 GetCurrentOffset() const {
  47. return static_cast<u32>(index);
  48. }
  49. void SetCurrentOffset(u32 offset) {
  50. index = static_cast<ptrdiff_t>(offset);
  51. }
  52. };
  53. class ResponseBuilder : public RequestHelperBase {
  54. public:
  55. /// Flags used for customizing the behavior of ResponseBuilder
  56. enum class Flags : u32 {
  57. None = 0,
  58. /// Uses move handles to move objects in the response, even when in a domain. This is
  59. /// required when PushMoveObjects is used.
  60. AlwaysMoveHandles = 1,
  61. };
  62. explicit ResponseBuilder(Kernel::HLERequestContext& context, u32 normal_params_size,
  63. u32 num_handles_to_copy = 0, u32 num_objects_to_move = 0,
  64. Flags flags = Flags::None)
  65. : RequestHelperBase(context), normal_params_size(normal_params_size),
  66. num_handles_to_copy(num_handles_to_copy),
  67. num_objects_to_move(num_objects_to_move), kernel{context.kernel} {
  68. memset(cmdbuf, 0, sizeof(u32) * IPC::COMMAND_BUFFER_LENGTH);
  69. context.ClearIncomingObjects();
  70. IPC::CommandHeader header{};
  71. // The entire size of the raw data section in u32 units, including the 16 bytes of mandatory
  72. // padding.
  73. u64 raw_data_size = sizeof(IPC::DataPayloadHeader) / 4 + 4 + normal_params_size;
  74. u32 num_handles_to_move{};
  75. u32 num_domain_objects{};
  76. const bool always_move_handles{
  77. (static_cast<u32>(flags) & static_cast<u32>(Flags::AlwaysMoveHandles)) != 0};
  78. if (!context.Session()->IsDomain() || always_move_handles) {
  79. num_handles_to_move = num_objects_to_move;
  80. } else {
  81. num_domain_objects = num_objects_to_move;
  82. }
  83. if (context.Session()->IsDomain()) {
  84. raw_data_size += sizeof(DomainMessageHeader) / 4 + num_domain_objects;
  85. }
  86. header.data_size.Assign(static_cast<u32>(raw_data_size));
  87. if (num_handles_to_copy || num_handles_to_move) {
  88. header.enable_handle_descriptor.Assign(1);
  89. }
  90. PushRaw(header);
  91. if (header.enable_handle_descriptor) {
  92. IPC::HandleDescriptorHeader handle_descriptor_header{};
  93. handle_descriptor_header.num_handles_to_copy.Assign(num_handles_to_copy);
  94. handle_descriptor_header.num_handles_to_move.Assign(num_handles_to_move);
  95. PushRaw(handle_descriptor_header);
  96. Skip(num_handles_to_copy + num_handles_to_move, true);
  97. }
  98. AlignWithPadding();
  99. if (context.Session()->IsDomain() && context.HasDomainMessageHeader()) {
  100. IPC::DomainMessageHeader domain_header{};
  101. domain_header.num_objects = num_domain_objects;
  102. PushRaw(domain_header);
  103. }
  104. IPC::DataPayloadHeader data_payload_header{};
  105. data_payload_header.magic = Common::MakeMagic('S', 'F', 'C', 'O');
  106. PushRaw(data_payload_header);
  107. datapayload_index = index;
  108. }
  109. template <class T>
  110. void PushIpcInterface(std::shared_ptr<T> iface) {
  111. if (context->Session()->IsDomain()) {
  112. context->AddDomainObject(std::move(iface));
  113. } else {
  114. auto [client, server] = Kernel::Session::Create(kernel, iface->GetServiceName());
  115. context->AddMoveObject(std::move(client));
  116. iface->ClientConnected(std::move(server));
  117. }
  118. }
  119. template <class T, class... Args>
  120. void PushIpcInterface(Args&&... args) {
  121. PushIpcInterface<T>(std::make_shared<T>(std::forward<Args>(args)...));
  122. }
  123. void ValidateHeader() {
  124. const std::size_t num_domain_objects = context->NumDomainObjects();
  125. const std::size_t num_move_objects = context->NumMoveObjects();
  126. ASSERT_MSG(!num_domain_objects || !num_move_objects,
  127. "cannot move normal handles and domain objects");
  128. ASSERT_MSG((index - datapayload_index) == normal_params_size,
  129. "normal_params_size value is incorrect");
  130. ASSERT_MSG((num_domain_objects + num_move_objects) == num_objects_to_move,
  131. "num_objects_to_move value is incorrect");
  132. ASSERT_MSG(context->NumCopyObjects() == num_handles_to_copy,
  133. "num_handles_to_copy value is incorrect");
  134. }
  135. // Validate on destruction, as there shouldn't be any case where we don't want it
  136. ~ResponseBuilder() {
  137. ValidateHeader();
  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(std::shared_ptr<O>... pointers);
  184. template <typename... O>
  185. void PushCopyObjects(std::shared_ptr<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. std::ptrdiff_t datapayload_index{};
  191. Kernel::KernelCore& kernel;
  192. };
  193. /// Push ///
  194. inline void ResponseBuilder::PushImpl(s32 value) {
  195. cmdbuf[index++] = static_cast<u32>(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(ResultCode 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(std::shared_ptr<O>... pointers) {
  252. auto objects = {pointers...};
  253. for (auto& object : objects) {
  254. context->AddCopyObject(std::move(object));
  255. }
  256. }
  257. template <typename... O>
  258. inline void ResponseBuilder::PushMoveObjects(std::shared_ptr<O>... pointers) {
  259. auto objects = {pointers...};
  260. for (auto& object : objects) {
  261. context->AddMoveObject(std::move(object));
  262. }
  263. }
  264. class RequestParser : public RequestHelperBase {
  265. public:
  266. explicit RequestParser(u32* command_buffer) : RequestHelperBase(command_buffer) {}
  267. explicit RequestParser(Kernel::HLERequestContext& context) : RequestHelperBase(context) {
  268. ASSERT_MSG(context.GetDataPayloadOffset(), "context is incomplete");
  269. Skip(context.GetDataPayloadOffset(), false);
  270. // Skip the u64 command id, it's already stored in the context
  271. static constexpr u32 CommandIdSize = 2;
  272. Skip(CommandIdSize, false);
  273. }
  274. template <typename T>
  275. T Pop();
  276. template <typename T>
  277. void Pop(T& value);
  278. template <typename First, typename... Other>
  279. void Pop(First& first_value, Other&... other_values);
  280. template <typename T>
  281. T PopEnum() {
  282. static_assert(std::is_enum_v<T>, "T must be an enum type within a PopEnum call.");
  283. static_assert(!std::is_convertible_v<T, int>,
  284. "enum type in PopEnum must be a strongly typed enum.");
  285. return static_cast<T>(Pop<std::underlying_type_t<T>>());
  286. }
  287. /**
  288. * @brief Reads the next normal parameters as a struct, by copying it
  289. * @note: The output class must be correctly packed/padded to fit hardware layout.
  290. */
  291. template <typename T>
  292. void PopRaw(T& value);
  293. /**
  294. * @brief Reads the next normal parameters as a struct, by copying it into a new value
  295. * @note: The output class must be correctly packed/padded to fit hardware layout.
  296. */
  297. template <typename T>
  298. T PopRaw();
  299. template <typename T>
  300. std::shared_ptr<T> GetMoveObject(std::size_t index);
  301. template <typename T>
  302. std::shared_ptr<T> GetCopyObject(std::size_t index);
  303. template <class T>
  304. std::shared_ptr<T> PopIpcInterface() {
  305. ASSERT(context->Session()->IsDomain());
  306. ASSERT(context->GetDomainMessageHeader().input_object_count > 0);
  307. return context->GetDomainRequestHandler<T>(Pop<u32>() - 1);
  308. }
  309. };
  310. /// Pop ///
  311. template <>
  312. inline u32 RequestParser::Pop() {
  313. return cmdbuf[index++];
  314. }
  315. template <>
  316. inline s32 RequestParser::Pop() {
  317. return static_cast<s32>(Pop<u32>());
  318. }
  319. template <typename T>
  320. void RequestParser::PopRaw(T& value) {
  321. static_assert(std::is_trivially_copyable_v<T>,
  322. "It's undefined behavior to use memcpy with non-trivially copyable objects");
  323. std::memcpy(&value, cmdbuf + index, sizeof(T));
  324. index += (sizeof(T) + 3) / 4; // round up to word length
  325. }
  326. template <typename T>
  327. T RequestParser::PopRaw() {
  328. T value;
  329. PopRaw(value);
  330. return value;
  331. }
  332. template <>
  333. inline u8 RequestParser::Pop() {
  334. return PopRaw<u8>();
  335. }
  336. template <>
  337. inline u16 RequestParser::Pop() {
  338. return PopRaw<u16>();
  339. }
  340. template <>
  341. inline u64 RequestParser::Pop() {
  342. const u64 lsw = Pop<u32>();
  343. const u64 msw = Pop<u32>();
  344. return msw << 32 | lsw;
  345. }
  346. template <>
  347. inline s8 RequestParser::Pop() {
  348. return static_cast<s8>(Pop<u8>());
  349. }
  350. template <>
  351. inline s16 RequestParser::Pop() {
  352. return static_cast<s16>(Pop<u16>());
  353. }
  354. template <>
  355. inline s64 RequestParser::Pop() {
  356. return static_cast<s64>(Pop<u64>());
  357. }
  358. template <>
  359. inline float RequestParser::Pop() {
  360. const u32 value = Pop<u32>();
  361. float real;
  362. std::memcpy(&real, &value, sizeof(real));
  363. return real;
  364. }
  365. template <>
  366. inline double RequestParser::Pop() {
  367. const u64 value = Pop<u64>();
  368. double real;
  369. std::memcpy(&real, &value, sizeof(real));
  370. return real;
  371. }
  372. template <>
  373. inline bool RequestParser::Pop() {
  374. return Pop<u8>() != 0;
  375. }
  376. template <>
  377. inline ResultCode RequestParser::Pop() {
  378. return ResultCode{Pop<u32>()};
  379. }
  380. template <typename T>
  381. void RequestParser::Pop(T& value) {
  382. value = Pop<T>();
  383. }
  384. template <typename First, typename... Other>
  385. void RequestParser::Pop(First& first_value, Other&... other_values) {
  386. first_value = Pop<First>();
  387. Pop(other_values...);
  388. }
  389. template <typename T>
  390. std::shared_ptr<T> RequestParser::GetMoveObject(std::size_t index) {
  391. return context->GetMoveObject<T>(index);
  392. }
  393. template <typename T>
  394. std::shared_ptr<T> RequestParser::GetCopyObject(std::size_t index) {
  395. return context->GetCopyObject<T>(index);
  396. }
  397. } // namespace IPC