IApplicationFunctions.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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.Exceptions;
  9. using Ryujinx.HLE.HOS.Ipc;
  10. using Ryujinx.HLE.HOS.Kernel.Common;
  11. using Ryujinx.HLE.HOS.Kernel.Memory;
  12. using Ryujinx.HLE.HOS.Kernel.Threading;
  13. using Ryujinx.HLE.HOS.Services.Am.AppletAE.Storage;
  14. using Ryujinx.HLE.HOS.Services.Am.AppletOE.ApplicationProxyService.ApplicationProxy.Types;
  15. using Ryujinx.HLE.HOS.Services.Sdb.Pdm.QueryService;
  16. using Ryujinx.HLE.HOS.SystemState;
  17. using System;
  18. using System.Numerics;
  19. using static LibHac.Fs.ApplicationSaveDataManagement;
  20. using AccountUid = Ryujinx.HLE.HOS.Services.Account.Acc.UserId;
  21. using ApplicationId = LibHac.Ncm.ApplicationId;
  22. namespace Ryujinx.HLE.HOS.Services.Am.AppletOE.ApplicationProxyService.ApplicationProxy
  23. {
  24. class IApplicationFunctions : IpcService
  25. {
  26. private KEvent _gpuErrorDetectedSystemEvent;
  27. private KEvent _friendInvitationStorageChannelEvent;
  28. private KEvent _notificationStorageChannelEvent;
  29. public IApplicationFunctions(Horizon system)
  30. {
  31. _gpuErrorDetectedSystemEvent = new KEvent(system.KernelContext);
  32. _friendInvitationStorageChannelEvent = new KEvent(system.KernelContext);
  33. _notificationStorageChannelEvent = new KEvent(system.KernelContext);
  34. }
  35. [Command(1)]
  36. // PopLaunchParameter(LaunchParameterKind kind) -> object<nn::am::service::IStorage>
  37. public ResultCode PopLaunchParameter(ServiceCtx context)
  38. {
  39. LaunchParameterKind kind = (LaunchParameterKind)context.RequestData.ReadUInt32();
  40. byte[] storageData;
  41. switch (kind)
  42. {
  43. case LaunchParameterKind.UserChannel:
  44. storageData = context.Device.UserChannelPersistence.Pop();
  45. break;
  46. case LaunchParameterKind.PreselectedUser:
  47. // Only the first 0x18 bytes of the Data seems to be actually used.
  48. storageData = StorageHelper.MakeLaunchParams(context.Device.System.State.Account.LastOpenedUser);
  49. break;
  50. case LaunchParameterKind.Unknown:
  51. throw new NotImplementedException("Unknown LaunchParameterKind.");
  52. default:
  53. return ResultCode.ObjectInvalid;
  54. }
  55. if (storageData == null)
  56. {
  57. return ResultCode.NotAvailable;
  58. }
  59. MakeObject(context, new AppletAE.IStorage(storageData));
  60. return ResultCode.Success;
  61. }
  62. [Command(20)]
  63. // EnsureSaveData(nn::account::Uid) -> u64
  64. public ResultCode EnsureSaveData(ServiceCtx context)
  65. {
  66. Uid userId = context.RequestData.ReadStruct<AccountUid>().ToLibHacUid();
  67. ApplicationId applicationId = new ApplicationId(context.Process.TitleId);
  68. BlitStruct<ApplicationControlProperty> controlHolder = context.Device.Application.ControlData;
  69. ref ApplicationControlProperty control = ref controlHolder.Value;
  70. if (LibHac.Utilities.IsEmpty(controlHolder.ByteSpan))
  71. {
  72. // If the current application doesn't have a loaded control property, create a dummy one
  73. // and set the savedata sizes so a user savedata will be created.
  74. control = ref new BlitStruct<ApplicationControlProperty>(1).Value;
  75. // The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
  76. control.UserAccountSaveDataSize = 0x4000;
  77. control.UserAccountSaveDataJournalSize = 0x4000;
  78. Logger.Warning?.Print(LogClass.ServiceAm,
  79. "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games.");
  80. }
  81. Result result = EnsureApplicationSaveData(context.Device.FileSystem.FsClient, out long requiredSize, applicationId,
  82. ref control, ref userId);
  83. context.ResponseData.Write(requiredSize);
  84. return (ResultCode)result.Value;
  85. }
  86. [Command(21)]
  87. // GetDesiredLanguage() -> nn::settings::LanguageCode
  88. public ResultCode GetDesiredLanguage(ServiceCtx context)
  89. {
  90. // This seems to be calling ns:am GetApplicationDesiredLanguage followed by ConvertApplicationLanguageToLanguageCode
  91. // Calls are from a IReadOnlyApplicationControlDataInterface object
  92. // ConvertApplicationLanguageToLanguageCode compares language code strings and returns the index
  93. // TODO: When above calls are implemented, switch to using ns:am
  94. long desiredLanguageCode = context.Device.System.State.DesiredLanguageCode;
  95. int supportedLanguages = (int)context.Device.Application.ControlData.Value.SupportedLanguages;
  96. int firstSupported = BitOperations.TrailingZeroCount(supportedLanguages);
  97. if (firstSupported > (int)SystemState.TitleLanguage.Chinese)
  98. {
  99. Logger.Warning?.Print(LogClass.ServiceAm, "Application has zero supported languages");
  100. context.ResponseData.Write(desiredLanguageCode);
  101. return ResultCode.Success;
  102. }
  103. // If desired language is not supported by application, use first supported language from TitleLanguage.
  104. // TODO: In the future, a GUI could enable user-specified search priority
  105. if (((1 << (int)context.Device.System.State.DesiredTitleLanguage) & supportedLanguages) == 0)
  106. {
  107. SystemLanguage newLanguage = Enum.Parse<SystemLanguage>(Enum.GetName(typeof(SystemState.TitleLanguage), firstSupported));
  108. desiredLanguageCode = SystemStateMgr.GetLanguageCode((int)newLanguage);
  109. Logger.Info?.Print(LogClass.ServiceAm, $"Application doesn't support configured language. Using {newLanguage}");
  110. }
  111. context.ResponseData.Write(desiredLanguageCode);
  112. return ResultCode.Success;
  113. }
  114. [Command(22)]
  115. // SetTerminateResult(u32)
  116. public ResultCode SetTerminateResult(ServiceCtx context)
  117. {
  118. Result result = new Result(context.RequestData.ReadUInt32());
  119. Logger.Info?.Print(LogClass.ServiceAm, $"Result = 0x{result.Value:x8} ({result.ToStringWithName()}).");
  120. return ResultCode.Success;
  121. }
  122. [Command(23)]
  123. // GetDisplayVersion() -> nn::oe::DisplayVersion
  124. public ResultCode GetDisplayVersion(ServiceCtx context)
  125. {
  126. // This should work as DisplayVersion U8Span always gives a 0x10 size byte array.
  127. // If an NACP isn't found, the buffer will be all '\0' which seems to be the correct implementation.
  128. context.ResponseData.Write(context.Device.Application.ControlData.Value.DisplayVersion);
  129. return ResultCode.Success;
  130. }
  131. // GetSaveDataSize(u8, nn::account::Uid) -> (u64, u64)
  132. [Command(26)] // 3.0.0+
  133. public ResultCode GetSaveDataSize(ServiceCtx context)
  134. {
  135. SaveDataType saveDataType = (SaveDataType)context.RequestData.ReadByte();
  136. context.RequestData.BaseStream.Seek(7, System.IO.SeekOrigin.Current);
  137. Uid userId = context.RequestData.ReadStruct<AccountUid>().ToLibHacUid();
  138. // TODO: We return a size of 2GB as we use a directory based save system. This should be enough for most of the games.
  139. context.ResponseData.Write(2000000000u);
  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. ResultCode resultCode = ResultCode.ObjectInvalid;
  240. if ((transferMemorySize & 0x3FFFF) != 0)
  241. {
  242. return ResultCode.InvalidParameters;
  243. }
  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(150)] // 9.0.0+
  375. // GetNotificationStorageChannelEvent() -> handle<copy>
  376. public ResultCode GetNotificationStorageChannelEvent(ServiceCtx context)
  377. {
  378. if (context.Process.HandleTable.GenerateHandle(_notificationStorageChannelEvent.ReadableEvent, out int notificationStorageChannelEventHandle) != KernelResult.Success)
  379. {
  380. throw new InvalidOperationException("Out of handles!");
  381. }
  382. context.Response.HandleDesc = IpcHandleDesc.MakeCopy(notificationStorageChannelEventHandle);
  383. return ResultCode.Success;
  384. }
  385. }
  386. }