Horizon.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. using LibHac;
  2. using LibHac.Account;
  3. using LibHac.Bcat;
  4. using LibHac.Common;
  5. using LibHac.Fs;
  6. using LibHac.FsSystem;
  7. using LibHac.FsSystem.NcaUtils;
  8. using LibHac.Ncm;
  9. using LibHac.Ns;
  10. using LibHac.Spl;
  11. using Ryujinx.Common;
  12. using Ryujinx.Common.Configuration;
  13. using Ryujinx.Common.Logging;
  14. using Ryujinx.Configuration;
  15. using Ryujinx.HLE.FileSystem.Content;
  16. using Ryujinx.HLE.HOS.Font;
  17. using Ryujinx.HLE.HOS.Kernel;
  18. using Ryujinx.HLE.HOS.Kernel.Memory;
  19. using Ryujinx.HLE.HOS.Kernel.Process;
  20. using Ryujinx.HLE.HOS.Kernel.Threading;
  21. using Ryujinx.HLE.HOS.Services.Am.AppletAE.AllSystemAppletProxiesService.SystemAppletProxy;
  22. using Ryujinx.HLE.HOS.Services.Arp;
  23. using Ryujinx.HLE.HOS.Services.Mii;
  24. using Ryujinx.HLE.HOS.Services.Nv;
  25. using Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostCtrl;
  26. using Ryujinx.HLE.HOS.Services.Pcv.Bpc;
  27. using Ryujinx.HLE.HOS.Services.Settings;
  28. using Ryujinx.HLE.HOS.Services.Sm;
  29. using Ryujinx.HLE.HOS.Services.SurfaceFlinger;
  30. using Ryujinx.HLE.HOS.Services.Time.Clock;
  31. using Ryujinx.HLE.HOS.SystemState;
  32. using Ryujinx.HLE.Loaders.Executables;
  33. using Ryujinx.HLE.Loaders.Npdm;
  34. using Ryujinx.HLE.Utilities;
  35. using System;
  36. using System.Collections.Generic;
  37. using System.IO;
  38. using System.Linq;
  39. using System.Reflection;
  40. using static LibHac.Fs.ApplicationSaveDataManagement;
  41. namespace Ryujinx.HLE.HOS
  42. {
  43. using TimeServiceManager = Services.Time.TimeManager;
  44. using JsonHelper = Common.Utilities.JsonHelper;
  45. public class Horizon : IDisposable
  46. {
  47. internal const int HidSize = 0x40000;
  48. internal const int FontSize = 0x1100000;
  49. internal const int IirsSize = 0x8000;
  50. internal const int TimeSize = 0x1000;
  51. internal KernelContext KernelContext { get; }
  52. internal Switch Device { get; private set; }
  53. internal SurfaceFlinger SurfaceFlinger { get; private set; }
  54. public SystemStateMgr State { get; private set; }
  55. internal AppletStateMgr AppletState { get; private set; }
  56. internal KSharedMemory HidSharedMem { get; private set; }
  57. internal KSharedMemory FontSharedMem { get; private set; }
  58. internal KSharedMemory IirsSharedMem { get; private set; }
  59. internal SharedFontManager Font { get; private set; }
  60. internal ContentManager ContentManager { get; private set; }
  61. internal KEvent VsyncEvent { get; private set; }
  62. internal KEvent DisplayResolutionChangeEvent { get; private set; }
  63. public Keyset KeySet => Device.FileSystem.KeySet;
  64. #pragma warning disable CS0649
  65. private bool _hasStarted;
  66. #pragma warning restore CS0649
  67. private bool _isDisposed;
  68. public BlitStruct<ApplicationControlProperty> ControlData { get; set; }
  69. public string TitleName { get; private set; }
  70. public ulong TitleId { get; private set; }
  71. public string TitleIdText => TitleId.ToString("x16");
  72. public string TitleVersionString { get; private set; }
  73. public bool TitleIs64Bit { get; private set; }
  74. public IntegrityCheckLevel FsIntegrityCheckLevel { get; set; }
  75. public int GlobalAccessLogMode { get; set; }
  76. internal ulong HidBaseAddress { get; private set; }
  77. internal NvHostSyncpt HostSyncpoint { get; private set; }
  78. internal LibHac.Horizon LibHacHorizonServer { get; private set; }
  79. internal HorizonClient LibHacHorizonClient { get; private set; }
  80. public Horizon(Switch device, ContentManager contentManager)
  81. {
  82. ControlData = new BlitStruct<ApplicationControlProperty>(1);
  83. KernelContext = new KernelContext(device, device.Memory);
  84. Device = device;
  85. State = new SystemStateMgr();
  86. // Note: This is not really correct, but with HLE of services, the only memory
  87. // region used that is used is Application, so we can use the other ones for anything.
  88. KMemoryRegionManager region = KernelContext.MemoryRegions[(int)MemoryRegion.NvServices];
  89. ulong hidPa = region.Address;
  90. ulong fontPa = region.Address + HidSize;
  91. ulong iirsPa = region.Address + HidSize + FontSize;
  92. ulong timePa = region.Address + HidSize + FontSize + IirsSize;
  93. HidBaseAddress = hidPa - DramMemoryMap.DramBase;
  94. KPageList hidPageList = new KPageList();
  95. KPageList fontPageList = new KPageList();
  96. KPageList iirsPageList = new KPageList();
  97. KPageList timePageList = new KPageList();
  98. hidPageList .AddRange(hidPa, HidSize / KMemoryManager.PageSize);
  99. fontPageList.AddRange(fontPa, FontSize / KMemoryManager.PageSize);
  100. iirsPageList.AddRange(iirsPa, IirsSize / KMemoryManager.PageSize);
  101. timePageList.AddRange(timePa, TimeSize / KMemoryManager.PageSize);
  102. HidSharedMem = new KSharedMemory(KernelContext, hidPageList, 0, 0, MemoryPermission.Read);
  103. FontSharedMem = new KSharedMemory(KernelContext, fontPageList, 0, 0, MemoryPermission.Read);
  104. IirsSharedMem = new KSharedMemory(KernelContext, iirsPageList, 0, 0, MemoryPermission.Read);
  105. KSharedMemory timeSharedMemory = new KSharedMemory(KernelContext, timePageList, 0, 0, MemoryPermission.Read);
  106. TimeServiceManager.Instance.Initialize(device, this, timeSharedMemory, timePa - DramMemoryMap.DramBase, TimeSize);
  107. AppletState = new AppletStateMgr(this);
  108. AppletState.SetFocus(true);
  109. Font = new SharedFontManager(device, fontPa - DramMemoryMap.DramBase);
  110. IUserInterface.InitializePort(this);
  111. VsyncEvent = new KEvent(KernelContext);
  112. DisplayResolutionChangeEvent = new KEvent(KernelContext);
  113. ContentManager = contentManager;
  114. // TODO: use set:sys (and get external clock source id from settings)
  115. // TODO: use "time!standard_steady_clock_rtc_update_interval_minutes" and implement a worker thread to be accurate.
  116. UInt128 clockSourceId = new UInt128(Guid.NewGuid().ToByteArray());
  117. IRtcManager.GetExternalRtcValue(out ulong rtcValue);
  118. // We assume the rtc is system time.
  119. TimeSpanType systemTime = TimeSpanType.FromSeconds((long)rtcValue);
  120. // Configure and setup internal offset
  121. TimeSpanType internalOffset = TimeSpanType.FromSeconds(ConfigurationState.Instance.System.SystemTimeOffset);
  122. TimeSpanType systemTimeOffset = new TimeSpanType(systemTime.NanoSeconds + internalOffset.NanoSeconds);
  123. if (systemTime.IsDaylightSavingTime() && !systemTimeOffset.IsDaylightSavingTime())
  124. {
  125. internalOffset = internalOffset.AddSeconds(3600L);
  126. }
  127. else if (!systemTime.IsDaylightSavingTime() && systemTimeOffset.IsDaylightSavingTime())
  128. {
  129. internalOffset = internalOffset.AddSeconds(-3600L);
  130. }
  131. internalOffset = new TimeSpanType(-internalOffset.NanoSeconds);
  132. // First init the standard steady clock
  133. TimeServiceManager.Instance.SetupStandardSteadyClock(null, clockSourceId, systemTime, internalOffset, TimeSpanType.Zero, false);
  134. TimeServiceManager.Instance.SetupStandardLocalSystemClock(null, new SystemClockContext(), systemTime.ToSeconds());
  135. if (NxSettings.Settings.TryGetValue("time!standard_network_clock_sufficient_accuracy_minutes", out object standardNetworkClockSufficientAccuracyMinutes))
  136. {
  137. TimeSpanType standardNetworkClockSufficientAccuracy = new TimeSpanType((int)standardNetworkClockSufficientAccuracyMinutes * 60000000000);
  138. TimeServiceManager.Instance.SetupStandardNetworkSystemClock(new SystemClockContext(), standardNetworkClockSufficientAccuracy);
  139. }
  140. TimeServiceManager.Instance.SetupStandardUserSystemClock(null, false, SteadyClockTimePoint.GetRandom());
  141. // FIXME: TimeZone shoud be init here but it's actually done in ContentManager
  142. TimeServiceManager.Instance.SetupEphemeralNetworkSystemClock();
  143. DatabaseImpl.Instance.InitializeDatabase(device);
  144. HostSyncpoint = new NvHostSyncpt(device);
  145. SurfaceFlinger = new SurfaceFlinger(device);
  146. ConfigurationState.Instance.System.EnableDockedMode.Event += OnDockedModeChange;
  147. InitLibHacHorizon();
  148. }
  149. private void InitLibHacHorizon()
  150. {
  151. LibHac.Horizon horizon = new LibHac.Horizon(null, Device.FileSystem.FsServer);
  152. horizon.CreateHorizonClient(out HorizonClient ryujinxClient).ThrowIfFailure();
  153. horizon.CreateHorizonClient(out HorizonClient bcatClient).ThrowIfFailure();
  154. ryujinxClient.Sm.RegisterService(new LibHacIReader(this), "arp:r").ThrowIfFailure();
  155. new BcatServer(bcatClient);
  156. LibHacHorizonServer = horizon;
  157. LibHacHorizonClient = ryujinxClient;
  158. }
  159. private void OnDockedModeChange(object sender, ReactiveEventArgs<bool> e)
  160. {
  161. if (e.NewValue != State.DockedMode)
  162. {
  163. State.DockedMode = e.NewValue;
  164. AppletState.EnqueueMessage(MessageInfo.OperationModeChanged);
  165. AppletState.EnqueueMessage(MessageInfo.PerformanceModeChanged);
  166. SignalDisplayResolutionChange();
  167. }
  168. }
  169. public void LoadCart(string exeFsDir, string romFsFile = null)
  170. {
  171. if (romFsFile != null)
  172. {
  173. Device.FileSystem.LoadRomFs(romFsFile);
  174. }
  175. LocalFileSystem codeFs = new LocalFileSystem(exeFsDir);
  176. LoadExeFs(codeFs, out _);
  177. if (TitleId != 0)
  178. {
  179. EnsureSaveData(new TitleId(TitleId));
  180. }
  181. }
  182. public void LoadXci(string xciFile)
  183. {
  184. FileStream file = new FileStream(xciFile, FileMode.Open, FileAccess.Read);
  185. Xci xci = new Xci(KeySet, file.AsStorage());
  186. (Nca mainNca, Nca patchNca, Nca controlNca) = GetXciGameData(xci);
  187. if (mainNca == null)
  188. {
  189. Logger.PrintError(LogClass.Loader, "Unable to load XCI");
  190. return;
  191. }
  192. ContentManager.LoadEntries(Device);
  193. LoadNca(mainNca, patchNca, controlNca);
  194. }
  195. public void LoadKip(string kipFile)
  196. {
  197. using (IStorage fs = new LocalStorage(kipFile, FileAccess.Read))
  198. {
  199. ProgramLoader.LoadKip(KernelContext, new KipExecutable(fs));
  200. }
  201. }
  202. private (Nca Main, Nca patch, Nca Control) GetXciGameData(Xci xci)
  203. {
  204. if (!xci.HasPartition(XciPartitionType.Secure))
  205. {
  206. throw new InvalidDataException("Could not find XCI secure partition");
  207. }
  208. Nca mainNca = null;
  209. Nca patchNca = null;
  210. Nca controlNca = null;
  211. XciPartition securePartition = xci.OpenPartition(XciPartitionType.Secure);
  212. foreach (DirectoryEntryEx ticketEntry in securePartition.EnumerateEntries("/", "*.tik"))
  213. {
  214. Result result = securePartition.OpenFile(out IFile ticketFile, ticketEntry.FullPath.ToU8Span(), OpenMode.Read);
  215. if (result.IsSuccess())
  216. {
  217. Ticket ticket = new Ticket(ticketFile.AsStream());
  218. KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(KeySet)));
  219. }
  220. }
  221. foreach (DirectoryEntryEx fileEntry in securePartition.EnumerateEntries("/", "*.nca"))
  222. {
  223. Result result = securePartition.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read);
  224. if (result.IsFailure())
  225. {
  226. continue;
  227. }
  228. Nca nca = new Nca(KeySet, ncaFile.AsStorage());
  229. if (nca.Header.ContentType == NcaContentType.Program)
  230. {
  231. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  232. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  233. {
  234. patchNca = nca;
  235. }
  236. else
  237. {
  238. mainNca = nca;
  239. }
  240. }
  241. else if (nca.Header.ContentType == NcaContentType.Control)
  242. {
  243. controlNca = nca;
  244. }
  245. }
  246. if (mainNca == null)
  247. {
  248. Logger.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided XCI file");
  249. }
  250. if (controlNca != null)
  251. {
  252. ReadControlData(controlNca);
  253. }
  254. else
  255. {
  256. ControlData.ByteSpan.Clear();
  257. }
  258. return (mainNca, patchNca, controlNca);
  259. }
  260. public void ReadControlData(Nca controlNca)
  261. {
  262. IFileSystem controlFs = controlNca.OpenFileSystem(NcaSectionType.Data, FsIntegrityCheckLevel);
  263. Result result = controlFs.OpenFile(out IFile controlFile, "/control.nacp".ToU8Span(), OpenMode.Read);
  264. if (result.IsSuccess())
  265. {
  266. result = controlFile.Read(out long bytesRead, 0, ControlData.ByteSpan, ReadOption.None);
  267. if (result.IsSuccess() && bytesRead == ControlData.ByteSpan.Length)
  268. {
  269. TitleName = ControlData.Value
  270. .Titles[(int) State.DesiredTitleLanguage].Name.ToString();
  271. if (string.IsNullOrWhiteSpace(TitleName))
  272. {
  273. TitleName = ControlData.Value.Titles.ToArray()
  274. .FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  275. }
  276. TitleVersionString = ControlData.Value.DisplayVersion.ToString();
  277. }
  278. }
  279. else
  280. {
  281. ControlData.ByteSpan.Clear();
  282. }
  283. }
  284. public void LoadNca(string ncaFile)
  285. {
  286. FileStream file = new FileStream(ncaFile, FileMode.Open, FileAccess.Read);
  287. Nca nca = new Nca(KeySet, file.AsStorage(false));
  288. LoadNca(nca, null, null);
  289. }
  290. public void LoadNsp(string nspFile)
  291. {
  292. FileStream file = new FileStream(nspFile, FileMode.Open, FileAccess.Read);
  293. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  294. foreach (DirectoryEntryEx ticketEntry in nsp.EnumerateEntries("/", "*.tik"))
  295. {
  296. Result result = nsp.OpenFile(out IFile ticketFile, ticketEntry.FullPath.ToU8Span(), OpenMode.Read);
  297. if (result.IsSuccess())
  298. {
  299. Ticket ticket = new Ticket(ticketFile.AsStream());
  300. KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(KeySet)));
  301. }
  302. }
  303. Nca mainNca = null;
  304. Nca patchNca = null;
  305. Nca controlNca = null;
  306. foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
  307. {
  308. nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  309. Nca nca = new Nca(KeySet, ncaFile.AsStorage());
  310. if (nca.Header.ContentType == NcaContentType.Program)
  311. {
  312. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  313. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  314. {
  315. patchNca = nca;
  316. }
  317. else
  318. {
  319. mainNca = nca;
  320. }
  321. }
  322. else if (nca.Header.ContentType == NcaContentType.Control)
  323. {
  324. controlNca = nca;
  325. }
  326. }
  327. if (mainNca != null)
  328. {
  329. LoadNca(mainNca, patchNca, controlNca);
  330. return;
  331. }
  332. // This is not a normal NSP, it's actually a ExeFS as a NSP
  333. LoadExeFs(nsp, out _);
  334. }
  335. public void LoadNca(Nca mainNca, Nca patchNca, Nca controlNca)
  336. {
  337. if (mainNca.Header.ContentType != NcaContentType.Program)
  338. {
  339. Logger.PrintError(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");
  340. return;
  341. }
  342. IStorage dataStorage = null;
  343. IFileSystem codeFs = null;
  344. string titleUpdateMetadataPath = System.IO.Path.Combine(Device.FileSystem.GetBasePath(), "games", mainNca.Header.TitleId.ToString("x16"), "updates.json");
  345. if (File.Exists(titleUpdateMetadataPath))
  346. {
  347. string updatePath = JsonHelper.DeserializeFromFile<TitleUpdateMetadata>(titleUpdateMetadataPath).Selected;
  348. if (File.Exists(updatePath))
  349. {
  350. FileStream file = new FileStream(updatePath, FileMode.Open, FileAccess.Read);
  351. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  352. foreach (DirectoryEntryEx ticketEntry in nsp.EnumerateEntries("/", "*.tik"))
  353. {
  354. Result result = nsp.OpenFile(out IFile ticketFile, ticketEntry.FullPath.ToU8Span(), OpenMode.Read);
  355. if (result.IsSuccess())
  356. {
  357. Ticket ticket = new Ticket(ticketFile.AsStream());
  358. KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(KeySet)));
  359. }
  360. }
  361. foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
  362. {
  363. nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  364. Nca nca = new Nca(KeySet, ncaFile.AsStorage());
  365. if ($"{nca.Header.TitleId.ToString("x16")[..^3]}000" != mainNca.Header.TitleId.ToString("x16"))
  366. {
  367. break;
  368. }
  369. if (nca.Header.ContentType == NcaContentType.Program)
  370. {
  371. patchNca = nca;
  372. }
  373. else if (nca.Header.ContentType == NcaContentType.Control)
  374. {
  375. controlNca = nca;
  376. }
  377. }
  378. }
  379. }
  380. if (patchNca == null)
  381. {
  382. if (mainNca.CanOpenSection(NcaSectionType.Data))
  383. {
  384. dataStorage = mainNca.OpenStorage(NcaSectionType.Data, FsIntegrityCheckLevel);
  385. }
  386. if (mainNca.CanOpenSection(NcaSectionType.Code))
  387. {
  388. codeFs = mainNca.OpenFileSystem(NcaSectionType.Code, FsIntegrityCheckLevel);
  389. }
  390. }
  391. else
  392. {
  393. if (patchNca.CanOpenSection(NcaSectionType.Data))
  394. {
  395. dataStorage = mainNca.OpenStorageWithPatch(patchNca, NcaSectionType.Data, FsIntegrityCheckLevel);
  396. }
  397. if (patchNca.CanOpenSection(NcaSectionType.Code))
  398. {
  399. codeFs = mainNca.OpenFileSystemWithPatch(patchNca, NcaSectionType.Code, FsIntegrityCheckLevel);
  400. }
  401. }
  402. if (codeFs == null)
  403. {
  404. Logger.PrintError(LogClass.Loader, "No ExeFS found in NCA");
  405. return;
  406. }
  407. if (dataStorage == null)
  408. {
  409. Logger.PrintWarning(LogClass.Loader, "No RomFS found in NCA");
  410. }
  411. else
  412. {
  413. Device.FileSystem.SetRomFs(dataStorage.AsStream(FileAccess.Read));
  414. }
  415. LoadExeFs(codeFs, out Npdm metaData);
  416. TitleId = metaData.Aci0.TitleId;
  417. TitleIs64Bit = metaData.Is64Bit;
  418. if (controlNca != null)
  419. {
  420. ReadControlData(controlNca);
  421. }
  422. else
  423. {
  424. ControlData.ByteSpan.Clear();
  425. }
  426. if (TitleId != 0)
  427. {
  428. EnsureSaveData(new TitleId(TitleId));
  429. }
  430. Logger.PrintInfo(LogClass.Loader, $"Application Loaded: {TitleName} v{TitleVersionString} [{TitleIdText}] [{(TitleIs64Bit ? "64-bit" : "32-bit")}]");
  431. }
  432. private void LoadExeFs(IFileSystem codeFs, out Npdm metaData)
  433. {
  434. Result result = codeFs.OpenFile(out IFile npdmFile, "/main.npdm".ToU8Span(), OpenMode.Read);
  435. if (ResultFs.PathNotFound.Includes(result))
  436. {
  437. Logger.PrintWarning(LogClass.Loader, "NPDM file not found, using default values!");
  438. metaData = GetDefaultNpdm();
  439. }
  440. else
  441. {
  442. metaData = new Npdm(npdmFile.AsStream());
  443. }
  444. List<IExecutable> staticObjects = new List<IExecutable>();
  445. void LoadNso(string filename)
  446. {
  447. foreach (DirectoryEntryEx file in codeFs.EnumerateEntries("/", $"{filename}*"))
  448. {
  449. if (Path.GetExtension(file.Name) != string.Empty)
  450. {
  451. continue;
  452. }
  453. Logger.PrintInfo(LogClass.Loader, $"Loading {file.Name}...");
  454. codeFs.OpenFile(out IFile nsoFile, file.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  455. NsoExecutable staticObject = new NsoExecutable(nsoFile.AsStorage());
  456. staticObjects.Add(staticObject);
  457. }
  458. }
  459. TitleId = metaData.Aci0.TitleId;
  460. TitleIs64Bit = metaData.Is64Bit;
  461. LoadNso("rtld");
  462. LoadNso("main");
  463. LoadNso("subsdk");
  464. LoadNso("sdk");
  465. ContentManager.LoadEntries(Device);
  466. ProgramLoader.LoadNsos(KernelContext, metaData, staticObjects.ToArray());
  467. }
  468. public void LoadProgram(string filePath)
  469. {
  470. Npdm metaData = GetDefaultNpdm();
  471. bool isNro = Path.GetExtension(filePath).ToLower() == ".nro";
  472. IExecutable staticObject;
  473. if (isNro)
  474. {
  475. FileStream input = new FileStream(filePath, FileMode.Open);
  476. NroExecutable obj = new NroExecutable(input);
  477. staticObject = obj;
  478. // homebrew NRO can actually have some data after the actual NRO
  479. if (input.Length > obj.FileSize)
  480. {
  481. input.Position = obj.FileSize;
  482. BinaryReader reader = new BinaryReader(input);
  483. uint asetMagic = reader.ReadUInt32();
  484. if (asetMagic == 0x54455341)
  485. {
  486. uint asetVersion = reader.ReadUInt32();
  487. if (asetVersion == 0)
  488. {
  489. ulong iconOffset = reader.ReadUInt64();
  490. ulong iconSize = reader.ReadUInt64();
  491. ulong nacpOffset = reader.ReadUInt64();
  492. ulong nacpSize = reader.ReadUInt64();
  493. ulong romfsOffset = reader.ReadUInt64();
  494. ulong romfsSize = reader.ReadUInt64();
  495. if (romfsSize != 0)
  496. {
  497. Device.FileSystem.SetRomFs(new HomebrewRomFsStream(input, obj.FileSize + (long)romfsOffset));
  498. }
  499. if (nacpSize != 0)
  500. {
  501. input.Seek(obj.FileSize + (long)nacpOffset, SeekOrigin.Begin);
  502. reader.Read(ControlData.ByteSpan);
  503. ref ApplicationControlProperty nacp = ref ControlData.Value;
  504. metaData.TitleName = nacp.Titles[(int)State.DesiredTitleLanguage].Name.ToString();
  505. if (string.IsNullOrWhiteSpace(metaData.TitleName))
  506. {
  507. metaData.TitleName = nacp.Titles.ToArray().FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  508. }
  509. if (nacp.PresenceGroupId != 0)
  510. {
  511. metaData.Aci0.TitleId = nacp.PresenceGroupId;
  512. }
  513. else if (nacp.SaveDataOwnerId.Value != 0)
  514. {
  515. metaData.Aci0.TitleId = nacp.SaveDataOwnerId.Value;
  516. }
  517. else if (nacp.AddOnContentBaseId != 0)
  518. {
  519. metaData.Aci0.TitleId = nacp.AddOnContentBaseId - 0x1000;
  520. }
  521. else
  522. {
  523. metaData.Aci0.TitleId = 0000000000000000;
  524. }
  525. }
  526. }
  527. else
  528. {
  529. Logger.PrintWarning(LogClass.Loader, $"Unsupported ASET header version found \"{asetVersion}\"");
  530. }
  531. }
  532. }
  533. }
  534. else
  535. {
  536. staticObject = new NsoExecutable(new LocalStorage(filePath, FileAccess.Read));
  537. }
  538. ContentManager.LoadEntries(Device);
  539. TitleName = metaData.TitleName;
  540. TitleId = metaData.Aci0.TitleId;
  541. TitleIs64Bit = metaData.Is64Bit;
  542. ProgramLoader.LoadNsos(KernelContext, metaData, new IExecutable[] { staticObject });
  543. }
  544. private Npdm GetDefaultNpdm()
  545. {
  546. Assembly asm = Assembly.GetCallingAssembly();
  547. using (Stream npdmStream = asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm"))
  548. {
  549. return new Npdm(npdmStream);
  550. }
  551. }
  552. private Result EnsureSaveData(TitleId titleId)
  553. {
  554. Logger.PrintInfo(LogClass.Application, "Ensuring required savedata exists.");
  555. Uid user = State.Account.LastOpenedUser.UserId.ToLibHacUid();
  556. ref ApplicationControlProperty control = ref ControlData.Value;
  557. if (LibHac.Util.IsEmpty(ControlData.ByteSpan))
  558. {
  559. // If the current application doesn't have a loaded control property, create a dummy one
  560. // and set the savedata sizes so a user savedata will be created.
  561. control = ref new BlitStruct<ApplicationControlProperty>(1).Value;
  562. // The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
  563. control.UserAccountSaveDataSize = 0x4000;
  564. control.UserAccountSaveDataJournalSize = 0x4000;
  565. Logger.PrintWarning(LogClass.Application,
  566. "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games.");
  567. }
  568. FileSystemClient fs = Device.FileSystem.FsClient;
  569. Result rc = fs.EnsureApplicationCacheStorage(out _, titleId, ref control);
  570. if (rc.IsFailure())
  571. {
  572. Logger.PrintError(LogClass.Application, $"Error calling EnsureApplicationCacheStorage. Result code {rc.ToStringWithName()}");
  573. }
  574. rc = EnsureApplicationSaveData(fs, out _, titleId, ref control, ref user);
  575. if (rc.IsFailure())
  576. {
  577. Logger.PrintError(LogClass.Application, $"Error calling EnsureApplicationSaveData. Result code {rc.ToStringWithName()}");
  578. }
  579. return rc;
  580. }
  581. public void SignalDisplayResolutionChange()
  582. {
  583. DisplayResolutionChangeEvent.ReadableEvent.Signal();
  584. }
  585. public void SignalVsync()
  586. {
  587. VsyncEvent.ReadableEvent.Signal();
  588. }
  589. public void EnableMultiCoreScheduling()
  590. {
  591. if (!_hasStarted)
  592. {
  593. KernelContext.Scheduler.MultiCoreScheduling = true;
  594. }
  595. }
  596. public void DisableMultiCoreScheduling()
  597. {
  598. if (!_hasStarted)
  599. {
  600. KernelContext.Scheduler.MultiCoreScheduling = false;
  601. }
  602. }
  603. public void Dispose()
  604. {
  605. Dispose(true);
  606. }
  607. protected virtual void Dispose(bool disposing)
  608. {
  609. if (!_isDisposed && disposing)
  610. {
  611. ConfigurationState.Instance.System.EnableDockedMode.Event -= OnDockedModeChange;
  612. _isDisposed = true;
  613. SurfaceFlinger.Dispose();
  614. KProcess terminationProcess = new KProcess(KernelContext);
  615. KThread terminationThread = new KThread(KernelContext);
  616. terminationThread.Initialize(0, 0, 0, 3, 0, terminationProcess, ThreadType.Kernel, () =>
  617. {
  618. // Force all threads to exit.
  619. lock (KernelContext.Processes)
  620. {
  621. foreach (KProcess process in KernelContext.Processes.Values)
  622. {
  623. process.Terminate();
  624. }
  625. }
  626. // Exit ourself now!
  627. KernelContext.Scheduler.ExitThread(terminationThread);
  628. KernelContext.Scheduler.GetCurrentThread().Exit();
  629. KernelContext.Scheduler.RemoveThread(terminationThread);
  630. });
  631. terminationThread.Start();
  632. // Destroy nvservices channels as KThread could be waiting on some user events.
  633. // This is safe as KThread that are likely to call ioctls are going to be terminated by the post handler hook on the SVC facade.
  634. INvDrvServices.Destroy();
  635. // This is needed as the IPC Dummy KThread is also counted in the ThreadCounter.
  636. KernelContext.ThreadCounter.Signal();
  637. // It's only safe to release resources once all threads
  638. // have exited.
  639. KernelContext.ThreadCounter.Signal();
  640. KernelContext.ThreadCounter.Wait();
  641. KernelContext.Dispose();
  642. Device.Unload();
  643. }
  644. }
  645. }
  646. }