Horizon.cs 32 KB

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