IApplicationFunctions.cs 21 KB

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