IApplicationFunctions.cs 19 KB

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