Horizon.cs 28 KB

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