apt.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  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. if (!next_parameter) {
  193. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  194. rb.Push(ResultCode(ErrorDescription::NoData, ErrorModule::Applet,
  195. ErrorSummary::InvalidState, ErrorLevel::Status));
  196. return;
  197. }
  198. if (next_parameter->destination_id != app_id) {
  199. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  200. rb.Push(ResultCode(ErrorDescription::NotFound, ErrorModule::Applet, ErrorSummary::NotFound,
  201. ErrorLevel::Status));
  202. return;
  203. }
  204. IPC::RequestBuilder rb = rp.MakeBuilder(4, 4);
  205. rb.Push(RESULT_SUCCESS); // No error
  206. rb.Push(next_parameter->sender_id);
  207. rb.Push(next_parameter->signal); // Signal type
  208. ASSERT_MSG(next_parameter->buffer.size() <= buffer_size, "Input static buffer is too small !");
  209. rb.Push(static_cast<u32>(next_parameter->buffer.size())); // Parameter buffer size
  210. rb.PushMoveHandles((next_parameter->object != nullptr)
  211. ? Kernel::g_handle_table.Create(next_parameter->object).Unwrap()
  212. : 0);
  213. rb.PushStaticBuffer(buffer, static_cast<u32>(next_parameter->buffer.size()), 0);
  214. Memory::WriteBlock(buffer, next_parameter->buffer.data(), next_parameter->buffer.size());
  215. LOG_WARNING(Service_APT, "called app_id=0x%08X, buffer_size=0x%08zX", app_id, buffer_size);
  216. }
  217. void GlanceParameter(Service::Interface* self) {
  218. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0xE, 2, 0); // 0xE0080
  219. u32 app_id = rp.Pop<u32>();
  220. u32 buffer_size = rp.Pop<u32>();
  221. size_t static_buff_size;
  222. VAddr buffer = rp.PeekStaticBuffer(0, &static_buff_size);
  223. if (buffer_size > static_buff_size)
  224. LOG_WARNING(
  225. Service_APT,
  226. "buffer_size is bigger than the size in the buffer descriptor (0x%08X > 0x%08zX)",
  227. buffer_size, static_buff_size);
  228. if (!next_parameter) {
  229. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  230. rb.Push(ResultCode(ErrorDescription::NoData, ErrorModule::Applet,
  231. ErrorSummary::InvalidState, ErrorLevel::Status));
  232. return;
  233. }
  234. if (next_parameter->destination_id != app_id) {
  235. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  236. rb.Push(ResultCode(ErrorDescription::NotFound, ErrorModule::Applet, ErrorSummary::NotFound,
  237. ErrorLevel::Status));
  238. return;
  239. }
  240. IPC::RequestBuilder rb = rp.MakeBuilder(4, 4);
  241. rb.Push(RESULT_SUCCESS); // No error
  242. rb.Push(next_parameter->sender_id);
  243. rb.Push(next_parameter->signal); // Signal type
  244. ASSERT_MSG(next_parameter->buffer.size() <= buffer_size, "Input static buffer is too small !");
  245. rb.Push(static_cast<u32>(next_parameter->buffer.size())); // Parameter buffer size
  246. rb.PushMoveHandles((next_parameter->object != nullptr)
  247. ? Kernel::g_handle_table.Create(next_parameter->object).Unwrap()
  248. : 0);
  249. rb.PushStaticBuffer(buffer, static_cast<u32>(next_parameter->buffer.size()), 0);
  250. Memory::WriteBlock(buffer, next_parameter->buffer.data(), next_parameter->buffer.size());
  251. LOG_WARNING(Service_APT, "called app_id=0x%08X, buffer_size=0x%08zX", app_id, buffer_size);
  252. }
  253. void CancelParameter(Service::Interface* self) {
  254. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0xF, 4, 0); // 0xF0100
  255. u32 check_sender = rp.Pop<u32>();
  256. u32 sender_appid = rp.Pop<u32>();
  257. u32 check_receiver = rp.Pop<u32>();
  258. u32 receiver_appid = rp.Pop<u32>();
  259. IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
  260. rb.Push(RESULT_SUCCESS); // No error
  261. rb.Push(true); // Set to Success
  262. LOG_WARNING(Service_APT, "(STUBBED) called check_sender=0x%08X, sender_appid=0x%08X, "
  263. "check_receiver=0x%08X, receiver_appid=0x%08X",
  264. check_sender, sender_appid, check_receiver, receiver_appid);
  265. }
  266. void PrepareToStartApplication(Service::Interface* self) {
  267. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x15, 5, 0); // 0x00150140
  268. u32 title_info1 = rp.Pop<u32>();
  269. u32 title_info2 = rp.Pop<u32>();
  270. u32 title_info3 = rp.Pop<u32>();
  271. u32 title_info4 = rp.Pop<u32>();
  272. u32 flags = rp.Pop<u32>();
  273. if (flags & 0x00000100) {
  274. unknown_ns_state_field = 1;
  275. }
  276. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  277. rb.Push(RESULT_SUCCESS); // No error
  278. LOG_WARNING(Service_APT,
  279. "(STUBBED) called title_info1=0x%08X, title_info2=0x%08X, title_info3=0x%08X,"
  280. "title_info4=0x%08X, flags=0x%08X",
  281. title_info1, title_info2, title_info3, title_info4, flags);
  282. }
  283. void StartApplication(Service::Interface* self) {
  284. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1B, 3, 4); // 0x001B00C4
  285. u32 buffer1_size = rp.Pop<u32>();
  286. u32 buffer2_size = rp.Pop<u32>();
  287. u32 flag = rp.Pop<u32>();
  288. size_t size1;
  289. VAddr buffer1_ptr = rp.PopStaticBuffer(&size1);
  290. size_t size2;
  291. VAddr buffer2_ptr = rp.PopStaticBuffer(&size2);
  292. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  293. rb.Push(RESULT_SUCCESS); // No error
  294. LOG_WARNING(Service_APT,
  295. "(STUBBED) called buffer1_size=0x%08X, buffer2_size=0x%08X, flag=0x%08X,"
  296. "size1=0x%08zX, buffer1_ptr=0x%08X, size2=0x%08zX, buffer2_ptr=0x%08X",
  297. buffer1_size, buffer2_size, flag, size1, buffer1_ptr, size2, buffer2_ptr);
  298. }
  299. void AppletUtility(Service::Interface* self) {
  300. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x4B, 3, 2); // 0x004B00C2
  301. // These are from 3dbrew - I'm not really sure what they're used for.
  302. u32 utility_command = rp.Pop<u32>();
  303. u32 input_size = rp.Pop<u32>();
  304. u32 output_size = rp.Pop<u32>();
  305. VAddr input_addr = rp.PopStaticBuffer();
  306. VAddr output_addr = rp.PeekStaticBuffer(0);
  307. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  308. rb.Push(RESULT_SUCCESS); // No error
  309. LOG_WARNING(Service_APT,
  310. "(STUBBED) called command=0x%08X, input_size=0x%08X, output_size=0x%08X, "
  311. "input_addr=0x%08X, output_addr=0x%08X",
  312. utility_command, input_size, output_size, input_addr, output_addr);
  313. }
  314. void SetAppCpuTimeLimit(Service::Interface* self) {
  315. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x4F, 2, 0); // 0x4F0080
  316. u32 value = rp.Pop<u32>();
  317. cpu_percent = rp.Pop<u32>();
  318. if (value != 1) {
  319. LOG_ERROR(Service_APT, "This value should be one, but is actually %u!", value);
  320. }
  321. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  322. rb.Push(RESULT_SUCCESS); // No error
  323. LOG_WARNING(Service_APT, "(STUBBED) called cpu_percent=%u, value=%u", cpu_percent, value);
  324. }
  325. void GetAppCpuTimeLimit(Service::Interface* self) {
  326. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x50, 1, 0); // 0x500040
  327. u32 value = rp.Pop<u32>();
  328. if (value != 1) {
  329. LOG_ERROR(Service_APT, "This value should be one, but is actually %u!", value);
  330. }
  331. IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
  332. rb.Push(RESULT_SUCCESS); // No error
  333. rb.Push(cpu_percent);
  334. LOG_WARNING(Service_APT, "(STUBBED) called value=%u", value);
  335. }
  336. void PrepareToStartLibraryApplet(Service::Interface* self) {
  337. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x18, 1, 0); // 0x180040
  338. AppletId applet_id = static_cast<AppletId>(rp.Pop<u32>());
  339. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  340. auto applet = HLE::Applets::Applet::Get(applet_id);
  341. if (applet) {
  342. LOG_WARNING(Service_APT, "applet has already been started id=%08X", applet_id);
  343. rb.Push(RESULT_SUCCESS);
  344. } else {
  345. rb.Push(HLE::Applets::Applet::Create(applet_id));
  346. }
  347. LOG_DEBUG(Service_APT, "called applet_id=%08X", applet_id);
  348. }
  349. void PreloadLibraryApplet(Service::Interface* self) {
  350. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x16, 1, 0); // 0x160040
  351. AppletId applet_id = static_cast<AppletId>(rp.Pop<u32>());
  352. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  353. auto applet = HLE::Applets::Applet::Get(applet_id);
  354. if (applet) {
  355. LOG_WARNING(Service_APT, "applet has already been started id=%08X", applet_id);
  356. rb.Push(RESULT_SUCCESS);
  357. } else {
  358. rb.Push(HLE::Applets::Applet::Create(applet_id));
  359. }
  360. LOG_DEBUG(Service_APT, "called applet_id=%08X", applet_id);
  361. }
  362. void StartLibraryApplet(Service::Interface* self) {
  363. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1E, 2, 4); // 0x1E0084
  364. AppletId applet_id = static_cast<AppletId>(rp.Pop<u32>());
  365. std::shared_ptr<HLE::Applets::Applet> applet = HLE::Applets::Applet::Get(applet_id);
  366. LOG_DEBUG(Service_APT, "called applet_id=%08X", applet_id);
  367. if (applet == nullptr) {
  368. LOG_ERROR(Service_APT, "unknown applet id=%08X", applet_id);
  369. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0, false);
  370. rb.Push<u32>(-1); // TODO(Subv): Find the right error code
  371. return;
  372. }
  373. size_t buffer_size = rp.Pop<u32>();
  374. Kernel::Handle handle = rp.PopHandle();
  375. VAddr buffer_addr = rp.PopStaticBuffer();
  376. AppletStartupParameter parameter;
  377. parameter.object = Kernel::g_handle_table.GetGeneric(handle);
  378. parameter.buffer.resize(buffer_size);
  379. Memory::ReadBlock(buffer_addr, parameter.buffer.data(), parameter.buffer.size());
  380. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  381. rb.Push(applet->Start(parameter));
  382. }
  383. void CancelLibraryApplet(Service::Interface* self) {
  384. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x3B, 1, 0); // 0x003B0040
  385. bool exiting = rp.Pop<bool>();
  386. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  387. rb.Push<u32>(1); // TODO: Find the return code meaning
  388. LOG_WARNING(Service_APT, "(STUBBED) called exiting=%d", exiting);
  389. }
  390. void SetScreenCapPostPermission(Service::Interface* self) {
  391. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x55, 1, 0); // 0x00550040
  392. screen_capture_post_permission = static_cast<ScreencapPostPermission>(rp.Pop<u32>() & 0xF);
  393. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  394. rb.Push(RESULT_SUCCESS); // No error
  395. LOG_WARNING(Service_APT, "(STUBBED) screen_capture_post_permission=%u",
  396. screen_capture_post_permission);
  397. }
  398. void GetScreenCapPostPermission(Service::Interface* self) {
  399. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x56, 0, 0); // 0x00560000
  400. IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
  401. rb.Push(RESULT_SUCCESS); // No error
  402. rb.Push(static_cast<u32>(screen_capture_post_permission));
  403. LOG_WARNING(Service_APT, "(STUBBED) screen_capture_post_permission=%u",
  404. screen_capture_post_permission);
  405. }
  406. void GetAppletInfo(Service::Interface* self) {
  407. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x6, 1, 0); // 0x60040
  408. auto app_id = static_cast<AppletId>(rp.Pop<u32>());
  409. if (auto applet = HLE::Applets::Applet::Get(app_id)) {
  410. // TODO(Subv): Get the title id for the current applet and write it in the response[2-3]
  411. IPC::RequestBuilder rb = rp.MakeBuilder(7, 0);
  412. rb.Push(RESULT_SUCCESS);
  413. u64 title_id = 0;
  414. rb.Push(title_id);
  415. rb.Push(static_cast<u32>(Service::FS::MediaType::NAND));
  416. rb.Push(true); // Registered
  417. rb.Push(true); // Loaded
  418. rb.Push<u32>(0); // Applet Attributes
  419. } else {
  420. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  421. rb.Push(ResultCode(ErrorDescription::NotFound, ErrorModule::Applet, ErrorSummary::NotFound,
  422. ErrorLevel::Status));
  423. }
  424. LOG_WARNING(Service_APT, "(stubbed) called appid=%u", app_id);
  425. }
  426. void GetStartupArgument(Service::Interface* self) {
  427. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x51, 2, 0); // 0x00510080
  428. u32 parameter_size = rp.Pop<u32>();
  429. StartupArgumentType startup_argument_type = static_cast<StartupArgumentType>(rp.Pop<u8>());
  430. if (parameter_size >= 0x300) {
  431. LOG_ERROR(
  432. Service_APT,
  433. "Parameter size is outside the valid range (capped to 0x300): parameter_size=0x%08x",
  434. parameter_size);
  435. return;
  436. }
  437. size_t static_buff_size;
  438. VAddr addr = rp.PeekStaticBuffer(0, &static_buff_size);
  439. if (parameter_size > static_buff_size)
  440. LOG_WARNING(
  441. Service_APT,
  442. "parameter_size is bigger than the size in the buffer descriptor (0x%08X > 0x%08zX)",
  443. parameter_size, static_buff_size);
  444. if (addr && parameter_size) {
  445. Memory::ZeroBlock(addr, parameter_size);
  446. }
  447. LOG_WARNING(Service_APT, "(stubbed) called startup_argument_type=%u , parameter_size=0x%08x",
  448. startup_argument_type, parameter_size);
  449. IPC::RequestBuilder rb = rp.MakeBuilder(2, 2);
  450. rb.Push(RESULT_SUCCESS);
  451. rb.Push<u32>(0);
  452. rb.PushStaticBuffer(addr, parameter_size, 0);
  453. }
  454. void Wrap(Service::Interface* self) {
  455. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x46, 4, 4);
  456. const u32 output_size = rp.Pop<u32>();
  457. const u32 input_size = rp.Pop<u32>();
  458. const u32 nonce_offset = rp.Pop<u32>();
  459. u32 nonce_size = rp.Pop<u32>();
  460. size_t desc_size;
  461. IPC::MappedBufferPermissions desc_permission;
  462. const VAddr input = rp.PopMappedBuffer(&desc_size, &desc_permission);
  463. ASSERT(desc_size == input_size && desc_permission == IPC::MappedBufferPermissions::R);
  464. const VAddr output = rp.PopMappedBuffer(&desc_size, &desc_permission);
  465. ASSERT(desc_size == output_size && desc_permission == IPC::MappedBufferPermissions::W);
  466. // Note: real 3DS still returns SUCCESS when the sizes don't match. It seems that it doesn't
  467. // check the buffer size and writes data with potential overflow.
  468. ASSERT_MSG(output_size == input_size + HW::AES::CCM_MAC_SIZE,
  469. "input_size (%d) doesn't match to output_size (%d)", input_size, output_size);
  470. LOG_DEBUG(Service_APT, "called, output_size=%u, input_size=%u, nonce_offset=%u, nonce_size=%u",
  471. output_size, input_size, nonce_offset, nonce_size);
  472. // Note: This weird nonce size modification is verified against real 3DS
  473. nonce_size = std::min<u32>(nonce_size & ~3, HW::AES::CCM_NONCE_SIZE);
  474. // Reads nonce and concatenates the rest of the input as plaintext
  475. HW::AES::CCMNonce nonce{};
  476. Memory::ReadBlock(input + nonce_offset, nonce.data(), nonce_size);
  477. u32 pdata_size = input_size - nonce_size;
  478. std::vector<u8> pdata(pdata_size);
  479. Memory::ReadBlock(input, pdata.data(), nonce_offset);
  480. Memory::ReadBlock(input + nonce_offset + nonce_size, pdata.data() + nonce_offset,
  481. pdata_size - nonce_offset);
  482. // Encrypts the plaintext using AES-CCM
  483. auto cipher = HW::AES::EncryptSignCCM(pdata, nonce, HW::AES::KeySlotID::APTWrap);
  484. // Puts the nonce to the beginning of the output, with ciphertext followed
  485. Memory::WriteBlock(output, nonce.data(), nonce_size);
  486. Memory::WriteBlock(output + nonce_size, cipher.data(), cipher.size());
  487. IPC::RequestBuilder rb = rp.MakeBuilder(1, 4);
  488. rb.Push(RESULT_SUCCESS);
  489. // Unmap buffer
  490. rb.PushMappedBuffer(input, input_size, IPC::MappedBufferPermissions::R);
  491. rb.PushMappedBuffer(output, output_size, IPC::MappedBufferPermissions::W);
  492. }
  493. void Unwrap(Service::Interface* self) {
  494. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x47, 4, 4);
  495. const u32 output_size = rp.Pop<u32>();
  496. const u32 input_size = rp.Pop<u32>();
  497. const u32 nonce_offset = rp.Pop<u32>();
  498. u32 nonce_size = rp.Pop<u32>();
  499. size_t desc_size;
  500. IPC::MappedBufferPermissions desc_permission;
  501. const VAddr input = rp.PopMappedBuffer(&desc_size, &desc_permission);
  502. ASSERT(desc_size == input_size && desc_permission == IPC::MappedBufferPermissions::R);
  503. const VAddr output = rp.PopMappedBuffer(&desc_size, &desc_permission);
  504. ASSERT(desc_size == output_size && desc_permission == IPC::MappedBufferPermissions::W);
  505. // Note: real 3DS still returns SUCCESS when the sizes don't match. It seems that it doesn't
  506. // check the buffer size and writes data with potential overflow.
  507. ASSERT_MSG(output_size == input_size - HW::AES::CCM_MAC_SIZE,
  508. "input_size (%d) doesn't match to output_size (%d)", input_size, output_size);
  509. LOG_DEBUG(Service_APT, "called, output_size=%u, input_size=%u, nonce_offset=%u, nonce_size=%u",
  510. output_size, input_size, nonce_offset, nonce_size);
  511. // Note: This weird nonce size modification is verified against real 3DS
  512. nonce_size = std::min<u32>(nonce_size & ~3, HW::AES::CCM_NONCE_SIZE);
  513. // Reads nonce and cipher text
  514. HW::AES::CCMNonce nonce{};
  515. Memory::ReadBlock(input, nonce.data(), nonce_size);
  516. u32 cipher_size = input_size - nonce_size;
  517. std::vector<u8> cipher(cipher_size);
  518. Memory::ReadBlock(input + nonce_size, cipher.data(), cipher_size);
  519. // Decrypts the ciphertext using AES-CCM
  520. auto pdata = HW::AES::DecryptVerifyCCM(cipher, nonce, HW::AES::KeySlotID::APTWrap);
  521. IPC::RequestBuilder rb = rp.MakeBuilder(1, 4);
  522. if (!pdata.empty()) {
  523. // Splits the plaintext and put the nonce in between
  524. Memory::WriteBlock(output, pdata.data(), nonce_offset);
  525. Memory::WriteBlock(output + nonce_offset, nonce.data(), nonce_size);
  526. Memory::WriteBlock(output + nonce_offset + nonce_size, pdata.data() + nonce_offset,
  527. pdata.size() - nonce_offset);
  528. rb.Push(RESULT_SUCCESS);
  529. } else {
  530. LOG_ERROR(Service_APT, "Failed to decrypt data");
  531. rb.Push(ResultCode(static_cast<ErrorDescription>(1), ErrorModule::PS,
  532. ErrorSummary::WrongArgument, ErrorLevel::Status));
  533. }
  534. // Unmap buffer
  535. rb.PushMappedBuffer(input, input_size, IPC::MappedBufferPermissions::R);
  536. rb.PushMappedBuffer(output, output_size, IPC::MappedBufferPermissions::W);
  537. }
  538. void CheckNew3DSApp(Service::Interface* self) {
  539. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x101, 0, 0); // 0x01010000
  540. IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
  541. if (unknown_ns_state_field) {
  542. rb.Push(RESULT_SUCCESS);
  543. rb.Push<u32>(0);
  544. } else {
  545. PTM::CheckNew3DS(rb);
  546. }
  547. LOG_WARNING(Service_APT, "(STUBBED) called");
  548. }
  549. void CheckNew3DS(Service::Interface* self) {
  550. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x102, 0, 0); // 0x01020000
  551. IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
  552. PTM::CheckNew3DS(rb);
  553. LOG_WARNING(Service_APT, "(STUBBED) called");
  554. }
  555. static u32 DecompressLZ11(const u8* in, u8* out) {
  556. u32_le decompressed_size;
  557. memcpy(&decompressed_size, in, sizeof(u32));
  558. in += 4;
  559. u8 type = decompressed_size & 0xFF;
  560. ASSERT(type == 0x11);
  561. decompressed_size >>= 8;
  562. u32 current_out_size = 0;
  563. u8 flags = 0, mask = 1;
  564. while (current_out_size < decompressed_size) {
  565. if (mask == 1) {
  566. flags = *(in++);
  567. mask = 0x80;
  568. } else {
  569. mask >>= 1;
  570. }
  571. if (flags & mask) {
  572. u8 byte1 = *(in++);
  573. u32 length = byte1 >> 4;
  574. u32 offset;
  575. if (length == 0) {
  576. u8 byte2 = *(in++);
  577. u8 byte3 = *(in++);
  578. length = (((byte1 & 0x0F) << 4) | (byte2 >> 4)) + 0x11;
  579. offset = (((byte2 & 0x0F) << 8) | byte3) + 0x1;
  580. } else if (length == 1) {
  581. u8 byte2 = *(in++);
  582. u8 byte3 = *(in++);
  583. u8 byte4 = *(in++);
  584. length = (((byte1 & 0x0F) << 12) | (byte2 << 4) | (byte3 >> 4)) + 0x111;
  585. offset = (((byte3 & 0x0F) << 8) | byte4) + 0x1;
  586. } else {
  587. u8 byte2 = *(in++);
  588. length = (byte1 >> 4) + 0x1;
  589. offset = (((byte1 & 0x0F) << 8) | byte2) + 0x1;
  590. }
  591. for (u32 i = 0; i < length; i++) {
  592. *out = *(out - offset);
  593. ++out;
  594. }
  595. current_out_size += length;
  596. } else {
  597. *(out++) = *(in++);
  598. current_out_size++;
  599. }
  600. }
  601. return decompressed_size;
  602. }
  603. static bool LoadSharedFont() {
  604. // TODO (wwylele): load different font archive for region CHN/KOR/TWN
  605. const u64_le shared_font_archive_id_low = 0x0004009b00014002;
  606. const u64_le shared_font_archive_id_high = 0x00000001ffffff00;
  607. std::vector<u8> shared_font_archive_id(16);
  608. std::memcpy(&shared_font_archive_id[0], &shared_font_archive_id_low, sizeof(u64));
  609. std::memcpy(&shared_font_archive_id[8], &shared_font_archive_id_high, sizeof(u64));
  610. FileSys::Path archive_path(shared_font_archive_id);
  611. auto archive_result = Service::FS::OpenArchive(Service::FS::ArchiveIdCode::NCCH, archive_path);
  612. if (archive_result.Failed())
  613. return false;
  614. std::vector<u8> romfs_path(20, 0); // 20-byte all zero path for opening RomFS
  615. FileSys::Path file_path(romfs_path);
  616. FileSys::Mode open_mode = {};
  617. open_mode.read_flag.Assign(1);
  618. auto file_result = Service::FS::OpenFileFromArchive(*archive_result, file_path, open_mode);
  619. if (file_result.Failed())
  620. return false;
  621. auto romfs = std::move(file_result).Unwrap();
  622. std::vector<u8> romfs_buffer(romfs->backend->GetSize());
  623. romfs->backend->Read(0, romfs_buffer.size(), romfs_buffer.data());
  624. romfs->backend->Close();
  625. const u8* font_file = RomFS::GetFilePointer(romfs_buffer.data(), {u"cbf_std.bcfnt.lz"});
  626. if (font_file == nullptr)
  627. return false;
  628. struct {
  629. u32_le status;
  630. u32_le region;
  631. u32_le decompressed_size;
  632. INSERT_PADDING_WORDS(0x1D);
  633. } shared_font_header{};
  634. static_assert(sizeof(shared_font_header) == 0x80, "shared_font_header has incorrect size");
  635. shared_font_header.status = 2; // successfully loaded
  636. shared_font_header.region = 1; // region JPN/EUR/USA
  637. shared_font_header.decompressed_size =
  638. DecompressLZ11(font_file, shared_font_mem->GetPointer(0x80));
  639. std::memcpy(shared_font_mem->GetPointer(), &shared_font_header, sizeof(shared_font_header));
  640. *shared_font_mem->GetPointer(0x83) = 'U'; // Change the magic from "CFNT" to "CFNU"
  641. return true;
  642. }
  643. static bool LoadLegacySharedFont() {
  644. // This is the legacy method to load shared font.
  645. // The expected format is a decrypted, uncompressed BCFNT file with the 0x80 byte header
  646. // generated by the APT:U service. The best way to get is by dumping it from RAM. We've provided
  647. // a homebrew app to do this: https://github.com/citra-emu/3dsutils. Put the resulting file
  648. // "shared_font.bin" in the Citra "sysdata" directory.
  649. std::string filepath = FileUtil::GetUserPath(D_SYSDATA_IDX) + SHARED_FONT;
  650. FileUtil::CreateFullPath(filepath); // Create path if not already created
  651. FileUtil::IOFile file(filepath, "rb");
  652. if (file.IsOpen()) {
  653. file.ReadBytes(shared_font_mem->GetPointer(), file.GetSize());
  654. return true;
  655. }
  656. return false;
  657. }
  658. void Init() {
  659. AddService(new APT_A_Interface);
  660. AddService(new APT_S_Interface);
  661. AddService(new APT_U_Interface);
  662. HLE::Applets::Init();
  663. using Kernel::MemoryPermission;
  664. shared_font_mem =
  665. Kernel::SharedMemory::Create(nullptr, 0x332000, // 3272 KB
  666. MemoryPermission::ReadWrite, MemoryPermission::Read, 0,
  667. Kernel::MemoryRegion::SYSTEM, "APT:SharedFont");
  668. if (LoadSharedFont()) {
  669. shared_font_loaded = true;
  670. } else if (LoadLegacySharedFont()) {
  671. LOG_WARNING(Service_APT, "Loaded shared font by legacy method");
  672. shared_font_loaded = true;
  673. } else {
  674. LOG_WARNING(Service_APT, "Unable to load shared font");
  675. shared_font_loaded = false;
  676. }
  677. lock = Kernel::Mutex::Create(false, "APT_U:Lock");
  678. cpu_percent = 0;
  679. unknown_ns_state_field = 0;
  680. screen_capture_post_permission =
  681. ScreencapPostPermission::CleanThePermission; // TODO(JamePeng): verify the initial value
  682. // TODO(bunnei): Check if these are created in Initialize or on APT process startup.
  683. notification_event = Kernel::Event::Create(Kernel::ResetType::OneShot, "APT_U:Notification");
  684. parameter_event = Kernel::Event::Create(Kernel::ResetType::OneShot, "APT_U:Start");
  685. // Initialize the parameter to wake up the application.
  686. next_parameter.emplace();
  687. next_parameter->signal = static_cast<u32>(SignalType::Wakeup);
  688. next_parameter->destination_id = static_cast<u32>(AppletId::Application);
  689. }
  690. void Shutdown() {
  691. shared_font_mem = nullptr;
  692. shared_font_loaded = false;
  693. shared_font_relocated = false;
  694. lock = nullptr;
  695. notification_event = nullptr;
  696. parameter_event = nullptr;
  697. next_parameter = boost::none;
  698. HLE::Applets::Shutdown();
  699. }
  700. } // namespace APT
  701. } // namespace Service