apt.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. // Copyright 2015 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <boost/optional.hpp>
  5. #include "common/common_paths.h"
  6. #include "common/file_util.h"
  7. #include "common/logging/log.h"
  8. #include "core/core.h"
  9. #include "core/file_sys/file_backend.h"
  10. #include "core/hle/applets/applet.h"
  11. #include "core/hle/kernel/event.h"
  12. #include "core/hle/kernel/mutex.h"
  13. #include "core/hle/kernel/process.h"
  14. #include "core/hle/kernel/shared_memory.h"
  15. #include "core/hle/romfs.h"
  16. #include "core/hle/service/apt/apt.h"
  17. #include "core/hle/service/apt/apt_a.h"
  18. #include "core/hle/service/apt/apt_s.h"
  19. #include "core/hle/service/apt/apt_u.h"
  20. #include "core/hle/service/apt/bcfnt/bcfnt.h"
  21. #include "core/hle/service/fs/archive.h"
  22. #include "core/hle/service/ptm/ptm.h"
  23. #include "core/hle/service/service.h"
  24. #include "core/hw/aes/ccm.h"
  25. #include "core/hw/aes/key.h"
  26. namespace Service {
  27. namespace APT {
  28. /// Handle to shared memory region designated to for shared system font
  29. static Kernel::SharedPtr<Kernel::SharedMemory> shared_font_mem;
  30. static bool shared_font_loaded = false;
  31. static bool shared_font_relocated = false;
  32. static Kernel::SharedPtr<Kernel::Mutex> lock;
  33. static Kernel::SharedPtr<Kernel::Event> notification_event; ///< APT notification event
  34. static Kernel::SharedPtr<Kernel::Event> parameter_event; ///< APT parameter event
  35. static u32 cpu_percent; ///< CPU time available to the running application
  36. // APT::CheckNew3DSApp will check this unknown_ns_state_field to determine processing mode
  37. static u8 unknown_ns_state_field;
  38. static ScreencapPostPermission screen_capture_post_permission;
  39. /// Parameter data to be returned in the next call to Glance/ReceiveParameter
  40. static boost::optional<MessageParameter> next_parameter;
  41. void SendParameter(const MessageParameter& parameter) {
  42. next_parameter = parameter;
  43. // Signal the event to let the application know that a new parameter is ready to be read
  44. parameter_event->Signal();
  45. }
  46. void Initialize(Service::Interface* self) {
  47. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x2, 2, 0); // 0x20080
  48. u32 app_id = rp.Pop<u32>();
  49. u32 flags = rp.Pop<u32>();
  50. IPC::RequestBuilder rb = rp.MakeBuilder(1, 3);
  51. rb.Push(RESULT_SUCCESS);
  52. rb.PushCopyHandles(Kernel::g_handle_table.Create(notification_event).Unwrap(),
  53. Kernel::g_handle_table.Create(parameter_event).Unwrap());
  54. // TODO(bunnei): Check if these events are cleared every time Initialize is called.
  55. notification_event->Clear();
  56. parameter_event->Clear();
  57. ASSERT_MSG((nullptr != lock), "Cannot initialize without lock");
  58. lock->Release();
  59. LOG_DEBUG(Service_APT, "called app_id=0x%08X, flags=0x%08X", app_id, flags);
  60. }
  61. void GetSharedFont(Service::Interface* self) {
  62. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x44, 0, 0); // 0x00440000
  63. IPC::RequestBuilder rb = rp.MakeBuilder(2, 2);
  64. if (!shared_font_loaded) {
  65. LOG_ERROR(Service_APT, "shared font file missing - go dump it from your 3ds");
  66. rb.Push<u32>(-1); // TODO: Find the right error code
  67. rb.Skip(1 + 2, true);
  68. Core::System::GetInstance().SetStatus(Core::System::ResultStatus::ErrorSharedFont);
  69. return;
  70. }
  71. // The shared font has to be relocated to the new address before being passed to the
  72. // application.
  73. VAddr target_address =
  74. Memory::PhysicalToVirtualAddress(shared_font_mem->linear_heap_phys_address);
  75. if (!shared_font_relocated) {
  76. BCFNT::RelocateSharedFont(shared_font_mem, target_address);
  77. shared_font_relocated = true;
  78. }
  79. rb.Push(RESULT_SUCCESS); // No error
  80. // Since the SharedMemory interface doesn't provide the address at which the memory was
  81. // allocated, the real APT service calculates this address by scanning the entire address space
  82. // (using svcQueryMemory) and searches for an allocation of the same size as the Shared Font.
  83. rb.Push(target_address);
  84. rb.PushCopyHandles(Kernel::g_handle_table.Create(shared_font_mem).Unwrap());
  85. }
  86. void NotifyToWait(Service::Interface* self) {
  87. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x43, 1, 0); // 0x430040
  88. u32 app_id = rp.Pop<u32>();
  89. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  90. rb.Push(RESULT_SUCCESS); // No error
  91. LOG_WARNING(Service_APT, "(STUBBED) app_id=%u", app_id);
  92. }
  93. void GetLockHandle(Service::Interface* self) {
  94. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1, 1, 0); // 0x10040
  95. // Bits [0:2] are the applet type (System, Library, etc)
  96. // Bit 5 tells the application that there's a pending APT parameter,
  97. // this will cause the app to wait until parameter_event is signaled.
  98. u32 applet_attributes = rp.Pop<u32>();
  99. IPC::RequestBuilder rb = rp.MakeBuilder(3, 2);
  100. rb.Push(RESULT_SUCCESS); // No error
  101. rb.Push(applet_attributes); // Applet Attributes, this value is passed to Enable.
  102. rb.Push<u32>(0); // Least significant bit = power button state
  103. Kernel::Handle handle_copy = Kernel::g_handle_table.Create(lock).Unwrap();
  104. rb.PushCopyHandles(handle_copy);
  105. LOG_WARNING(Service_APT, "(STUBBED) called handle=0x%08X applet_attributes=0x%08X", handle_copy,
  106. applet_attributes);
  107. }
  108. void Enable(Service::Interface* self) {
  109. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x3, 1, 0); // 0x30040
  110. u32 attributes = rp.Pop<u32>();
  111. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  112. rb.Push(RESULT_SUCCESS); // No error
  113. parameter_event->Signal(); // Let the application know that it has been started
  114. LOG_WARNING(Service_APT, "(STUBBED) called attributes=0x%08X", attributes);
  115. }
  116. void GetAppletManInfo(Service::Interface* self) {
  117. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x5, 1, 0); // 0x50040
  118. u32 unk = rp.Pop<u32>();
  119. IPC::RequestBuilder rb = rp.MakeBuilder(5, 0);
  120. rb.Push(RESULT_SUCCESS); // No error
  121. rb.Push<u32>(0);
  122. rb.Push<u32>(0);
  123. rb.Push(static_cast<u32>(AppletId::HomeMenu)); // Home menu AppID
  124. rb.Push(static_cast<u32>(AppletId::Application)); // TODO(purpasmart96): Do this correctly
  125. LOG_WARNING(Service_APT, "(STUBBED) called unk=0x%08X", unk);
  126. }
  127. void IsRegistered(Service::Interface* self) {
  128. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x9, 1, 0); // 0x90040
  129. u32 app_id = rp.Pop<u32>();
  130. IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
  131. rb.Push(RESULT_SUCCESS); // No error
  132. // TODO(Subv): An application is considered "registered" if it has already called APT::Enable
  133. // handle this properly once we implement multiprocess support.
  134. bool is_registered = false; // Set to not registered by default
  135. if (app_id == static_cast<u32>(AppletId::AnyLibraryApplet)) {
  136. is_registered = HLE::Applets::IsLibraryAppletRunning();
  137. } else if (auto applet = HLE::Applets::Applet::Get(static_cast<AppletId>(app_id))) {
  138. is_registered = true; // Set to registered
  139. }
  140. rb.Push(is_registered);
  141. LOG_WARNING(Service_APT, "(STUBBED) called app_id=0x%08X", app_id);
  142. }
  143. void InquireNotification(Service::Interface* self) {
  144. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0xB, 1, 0); // 0xB0040
  145. u32 app_id = rp.Pop<u32>();
  146. IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
  147. rb.Push(RESULT_SUCCESS); // No error
  148. rb.Push(static_cast<u32>(SignalType::None)); // Signal type
  149. LOG_WARNING(Service_APT, "(STUBBED) called app_id=0x%08X", app_id);
  150. }
  151. void SendParameter(Service::Interface* self) {
  152. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0xC, 4, 4); // 0xC0104
  153. u32 src_app_id = rp.Pop<u32>();
  154. u32 dst_app_id = rp.Pop<u32>();
  155. u32 signal_type = rp.Pop<u32>();
  156. u32 buffer_size = rp.Pop<u32>();
  157. Kernel::Handle handle = rp.PopHandle();
  158. size_t size;
  159. VAddr buffer = rp.PopStaticBuffer(&size);
  160. std::shared_ptr<HLE::Applets::Applet> dest_applet =
  161. HLE::Applets::Applet::Get(static_cast<AppletId>(dst_app_id));
  162. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  163. if (dest_applet == nullptr) {
  164. LOG_ERROR(Service_APT, "Unknown applet id=0x%08X", dst_app_id);
  165. rb.Push<u32>(-1); // TODO(Subv): Find the right error code
  166. return;
  167. }
  168. MessageParameter param;
  169. param.destination_id = dst_app_id;
  170. param.sender_id = src_app_id;
  171. param.object = Kernel::g_handle_table.GetGeneric(handle);
  172. param.signal = signal_type;
  173. param.buffer.resize(buffer_size);
  174. Memory::ReadBlock(buffer, param.buffer.data(), param.buffer.size());
  175. rb.Push(dest_applet->ReceiveParameter(param));
  176. LOG_WARNING(Service_APT,
  177. "(STUBBED) called src_app_id=0x%08X, dst_app_id=0x%08X, signal_type=0x%08X,"
  178. "buffer_size=0x%08X, handle=0x%08X, size=0x%08zX, in_param_buffer_ptr=0x%08X",
  179. src_app_id, dst_app_id, signal_type, buffer_size, handle, size, buffer);
  180. }
  181. void ReceiveParameter(Service::Interface* self) {
  182. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0xD, 2, 0); // 0xD0080
  183. u32 app_id = rp.Pop<u32>();
  184. u32 buffer_size = rp.Pop<u32>();
  185. size_t static_buff_size;
  186. VAddr buffer = rp.PeekStaticBuffer(0, &static_buff_size);
  187. if (buffer_size > static_buff_size)
  188. LOG_WARNING(
  189. Service_APT,
  190. "buffer_size is bigger than the size in the buffer descriptor (0x%08X > 0x%08zX)",
  191. buffer_size, static_buff_size);
  192. IPC::RequestBuilder rb = rp.MakeBuilder(4, 4);
  193. rb.Push(RESULT_SUCCESS); // No error
  194. rb.Push(next_parameter->sender_id);
  195. rb.Push(next_parameter->signal); // Signal type
  196. ASSERT_MSG(next_parameter->buffer.size() <= buffer_size, "Input static buffer is too small !");
  197. rb.Push(static_cast<u32>(next_parameter->buffer.size())); // Parameter buffer size
  198. rb.PushMoveHandles((next_parameter->object != nullptr)
  199. ? Kernel::g_handle_table.Create(next_parameter->object).Unwrap()
  200. : 0);
  201. rb.PushStaticBuffer(buffer, static_cast<u32>(next_parameter->buffer.size()), 0);
  202. Memory::WriteBlock(buffer, next_parameter->buffer.data(), next_parameter->buffer.size());
  203. LOG_WARNING(Service_APT, "called app_id=0x%08X, buffer_size=0x%08zX", app_id, buffer_size);
  204. }
  205. void GlanceParameter(Service::Interface* self) {
  206. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0xE, 2, 0); // 0xE0080
  207. u32 app_id = rp.Pop<u32>();
  208. u32 buffer_size = rp.Pop<u32>();
  209. size_t static_buff_size;
  210. VAddr buffer = rp.PeekStaticBuffer(0, &static_buff_size);
  211. if (buffer_size > static_buff_size)
  212. LOG_WARNING(
  213. Service_APT,
  214. "buffer_size is bigger than the size in the buffer descriptor (0x%08X > 0x%08zX)",
  215. buffer_size, static_buff_size);
  216. IPC::RequestBuilder rb = rp.MakeBuilder(4, 4);
  217. rb.Push(RESULT_SUCCESS); // No error
  218. rb.Push(next_parameter->sender_id);
  219. rb.Push(next_parameter->signal); // Signal type
  220. ASSERT_MSG(next_parameter->buffer.size() <= buffer_size, "Input static buffer is too small !");
  221. rb.Push(static_cast<u32>(next_parameter->buffer.size())); // Parameter buffer size
  222. rb.PushMoveHandles((next_parameter->object != nullptr)
  223. ? Kernel::g_handle_table.Create(next_parameter->object).Unwrap()
  224. : 0);
  225. rb.PushStaticBuffer(buffer, static_cast<u32>(next_parameter->buffer.size()), 0);
  226. Memory::WriteBlock(buffer, next_parameter->buffer.data(), next_parameter->buffer.size());
  227. LOG_WARNING(Service_APT, "called app_id=0x%08X, buffer_size=0x%08zX", app_id, buffer_size);
  228. }
  229. void CancelParameter(Service::Interface* self) {
  230. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0xF, 4, 0); // 0xF0100
  231. u32 check_sender = rp.Pop<u32>();
  232. u32 sender_appid = rp.Pop<u32>();
  233. u32 check_receiver = rp.Pop<u32>();
  234. u32 receiver_appid = rp.Pop<u32>();
  235. IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
  236. rb.Push(RESULT_SUCCESS); // No error
  237. rb.Push(true); // Set to Success
  238. LOG_WARNING(Service_APT, "(STUBBED) called check_sender=0x%08X, sender_appid=0x%08X, "
  239. "check_receiver=0x%08X, receiver_appid=0x%08X",
  240. check_sender, sender_appid, check_receiver, receiver_appid);
  241. }
  242. void PrepareToStartApplication(Service::Interface* self) {
  243. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x15, 5, 0); // 0x00150140
  244. u32 title_info1 = rp.Pop<u32>();
  245. u32 title_info2 = rp.Pop<u32>();
  246. u32 title_info3 = rp.Pop<u32>();
  247. u32 title_info4 = rp.Pop<u32>();
  248. u32 flags = rp.Pop<u32>();
  249. if (flags & 0x00000100) {
  250. unknown_ns_state_field = 1;
  251. }
  252. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  253. rb.Push(RESULT_SUCCESS); // No error
  254. LOG_WARNING(Service_APT,
  255. "(STUBBED) called title_info1=0x%08X, title_info2=0x%08X, title_info3=0x%08X,"
  256. "title_info4=0x%08X, flags=0x%08X",
  257. title_info1, title_info2, title_info3, title_info4, flags);
  258. }
  259. void StartApplication(Service::Interface* self) {
  260. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1B, 3, 4); // 0x001B00C4
  261. u32 buffer1_size = rp.Pop<u32>();
  262. u32 buffer2_size = rp.Pop<u32>();
  263. u32 flag = rp.Pop<u32>();
  264. size_t size1;
  265. VAddr buffer1_ptr = rp.PopStaticBuffer(&size1);
  266. size_t size2;
  267. VAddr buffer2_ptr = rp.PopStaticBuffer(&size2);
  268. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  269. rb.Push(RESULT_SUCCESS); // No error
  270. LOG_WARNING(Service_APT,
  271. "(STUBBED) called buffer1_size=0x%08X, buffer2_size=0x%08X, flag=0x%08X,"
  272. "size1=0x%08zX, buffer1_ptr=0x%08X, size2=0x%08zX, buffer2_ptr=0x%08X",
  273. buffer1_size, buffer2_size, flag, size1, buffer1_ptr, size2, buffer2_ptr);
  274. }
  275. void AppletUtility(Service::Interface* self) {
  276. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x4B, 3, 2); // 0x004B00C2
  277. // These are from 3dbrew - I'm not really sure what they're used for.
  278. u32 utility_command = rp.Pop<u32>();
  279. u32 input_size = rp.Pop<u32>();
  280. u32 output_size = rp.Pop<u32>();
  281. VAddr input_addr = rp.PopStaticBuffer();
  282. VAddr output_addr = rp.PeekStaticBuffer(0);
  283. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  284. rb.Push(RESULT_SUCCESS); // No error
  285. LOG_WARNING(Service_APT,
  286. "(STUBBED) called command=0x%08X, input_size=0x%08X, output_size=0x%08X, "
  287. "input_addr=0x%08X, output_addr=0x%08X",
  288. utility_command, input_size, output_size, input_addr, output_addr);
  289. }
  290. void SetAppCpuTimeLimit(Service::Interface* self) {
  291. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x4F, 2, 0); // 0x4F0080
  292. u32 value = rp.Pop<u32>();
  293. cpu_percent = rp.Pop<u32>();
  294. if (value != 1) {
  295. LOG_ERROR(Service_APT, "This value should be one, but is actually %u!", value);
  296. }
  297. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  298. rb.Push(RESULT_SUCCESS); // No error
  299. LOG_WARNING(Service_APT, "(STUBBED) called cpu_percent=%u, value=%u", cpu_percent, value);
  300. }
  301. void GetAppCpuTimeLimit(Service::Interface* self) {
  302. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x50, 1, 0); // 0x500040
  303. u32 value = rp.Pop<u32>();
  304. if (value != 1) {
  305. LOG_ERROR(Service_APT, "This value should be one, but is actually %u!", value);
  306. }
  307. IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
  308. rb.Push(RESULT_SUCCESS); // No error
  309. rb.Push(cpu_percent);
  310. LOG_WARNING(Service_APT, "(STUBBED) called value=%u", value);
  311. }
  312. void PrepareToStartLibraryApplet(Service::Interface* self) {
  313. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x18, 1, 0); // 0x180040
  314. AppletId applet_id = static_cast<AppletId>(rp.Pop<u32>());
  315. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  316. auto applet = HLE::Applets::Applet::Get(applet_id);
  317. if (applet) {
  318. LOG_WARNING(Service_APT, "applet has already been started id=%08X", applet_id);
  319. rb.Push(RESULT_SUCCESS);
  320. } else {
  321. rb.Push(HLE::Applets::Applet::Create(applet_id));
  322. }
  323. LOG_DEBUG(Service_APT, "called applet_id=%08X", applet_id);
  324. }
  325. void PreloadLibraryApplet(Service::Interface* self) {
  326. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x16, 1, 0); // 0x160040
  327. AppletId applet_id = static_cast<AppletId>(rp.Pop<u32>());
  328. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  329. auto applet = HLE::Applets::Applet::Get(applet_id);
  330. if (applet) {
  331. LOG_WARNING(Service_APT, "applet has already been started id=%08X", applet_id);
  332. rb.Push(RESULT_SUCCESS);
  333. } else {
  334. rb.Push(HLE::Applets::Applet::Create(applet_id));
  335. }
  336. LOG_DEBUG(Service_APT, "called applet_id=%08X", applet_id);
  337. }
  338. void StartLibraryApplet(Service::Interface* self) {
  339. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1E, 2, 4); // 0x1E0084
  340. AppletId applet_id = static_cast<AppletId>(rp.Pop<u32>());
  341. std::shared_ptr<HLE::Applets::Applet> applet = HLE::Applets::Applet::Get(applet_id);
  342. LOG_DEBUG(Service_APT, "called applet_id=%08X", applet_id);
  343. if (applet == nullptr) {
  344. LOG_ERROR(Service_APT, "unknown applet id=%08X", applet_id);
  345. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0, false);
  346. rb.Push<u32>(-1); // TODO(Subv): Find the right error code
  347. return;
  348. }
  349. size_t buffer_size = rp.Pop<u32>();
  350. Kernel::Handle handle = rp.PopHandle();
  351. VAddr buffer_addr = rp.PopStaticBuffer();
  352. AppletStartupParameter parameter;
  353. parameter.object = Kernel::g_handle_table.GetGeneric(handle);
  354. parameter.buffer.resize(buffer_size);
  355. Memory::ReadBlock(buffer_addr, parameter.buffer.data(), parameter.buffer.size());
  356. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  357. rb.Push(applet->Start(parameter));
  358. }
  359. void CancelLibraryApplet(Service::Interface* self) {
  360. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x3B, 1, 0); // 0x003B0040
  361. bool exiting = rp.Pop<bool>();
  362. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  363. rb.Push<u32>(1); // TODO: Find the return code meaning
  364. LOG_WARNING(Service_APT, "(STUBBED) called exiting=%d", exiting);
  365. }
  366. void SetScreenCapPostPermission(Service::Interface* self) {
  367. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x55, 1, 0); // 0x00550040
  368. screen_capture_post_permission = static_cast<ScreencapPostPermission>(rp.Pop<u32>() & 0xF);
  369. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  370. rb.Push(RESULT_SUCCESS); // No error
  371. LOG_WARNING(Service_APT, "(STUBBED) screen_capture_post_permission=%u",
  372. screen_capture_post_permission);
  373. }
  374. void GetScreenCapPostPermission(Service::Interface* self) {
  375. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x56, 0, 0); // 0x00560000
  376. IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
  377. rb.Push(RESULT_SUCCESS); // No error
  378. rb.Push(static_cast<u32>(screen_capture_post_permission));
  379. LOG_WARNING(Service_APT, "(STUBBED) screen_capture_post_permission=%u",
  380. screen_capture_post_permission);
  381. }
  382. void GetAppletInfo(Service::Interface* self) {
  383. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x6, 1, 0); // 0x60040
  384. auto app_id = static_cast<AppletId>(rp.Pop<u32>());
  385. if (auto applet = HLE::Applets::Applet::Get(app_id)) {
  386. // TODO(Subv): Get the title id for the current applet and write it in the response[2-3]
  387. IPC::RequestBuilder rb = rp.MakeBuilder(7, 0);
  388. rb.Push(RESULT_SUCCESS);
  389. u64 title_id = 0;
  390. rb.Push(title_id);
  391. rb.Push(static_cast<u32>(Service::FS::MediaType::NAND));
  392. rb.Push(true); // Registered
  393. rb.Push(true); // Loaded
  394. rb.Push<u32>(0); // Applet Attributes
  395. } else {
  396. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  397. rb.Push(ResultCode(ErrorDescription::NotFound, ErrorModule::Applet, ErrorSummary::NotFound,
  398. ErrorLevel::Status));
  399. }
  400. LOG_WARNING(Service_APT, "(stubbed) called appid=%u", app_id);
  401. }
  402. void GetStartupArgument(Service::Interface* self) {
  403. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x51, 2, 0); // 0x00510080
  404. u32 parameter_size = rp.Pop<u32>();
  405. StartupArgumentType startup_argument_type = static_cast<StartupArgumentType>(rp.Pop<u8>());
  406. if (parameter_size >= 0x300) {
  407. LOG_ERROR(
  408. Service_APT,
  409. "Parameter size is outside the valid range (capped to 0x300): parameter_size=0x%08x",
  410. parameter_size);
  411. return;
  412. }
  413. size_t static_buff_size;
  414. VAddr addr = rp.PeekStaticBuffer(0, &static_buff_size);
  415. if (parameter_size > static_buff_size)
  416. LOG_WARNING(
  417. Service_APT,
  418. "parameter_size is bigger than the size in the buffer descriptor (0x%08X > 0x%08zX)",
  419. parameter_size, static_buff_size);
  420. if (addr && parameter_size) {
  421. Memory::ZeroBlock(addr, parameter_size);
  422. }
  423. LOG_WARNING(Service_APT, "(stubbed) called startup_argument_type=%u , parameter_size=0x%08x",
  424. startup_argument_type, parameter_size);
  425. IPC::RequestBuilder rb = rp.MakeBuilder(2, 2);
  426. rb.Push(RESULT_SUCCESS);
  427. rb.Push<u32>(0);
  428. rb.PushStaticBuffer(addr, parameter_size, 0);
  429. }
  430. void Wrap(Service::Interface* self) {
  431. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x46, 4, 4);
  432. const u32 output_size = rp.Pop<u32>();
  433. const u32 input_size = rp.Pop<u32>();
  434. const u32 nonce_offset = rp.Pop<u32>();
  435. u32 nonce_size = rp.Pop<u32>();
  436. size_t desc_size;
  437. IPC::MappedBufferPermissions desc_permission;
  438. const VAddr input = rp.PopMappedBuffer(&desc_size, &desc_permission);
  439. ASSERT(desc_size == input_size && desc_permission == IPC::MappedBufferPermissions::R);
  440. const VAddr output = rp.PopMappedBuffer(&desc_size, &desc_permission);
  441. ASSERT(desc_size == output_size && desc_permission == IPC::MappedBufferPermissions::W);
  442. // Note: real 3DS still returns SUCCESS when the sizes don't match. It seems that it doesn't
  443. // check the buffer size and writes data with potential overflow.
  444. ASSERT_MSG(output_size == input_size + HW::AES::CCM_MAC_SIZE,
  445. "input_size (%d) doesn't match to output_size (%d)", input_size, output_size);
  446. LOG_DEBUG(Service_APT, "called, output_size=%u, input_size=%u, nonce_offset=%u, nonce_size=%u",
  447. output_size, input_size, nonce_offset, nonce_size);
  448. // Note: This weird nonce size modification is verified against real 3DS
  449. nonce_size = std::min<u32>(nonce_size & ~3, HW::AES::CCM_NONCE_SIZE);
  450. // Reads nonce and concatenates the rest of the input as plaintext
  451. HW::AES::CCMNonce nonce{};
  452. Memory::ReadBlock(input + nonce_offset, nonce.data(), nonce_size);
  453. u32 pdata_size = input_size - nonce_size;
  454. std::vector<u8> pdata(pdata_size);
  455. Memory::ReadBlock(input, pdata.data(), nonce_offset);
  456. Memory::ReadBlock(input + nonce_offset + nonce_size, pdata.data() + nonce_offset,
  457. pdata_size - nonce_offset);
  458. // Encrypts the plaintext using AES-CCM
  459. auto cipher = HW::AES::EncryptSignCCM(pdata, nonce, HW::AES::KeySlotID::APTWrap);
  460. // Puts the nonce to the beginning of the output, with ciphertext followed
  461. Memory::WriteBlock(output, nonce.data(), nonce_size);
  462. Memory::WriteBlock(output + nonce_size, cipher.data(), cipher.size());
  463. IPC::RequestBuilder rb = rp.MakeBuilder(1, 4);
  464. rb.Push(RESULT_SUCCESS);
  465. // Unmap buffer
  466. rb.PushMappedBuffer(input, input_size, IPC::MappedBufferPermissions::R);
  467. rb.PushMappedBuffer(output, output_size, IPC::MappedBufferPermissions::W);
  468. }
  469. void Unwrap(Service::Interface* self) {
  470. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x47, 4, 4);
  471. const u32 output_size = rp.Pop<u32>();
  472. const u32 input_size = rp.Pop<u32>();
  473. const u32 nonce_offset = rp.Pop<u32>();
  474. u32 nonce_size = rp.Pop<u32>();
  475. size_t desc_size;
  476. IPC::MappedBufferPermissions desc_permission;
  477. const VAddr input = rp.PopMappedBuffer(&desc_size, &desc_permission);
  478. ASSERT(desc_size == input_size && desc_permission == IPC::MappedBufferPermissions::R);
  479. const VAddr output = rp.PopMappedBuffer(&desc_size, &desc_permission);
  480. ASSERT(desc_size == output_size && desc_permission == IPC::MappedBufferPermissions::W);
  481. // Note: real 3DS still returns SUCCESS when the sizes don't match. It seems that it doesn't
  482. // check the buffer size and writes data with potential overflow.
  483. ASSERT_MSG(output_size == input_size - HW::AES::CCM_MAC_SIZE,
  484. "input_size (%d) doesn't match to output_size (%d)", input_size, output_size);
  485. LOG_DEBUG(Service_APT, "called, output_size=%u, input_size=%u, nonce_offset=%u, nonce_size=%u",
  486. output_size, input_size, nonce_offset, nonce_size);
  487. // Note: This weird nonce size modification is verified against real 3DS
  488. nonce_size = std::min<u32>(nonce_size & ~3, HW::AES::CCM_NONCE_SIZE);
  489. // Reads nonce and cipher text
  490. HW::AES::CCMNonce nonce{};
  491. Memory::ReadBlock(input, nonce.data(), nonce_size);
  492. u32 cipher_size = input_size - nonce_size;
  493. std::vector<u8> cipher(cipher_size);
  494. Memory::ReadBlock(input + nonce_size, cipher.data(), cipher_size);
  495. // Decrypts the ciphertext using AES-CCM
  496. auto pdata = HW::AES::DecryptVerifyCCM(cipher, nonce, HW::AES::KeySlotID::APTWrap);
  497. IPC::RequestBuilder rb = rp.MakeBuilder(1, 4);
  498. if (!pdata.empty()) {
  499. // Splits the plaintext and put the nonce in between
  500. Memory::WriteBlock(output, pdata.data(), nonce_offset);
  501. Memory::WriteBlock(output + nonce_offset, nonce.data(), nonce_size);
  502. Memory::WriteBlock(output + nonce_offset + nonce_size, pdata.data() + nonce_offset,
  503. pdata.size() - nonce_offset);
  504. rb.Push(RESULT_SUCCESS);
  505. } else {
  506. LOG_ERROR(Service_APT, "Failed to decrypt data");
  507. rb.Push(ResultCode(static_cast<ErrorDescription>(1), ErrorModule::PS,
  508. ErrorSummary::WrongArgument, ErrorLevel::Status));
  509. }
  510. // Unmap buffer
  511. rb.PushMappedBuffer(input, input_size, IPC::MappedBufferPermissions::R);
  512. rb.PushMappedBuffer(output, output_size, IPC::MappedBufferPermissions::W);
  513. }
  514. void CheckNew3DSApp(Service::Interface* self) {
  515. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x101, 0, 0); // 0x01010000
  516. IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
  517. if (unknown_ns_state_field) {
  518. rb.Push(RESULT_SUCCESS);
  519. rb.Push<u32>(0);
  520. } else {
  521. PTM::CheckNew3DS(rb);
  522. }
  523. LOG_WARNING(Service_APT, "(STUBBED) called");
  524. }
  525. void CheckNew3DS(Service::Interface* self) {
  526. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x102, 0, 0); // 0x01020000
  527. IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
  528. PTM::CheckNew3DS(rb);
  529. LOG_WARNING(Service_APT, "(STUBBED) called");
  530. }
  531. static u32 DecompressLZ11(const u8* in, u8* out) {
  532. u32_le decompressed_size;
  533. memcpy(&decompressed_size, in, sizeof(u32));
  534. in += 4;
  535. u8 type = decompressed_size & 0xFF;
  536. ASSERT(type == 0x11);
  537. decompressed_size >>= 8;
  538. u32 current_out_size = 0;
  539. u8 flags = 0, mask = 1;
  540. while (current_out_size < decompressed_size) {
  541. if (mask == 1) {
  542. flags = *(in++);
  543. mask = 0x80;
  544. } else {
  545. mask >>= 1;
  546. }
  547. if (flags & mask) {
  548. u8 byte1 = *(in++);
  549. u32 length = byte1 >> 4;
  550. u32 offset;
  551. if (length == 0) {
  552. u8 byte2 = *(in++);
  553. u8 byte3 = *(in++);
  554. length = (((byte1 & 0x0F) << 4) | (byte2 >> 4)) + 0x11;
  555. offset = (((byte2 & 0x0F) << 8) | byte3) + 0x1;
  556. } else if (length == 1) {
  557. u8 byte2 = *(in++);
  558. u8 byte3 = *(in++);
  559. u8 byte4 = *(in++);
  560. length = (((byte1 & 0x0F) << 12) | (byte2 << 4) | (byte3 >> 4)) + 0x111;
  561. offset = (((byte3 & 0x0F) << 8) | byte4) + 0x1;
  562. } else {
  563. u8 byte2 = *(in++);
  564. length = (byte1 >> 4) + 0x1;
  565. offset = (((byte1 & 0x0F) << 8) | byte2) + 0x1;
  566. }
  567. for (u32 i = 0; i < length; i++) {
  568. *out = *(out - offset);
  569. ++out;
  570. }
  571. current_out_size += length;
  572. } else {
  573. *(out++) = *(in++);
  574. current_out_size++;
  575. }
  576. }
  577. return decompressed_size;
  578. }
  579. static bool LoadSharedFont() {
  580. // TODO (wwylele): load different font archive for region CHN/KOR/TWN
  581. const u64_le shared_font_archive_id_low = 0x0004009b00014002;
  582. const u64_le shared_font_archive_id_high = 0x00000001ffffff00;
  583. std::vector<u8> shared_font_archive_id(16);
  584. std::memcpy(&shared_font_archive_id[0], &shared_font_archive_id_low, sizeof(u64));
  585. std::memcpy(&shared_font_archive_id[8], &shared_font_archive_id_high, sizeof(u64));
  586. FileSys::Path archive_path(shared_font_archive_id);
  587. auto archive_result = Service::FS::OpenArchive(Service::FS::ArchiveIdCode::NCCH, archive_path);
  588. if (archive_result.Failed())
  589. return false;
  590. std::vector<u8> romfs_path(20, 0); // 20-byte all zero path for opening RomFS
  591. FileSys::Path file_path(romfs_path);
  592. FileSys::Mode open_mode = {};
  593. open_mode.read_flag.Assign(1);
  594. auto file_result = Service::FS::OpenFileFromArchive(*archive_result, file_path, open_mode);
  595. if (file_result.Failed())
  596. return false;
  597. auto romfs = std::move(file_result).Unwrap();
  598. std::vector<u8> romfs_buffer(romfs->backend->GetSize());
  599. romfs->backend->Read(0, romfs_buffer.size(), romfs_buffer.data());
  600. romfs->backend->Close();
  601. const u8* font_file = RomFS::GetFilePointer(romfs_buffer.data(), {u"cbf_std.bcfnt.lz"});
  602. if (font_file == nullptr)
  603. return false;
  604. struct {
  605. u32_le status;
  606. u32_le region;
  607. u32_le decompressed_size;
  608. INSERT_PADDING_WORDS(0x1D);
  609. } shared_font_header{};
  610. static_assert(sizeof(shared_font_header) == 0x80, "shared_font_header has incorrect size");
  611. shared_font_header.status = 2; // successfully loaded
  612. shared_font_header.region = 1; // region JPN/EUR/USA
  613. shared_font_header.decompressed_size =
  614. DecompressLZ11(font_file, shared_font_mem->GetPointer(0x80));
  615. std::memcpy(shared_font_mem->GetPointer(), &shared_font_header, sizeof(shared_font_header));
  616. *shared_font_mem->GetPointer(0x83) = 'U'; // Change the magic from "CFNT" to "CFNU"
  617. return true;
  618. }
  619. static bool LoadLegacySharedFont() {
  620. // This is the legacy method to load shared font.
  621. // The expected format is a decrypted, uncompressed BCFNT file with the 0x80 byte header
  622. // generated by the APT:U service. The best way to get is by dumping it from RAM. We've provided
  623. // a homebrew app to do this: https://github.com/citra-emu/3dsutils. Put the resulting file
  624. // "shared_font.bin" in the Citra "sysdata" directory.
  625. std::string filepath = FileUtil::GetUserPath(D_SYSDATA_IDX) + SHARED_FONT;
  626. FileUtil::CreateFullPath(filepath); // Create path if not already created
  627. FileUtil::IOFile file(filepath, "rb");
  628. if (file.IsOpen()) {
  629. file.ReadBytes(shared_font_mem->GetPointer(), file.GetSize());
  630. return true;
  631. }
  632. return false;
  633. }
  634. void Init() {
  635. AddService(new APT_A_Interface);
  636. AddService(new APT_S_Interface);
  637. AddService(new APT_U_Interface);
  638. HLE::Applets::Init();
  639. using Kernel::MemoryPermission;
  640. shared_font_mem =
  641. Kernel::SharedMemory::Create(nullptr, 0x332000, // 3272 KB
  642. MemoryPermission::ReadWrite, MemoryPermission::Read, 0,
  643. Kernel::MemoryRegion::SYSTEM, "APT:SharedFont");
  644. if (LoadSharedFont()) {
  645. shared_font_loaded = true;
  646. } else if (LoadLegacySharedFont()) {
  647. LOG_WARNING(Service_APT, "Loaded shared font by legacy method");
  648. shared_font_loaded = true;
  649. } else {
  650. LOG_WARNING(Service_APT, "Unable to load shared font");
  651. shared_font_loaded = false;
  652. }
  653. lock = Kernel::Mutex::Create(false, "APT_U:Lock");
  654. cpu_percent = 0;
  655. unknown_ns_state_field = 0;
  656. screen_capture_post_permission =
  657. ScreencapPostPermission::CleanThePermission; // TODO(JamePeng): verify the initial value
  658. // TODO(bunnei): Check if these are created in Initialize or on APT process startup.
  659. notification_event = Kernel::Event::Create(Kernel::ResetType::OneShot, "APT_U:Notification");
  660. parameter_event = Kernel::Event::Create(Kernel::ResetType::OneShot, "APT_U:Start");
  661. // Initialize the parameter to wake up the application.
  662. next_parameter.emplace();
  663. next_parameter->signal = static_cast<u32>(SignalType::Wakeup);
  664. next_parameter->destination_id = static_cast<u32>(AppletId::Application);
  665. }
  666. void Shutdown() {
  667. shared_font_mem = nullptr;
  668. shared_font_loaded = false;
  669. shared_font_relocated = false;
  670. lock = nullptr;
  671. notification_event = nullptr;
  672. parameter_event = nullptr;
  673. next_parameter = boost::none;
  674. HLE::Applets::Shutdown();
  675. }
  676. } // namespace APT
  677. } // namespace Service