IApplicationFunctions.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. using LibHac;
  2. using LibHac.Account;
  3. using LibHac.Common;
  4. using LibHac.Fs;
  5. using LibHac.FsSystem;
  6. using LibHac.Ncm;
  7. using LibHac.Ns;
  8. using Ryujinx.Common;
  9. using Ryujinx.Common.Logging;
  10. using Ryujinx.HLE.Exceptions;
  11. using Ryujinx.HLE.HOS.Ipc;
  12. using Ryujinx.HLE.HOS.Kernel.Common;
  13. using Ryujinx.HLE.HOS.Kernel.Memory;
  14. using Ryujinx.HLE.HOS.Kernel.Threading;
  15. using Ryujinx.HLE.HOS.Services.Am.AppletAE.Storage;
  16. using Ryujinx.HLE.HOS.Services.Am.AppletOE.ApplicationProxyService.ApplicationProxy.Types;
  17. using Ryujinx.HLE.HOS.Services.Sdb.Pdm.QueryService;
  18. using Ryujinx.HLE.HOS.Services.Sm;
  19. using Ryujinx.HLE.HOS.SystemState;
  20. using System;
  21. using System.Numerics;
  22. using System.Threading;
  23. using static LibHac.Fs.ApplicationSaveDataManagement;
  24. using AccountUid = Ryujinx.HLE.HOS.Services.Account.Acc.UserId;
  25. using ApplicationId = LibHac.Ncm.ApplicationId;
  26. namespace Ryujinx.HLE.HOS.Services.Am.AppletOE.ApplicationProxyService.ApplicationProxy
  27. {
  28. class IApplicationFunctions : IpcService
  29. {
  30. private ulong _defaultSaveDataSize = 200000000;
  31. private ulong _defaultJournalSaveDataSize = 200000000;
  32. private KEvent _gpuErrorDetectedSystemEvent;
  33. private KEvent _friendInvitationStorageChannelEvent;
  34. private KEvent _notificationStorageChannelEvent;
  35. private KEvent _healthWarningDisappearedSystemEvent;
  36. private int _gpuErrorDetectedSystemEventHandle;
  37. private int _friendInvitationStorageChannelEventHandle;
  38. private int _notificationStorageChannelEventHandle;
  39. private int _healthWarningDisappearedSystemEventHandle;
  40. private int _jitLoaded;
  41. private HorizonClient _horizon;
  42. public IApplicationFunctions(Horizon system)
  43. {
  44. // TODO: Find where they are signaled.
  45. _gpuErrorDetectedSystemEvent = new KEvent(system.KernelContext);
  46. _friendInvitationStorageChannelEvent = new KEvent(system.KernelContext);
  47. _notificationStorageChannelEvent = new KEvent(system.KernelContext);
  48. _healthWarningDisappearedSystemEvent = new KEvent(system.KernelContext);
  49. _horizon = system.LibHacHorizonManager.AmClient;
  50. }
  51. [CommandHipc(1)]
  52. // PopLaunchParameter(LaunchParameterKind kind) -> object<nn::am::service::IStorage>
  53. public ResultCode PopLaunchParameter(ServiceCtx context)
  54. {
  55. LaunchParameterKind kind = (LaunchParameterKind)context.RequestData.ReadUInt32();
  56. byte[] storageData;
  57. switch (kind)
  58. {
  59. case LaunchParameterKind.UserChannel:
  60. storageData = context.Device.Configuration.UserChannelPersistence.Pop();
  61. break;
  62. case LaunchParameterKind.PreselectedUser:
  63. // Only the first 0x18 bytes of the Data seems to be actually used.
  64. storageData = StorageHelper.MakeLaunchParams(context.Device.System.AccountManager.LastOpenedUser);
  65. break;
  66. case LaunchParameterKind.Unknown:
  67. throw new NotImplementedException("Unknown LaunchParameterKind.");
  68. default:
  69. return ResultCode.ObjectInvalid;
  70. }
  71. if (storageData == null)
  72. {
  73. return ResultCode.NotAvailable;
  74. }
  75. MakeObject(context, new AppletAE.IStorage(storageData));
  76. return ResultCode.Success;
  77. }
  78. [CommandHipc(12)] // 4.0.0+
  79. // CreateApplicationAndRequestToStart(u64 title_id)
  80. public ResultCode CreateApplicationAndRequestToStart(ServiceCtx context)
  81. {
  82. ulong titleId = context.RequestData.ReadUInt64();
  83. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { titleId });
  84. if (titleId == 0)
  85. {
  86. context.Device.UiHandler.ExecuteProgram(context.Device, ProgramSpecifyKind.RestartProgram, titleId);
  87. }
  88. else
  89. {
  90. throw new NotImplementedException();
  91. }
  92. return ResultCode.Success;
  93. }
  94. [CommandHipc(20)]
  95. // EnsureSaveData(nn::account::Uid) -> u64
  96. public ResultCode EnsureSaveData(ServiceCtx context)
  97. {
  98. Uid userId = context.RequestData.ReadStruct<AccountUid>().ToLibHacUid();
  99. // Mask out the low nibble of the program ID to get the application ID
  100. ApplicationId applicationId = new ApplicationId(context.Device.Application.TitleId & ~0xFul);
  101. BlitStruct<ApplicationControlProperty> controlHolder = context.Device.Application.ControlData;
  102. ref ApplicationControlProperty control = ref controlHolder.Value;
  103. if (LibHac.Common.Utilities.IsZeros(controlHolder.ByteSpan))
  104. {
  105. // If the current application doesn't have a loaded control property, create a dummy one
  106. // and set the savedata sizes so a user savedata will be created.
  107. control = ref new BlitStruct<ApplicationControlProperty>(1).Value;
  108. // The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
  109. control.UserAccountSaveDataSize = 0x4000;
  110. control.UserAccountSaveDataJournalSize = 0x4000;
  111. Logger.Warning?.Print(LogClass.ServiceAm,
  112. "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games.");
  113. }
  114. HorizonClient hos = context.Device.System.LibHacHorizonManager.AmClient;
  115. Result result = hos.Fs.EnsureApplicationSaveData(out long requiredSize, applicationId, in control, in userId);
  116. context.ResponseData.Write(requiredSize);
  117. return (ResultCode)result.Value;
  118. }
  119. [CommandHipc(21)]
  120. // GetDesiredLanguage() -> nn::settings::LanguageCode
  121. public ResultCode GetDesiredLanguage(ServiceCtx context)
  122. {
  123. // This seems to be calling ns:am GetApplicationDesiredLanguage followed by ConvertApplicationLanguageToLanguageCode
  124. // Calls are from a IReadOnlyApplicationControlDataInterface object
  125. // ConvertApplicationLanguageToLanguageCode compares language code strings and returns the index
  126. // TODO: When above calls are implemented, switch to using ns:am
  127. long desiredLanguageCode = context.Device.System.State.DesiredLanguageCode;
  128. int supportedLanguages = (int)context.Device.Application.ControlData.Value.SupportedLanguageFlag;
  129. int firstSupported = BitOperations.TrailingZeroCount(supportedLanguages);
  130. if (firstSupported > (int)SystemState.TitleLanguage.BrazilianPortuguese)
  131. {
  132. Logger.Warning?.Print(LogClass.ServiceAm, "Application has zero supported languages");
  133. context.ResponseData.Write(desiredLanguageCode);
  134. return ResultCode.Success;
  135. }
  136. // If desired language is not supported by application, use first supported language from TitleLanguage.
  137. // TODO: In the future, a GUI could enable user-specified search priority
  138. if (((1 << (int)context.Device.System.State.DesiredTitleLanguage) & supportedLanguages) == 0)
  139. {
  140. SystemLanguage newLanguage = Enum.Parse<SystemLanguage>(Enum.GetName(typeof(SystemState.TitleLanguage), firstSupported));
  141. desiredLanguageCode = SystemStateMgr.GetLanguageCode((int)newLanguage);
  142. Logger.Info?.Print(LogClass.ServiceAm, $"Application doesn't support configured language. Using {newLanguage}");
  143. }
  144. context.ResponseData.Write(desiredLanguageCode);
  145. return ResultCode.Success;
  146. }
  147. [CommandHipc(22)]
  148. // SetTerminateResult(u32)
  149. public ResultCode SetTerminateResult(ServiceCtx context)
  150. {
  151. Result result = new Result(context.RequestData.ReadUInt32());
  152. Logger.Info?.Print(LogClass.ServiceAm, $"Result = 0x{result.Value:x8} ({result.ToStringWithName()}).");
  153. return ResultCode.Success;
  154. }
  155. [CommandHipc(23)]
  156. // GetDisplayVersion() -> nn::oe::DisplayVersion
  157. public ResultCode GetDisplayVersion(ServiceCtx context)
  158. {
  159. // If an NACP isn't found, the buffer will be all '\0' which seems to be the correct implementation.
  160. context.ResponseData.Write(context.Device.Application.ControlData.Value.DisplayVersion);
  161. return ResultCode.Success;
  162. }
  163. [CommandHipc(25)] // 3.0.0+
  164. // ExtendSaveData(u8 save_data_type, nn::account::Uid, u64 save_size, u64 journal_size) -> u64 result_code
  165. public ResultCode ExtendSaveData(ServiceCtx context)
  166. {
  167. SaveDataType saveDataType = (SaveDataType)context.RequestData.ReadUInt64();
  168. Uid userId = context.RequestData.ReadStruct<Uid>();
  169. ulong saveDataSize = context.RequestData.ReadUInt64();
  170. ulong journalSize = context.RequestData.ReadUInt64();
  171. // NOTE: Service calls nn::fs::ExtendApplicationSaveData.
  172. // Since LibHac currently doesn't support this method, we can stub it for now.
  173. _defaultSaveDataSize = saveDataSize;
  174. _defaultJournalSaveDataSize = journalSize;
  175. context.ResponseData.Write((uint)ResultCode.Success);
  176. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { saveDataType, userId, saveDataSize, journalSize });
  177. return ResultCode.Success;
  178. }
  179. [CommandHipc(26)] // 3.0.0+
  180. // GetSaveDataSize(u8 save_data_type, nn::account::Uid) -> (u64 save_size, u64 journal_size)
  181. public ResultCode GetSaveDataSize(ServiceCtx context)
  182. {
  183. SaveDataType saveDataType = (SaveDataType)context.RequestData.ReadUInt64();
  184. Uid userId = context.RequestData.ReadStruct<Uid>();
  185. // NOTE: Service calls nn::fs::FindSaveDataWithFilter with SaveDataType = 1 hardcoded.
  186. // Then it calls nn::fs::GetSaveDataAvailableSize and nn::fs::GetSaveDataJournalSize to get the sizes.
  187. // Since LibHac currently doesn't support the 2 last methods, we can hardcode the values to 200mb.
  188. context.ResponseData.Write(_defaultSaveDataSize);
  189. context.ResponseData.Write(_defaultJournalSaveDataSize);
  190. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { saveDataType, userId });
  191. return ResultCode.Success;
  192. }
  193. [CommandHipc(27)] // 5.0.0+
  194. // CreateCacheStorage(u16 index, s64 save_size, s64 journal_size) -> (u32 storageTarget, u64 requiredSize)
  195. public ResultCode CreateCacheStorage(ServiceCtx context)
  196. {
  197. ushort index = (ushort)context.RequestData.ReadUInt64();
  198. long saveSize = context.RequestData.ReadInt64();
  199. long journalSize = context.RequestData.ReadInt64();
  200. // Mask out the low nibble of the program ID to get the application ID
  201. ApplicationId applicationId = new ApplicationId(context.Device.Application.TitleId & ~0xFul);
  202. BlitStruct<ApplicationControlProperty> controlHolder = context.Device.Application.ControlData;
  203. Result result = _horizon.Fs.CreateApplicationCacheStorage(out long requiredSize,
  204. out CacheStorageTargetMedia storageTarget, applicationId, in controlHolder.Value, index, saveSize,
  205. journalSize);
  206. if (result.IsFailure()) return (ResultCode)result.Value;
  207. context.ResponseData.Write((ulong)storageTarget);
  208. context.ResponseData.Write(requiredSize);
  209. return ResultCode.Success;
  210. }
  211. [CommandHipc(30)]
  212. // BeginBlockingHomeButtonShortAndLongPressed()
  213. public ResultCode BeginBlockingHomeButtonShortAndLongPressed(ServiceCtx context)
  214. {
  215. // NOTE: This set two internal fields at offsets 0x89 and 0x8B to value 1 then it signals an internal event.
  216. Logger.Stub?.PrintStub(LogClass.ServiceAm);
  217. return ResultCode.Success;
  218. }
  219. [CommandHipc(31)]
  220. // EndBlockingHomeButtonShortAndLongPressed()
  221. public ResultCode EndBlockingHomeButtonShortAndLongPressed(ServiceCtx context)
  222. {
  223. // NOTE: This set two internal fields at offsets 0x89 and 0x8B to value 0 then it signals an internal event.
  224. Logger.Stub?.PrintStub(LogClass.ServiceAm);
  225. return ResultCode.Success;
  226. }
  227. [CommandHipc(32)] // 2.0.0+
  228. // BeginBlockingHomeButton(u64 nano_second)
  229. public ResultCode BeginBlockingHomeButton(ServiceCtx context)
  230. {
  231. ulong nanoSeconds = context.RequestData.ReadUInt64();
  232. // NOTE: This set two internal fields at offsets 0x89 to value 1 and 0x90 to value of "nanoSeconds" then it signals an internal event.
  233. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { nanoSeconds });
  234. return ResultCode.Success;
  235. }
  236. [CommandHipc(33)] // 2.0.0+
  237. // EndBlockingHomeButton()
  238. public ResultCode EndBlockingHomeButton(ServiceCtx context)
  239. {
  240. // NOTE: This set two internal fields at offsets 0x89 and 0x90 to value 0 then it signals an internal event.
  241. Logger.Stub?.PrintStub(LogClass.ServiceAm);
  242. return ResultCode.Success;
  243. }
  244. [CommandHipc(40)]
  245. // NotifyRunning() -> b8
  246. public ResultCode NotifyRunning(ServiceCtx context)
  247. {
  248. context.ResponseData.Write(true);
  249. return ResultCode.Success;
  250. }
  251. [CommandHipc(50)] // 2.0.0+
  252. // GetPseudoDeviceId() -> nn::util::Uuid
  253. public ResultCode GetPseudoDeviceId(ServiceCtx context)
  254. {
  255. context.ResponseData.Write(0L);
  256. context.ResponseData.Write(0L);
  257. Logger.Stub?.PrintStub(LogClass.ServiceAm);
  258. return ResultCode.Success;
  259. }
  260. [CommandHipc(60)] // 2.0.0+
  261. // SetMediaPlaybackStateForApplication(bool enabled)
  262. public ResultCode SetMediaPlaybackStateForApplication(ServiceCtx context)
  263. {
  264. bool enabled = context.RequestData.ReadBoolean();
  265. // NOTE: Service stores the "enabled" value in a private field, when enabled is false, it stores nn::os::GetSystemTick() too.
  266. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { enabled });
  267. return ResultCode.Success;
  268. }
  269. [CommandHipc(66)] // 3.0.0+
  270. // InitializeGamePlayRecording(u64, handle<copy>)
  271. public ResultCode InitializeGamePlayRecording(ServiceCtx context)
  272. {
  273. Logger.Stub?.PrintStub(LogClass.ServiceAm);
  274. return ResultCode.Success;
  275. }
  276. [CommandHipc(67)] // 3.0.0+
  277. // SetGamePlayRecordingState(u32)
  278. public ResultCode SetGamePlayRecordingState(ServiceCtx context)
  279. {
  280. int state = context.RequestData.ReadInt32();
  281. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { state });
  282. return ResultCode.Success;
  283. }
  284. [CommandHipc(90)] // 4.0.0+
  285. // EnableApplicationCrashReport(u8)
  286. public ResultCode EnableApplicationCrashReport(ServiceCtx context)
  287. {
  288. bool applicationCrashReportEnabled = context.RequestData.ReadBoolean();
  289. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { applicationCrashReportEnabled });
  290. return ResultCode.Success;
  291. }
  292. [CommandHipc(100)] // 5.0.0+
  293. // InitializeApplicationCopyrightFrameBuffer(s32 width, s32 height, handle<copy, transfer_memory> transfer_memory, u64 transfer_memory_size)
  294. public ResultCode InitializeApplicationCopyrightFrameBuffer(ServiceCtx context)
  295. {
  296. int width = context.RequestData.ReadInt32();
  297. int height = context.RequestData.ReadInt32();
  298. ulong transferMemorySize = context.RequestData.ReadUInt64();
  299. int transferMemoryHandle = context.Request.HandleDesc.ToCopy[0];
  300. ulong transferMemoryAddress = context.Process.HandleTable.GetObject<KTransferMemory>(transferMemoryHandle).Address;
  301. ResultCode resultCode = ResultCode.InvalidParameters;
  302. if (((transferMemorySize & 0x3FFFF) == 0) && width <= 1280 && height <= 720)
  303. {
  304. resultCode = InitializeApplicationCopyrightFrameBufferImpl(transferMemoryAddress, transferMemorySize, width, height);
  305. }
  306. if (transferMemoryHandle != 0)
  307. {
  308. context.Device.System.KernelContext.Syscall.CloseHandle(transferMemoryHandle);
  309. }
  310. return resultCode;
  311. }
  312. private ResultCode InitializeApplicationCopyrightFrameBufferImpl(ulong transferMemoryAddress, ulong transferMemorySize, int width, int height)
  313. {
  314. if ((transferMemorySize & 0x3FFFF) != 0)
  315. {
  316. return ResultCode.InvalidParameters;
  317. }
  318. ResultCode resultCode;
  319. // if (_copyrightBuffer == null)
  320. {
  321. // TODO: Initialize buffer and object.
  322. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { transferMemoryAddress, transferMemorySize, width, height });
  323. resultCode = ResultCode.Success;
  324. }
  325. return resultCode;
  326. }
  327. [CommandHipc(101)] // 5.0.0+
  328. // SetApplicationCopyrightImage(buffer<bytes, 0x45> frame_buffer, s32 x, s32 y, s32 width, s32 height, s32 window_origin_mode)
  329. public ResultCode SetApplicationCopyrightImage(ServiceCtx context)
  330. {
  331. ulong frameBufferPos = context.Request.SendBuff[0].Position;
  332. ulong frameBufferSize = context.Request.SendBuff[0].Size;
  333. int x = context.RequestData.ReadInt32();
  334. int y = context.RequestData.ReadInt32();
  335. int width = context.RequestData.ReadInt32();
  336. int height = context.RequestData.ReadInt32();
  337. uint windowOriginMode = context.RequestData.ReadUInt32();
  338. ResultCode resultCode = ResultCode.InvalidParameters;
  339. if (((y | x) >= 0) && width >= 1 && height >= 1)
  340. {
  341. ResultCode result = SetApplicationCopyrightImageImpl(x, y, width, height, frameBufferPos, frameBufferSize, windowOriginMode);
  342. if (result != ResultCode.Success)
  343. {
  344. resultCode = result;
  345. }
  346. else
  347. {
  348. resultCode = ResultCode.Success;
  349. }
  350. }
  351. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { frameBufferPos, frameBufferSize, x, y, width, height, windowOriginMode });
  352. return resultCode;
  353. }
  354. private ResultCode SetApplicationCopyrightImageImpl(int x, int y, int width, int height, ulong frameBufferPos, ulong frameBufferSize, uint windowOriginMode)
  355. {
  356. /*
  357. if (_copyrightBuffer == null)
  358. {
  359. return ResultCode.NullCopyrightObject;
  360. }
  361. */
  362. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { x, y, width, height, frameBufferPos, frameBufferSize, windowOriginMode });
  363. return ResultCode.Success;
  364. }
  365. [CommandHipc(102)] // 5.0.0+
  366. // SetApplicationCopyrightVisibility(bool visible)
  367. public ResultCode SetApplicationCopyrightVisibility(ServiceCtx context)
  368. {
  369. bool visible = context.RequestData.ReadBoolean();
  370. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { visible });
  371. // NOTE: It sets an internal field and return ResultCode.Success in all case.
  372. return ResultCode.Success;
  373. }
  374. [CommandHipc(110)] // 5.0.0+
  375. // QueryApplicationPlayStatistics(buffer<bytes, 5> title_id_list) -> (buffer<bytes, 6> entries, s32 entries_count)
  376. public ResultCode QueryApplicationPlayStatistics(ServiceCtx context)
  377. {
  378. // TODO: Call pdm:qry cmd 13 when IPC call between services will be implemented.
  379. return (ResultCode)QueryPlayStatisticsManager.GetPlayStatistics(context);
  380. }
  381. [CommandHipc(111)] // 6.0.0+
  382. // QueryApplicationPlayStatisticsByUid(nn::account::Uid, buffer<bytes, 5> title_id_list) -> (buffer<bytes, 6> entries, s32 entries_count)
  383. public ResultCode QueryApplicationPlayStatisticsByUid(ServiceCtx context)
  384. {
  385. // TODO: Call pdm:qry cmd 16 when IPC call between services will be implemented.
  386. return (ResultCode)QueryPlayStatisticsManager.GetPlayStatistics(context, true);
  387. }
  388. [CommandHipc(120)] // 5.0.0+
  389. // ExecuteProgram(ProgramSpecifyKind kind, u64 value)
  390. public ResultCode ExecuteProgram(ServiceCtx context)
  391. {
  392. ProgramSpecifyKind kind = (ProgramSpecifyKind)context.RequestData.ReadUInt32();
  393. // padding
  394. context.RequestData.ReadUInt32();
  395. ulong value = context.RequestData.ReadUInt64();
  396. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { kind, value });
  397. context.Device.UiHandler.ExecuteProgram(context.Device, kind, value);
  398. return ResultCode.Success;
  399. }
  400. [CommandHipc(121)] // 5.0.0+
  401. // ClearUserChannel()
  402. public ResultCode ClearUserChannel(ServiceCtx context)
  403. {
  404. context.Device.Configuration.UserChannelPersistence.Clear();
  405. return ResultCode.Success;
  406. }
  407. [CommandHipc(122)] // 5.0.0+
  408. // UnpopToUserChannel(object<nn::am::service::IStorage> input_storage)
  409. public ResultCode UnpopToUserChannel(ServiceCtx context)
  410. {
  411. AppletAE.IStorage data = GetObject<AppletAE.IStorage>(context, 0);
  412. context.Device.Configuration.UserChannelPersistence.Push(data.Data);
  413. return ResultCode.Success;
  414. }
  415. [CommandHipc(123)] // 5.0.0+
  416. // GetPreviousProgramIndex() -> s32 program_index
  417. public ResultCode GetPreviousProgramIndex(ServiceCtx context)
  418. {
  419. int previousProgramIndex = context.Device.Configuration.UserChannelPersistence.PreviousIndex;
  420. context.ResponseData.Write(previousProgramIndex);
  421. Logger.Stub?.PrintStub(LogClass.ServiceAm, new { previousProgramIndex });
  422. return ResultCode.Success;
  423. }
  424. [CommandHipc(130)] // 8.0.0+
  425. // GetGpuErrorDetectedSystemEvent() -> handle<copy>
  426. public ResultCode GetGpuErrorDetectedSystemEvent(ServiceCtx context)
  427. {
  428. if (_gpuErrorDetectedSystemEventHandle == 0)
  429. {
  430. if (context.Process.HandleTable.GenerateHandle(_gpuErrorDetectedSystemEvent.ReadableEvent, out _gpuErrorDetectedSystemEventHandle) != KernelResult.Success)
  431. {
  432. throw new InvalidOperationException("Out of handles!");
  433. }
  434. }
  435. context.Response.HandleDesc = IpcHandleDesc.MakeCopy(_gpuErrorDetectedSystemEventHandle);
  436. // NOTE: This is used by "sdk" NSO during applet-application initialization.
  437. // A separate thread is setup where event-waiting is handled.
  438. // When the Event is signaled, official sw will assert.
  439. return ResultCode.Success;
  440. }
  441. [CommandHipc(140)] // 9.0.0+
  442. // GetFriendInvitationStorageChannelEvent() -> handle<copy>
  443. public ResultCode GetFriendInvitationStorageChannelEvent(ServiceCtx context)
  444. {
  445. if (_friendInvitationStorageChannelEventHandle == 0)
  446. {
  447. if (context.Process.HandleTable.GenerateHandle(_friendInvitationStorageChannelEvent.ReadableEvent, out _friendInvitationStorageChannelEventHandle) != KernelResult.Success)
  448. {
  449. throw new InvalidOperationException("Out of handles!");
  450. }
  451. }
  452. context.Response.HandleDesc = IpcHandleDesc.MakeCopy(_friendInvitationStorageChannelEventHandle);
  453. return ResultCode.Success;
  454. }
  455. [CommandHipc(141)] // 9.0.0+
  456. // TryPopFromFriendInvitationStorageChannel() -> object<nn::am::service::IStorage>
  457. public ResultCode TryPopFromFriendInvitationStorageChannel(ServiceCtx context)
  458. {
  459. // NOTE: IStorage are pushed in the channel with IApplicationAccessor PushToFriendInvitationStorageChannel
  460. // If _friendInvitationStorageChannelEvent is signaled, the event is cleared.
  461. // If an IStorage is available, returns it with ResultCode.Success.
  462. // If not, just returns ResultCode.NotAvailable. Since we don't support friend feature for now, it's fine to do the same.
  463. Logger.Stub?.PrintStub(LogClass.ServiceAm);
  464. return ResultCode.NotAvailable;
  465. }
  466. [CommandHipc(150)] // 9.0.0+
  467. // GetNotificationStorageChannelEvent() -> handle<copy>
  468. public ResultCode GetNotificationStorageChannelEvent(ServiceCtx context)
  469. {
  470. if (_notificationStorageChannelEventHandle == 0)
  471. {
  472. if (context.Process.HandleTable.GenerateHandle(_notificationStorageChannelEvent.ReadableEvent, out _notificationStorageChannelEventHandle) != KernelResult.Success)
  473. {
  474. throw new InvalidOperationException("Out of handles!");
  475. }
  476. }
  477. context.Response.HandleDesc = IpcHandleDesc.MakeCopy(_notificationStorageChannelEventHandle);
  478. return ResultCode.Success;
  479. }
  480. [CommandHipc(160)] // 9.0.0+
  481. // GetHealthWarningDisappearedSystemEvent() -> handle<copy>
  482. public ResultCode GetHealthWarningDisappearedSystemEvent(ServiceCtx context)
  483. {
  484. if (_healthWarningDisappearedSystemEventHandle == 0)
  485. {
  486. if (context.Process.HandleTable.GenerateHandle(_healthWarningDisappearedSystemEvent.ReadableEvent, out _healthWarningDisappearedSystemEventHandle) != KernelResult.Success)
  487. {
  488. throw new InvalidOperationException("Out of handles!");
  489. }
  490. }
  491. context.Response.HandleDesc = IpcHandleDesc.MakeCopy(_healthWarningDisappearedSystemEventHandle);
  492. return ResultCode.Success;
  493. }
  494. [CommandHipc(1001)] // 10.0.0+
  495. // PrepareForJit()
  496. public ResultCode PrepareForJit(ServiceCtx context)
  497. {
  498. if (Interlocked.Exchange(ref _jitLoaded, 1) == 0)
  499. {
  500. string jitPath = context.Device.System.ContentManager.GetInstalledContentPath(0x010000000000003B, StorageId.BuiltInSystem, NcaContentType.Program);
  501. string filePath = context.Device.FileSystem.SwitchPathToSystemPath(jitPath);
  502. if (string.IsNullOrWhiteSpace(filePath))
  503. {
  504. throw new InvalidSystemResourceException($"JIT (010000000000003B) system title not found! The JIT will not work, provide the system archive to fix this error. (See https://github.com/Ryujinx/Ryujinx#requirements for more information)");
  505. }
  506. context.Device.Application.LoadServiceNca(filePath);
  507. // FIXME: Most likely not how this should be done?
  508. while (!context.Device.System.SmRegistry.IsServiceRegistered("jit:u"))
  509. {
  510. context.Device.System.SmRegistry.WaitForServiceRegistration();
  511. }
  512. }
  513. return ResultCode.Success;
  514. }
  515. }
  516. }