IApplicationFunctions.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. using LibHac;
  2. using LibHac.Account;
  3. using LibHac.Common;
  4. using LibHac.Fs;
  5. using LibHac.Ncm;
  6. using LibHac.Ns;
  7. using Ryujinx.Common;
  8. using Ryujinx.Common.Logging;
  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.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. 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. TitleId titleId = new TitleId(context.Process.TitleId);
  47. BlitStruct<ApplicationControlProperty> controlHolder = context.Device.Application.ControlData;
  48. ref ApplicationControlProperty control = ref controlHolder.Value;
  49. if (Util.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, titleId,
  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(40)]
  123. // NotifyRunning() -> b8
  124. public ResultCode NotifyRunning(ServiceCtx context)
  125. {
  126. context.ResponseData.Write(true);
  127. return ResultCode.Success;
  128. }
  129. [Command(50)] // 2.0.0+
  130. // GetPseudoDeviceId() -> nn::util::Uuid
  131. public ResultCode GetPseudoDeviceId(ServiceCtx context)
  132. {
  133. context.ResponseData.Write(0L);
  134. context.ResponseData.Write(0L);
  135. Logger.Stub?.PrintStub(LogClass.ServiceAm);
  136. return ResultCode.Success;
  137. }
  138. [Command(66)] // 3.0.0+
  139. // InitializeGamePlayRecording(u64, handle<copy>)
  140. public ResultCode InitializeGamePlayRecording(ServiceCtx context)
  141. {
  142. Logger.Stub?.PrintStub(LogClass.ServiceAm);
  143. return ResultCode.Success;
  144. }
  145. [Command(67)] // 3.0.0+
  146. // SetGamePlayRecordingState(u32)
  147. public ResultCode SetGamePlayRecordingState(ServiceCtx context)
  148. {
  149. int state = context.RequestData.ReadInt32();
  150. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { state });
  151. return ResultCode.Success;
  152. }
  153. [Command(90)] // 4.0.0+
  154. // EnableApplicationCrashReport(u8)
  155. public ResultCode EnableApplicationCrashReport(ServiceCtx context)
  156. {
  157. bool applicationCrashReportEnabled = context.RequestData.ReadBoolean();
  158. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { applicationCrashReportEnabled });
  159. return ResultCode.Success;
  160. }
  161. [Command(100)] // 5.0.0+
  162. // InitializeApplicationCopyrightFrameBuffer(s32 width, s32 height, handle<copy, transfer_memory> transfer_memory, u64 transfer_memory_size)
  163. public ResultCode InitializeApplicationCopyrightFrameBuffer(ServiceCtx context)
  164. {
  165. int width = context.RequestData.ReadInt32();
  166. int height = context.RequestData.ReadInt32();
  167. ulong transferMemorySize = context.RequestData.ReadUInt64();
  168. int transferMemoryHandle = context.Request.HandleDesc.ToCopy[0];
  169. ulong transferMemoryAddress = context.Process.HandleTable.GetObject<KTransferMemory>(transferMemoryHandle).Address;
  170. ResultCode resultCode = ResultCode.InvalidParameters;
  171. if (((transferMemorySize & 0x3FFFF) == 0) && width <= 1280 && height <= 720)
  172. {
  173. resultCode = InitializeApplicationCopyrightFrameBufferImpl(transferMemoryAddress, transferMemorySize, width, height);
  174. }
  175. /*
  176. if (transferMemoryHandle)
  177. {
  178. svcCloseHandle(transferMemoryHandle);
  179. }
  180. */
  181. return resultCode;
  182. }
  183. private ResultCode InitializeApplicationCopyrightFrameBufferImpl(ulong transferMemoryAddress, ulong transferMemorySize, int width, int height)
  184. {
  185. ResultCode resultCode = ResultCode.ObjectInvalid;
  186. if ((transferMemorySize & 0x3FFFF) != 0)
  187. {
  188. return ResultCode.InvalidParameters;
  189. }
  190. // if (_copyrightBuffer == null)
  191. {
  192. // TODO: Initialize buffer and object.
  193. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { transferMemoryAddress, transferMemorySize, width, height });
  194. resultCode = ResultCode.Success;
  195. }
  196. return resultCode;
  197. }
  198. [Command(101)] // 5.0.0+
  199. // SetApplicationCopyrightImage(buffer<bytes, 0x45> frame_buffer, s32 x, s32 y, s32 width, s32 height, s32 window_origin_mode)
  200. public ResultCode SetApplicationCopyrightImage(ServiceCtx context)
  201. {
  202. long frameBufferPos = context.Request.SendBuff[0].Position;
  203. long frameBufferSize = context.Request.SendBuff[0].Size;
  204. int x = context.RequestData.ReadInt32();
  205. int y = context.RequestData.ReadInt32();
  206. int width = context.RequestData.ReadInt32();
  207. int height = context.RequestData.ReadInt32();
  208. uint windowOriginMode = context.RequestData.ReadUInt32();
  209. ResultCode resultCode = ResultCode.InvalidParameters;
  210. if (((y | x) >= 0) && width >= 1 && height >= 1)
  211. {
  212. ResultCode result = SetApplicationCopyrightImageImpl(x, y, width, height, frameBufferPos, frameBufferSize, windowOriginMode);
  213. if (resultCode != ResultCode.Success)
  214. {
  215. resultCode = result;
  216. }
  217. else
  218. {
  219. resultCode = ResultCode.Success;
  220. }
  221. }
  222. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { frameBufferPos, frameBufferSize, x, y, width, height, windowOriginMode });
  223. return resultCode;
  224. }
  225. private ResultCode SetApplicationCopyrightImageImpl(int x, int y, int width, int height, long frameBufferPos, long frameBufferSize, uint windowOriginMode)
  226. {
  227. /*
  228. if (_copyrightBuffer == null)
  229. {
  230. return ResultCode.NullCopyrightObject;
  231. }
  232. */
  233. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { x, y, width, height, frameBufferPos, frameBufferSize, windowOriginMode });
  234. return ResultCode.Success;
  235. }
  236. [Command(102)] // 5.0.0+
  237. // SetApplicationCopyrightVisibility(bool visible)
  238. public ResultCode SetApplicationCopyrightVisibility(ServiceCtx context)
  239. {
  240. bool visible = context.RequestData.ReadBoolean();
  241. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { visible });
  242. // NOTE: It sets an internal field and return ResultCode.Success in all case.
  243. return ResultCode.Success;
  244. }
  245. [Command(110)] // 5.0.0+
  246. // QueryApplicationPlayStatistics(buffer<bytes, 5> title_id_list) -> (buffer<bytes, 6> entries, s32 entries_count)
  247. public ResultCode QueryApplicationPlayStatistics(ServiceCtx context)
  248. {
  249. // TODO: Call pdm:qry cmd 13 when IPC call between services will be implemented.
  250. return (ResultCode)QueryPlayStatisticsManager.GetPlayStatistics(context);
  251. }
  252. [Command(111)] // 6.0.0+
  253. // QueryApplicationPlayStatisticsByUid(nn::account::Uid, buffer<bytes, 5> title_id_list) -> (buffer<bytes, 6> entries, s32 entries_count)
  254. public ResultCode QueryApplicationPlayStatisticsByUid(ServiceCtx context)
  255. {
  256. // TODO: Call pdm:qry cmd 16 when IPC call between services will be implemented.
  257. return (ResultCode)QueryPlayStatisticsManager.GetPlayStatistics(context, true);
  258. }
  259. [Command(123)] // 5.0.0+
  260. // GetPreviousProgramIndex() -> s32 program_index
  261. public ResultCode GetPreviousProgramIndex(ServiceCtx context)
  262. {
  263. // TODO: The output PreviousProgramIndex is -1 when there was no previous title.
  264. // When multi-process will be supported, return the last program index.
  265. int previousProgramIndex = -1;
  266. context.ResponseData.Write(previousProgramIndex);
  267. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { previousProgramIndex });
  268. return ResultCode.Success;
  269. }
  270. [Command(130)] // 8.0.0+
  271. // GetGpuErrorDetectedSystemEvent() -> handle<copy>
  272. public ResultCode GetGpuErrorDetectedSystemEvent(ServiceCtx context)
  273. {
  274. if (context.Process.HandleTable.GenerateHandle(_gpuErrorDetectedSystemEvent.ReadableEvent, out int gpuErrorDetectedSystemEventHandle) != KernelResult.Success)
  275. {
  276. throw new InvalidOperationException("Out of handles!");
  277. }
  278. context.Response.HandleDesc = IpcHandleDesc.MakeCopy(gpuErrorDetectedSystemEventHandle);
  279. // NOTE: This is used by "sdk" NSO during applet-application initialization.
  280. // A seperate thread is setup where event-waiting is handled.
  281. // When the Event is signaled, official sw will assert.
  282. return ResultCode.Success;
  283. }
  284. [Command(140)] // 9.0.0+
  285. // GetFriendInvitationStorageChannelEvent() -> handle<copy>
  286. public ResultCode GetFriendInvitationStorageChannelEvent(ServiceCtx context)
  287. {
  288. if (context.Process.HandleTable.GenerateHandle(_friendInvitationStorageChannelEvent.ReadableEvent, out int friendInvitationStorageChannelEventHandle) != KernelResult.Success)
  289. {
  290. throw new InvalidOperationException("Out of handles!");
  291. }
  292. context.Response.HandleDesc = IpcHandleDesc.MakeCopy(friendInvitationStorageChannelEventHandle);
  293. return ResultCode.Success;
  294. }
  295. [Command(150)] // 9.0.0+
  296. // GetNotificationStorageChannelEvent() -> handle<copy>
  297. public ResultCode GetNotificationStorageChannelEvent(ServiceCtx context)
  298. {
  299. if (context.Process.HandleTable.GenerateHandle(_notificationStorageChannelEvent.ReadableEvent, out int notificationStorageChannelEventHandle) != KernelResult.Success)
  300. {
  301. throw new InvalidOperationException("Out of handles!");
  302. }
  303. context.Response.HandleDesc = IpcHandleDesc.MakeCopy(notificationStorageChannelEventHandle);
  304. return ResultCode.Success;
  305. }
  306. }
  307. }