Horizon.cs 34 KB

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