Horizon.cs 34 KB

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