Horizon.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. using LibHac;
  2. using LibHac.Fs;
  3. using LibHac.FsService;
  4. using LibHac.FsSystem;
  5. using LibHac.FsSystem.NcaUtils;
  6. using LibHac.Spl;
  7. using Ryujinx.Common.Logging;
  8. using Ryujinx.HLE.FileSystem.Content;
  9. using Ryujinx.HLE.HOS.Font;
  10. using Ryujinx.HLE.HOS.Kernel.Common;
  11. using Ryujinx.HLE.HOS.Kernel.Memory;
  12. using Ryujinx.HLE.HOS.Kernel.Process;
  13. using Ryujinx.HLE.HOS.Kernel.Threading;
  14. using Ryujinx.HLE.HOS.Services.Pcv.Bpc;
  15. using Ryujinx.HLE.HOS.Services.Settings;
  16. using Ryujinx.HLE.HOS.Services.Sm;
  17. using Ryujinx.HLE.HOS.Services.Time.Clock;
  18. using Ryujinx.HLE.HOS.SystemState;
  19. using Ryujinx.HLE.Loaders.Executables;
  20. using Ryujinx.HLE.Loaders.Npdm;
  21. using Ryujinx.HLE.Utilities;
  22. using System;
  23. using System.Collections.Concurrent;
  24. using System.Collections.Generic;
  25. using System.IO;
  26. using System.Linq;
  27. using System.Reflection;
  28. using System.Threading;
  29. using TimeServiceManager = Ryujinx.HLE.HOS.Services.Time.TimeManager;
  30. using NxStaticObject = Ryujinx.HLE.Loaders.Executables.NxStaticObject;
  31. namespace Ryujinx.HLE.HOS
  32. {
  33. public class Horizon : IDisposable
  34. {
  35. internal const int InitialKipId = 1;
  36. internal const int InitialProcessId = 0x51;
  37. internal const int HidSize = 0x40000;
  38. internal const int FontSize = 0x1100000;
  39. internal const int IirsSize = 0x8000;
  40. internal const int TimeSize = 0x1000;
  41. private const int MemoryBlockAllocatorSize = 0x2710;
  42. private const ulong UserSlabHeapBase = DramMemoryMap.SlabHeapBase;
  43. private const ulong UserSlabHeapItemSize = KMemoryManager.PageSize;
  44. private const ulong UserSlabHeapSize = 0x3de000;
  45. internal long PrivilegedProcessLowestId { get; set; } = 1;
  46. internal long PrivilegedProcessHighestId { get; set; } = 8;
  47. internal Switch Device { get; private set; }
  48. public SystemStateMgr State { get; private set; }
  49. internal bool KernelInitialized { get; private set; }
  50. internal KResourceLimit ResourceLimit { get; private set; }
  51. internal KMemoryRegionManager[] MemoryRegions { get; private set; }
  52. internal KMemoryBlockAllocator LargeMemoryBlockAllocator { get; private set; }
  53. internal KMemoryBlockAllocator SmallMemoryBlockAllocator { get; private set; }
  54. internal KSlabHeap UserSlabHeapPages { get; private set; }
  55. internal KCriticalSection CriticalSection { get; private set; }
  56. internal KScheduler Scheduler { get; private set; }
  57. internal KTimeManager TimeManager { get; private set; }
  58. internal KSynchronization Synchronization { get; private set; }
  59. internal KContextIdManager ContextIdManager { get; private set; }
  60. private long _kipId;
  61. private long _processId;
  62. private long _threadUid;
  63. internal CountdownEvent ThreadCounter;
  64. internal SortedDictionary<long, KProcess> Processes;
  65. internal ConcurrentDictionary<string, KAutoObject> AutoObjectNames;
  66. internal bool EnableVersionChecks { get; private set; }
  67. internal AppletStateMgr AppletState { get; private set; }
  68. internal KSharedMemory HidSharedMem { get; private set; }
  69. internal KSharedMemory FontSharedMem { get; private set; }
  70. internal KSharedMemory IirsSharedMem { get; private set; }
  71. internal SharedFontManager Font { get; private set; }
  72. internal ContentManager ContentManager { get; private set; }
  73. internal KEvent VsyncEvent { get; private set; }
  74. public Keyset KeySet { get; private set; }
  75. private bool _hasStarted;
  76. public Nacp ControlData { get; set; }
  77. public string CurrentTitle { get; private set; }
  78. public string TitleName { get; private set; }
  79. public string TitleID { get; private set; }
  80. public IntegrityCheckLevel FsIntegrityCheckLevel { get; set; }
  81. public int GlobalAccessLogMode { get; set; }
  82. internal long HidBaseAddress { get; private set; }
  83. internal FileSystemServer FsServer { get; private set; }
  84. internal EmulatedGameCard GameCard { get; private set; }
  85. public Horizon(Switch device)
  86. {
  87. ControlData = new Nacp();
  88. Device = device;
  89. State = new SystemStateMgr();
  90. ResourceLimit = new KResourceLimit(this);
  91. KernelInit.InitializeResourceLimit(ResourceLimit);
  92. MemoryRegions = KernelInit.GetMemoryRegions();
  93. LargeMemoryBlockAllocator = new KMemoryBlockAllocator(MemoryBlockAllocatorSize * 2);
  94. SmallMemoryBlockAllocator = new KMemoryBlockAllocator(MemoryBlockAllocatorSize);
  95. UserSlabHeapPages = new KSlabHeap(
  96. UserSlabHeapBase,
  97. UserSlabHeapItemSize,
  98. UserSlabHeapSize);
  99. CriticalSection = new KCriticalSection(this);
  100. Scheduler = new KScheduler(this);
  101. TimeManager = new KTimeManager();
  102. Synchronization = new KSynchronization(this);
  103. ContextIdManager = new KContextIdManager();
  104. _kipId = InitialKipId;
  105. _processId = InitialProcessId;
  106. Scheduler.StartAutoPreemptionThread();
  107. KernelInitialized = true;
  108. ThreadCounter = new CountdownEvent(1);
  109. Processes = new SortedDictionary<long, KProcess>();
  110. AutoObjectNames = new ConcurrentDictionary<string, KAutoObject>();
  111. // Note: This is not really correct, but with HLE of services, the only memory
  112. // region used that is used is Application, so we can use the other ones for anything.
  113. KMemoryRegionManager region = MemoryRegions[(int)MemoryRegion.NvServices];
  114. ulong hidPa = region.Address;
  115. ulong fontPa = region.Address + HidSize;
  116. ulong iirsPa = region.Address + HidSize + FontSize;
  117. ulong timePa = region.Address + HidSize + FontSize + IirsSize;
  118. HidBaseAddress = (long)(hidPa - DramMemoryMap.DramBase);
  119. KPageList hidPageList = new KPageList();
  120. KPageList fontPageList = new KPageList();
  121. KPageList iirsPageList = new KPageList();
  122. KPageList timePageList = new KPageList();
  123. hidPageList .AddRange(hidPa, HidSize / KMemoryManager.PageSize);
  124. fontPageList.AddRange(fontPa, FontSize / KMemoryManager.PageSize);
  125. iirsPageList.AddRange(iirsPa, IirsSize / KMemoryManager.PageSize);
  126. timePageList.AddRange(timePa, TimeSize / KMemoryManager.PageSize);
  127. HidSharedMem = new KSharedMemory(this, hidPageList, 0, 0, MemoryPermission.Read);
  128. FontSharedMem = new KSharedMemory(this, fontPageList, 0, 0, MemoryPermission.Read);
  129. IirsSharedMem = new KSharedMemory(this, iirsPageList, 0, 0, MemoryPermission.Read);
  130. KSharedMemory timeSharedMemory = new KSharedMemory(this, timePageList, 0, 0, MemoryPermission.Read);
  131. TimeServiceManager.Instance.Initialize(device, this, timeSharedMemory, (long)(timePa - DramMemoryMap.DramBase), TimeSize);
  132. AppletState = new AppletStateMgr(this);
  133. AppletState.SetFocus(true);
  134. Font = new SharedFontManager(device, (long)(fontPa - DramMemoryMap.DramBase));
  135. IUserInterface.InitializePort(this);
  136. VsyncEvent = new KEvent(this);
  137. LoadKeySet();
  138. ContentManager = new ContentManager(device);
  139. // TODO: use set:sys (and get external clock source id from settings)
  140. // TODO: use "time!standard_steady_clock_rtc_update_interval_minutes" and implement a worker thread to be accurate.
  141. UInt128 clockSourceId = new UInt128(Guid.NewGuid().ToByteArray());
  142. IRtcManager.GetExternalRtcValue(out ulong rtcValue);
  143. // We assume the rtc is system time.
  144. TimeSpanType systemTime = TimeSpanType.FromSeconds((long)rtcValue);
  145. // First init the standard steady clock
  146. TimeServiceManager.Instance.SetupStandardSteadyClock(null, clockSourceId, systemTime, TimeSpanType.Zero, TimeSpanType.Zero, false);
  147. TimeServiceManager.Instance.SetupStandardLocalSystemClock(null, new SystemClockContext(), systemTime.ToSeconds());
  148. if (NxSettings.Settings.TryGetValue("time!standard_network_clock_sufficient_accuracy_minutes", out object standardNetworkClockSufficientAccuracyMinutes))
  149. {
  150. TimeSpanType standardNetworkClockSufficientAccuracy = new TimeSpanType((int)standardNetworkClockSufficientAccuracyMinutes * 60000000000);
  151. TimeServiceManager.Instance.SetupStandardNetworkSystemClock(new SystemClockContext(), standardNetworkClockSufficientAccuracy);
  152. }
  153. TimeServiceManager.Instance.SetupStandardUserSystemClock(null, false, SteadyClockTimePoint.GetRandom());
  154. // FIXME: TimeZone shoud be init here but it's actually done in ContentManager
  155. TimeServiceManager.Instance.SetupEphemeralNetworkSystemClock();
  156. LocalFileSystem serverBaseFs = new LocalFileSystem(device.FileSystem.GetBasePath());
  157. DefaultFsServerObjects fsServerObjects = DefaultFsServerObjects.GetDefaultEmulatedCreators(serverBaseFs, KeySet);
  158. GameCard = fsServerObjects.GameCard;
  159. FileSystemServerConfig fsServerConfig = new FileSystemServerConfig
  160. {
  161. FsCreators = fsServerObjects.FsCreators,
  162. DeviceOperator = fsServerObjects.DeviceOperator,
  163. ExternalKeySet = KeySet.ExternalKeySet
  164. };
  165. FsServer = new FileSystemServer(fsServerConfig);
  166. }
  167. public void LoadCart(string exeFsDir, string romFsFile = null)
  168. {
  169. if (romFsFile != null)
  170. {
  171. Device.FileSystem.LoadRomFs(romFsFile);
  172. }
  173. LocalFileSystem codeFs = new LocalFileSystem(exeFsDir);
  174. LoadExeFs(codeFs, out _);
  175. }
  176. public void LoadXci(string xciFile)
  177. {
  178. FileStream file = new FileStream(xciFile, FileMode.Open, FileAccess.Read);
  179. Xci xci = new Xci(KeySet, file.AsStorage());
  180. (Nca mainNca, Nca patchNca, Nca controlNca) = GetXciGameData(xci);
  181. if (mainNca == null)
  182. {
  183. Logger.PrintError(LogClass.Loader, "Unable to load XCI");
  184. return;
  185. }
  186. ContentManager.LoadEntries();
  187. LoadNca(mainNca, patchNca, controlNca);
  188. }
  189. public void LoadKip(string kipFile)
  190. {
  191. using (FileStream fs = new FileStream(kipFile, FileMode.Open))
  192. {
  193. ProgramLoader.LoadKernelInitalProcess(this, new KernelInitialProcess(fs));
  194. }
  195. }
  196. private (Nca Main, Nca patch, Nca Control) GetXciGameData(Xci xci)
  197. {
  198. if (!xci.HasPartition(XciPartitionType.Secure))
  199. {
  200. throw new InvalidDataException("Could not find XCI secure partition");
  201. }
  202. Nca mainNca = null;
  203. Nca patchNca = null;
  204. Nca controlNca = null;
  205. XciPartition securePartition = xci.OpenPartition(XciPartitionType.Secure);
  206. foreach (DirectoryEntryEx ticketEntry in securePartition.EnumerateEntries("/", "*.tik"))
  207. {
  208. Result result = securePartition.OpenFile(out IFile ticketFile, ticketEntry.FullPath, OpenMode.Read);
  209. if (result.IsSuccess())
  210. {
  211. Ticket ticket = new Ticket(ticketFile.AsStream());
  212. KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(KeySet)));
  213. }
  214. }
  215. foreach (DirectoryEntryEx fileEntry in securePartition.EnumerateEntries("/", "*.nca"))
  216. {
  217. Result result = securePartition.OpenFile(out IFile ncaFile, fileEntry.FullPath, OpenMode.Read);
  218. if (result.IsFailure())
  219. {
  220. continue;
  221. }
  222. Nca nca = new Nca(KeySet, ncaFile.AsStorage());
  223. if (nca.Header.ContentType == NcaContentType.Program)
  224. {
  225. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  226. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  227. {
  228. patchNca = nca;
  229. }
  230. else
  231. {
  232. mainNca = nca;
  233. }
  234. }
  235. else if (nca.Header.ContentType == NcaContentType.Control)
  236. {
  237. controlNca = nca;
  238. }
  239. }
  240. if (mainNca == null)
  241. {
  242. Logger.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided XCI file");
  243. }
  244. if (controlNca != null)
  245. {
  246. ReadControlData(controlNca);
  247. }
  248. return (mainNca, patchNca, controlNca);
  249. }
  250. public void ReadControlData(Nca controlNca)
  251. {
  252. IFileSystem controlFs = controlNca.OpenFileSystem(NcaSectionType.Data, FsIntegrityCheckLevel);
  253. Result result = controlFs.OpenFile(out IFile controlFile, "/control.nacp", OpenMode.Read);
  254. if (result.IsSuccess())
  255. {
  256. ControlData = new Nacp(controlFile.AsStream());
  257. TitleName = CurrentTitle = ControlData.Descriptions[(int) State.DesiredTitleLanguage].Title;
  258. }
  259. }
  260. public void LoadNca(string ncaFile)
  261. {
  262. FileStream file = new FileStream(ncaFile, FileMode.Open, FileAccess.Read);
  263. Nca nca = new Nca(KeySet, file.AsStorage(false));
  264. LoadNca(nca, null, null);
  265. }
  266. public void LoadNsp(string nspFile)
  267. {
  268. FileStream file = new FileStream(nspFile, FileMode.Open, FileAccess.Read);
  269. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  270. foreach (DirectoryEntryEx ticketEntry in nsp.EnumerateEntries("/", "*.tik"))
  271. {
  272. Result result = nsp.OpenFile(out IFile ticketFile, ticketEntry.FullPath, OpenMode.Read);
  273. if (result.IsSuccess())
  274. {
  275. Ticket ticket = new Ticket(ticketFile.AsStream());
  276. KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(KeySet)));
  277. }
  278. }
  279. Nca mainNca = null;
  280. Nca patchNca = null;
  281. Nca controlNca = null;
  282. foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
  283. {
  284. nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath, OpenMode.Read).ThrowIfFailure();
  285. Nca nca = new Nca(KeySet, ncaFile.AsStorage());
  286. if (nca.Header.ContentType == NcaContentType.Program)
  287. {
  288. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  289. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  290. {
  291. patchNca = nca;
  292. }
  293. else
  294. {
  295. mainNca = nca;
  296. }
  297. }
  298. else if (nca.Header.ContentType == NcaContentType.Control)
  299. {
  300. controlNca = nca;
  301. }
  302. }
  303. if (mainNca != null)
  304. {
  305. LoadNca(mainNca, patchNca, controlNca);
  306. return;
  307. }
  308. // This is not a normal NSP, it's actually a ExeFS as a NSP
  309. LoadExeFs(nsp, out _);
  310. }
  311. public void LoadNca(Nca mainNca, Nca patchNca, Nca controlNca)
  312. {
  313. if (mainNca.Header.ContentType != NcaContentType.Program)
  314. {
  315. Logger.PrintError(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");
  316. return;
  317. }
  318. IStorage dataStorage = null;
  319. IFileSystem codeFs = null;
  320. if (patchNca == null)
  321. {
  322. if (mainNca.CanOpenSection(NcaSectionType.Data))
  323. {
  324. dataStorage = mainNca.OpenStorage(NcaSectionType.Data, FsIntegrityCheckLevel);
  325. }
  326. if (mainNca.CanOpenSection(NcaSectionType.Code))
  327. {
  328. codeFs = mainNca.OpenFileSystem(NcaSectionType.Code, FsIntegrityCheckLevel);
  329. }
  330. }
  331. else
  332. {
  333. if (patchNca.CanOpenSection(NcaSectionType.Data))
  334. {
  335. dataStorage = mainNca.OpenStorageWithPatch(patchNca, NcaSectionType.Data, FsIntegrityCheckLevel);
  336. }
  337. if (patchNca.CanOpenSection(NcaSectionType.Code))
  338. {
  339. codeFs = mainNca.OpenFileSystemWithPatch(patchNca, NcaSectionType.Code, FsIntegrityCheckLevel);
  340. }
  341. }
  342. if (codeFs == null)
  343. {
  344. Logger.PrintError(LogClass.Loader, "No ExeFS found in NCA");
  345. return;
  346. }
  347. if (dataStorage == null)
  348. {
  349. Logger.PrintWarning(LogClass.Loader, "No RomFS found in NCA");
  350. }
  351. else
  352. {
  353. Device.FileSystem.SetRomFs(dataStorage.AsStream(FileAccess.Read));
  354. }
  355. LoadExeFs(codeFs, out Npdm metaData);
  356. Nacp ReadControlData()
  357. {
  358. IFileSystem controlRomfs = controlNca.OpenFileSystem(NcaSectionType.Data, FsIntegrityCheckLevel);
  359. controlRomfs.OpenFile(out IFile controlFile, "/control.nacp", OpenMode.Read).ThrowIfFailure();
  360. Nacp controlData = new Nacp(controlFile.AsStream());
  361. TitleName = CurrentTitle = controlData.Descriptions[(int)State.DesiredTitleLanguage].Title;
  362. TitleID = metaData.Aci0.TitleId.ToString("x16");
  363. if (string.IsNullOrWhiteSpace(CurrentTitle))
  364. {
  365. TitleName = CurrentTitle = controlData.Descriptions.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Title)).Title;
  366. }
  367. return controlData;
  368. }
  369. if (controlNca != null)
  370. {
  371. ReadControlData();
  372. }
  373. else
  374. {
  375. TitleID = CurrentTitle = metaData.Aci0.TitleId.ToString("x16");
  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 = CurrentTitle = metaData.Aci0.TitleId.ToString("x16");
  406. LoadNso("rtld");
  407. LoadNso("main");
  408. LoadNso("subsdk");
  409. LoadNso("sdk");
  410. ContentManager.LoadEntries();
  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. using (MemoryStream stream = new MemoryStream(reader.ReadBytes((int)nacpSize)))
  448. {
  449. ControlData = new Nacp(stream);
  450. }
  451. metaData.TitleName = ControlData.Descriptions[(int)State.DesiredTitleLanguage].Title;
  452. if (string.IsNullOrWhiteSpace(metaData.TitleName))
  453. {
  454. metaData.TitleName = ControlData.Descriptions.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Title)).Title;
  455. }
  456. metaData.Aci0.TitleId = ControlData.PresenceGroupId;
  457. if (metaData.Aci0.TitleId == 0)
  458. {
  459. metaData.Aci0.TitleId = ControlData.SaveDataOwnerId;
  460. }
  461. if (metaData.Aci0.TitleId == 0)
  462. {
  463. metaData.Aci0.TitleId = ControlData.AddOnContentBaseId - 0x1000;
  464. }
  465. if (metaData.Aci0.TitleId.ToString("x16") == "fffffffffffff000")
  466. {
  467. metaData.Aci0.TitleId = 0000000000000000;
  468. }
  469. }
  470. }
  471. else
  472. {
  473. Logger.PrintWarning(LogClass.Loader, $"Unsupported ASET header version found \"{asetVersion}\"");
  474. }
  475. }
  476. }
  477. }
  478. else
  479. {
  480. staticObject = new NxStaticObject(input);
  481. }
  482. ContentManager.LoadEntries();
  483. TitleName = CurrentTitle = metaData.TitleName;
  484. TitleID = metaData.Aci0.TitleId.ToString("x16");
  485. ProgramLoader.LoadStaticObjects(this, metaData, new IExecutable[] { staticObject });
  486. }
  487. private Npdm GetDefaultNpdm()
  488. {
  489. Assembly asm = Assembly.GetCallingAssembly();
  490. using (Stream npdmStream = asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm"))
  491. {
  492. return new Npdm(npdmStream);
  493. }
  494. }
  495. public void LoadKeySet()
  496. {
  497. string keyFile = null;
  498. string titleKeyFile = null;
  499. string consoleKeyFile = null;
  500. string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
  501. LoadSetAtPath(Path.Combine(home, ".switch"));
  502. LoadSetAtPath(Device.FileSystem.GetSystemPath());
  503. KeySet = ExternalKeyReader.ReadKeyFile(keyFile, titleKeyFile, consoleKeyFile);
  504. void LoadSetAtPath(string basePath)
  505. {
  506. string localKeyFile = Path.Combine(basePath, "prod.keys");
  507. string localTitleKeyFile = Path.Combine(basePath, "title.keys");
  508. string localConsoleKeyFile = Path.Combine(basePath, "console.keys");
  509. if (File.Exists(localKeyFile))
  510. {
  511. keyFile = localKeyFile;
  512. }
  513. if (File.Exists(localTitleKeyFile))
  514. {
  515. titleKeyFile = localTitleKeyFile;
  516. }
  517. if (File.Exists(localConsoleKeyFile))
  518. {
  519. consoleKeyFile = localConsoleKeyFile;
  520. }
  521. }
  522. }
  523. public void SignalVsync()
  524. {
  525. VsyncEvent.ReadableEvent.Signal();
  526. }
  527. internal long GetThreadUid()
  528. {
  529. return Interlocked.Increment(ref _threadUid) - 1;
  530. }
  531. internal long GetKipId()
  532. {
  533. return Interlocked.Increment(ref _kipId) - 1;
  534. }
  535. internal long GetProcessId()
  536. {
  537. return Interlocked.Increment(ref _processId) - 1;
  538. }
  539. public void EnableMultiCoreScheduling()
  540. {
  541. if (!_hasStarted)
  542. {
  543. Scheduler.MultiCoreScheduling = true;
  544. }
  545. }
  546. public void DisableMultiCoreScheduling()
  547. {
  548. if (!_hasStarted)
  549. {
  550. Scheduler.MultiCoreScheduling = false;
  551. }
  552. }
  553. public void Dispose()
  554. {
  555. Dispose(true);
  556. }
  557. protected virtual void Dispose(bool disposing)
  558. {
  559. if (disposing)
  560. {
  561. // Force all threads to exit.
  562. lock (Processes)
  563. {
  564. foreach (KProcess process in Processes.Values)
  565. {
  566. process.StopAllThreads();
  567. }
  568. }
  569. // It's only safe to release resources once all threads
  570. // have exited.
  571. ThreadCounter.Signal();
  572. //ThreadCounter.Wait(); // FIXME: Uncomment this
  573. // BODY: Right now, guest processes don't exit properly because the logic waits for them to exit.
  574. // BODY: However, this doesn't happen when you close the main window so we need to find a way to make them exit gracefully
  575. Scheduler.Dispose();
  576. TimeManager.Dispose();
  577. Device.Unload();
  578. }
  579. }
  580. }
  581. }