Horizon.cs 32 KB

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