IApplicationFunctions.cs 21 KB

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