apt.cpp 32 KB

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