Horizon.cs 27 KB

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