Horizon.cs 33 KB

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