IApplicationFunctions.cs 18 KB

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