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