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