ipc_helpers.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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 <tuple>
  7. #include <type_traits>
  8. #include <utility>
  9. #include "core/hle/ipc.h"
  10. #include "core/hle/kernel/handle_table.h"
  11. #include "core/hle/kernel/hle_ipc.h"
  12. #include "core/hle/kernel/kernel.h"
  13. namespace IPC {
  14. class RequestHelperBase {
  15. protected:
  16. Kernel::HLERequestContext* context = nullptr;
  17. u32* cmdbuf;
  18. ptrdiff_t index = 0;
  19. public:
  20. RequestHelperBase(u32* command_buffer) : cmdbuf(command_buffer) {}
  21. RequestHelperBase(Kernel::HLERequestContext& context)
  22. : context(&context), cmdbuf(context.CommandBuffer()) {}
  23. void ValidateHeader() {
  24. // DEBUG_ASSERT_MSG(index == TotalSize(), "Operations do not match the header (cmd 0x%x)",
  25. // header.raw);
  26. }
  27. void Skip(unsigned size_in_words, bool set_to_null) {
  28. if (set_to_null)
  29. memset(cmdbuf + index, 0, size_in_words * sizeof(u32));
  30. index += size_in_words;
  31. }
  32. /**
  33. * Aligns the current position forward to a 16-byte boundary, padding with zeros.
  34. */
  35. void AlignWithPadding() {
  36. if (index & 3) {
  37. Skip(4 - (index & 3), true);
  38. }
  39. }
  40. unsigned GetCurrentOffset() const {
  41. return static_cast<unsigned>(index);
  42. }
  43. };
  44. class RequestBuilder : public RequestHelperBase {
  45. public:
  46. RequestBuilder(u32* command_buffer) : RequestHelperBase(command_buffer) {}
  47. RequestBuilder(Kernel::HLERequestContext& context, unsigned normal_params_size,
  48. u32 num_handles_to_copy = 0, u32 num_handles_to_move = 0)
  49. : RequestHelperBase(context) {
  50. memset(cmdbuf, 0, 64);
  51. context.ClearIncomingObjects();
  52. IPC::CommandHeader header{};
  53. header.data_size.Assign(normal_params_size * sizeof(u32));
  54. if (num_handles_to_copy || num_handles_to_move) {
  55. header.enable_handle_descriptor.Assign(1);
  56. }
  57. PushRaw(header);
  58. if (header.enable_handle_descriptor) {
  59. IPC::HandleDescriptorHeader handle_descriptor_header{};
  60. handle_descriptor_header.num_handles_to_copy.Assign(num_handles_to_copy);
  61. handle_descriptor_header.num_handles_to_move.Assign(num_handles_to_move);
  62. PushRaw(handle_descriptor_header);
  63. Skip(num_handles_to_copy + num_handles_to_move, true);
  64. }
  65. AlignWithPadding();
  66. IPC::DataPayloadHeader data_payload_header{};
  67. data_payload_header.magic = Common::MakeMagic('S', 'F', 'C', 'O');
  68. PushRaw(data_payload_header);
  69. }
  70. // Validate on destruction, as there shouldn't be any case where we don't want it
  71. ~RequestBuilder() {
  72. ValidateHeader();
  73. }
  74. template <typename T>
  75. void Push(T value);
  76. template <typename First, typename... Other>
  77. void Push(const First& first_value, const Other&... other_values);
  78. /**
  79. * @brief Copies the content of the given trivially copyable class to the buffer as a normal
  80. * param
  81. * @note: The input class must be correctly packed/padded to fit hardware layout.
  82. */
  83. template <typename T>
  84. void PushRaw(const T& value);
  85. // TODO : ensure that translate params are added after all regular params
  86. template <typename... H>
  87. void PushCopyHandles(H... handles);
  88. template <typename... H>
  89. void PushMoveHandles(H... handles);
  90. template <typename... O>
  91. void PushObjects(Kernel::SharedPtr<O>... pointers);
  92. void PushCurrentPIDHandle();
  93. void PushStaticBuffer(VAddr buffer_vaddr, size_t size, u8 buffer_id);
  94. void PushMappedBuffer(VAddr buffer_vaddr, size_t size, MappedBufferPermissions perms);
  95. };
  96. /// Push ///
  97. template <>
  98. inline void RequestBuilder::Push(u32 value) {
  99. cmdbuf[index++] = value;
  100. }
  101. template <typename T>
  102. void RequestBuilder::PushRaw(const T& value) {
  103. std::memcpy(cmdbuf + index, &value, sizeof(T));
  104. index += (sizeof(T) + 3) / 4; // round up to word length
  105. }
  106. template <>
  107. inline void RequestBuilder::Push(u8 value) {
  108. PushRaw(value);
  109. }
  110. template <>
  111. inline void RequestBuilder::Push(u16 value) {
  112. PushRaw(value);
  113. }
  114. template <>
  115. inline void RequestBuilder::Push(u64 value) {
  116. Push(static_cast<u32>(value));
  117. Push(static_cast<u32>(value >> 32));
  118. }
  119. template <>
  120. inline void RequestBuilder::Push(bool value) {
  121. Push(static_cast<u8>(value));
  122. }
  123. template <>
  124. inline void RequestBuilder::Push(ResultCode value) {
  125. Push(value.raw);
  126. }
  127. template <typename First, typename... Other>
  128. void RequestBuilder::Push(const First& first_value, const Other&... other_values) {
  129. Push(first_value);
  130. Push(other_values...);
  131. }
  132. template <typename... H>
  133. inline void RequestBuilder::PushCopyHandles(H... handles) {
  134. Push(CopyHandleDesc(sizeof...(H)));
  135. Push(static_cast<Kernel::Handle>(handles)...);
  136. }
  137. template <typename... H>
  138. inline void RequestBuilder::PushMoveHandles(H... handles) {
  139. Push(MoveHandleDesc(sizeof...(H)));
  140. Push(static_cast<Kernel::Handle>(handles)...);
  141. }
  142. template <typename... O>
  143. inline void RequestBuilder::PushObjects(Kernel::SharedPtr<O>... pointers) {
  144. PushMoveHandles(context->AddOutgoingHandle(std::move(pointers))...);
  145. }
  146. inline void RequestBuilder::PushCurrentPIDHandle() {
  147. Push(CallingPidDesc());
  148. Push(u32(0));
  149. }
  150. inline void RequestBuilder::PushStaticBuffer(VAddr buffer_vaddr, size_t size, u8 buffer_id) {
  151. Push(StaticBufferDesc(size, buffer_id));
  152. Push(buffer_vaddr);
  153. }
  154. inline void RequestBuilder::PushMappedBuffer(VAddr buffer_vaddr, size_t size,
  155. MappedBufferPermissions perms) {
  156. Push(MappedBufferDesc(size, perms));
  157. Push(buffer_vaddr);
  158. }
  159. class RequestParser : public RequestHelperBase {
  160. public:
  161. RequestParser(u32* command_buffer) : RequestHelperBase(command_buffer) {}
  162. RequestParser(Kernel::HLERequestContext& context) : RequestHelperBase(context) {
  163. ASSERT_MSG(context.GetDataPayloadOffset(), "context is incomplete");
  164. Skip(context.GetDataPayloadOffset(), false);
  165. }
  166. RequestBuilder MakeBuilder(u32 normal_params_size, u32 num_handles_to_copy,
  167. u32 num_handles_to_move, bool validate_header = true) {
  168. if (validate_header) {
  169. ValidateHeader();
  170. }
  171. return {*context, normal_params_size, num_handles_to_copy, num_handles_to_move};
  172. }
  173. template <typename T>
  174. T Pop();
  175. template <typename T>
  176. void Pop(T& value);
  177. template <typename First, typename... Other>
  178. void Pop(First& first_value, Other&... other_values);
  179. /// Equivalent to calling `PopHandles<1>()[0]`.
  180. Kernel::Handle PopHandle();
  181. /**
  182. * Pops a descriptor containing `N` handles. The handles are returned as an array. The
  183. * descriptor must contain exactly `N` handles, it is not permitted to, for example, call
  184. * PopHandles<1>() twice to read a multi-handle descriptor with 2 handles, or to make a single
  185. * PopHandles<2>() call to read 2 single-handle descriptors.
  186. */
  187. template <unsigned int N>
  188. std::array<Kernel::Handle, N> PopHandles();
  189. /// Convenience wrapper around PopHandles() which assigns the handles to the passed references.
  190. template <typename... H>
  191. void PopHandles(H&... handles) {
  192. std::tie(handles...) = PopHandles<sizeof...(H)>();
  193. }
  194. /// Equivalent to calling `PopGenericObjects<1>()[0]`.
  195. Kernel::SharedPtr<Kernel::Object> PopGenericObject();
  196. /// Equivalent to calling `std::get<0>(PopObjects<T>())`.
  197. template <typename T>
  198. Kernel::SharedPtr<T> PopObject();
  199. /**
  200. * Pop a descriptor containing `N` handles and resolves them to Kernel::Object pointers. If a
  201. * handle is invalid, null is returned for that object instead. The same caveats from
  202. * PopHandles() apply regarding `N` matching the number of handles in the descriptor.
  203. */
  204. template <unsigned int N>
  205. std::array<Kernel::SharedPtr<Kernel::Object>, N> PopGenericObjects();
  206. /**
  207. * Resolves handles to Kernel::Objects as in PopGenericsObjects(), but then also casts them to
  208. * the passed `T` types, while verifying that the cast is valid. If the type of an object does
  209. * not match, null is returned instead.
  210. */
  211. template <typename... T>
  212. std::tuple<Kernel::SharedPtr<T>...> PopObjects();
  213. /// Convenience wrapper around PopObjects() which assigns the handles to the passed references.
  214. template <typename... T>
  215. void PopObjects(Kernel::SharedPtr<T>&... pointers) {
  216. std::tie(pointers...) = PopObjects<T...>();
  217. }
  218. /**
  219. * @brief Pops the static buffer vaddr
  220. * @return The virtual address of the buffer
  221. * @param[out] data_size If non-null, the pointed value will be set to the size of the data
  222. * @param[out] useStaticBuffersToGetVaddr Indicates if we should read the vaddr from the static
  223. * buffers (which is the correct thing to do, but no service presently implement it) instead of
  224. * using the same value as the process who sent the request
  225. * given by the source process
  226. *
  227. * Static buffers must be set up before any IPC request using those is sent.
  228. * It is the duty of the process (usually services) to allocate and set up the receiving static
  229. * buffer information
  230. * Please note that the setup uses virtual addresses.
  231. */
  232. VAddr PopStaticBuffer(size_t* data_size = nullptr, bool useStaticBuffersToGetVaddr = false);
  233. /**
  234. * @brief Pops the mapped buffer vaddr
  235. * @return The virtual address of the buffer
  236. * @param[out] data_size If non-null, the pointed value will be set to the size of the data
  237. * given by the source process
  238. * @param[out] buffer_perms If non-null, the pointed value will be set to the permissions of the
  239. * buffer
  240. */
  241. VAddr PopMappedBuffer(size_t* data_size = nullptr,
  242. MappedBufferPermissions* buffer_perms = nullptr);
  243. /**
  244. * @brief Reads the next normal parameters as a struct, by copying it
  245. * @note: The output class must be correctly packed/padded to fit hardware layout.
  246. */
  247. template <typename T>
  248. void PopRaw(T& value);
  249. /**
  250. * @brief Reads the next normal parameters as a struct, by copying it into a new value
  251. * @note: The output class must be correctly packed/padded to fit hardware layout.
  252. */
  253. template <typename T>
  254. T PopRaw();
  255. };
  256. /// Pop ///
  257. template <>
  258. inline u32 RequestParser::Pop() {
  259. return cmdbuf[index++];
  260. }
  261. template <typename T>
  262. void RequestParser::PopRaw(T& value) {
  263. std::memcpy(&value, cmdbuf + index, sizeof(T));
  264. index += (sizeof(T) + 3) / 4; // round up to word length
  265. }
  266. template <typename T>
  267. T RequestParser::PopRaw() {
  268. T value;
  269. PopRaw(value);
  270. return value;
  271. }
  272. template <>
  273. inline u8 RequestParser::Pop() {
  274. return PopRaw<u8>();
  275. }
  276. template <>
  277. inline u16 RequestParser::Pop() {
  278. return PopRaw<u16>();
  279. }
  280. template <>
  281. inline u64 RequestParser::Pop() {
  282. const u64 lsw = Pop<u32>();
  283. const u64 msw = Pop<u32>();
  284. return msw << 32 | lsw;
  285. }
  286. template <>
  287. inline bool RequestParser::Pop() {
  288. return Pop<u8>() != 0;
  289. }
  290. template <>
  291. inline ResultCode RequestParser::Pop() {
  292. return ResultCode{Pop<u32>()};
  293. }
  294. template <typename T>
  295. void RequestParser::Pop(T& value) {
  296. value = Pop<T>();
  297. }
  298. template <typename First, typename... Other>
  299. void RequestParser::Pop(First& first_value, Other&... other_values) {
  300. first_value = Pop<First>();
  301. Pop(other_values...);
  302. }
  303. inline Kernel::Handle RequestParser::PopHandle() {
  304. const u32 handle_descriptor = Pop<u32>();
  305. DEBUG_ASSERT_MSG(IsHandleDescriptor(handle_descriptor),
  306. "Tried to pop handle(s) but the descriptor is not a handle descriptor");
  307. DEBUG_ASSERT_MSG(HandleNumberFromDesc(handle_descriptor) == 1,
  308. "Descriptor indicates that there isn't exactly one handle");
  309. return Pop<Kernel::Handle>();
  310. }
  311. template <unsigned int N>
  312. std::array<Kernel::Handle, N> RequestParser::PopHandles() {
  313. u32 handle_descriptor = Pop<u32>();
  314. ASSERT_MSG(IsHandleDescriptor(handle_descriptor),
  315. "Tried to pop handle(s) but the descriptor is not a handle descriptor");
  316. ASSERT_MSG(N == HandleNumberFromDesc(handle_descriptor),
  317. "Number of handles doesn't match the descriptor");
  318. std::array<Kernel::Handle, N> handles{};
  319. for (Kernel::Handle& handle : handles) {
  320. handle = Pop<Kernel::Handle>();
  321. }
  322. return handles;
  323. }
  324. inline Kernel::SharedPtr<Kernel::Object> RequestParser::PopGenericObject() {
  325. Kernel::Handle handle = PopHandle();
  326. return context->GetIncomingHandle(handle);
  327. }
  328. template <typename T>
  329. Kernel::SharedPtr<T> RequestParser::PopObject() {
  330. return Kernel::DynamicObjectCast<T>(PopGenericObject());
  331. }
  332. template <unsigned int N>
  333. inline std::array<Kernel::SharedPtr<Kernel::Object>, N> RequestParser::PopGenericObjects() {
  334. std::array<Kernel::Handle, N> handles = PopHandles<N>();
  335. std::array<Kernel::SharedPtr<Kernel::Object>, N> pointers;
  336. for (int i = 0; i < N; ++i) {
  337. pointers[i] = context->GetIncomingHandle(handles[i]);
  338. }
  339. return pointers;
  340. }
  341. namespace detail {
  342. template <typename... T, size_t... I>
  343. std::tuple<Kernel::SharedPtr<T>...> PopObjectsHelper(
  344. std::array<Kernel::SharedPtr<Kernel::Object>, sizeof...(T)>&& pointers,
  345. std::index_sequence<I...>) {
  346. return std::make_tuple(Kernel::DynamicObjectCast<T>(std::move(pointers[I]))...);
  347. }
  348. } // namespace detail
  349. template <typename... T>
  350. inline std::tuple<Kernel::SharedPtr<T>...> RequestParser::PopObjects() {
  351. return detail::PopObjectsHelper<T...>(PopGenericObjects<sizeof...(T)>(),
  352. std::index_sequence_for<T...>{});
  353. }
  354. inline VAddr RequestParser::PopStaticBuffer(size_t* data_size, bool useStaticBuffersToGetVaddr) {
  355. const u32 sbuffer_descriptor = Pop<u32>();
  356. StaticBufferDescInfo bufferInfo{sbuffer_descriptor};
  357. if (data_size != nullptr)
  358. *data_size = bufferInfo.size;
  359. if (!useStaticBuffersToGetVaddr)
  360. return Pop<VAddr>();
  361. else {
  362. ASSERT_MSG(0, "remove the assert if multiprocess/IPC translation are implemented.");
  363. // The buffer has already been copied to the static buffer by the kernel during
  364. // translation
  365. Pop<VAddr>(); // Pop the calling process buffer address
  366. // and get the vaddr from the static buffers
  367. return cmdbuf[(0x100 >> 2) + bufferInfo.buffer_id * 2 + 1];
  368. }
  369. }
  370. inline VAddr RequestParser::PopMappedBuffer(size_t* data_size,
  371. MappedBufferPermissions* buffer_perms) {
  372. const u32 sbuffer_descriptor = Pop<u32>();
  373. MappedBufferDescInfo bufferInfo{sbuffer_descriptor};
  374. if (data_size != nullptr)
  375. *data_size = bufferInfo.size;
  376. if (buffer_perms != nullptr)
  377. *buffer_perms = bufferInfo.perms;
  378. return Pop<VAddr>();
  379. }
  380. } // namespace IPC