Horizon.cs 27 KB

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