IApplicationFunctions.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. using LibHac;
  2. using LibHac.Account;
  3. using LibHac.Common;
  4. using LibHac.Fs;
  5. using LibHac.Ns;
  6. using Ryujinx.Common;
  7. using Ryujinx.Common.Logging;
  8. using Ryujinx.HLE.HOS.Ipc;
  9. using Ryujinx.HLE.HOS.Kernel.Common;
  10. using Ryujinx.HLE.HOS.Kernel.Memory;
  11. using Ryujinx.HLE.HOS.Kernel.Threading;
  12. using Ryujinx.HLE.HOS.Services.Am.AppletAE.Storage;
  13. using Ryujinx.HLE.HOS.Services.Am.AppletOE.ApplicationProxyService.ApplicationProxy.Types;
  14. using Ryujinx.HLE.HOS.Services.Sdb.Pdm.QueryService;
  15. using Ryujinx.HLE.HOS.SystemState;
  16. using System;
  17. using System.Numerics;
  18. using static LibHac.Fs.ApplicationSaveDataManagement;
  19. using AccountUid = Ryujinx.HLE.HOS.Services.Account.Acc.UserId;
  20. using ApplicationId = LibHac.Ncm.ApplicationId;
  21. namespace Ryujinx.HLE.HOS.Services.Am.AppletOE.ApplicationProxyService.ApplicationProxy
  22. {
  23. class IApplicationFunctions : IpcService
  24. {
  25. private KEvent _gpuErrorDetectedSystemEvent;
  26. private KEvent _friendInvitationStorageChannelEvent;
  27. private KEvent _notificationStorageChannelEvent;
  28. private KEvent _healthWarningDisappearedSystemEvent;
  29. private int _gpuErrorDetectedSystemEventHandle;
  30. private int _friendInvitationStorageChannelEventHandle;
  31. private int _notificationStorageChannelEventHandle;
  32. private int _healthWarningDisappearedSystemEventHandle;
  33. public IApplicationFunctions(Horizon system)
  34. {
  35. // TODO: Find where they are signaled.
  36. _gpuErrorDetectedSystemEvent = new KEvent(system.KernelContext);
  37. _friendInvitationStorageChannelEvent = new KEvent(system.KernelContext);
  38. _notificationStorageChannelEvent = new KEvent(system.KernelContext);
  39. _healthWarningDisappearedSystemEvent = new KEvent(system.KernelContext);
  40. }
  41. [Command(1)]
  42. // PopLaunchParameter(LaunchParameterKind kind) -> object<nn::am::service::IStorage>
  43. public ResultCode PopLaunchParameter(ServiceCtx context)
  44. {
  45. LaunchParameterKind kind = (LaunchParameterKind)context.RequestData.ReadUInt32();
  46. byte[] storageData;
  47. switch (kind)
  48. {
  49. case LaunchParameterKind.UserChannel:
  50. storageData = context.Device.UserChannelPersistence.Pop();
  51. break;
  52. case LaunchParameterKind.PreselectedUser:
  53. // Only the first 0x18 bytes of the Data seems to be actually used.
  54. storageData = StorageHelper.MakeLaunchParams(context.Device.System.State.Account.LastOpenedUser);
  55. break;
  56. case LaunchParameterKind.Unknown:
  57. throw new NotImplementedException("Unknown LaunchParameterKind.");
  58. default:
  59. return ResultCode.ObjectInvalid;
  60. }
  61. if (storageData == null)
  62. {
  63. return ResultCode.NotAvailable;
  64. }
  65. MakeObject(context, new AppletAE.IStorage(storageData));
  66. return ResultCode.Success;
  67. }
  68. [Command(20)]
  69. // EnsureSaveData(nn::account::Uid) -> u64
  70. public ResultCode EnsureSaveData(ServiceCtx context)
  71. {
  72. Uid userId = context.RequestData.ReadStruct<AccountUid>().ToLibHacUid();
  73. ApplicationId applicationId = new ApplicationId(context.Process.TitleId);
  74. BlitStruct<ApplicationControlProperty> controlHolder = context.Device.Application.ControlData;
  75. ref ApplicationControlProperty control = ref controlHolder.Value;
  76. if (LibHac.Utilities.IsEmpty(controlHolder.ByteSpan))
  77. {
  78. // If the current application doesn't have a loaded control property, create a dummy one
  79. // and set the savedata sizes so a user savedata will be created.
  80. control = ref new BlitStruct<ApplicationControlProperty>(1).Value;
  81. // The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
  82. control.UserAccountSaveDataSize = 0x4000;
  83. control.UserAccountSaveDataJournalSize = 0x4000;
  84. Logger.Warning?.Print(LogClass.ServiceAm,
  85. "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games.");
  86. }
  87. Result result = EnsureApplicationSaveData(context.Device.FileSystem.FsClient, out long requiredSize, applicationId, ref control, ref userId);
  88. context.ResponseData.Write(requiredSize);
  89. return (ResultCode)result.Value;
  90. }
  91. [Command(21)]
  92. // GetDesiredLanguage() -> nn::settings::LanguageCode
  93. public ResultCode GetDesiredLanguage(ServiceCtx context)
  94. {
  95. // This seems to be calling ns:am GetApplicationDesiredLanguage followed by ConvertApplicationLanguageToLanguageCode
  96. // Calls are from a IReadOnlyApplicationControlDataInterface object
  97. // ConvertApplicationLanguageToLanguageCode compares language code strings and returns the index
  98. // TODO: When above calls are implemented, switch to using ns:am
  99. long desiredLanguageCode = context.Device.System.State.DesiredLanguageCode;
  100. int supportedLanguages = (int)context.Device.Application.ControlData.Value.SupportedLanguages;
  101. int firstSupported = BitOperations.TrailingZeroCount(supportedLanguages);
  102. if (firstSupported > (int)SystemState.TitleLanguage.Chinese)
  103. {
  104. Logger.Warning?.Print(LogClass.ServiceAm, "Application has zero supported languages");
  105. context.ResponseData.Write(desiredLanguageCode);
  106. return ResultCode.Success;
  107. }
  108. // If desired language is not supported by application, use first supported language from TitleLanguage.
  109. // TODO: In the future, a GUI could enable user-specified search priority
  110. if (((1 << (int)context.Device.System.State.DesiredTitleLanguage) & supportedLanguages) == 0)
  111. {
  112. SystemLanguage newLanguage = Enum.Parse<SystemLanguage>(Enum.GetName(typeof(SystemState.TitleLanguage), firstSupported));
  113. desiredLanguageCode = SystemStateMgr.GetLanguageCode((int)newLanguage);
  114. Logger.Info?.Print(LogClass.ServiceAm, $"Application doesn't support configured language. Using {newLanguage}");
  115. }
  116. context.ResponseData.Write(desiredLanguageCode);
  117. return ResultCode.Success;
  118. }
  119. [Command(22)]
  120. // SetTerminateResult(u32)
  121. public ResultCode SetTerminateResult(ServiceCtx context)
  122. {
  123. Result result = new Result(context.RequestData.ReadUInt32());
  124. Logger.Info?.Print(LogClass.ServiceAm, $"Result = 0x{result.Value:x8} ({result.ToStringWithName()}).");
  125. return ResultCode.Success;
  126. }
  127. [Command(23)]
  128. // GetDisplayVersion() -> nn::oe::DisplayVersion
  129. public ResultCode GetDisplayVersion(ServiceCtx context)
  130. {
  131. // This should work as DisplayVersion U8Span always gives a 0x10 size byte array.
  132. // If an NACP isn't found, the buffer will be all '\0' which seems to be the correct implementation.
  133. context.ResponseData.Write(context.Device.Application.ControlData.Value.DisplayVersion);
  134. return ResultCode.Success;
  135. }
  136. [Command(26)] // 3.0.0+
  137. // GetSaveDataSize(u8 save_data_type, nn::account::Uid) -> (u64 save_size, u64 journal_size)
  138. public ResultCode GetSaveDataSize(ServiceCtx context)
  139. {
  140. SaveDataType saveDataType = (SaveDataType)context.RequestData.ReadUInt64();
  141. Uid userId = context.RequestData.ReadStruct<AccountUid>().ToLibHacUid();
  142. // NOTE: Service calls nn::fs::FindSaveDataWithFilter with SaveDataType = 1 hardcoded.
  143. // Then it calls nn::fs::GetSaveDataAvailableSize and nn::fs::GetSaveDataJournalSize to get the sizes.
  144. // Since LibHac currently doesn't support the 2 last methods, we can hardcode the values to 200mb.
  145. context.ResponseData.Write((long)200000000);
  146. context.ResponseData.Write((long)200000000);
  147. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { saveDataType, userId });
  148. return ResultCode.Success;
  149. }
  150. [Command(30)]
  151. // BeginBlockingHomeButtonShortAndLongPressed()
  152. public ResultCode BeginBlockingHomeButtonShortAndLongPressed(ServiceCtx context)
  153. {
  154. // NOTE: This set two internal fields at offsets 0x89 and 0x8B to value 1 then it signals an internal event.
  155. Logger.Stub?.PrintStub(LogClass.ServiceAm);
  156. return ResultCode.Success;
  157. }
  158. [Command(31)]
  159. // EndBlockingHomeButtonShortAndLongPressed()
  160. public ResultCode EndBlockingHomeButtonShortAndLongPressed(ServiceCtx context)
  161. {
  162. // NOTE: This set two internal fields at offsets 0x89 and 0x8B to value 0 then it signals an internal event.
  163. Logger.Stub?.PrintStub(LogClass.ServiceAm);
  164. return ResultCode.Success;
  165. }
  166. [Command(32)] // 2.0.0+
  167. // BeginBlockingHomeButton(u64 nano_second)
  168. public ResultCode BeginBlockingHomeButton(ServiceCtx context)
  169. {
  170. ulong nanoSeconds = context.RequestData.ReadUInt64();
  171. // NOTE: This set two internal fields at offsets 0x89 to value 1 and 0x90 to value of "nanoSeconds" then it signals an internal event.
  172. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { nanoSeconds });
  173. return ResultCode.Success;
  174. }
  175. [Command(33)] // 2.0.0+
  176. // EndBlockingHomeButton()
  177. public ResultCode EndBlockingHomeButton(ServiceCtx context)
  178. {
  179. // NOTE: This set two internal fields at offsets 0x89 and 0x90 to value 0 then it signals an internal event.
  180. Logger.Stub?.PrintStub(LogClass.ServiceAm);
  181. return ResultCode.Success;
  182. }
  183. [Command(40)]
  184. // NotifyRunning() -> b8
  185. public ResultCode NotifyRunning(ServiceCtx context)
  186. {
  187. context.ResponseData.Write(true);
  188. return ResultCode.Success;
  189. }
  190. [Command(50)] // 2.0.0+
  191. // GetPseudoDeviceId() -> nn::util::Uuid
  192. public ResultCode GetPseudoDeviceId(ServiceCtx context)
  193. {
  194. context.ResponseData.Write(0L);
  195. context.ResponseData.Write(0L);
  196. Logger.Stub?.PrintStub(LogClass.ServiceAm);
  197. return ResultCode.Success;
  198. }
  199. [Command(66)] // 3.0.0+
  200. // InitializeGamePlayRecording(u64, handle<copy>)
  201. public ResultCode InitializeGamePlayRecording(ServiceCtx context)
  202. {
  203. Logger.Stub?.PrintStub(LogClass.ServiceAm);
  204. return ResultCode.Success;
  205. }
  206. [Command(67)] // 3.0.0+
  207. // SetGamePlayRecordingState(u32)
  208. public ResultCode SetGamePlayRecordingState(ServiceCtx context)
  209. {
  210. int state = context.RequestData.ReadInt32();
  211. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { state });
  212. return ResultCode.Success;
  213. }
  214. [Command(90)] // 4.0.0+
  215. // EnableApplicationCrashReport(u8)
  216. public ResultCode EnableApplicationCrashReport(ServiceCtx context)
  217. {
  218. bool applicationCrashReportEnabled = context.RequestData.ReadBoolean();
  219. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { applicationCrashReportEnabled });
  220. return ResultCode.Success;
  221. }
  222. [Command(100)] // 5.0.0+
  223. // InitializeApplicationCopyrightFrameBuffer(s32 width, s32 height, handle<copy, transfer_memory> transfer_memory, u64 transfer_memory_size)
  224. public ResultCode InitializeApplicationCopyrightFrameBuffer(ServiceCtx context)
  225. {
  226. int width = context.RequestData.ReadInt32();
  227. int height = context.RequestData.ReadInt32();
  228. ulong transferMemorySize = context.RequestData.ReadUInt64();
  229. int transferMemoryHandle = context.Request.HandleDesc.ToCopy[0];
  230. ulong transferMemoryAddress = context.Process.HandleTable.GetObject<KTransferMemory>(transferMemoryHandle).Address;
  231. ResultCode resultCode = ResultCode.InvalidParameters;
  232. if (((transferMemorySize & 0x3FFFF) == 0) && width <= 1280 && height <= 720)
  233. {
  234. resultCode = InitializeApplicationCopyrightFrameBufferImpl(transferMemoryAddress, transferMemorySize, width, height);
  235. }
  236. if (transferMemoryHandle != 0)
  237. {
  238. context.Device.System.KernelContext.Syscall.CloseHandle(transferMemoryHandle);
  239. }
  240. return resultCode;
  241. }
  242. private ResultCode InitializeApplicationCopyrightFrameBufferImpl(ulong transferMemoryAddress, ulong transferMemorySize, int width, int height)
  243. {
  244. if ((transferMemorySize & 0x3FFFF) != 0)
  245. {
  246. return ResultCode.InvalidParameters;
  247. }
  248. ResultCode resultCode;
  249. // if (_copyrightBuffer == null)
  250. {
  251. // TODO: Initialize buffer and object.
  252. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { transferMemoryAddress, transferMemorySize, width, height });
  253. resultCode = ResultCode.Success;
  254. }
  255. return resultCode;
  256. }
  257. [Command(101)] // 5.0.0+
  258. // SetApplicationCopyrightImage(buffer<bytes, 0x45> frame_buffer, s32 x, s32 y, s32 width, s32 height, s32 window_origin_mode)
  259. public ResultCode SetApplicationCopyrightImage(ServiceCtx context)
  260. {
  261. long frameBufferPos = context.Request.SendBuff[0].Position;
  262. long frameBufferSize = context.Request.SendBuff[0].Size;
  263. int x = context.RequestData.ReadInt32();
  264. int y = context.RequestData.ReadInt32();
  265. int width = context.RequestData.ReadInt32();
  266. int height = context.RequestData.ReadInt32();
  267. uint windowOriginMode = context.RequestData.ReadUInt32();
  268. ResultCode resultCode = ResultCode.InvalidParameters;
  269. if (((y | x) >= 0) && width >= 1 && height >= 1)
  270. {
  271. ResultCode result = SetApplicationCopyrightImageImpl(x, y, width, height, frameBufferPos, frameBufferSize, windowOriginMode);
  272. if (result != ResultCode.Success)
  273. {
  274. resultCode = result;
  275. }
  276. else
  277. {
  278. resultCode = ResultCode.Success;
  279. }
  280. }
  281. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { frameBufferPos, frameBufferSize, x, y, width, height, windowOriginMode });
  282. return resultCode;
  283. }
  284. private ResultCode SetApplicationCopyrightImageImpl(int x, int y, int width, int height, long frameBufferPos, long frameBufferSize, uint windowOriginMode)
  285. {
  286. /*
  287. if (_copyrightBuffer == null)
  288. {
  289. return ResultCode.NullCopyrightObject;
  290. }
  291. */
  292. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { x, y, width, height, frameBufferPos, frameBufferSize, windowOriginMode });
  293. return ResultCode.Success;
  294. }
  295. [Command(102)] // 5.0.0+
  296. // SetApplicationCopyrightVisibility(bool visible)
  297. public ResultCode SetApplicationCopyrightVisibility(ServiceCtx context)
  298. {
  299. bool visible = context.RequestData.ReadBoolean();
  300. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { visible });
  301. // NOTE: It sets an internal field and return ResultCode.Success in all case.
  302. return ResultCode.Success;
  303. }
  304. [Command(110)] // 5.0.0+
  305. // QueryApplicationPlayStatistics(buffer<bytes, 5> title_id_list) -> (buffer<bytes, 6> entries, s32 entries_count)
  306. public ResultCode QueryApplicationPlayStatistics(ServiceCtx context)
  307. {
  308. // TODO: Call pdm:qry cmd 13 when IPC call between services will be implemented.
  309. return (ResultCode)QueryPlayStatisticsManager.GetPlayStatistics(context);
  310. }
  311. [Command(111)] // 6.0.0+
  312. // QueryApplicationPlayStatisticsByUid(nn::account::Uid, buffer<bytes, 5> title_id_list) -> (buffer<bytes, 6> entries, s32 entries_count)
  313. public ResultCode QueryApplicationPlayStatisticsByUid(ServiceCtx context)
  314. {
  315. // TODO: Call pdm:qry cmd 16 when IPC call between services will be implemented.
  316. return (ResultCode)QueryPlayStatisticsManager.GetPlayStatistics(context, true);
  317. }
  318. [Command(120)] // 5.0.0+
  319. // ExecuteProgram(ProgramSpecifyKind kind, u64 value)
  320. public ResultCode ExecuteProgram(ServiceCtx context)
  321. {
  322. ProgramSpecifyKind kind = (ProgramSpecifyKind)context.RequestData.ReadUInt32();
  323. // padding
  324. context.RequestData.ReadUInt32();
  325. ulong value = context.RequestData.ReadUInt64();
  326. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { kind, value });
  327. context.Device.UiHandler.ExecuteProgram(context.Device, kind, value);
  328. return ResultCode.Success;
  329. }
  330. [Command(121)] // 5.0.0+
  331. // ClearUserChannel()
  332. public ResultCode ClearUserChannel(ServiceCtx context)
  333. {
  334. context.Device.UserChannelPersistence.Clear();
  335. return ResultCode.Success;
  336. }
  337. [Command(122)] // 5.0.0+
  338. // UnpopToUserChannel(object<nn::am::service::IStorage> input_storage)
  339. public ResultCode UnpopToUserChannel(ServiceCtx context)
  340. {
  341. AppletAE.IStorage data = GetObject<AppletAE.IStorage>(context, 0);
  342. context.Device.UserChannelPersistence.Push(data.Data);
  343. return ResultCode.Success;
  344. }
  345. [Command(123)] // 5.0.0+
  346. // GetPreviousProgramIndex() -> s32 program_index
  347. public ResultCode GetPreviousProgramIndex(ServiceCtx context)
  348. {
  349. int previousProgramIndex = context.Device.UserChannelPersistence.PreviousIndex;
  350. context.ResponseData.Write(previousProgramIndex);
  351. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { previousProgramIndex });
  352. return ResultCode.Success;
  353. }
  354. [Command(130)] // 8.0.0+
  355. // GetGpuErrorDetectedSystemEvent() -> handle<copy>
  356. public ResultCode GetGpuErrorDetectedSystemEvent(ServiceCtx context)
  357. {
  358. if (_gpuErrorDetectedSystemEventHandle == 0)
  359. {
  360. if (context.Process.HandleTable.GenerateHandle(_gpuErrorDetectedSystemEvent.ReadableEvent, out _gpuErrorDetectedSystemEventHandle) != KernelResult.Success)
  361. {
  362. throw new InvalidOperationException("Out of handles!");
  363. }
  364. }
  365. context.Response.HandleDesc = IpcHandleDesc.MakeCopy(_gpuErrorDetectedSystemEventHandle);
  366. // NOTE: This is used by "sdk" NSO during applet-application initialization.
  367. // A seperate thread is setup where event-waiting is handled.
  368. // When the Event is signaled, official sw will assert.
  369. return ResultCode.Success;
  370. }
  371. [Command(140)] // 9.0.0+
  372. // GetFriendInvitationStorageChannelEvent() -> handle<copy>
  373. public ResultCode GetFriendInvitationStorageChannelEvent(ServiceCtx context)
  374. {
  375. if (_friendInvitationStorageChannelEventHandle == 0)
  376. {
  377. if (context.Process.HandleTable.GenerateHandle(_friendInvitationStorageChannelEvent.ReadableEvent, out _friendInvitationStorageChannelEventHandle) != KernelResult.Success)
  378. {
  379. throw new InvalidOperationException("Out of handles!");
  380. }
  381. }
  382. context.Response.HandleDesc = IpcHandleDesc.MakeCopy(_friendInvitationStorageChannelEventHandle);
  383. return ResultCode.Success;
  384. }
  385. [Command(141)] // 9.0.0+
  386. // TryPopFromFriendInvitationStorageChannel() -> object<nn::am::service::IStorage>
  387. public ResultCode TryPopFromFriendInvitationStorageChannel(ServiceCtx context)
  388. {
  389. // NOTE: IStorage are pushed in the channel with IApplicationAccessor PushToFriendInvitationStorageChannel
  390. // If _friendInvitationStorageChannelEvent is signaled, the event is cleared.
  391. // If an IStorage is available, returns it with ResultCode.Success.
  392. // If not, just returns ResultCode.NotAvailable. Since we don't support friend feature for now, it's fine to do the same.
  393. Logger.Stub?.PrintStub(LogClass.ServiceAm);
  394. return ResultCode.NotAvailable;
  395. }
  396. [Command(150)] // 9.0.0+
  397. // GetNotificationStorageChannelEvent() -> handle<copy>
  398. public ResultCode GetNotificationStorageChannelEvent(ServiceCtx context)
  399. {
  400. if (_notificationStorageChannelEventHandle == 0)
  401. {
  402. if (context.Process.HandleTable.GenerateHandle(_notificationStorageChannelEvent.ReadableEvent, out _notificationStorageChannelEventHandle) != KernelResult.Success)
  403. {
  404. throw new InvalidOperationException("Out of handles!");
  405. }
  406. }
  407. context.Response.HandleDesc = IpcHandleDesc.MakeCopy(_notificationStorageChannelEventHandle);
  408. return ResultCode.Success;
  409. }
  410. [Command(160)] // 9.0.0+
  411. // GetHealthWarningDisappearedSystemEvent() -> handle<copy>
  412. public ResultCode GetHealthWarningDisappearedSystemEvent(ServiceCtx context)
  413. {
  414. if (_healthWarningDisappearedSystemEventHandle == 0)
  415. {
  416. if (context.Process.HandleTable.GenerateHandle(_healthWarningDisappearedSystemEvent.ReadableEvent, out _healthWarningDisappearedSystemEventHandle) != KernelResult.Success)
  417. {
  418. throw new InvalidOperationException("Out of handles!");
  419. }
  420. }
  421. context.Response.HandleDesc = IpcHandleDesc.MakeCopy(_healthWarningDisappearedSystemEventHandle);
  422. return ResultCode.Success;
  423. }
  424. }
  425. }