Horizon.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  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. public bool UseLegacyJit { get; set; }
  83. internal long HidBaseAddress { get; private set; }
  84. internal FileSystemServer FsServer { get; private set; }
  85. internal EmulatedGameCard GameCard { get; private set; }
  86. public Horizon(Switch device)
  87. {
  88. ControlData = new Nacp();
  89. Device = device;
  90. State = new SystemStateMgr();
  91. ResourceLimit = new KResourceLimit(this);
  92. KernelInit.InitializeResourceLimit(ResourceLimit);
  93. MemoryRegions = KernelInit.GetMemoryRegions();
  94. LargeMemoryBlockAllocator = new KMemoryBlockAllocator(MemoryBlockAllocatorSize * 2);
  95. SmallMemoryBlockAllocator = new KMemoryBlockAllocator(MemoryBlockAllocatorSize);
  96. UserSlabHeapPages = new KSlabHeap(
  97. UserSlabHeapBase,
  98. UserSlabHeapItemSize,
  99. UserSlabHeapSize);
  100. CriticalSection = new KCriticalSection(this);
  101. Scheduler = new KScheduler(this);
  102. TimeManager = new KTimeManager();
  103. Synchronization = new KSynchronization(this);
  104. ContextIdManager = new KContextIdManager();
  105. _kipId = InitialKipId;
  106. _processId = InitialProcessId;
  107. Scheduler.StartAutoPreemptionThread();
  108. KernelInitialized = true;
  109. ThreadCounter = new CountdownEvent(1);
  110. Processes = new SortedDictionary<long, KProcess>();
  111. AutoObjectNames = new ConcurrentDictionary<string, KAutoObject>();
  112. // Note: This is not really correct, but with HLE of services, the only memory
  113. // region used that is used is Application, so we can use the other ones for anything.
  114. KMemoryRegionManager region = MemoryRegions[(int)MemoryRegion.NvServices];
  115. ulong hidPa = region.Address;
  116. ulong fontPa = region.Address + HidSize;
  117. ulong iirsPa = region.Address + HidSize + FontSize;
  118. ulong timePa = region.Address + HidSize + FontSize + IirsSize;
  119. HidBaseAddress = (long)(hidPa - DramMemoryMap.DramBase);
  120. KPageList hidPageList = new KPageList();
  121. KPageList fontPageList = new KPageList();
  122. KPageList iirsPageList = new KPageList();
  123. KPageList timePageList = new KPageList();
  124. hidPageList .AddRange(hidPa, HidSize / KMemoryManager.PageSize);
  125. fontPageList.AddRange(fontPa, FontSize / KMemoryManager.PageSize);
  126. iirsPageList.AddRange(iirsPa, IirsSize / KMemoryManager.PageSize);
  127. timePageList.AddRange(timePa, TimeSize / KMemoryManager.PageSize);
  128. HidSharedMem = new KSharedMemory(this, hidPageList, 0, 0, MemoryPermission.Read);
  129. FontSharedMem = new KSharedMemory(this, fontPageList, 0, 0, MemoryPermission.Read);
  130. IirsSharedMem = new KSharedMemory(this, iirsPageList, 0, 0, MemoryPermission.Read);
  131. KSharedMemory timeSharedMemory = new KSharedMemory(this, timePageList, 0, 0, MemoryPermission.Read);
  132. TimeServiceManager.Instance.Initialize(device, this, timeSharedMemory, (long)(timePa - DramMemoryMap.DramBase), TimeSize);
  133. AppletState = new AppletStateMgr(this);
  134. AppletState.SetFocus(true);
  135. Font = new SharedFontManager(device, (long)(fontPa - DramMemoryMap.DramBase));
  136. IUserInterface.InitializePort(this);
  137. VsyncEvent = new KEvent(this);
  138. LoadKeySet();
  139. ContentManager = new ContentManager(device);
  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. LocalFileSystem serverBaseFs = new LocalFileSystem(device.FileSystem.GetBasePath());
  158. DefaultFsServerObjects fsServerObjects = DefaultFsServerObjects.GetDefaultEmulatedCreators(serverBaseFs, KeySet);
  159. GameCard = fsServerObjects.GameCard;
  160. FileSystemServerConfig fsServerConfig = new FileSystemServerConfig
  161. {
  162. FsCreators = fsServerObjects.FsCreators,
  163. DeviceOperator = fsServerObjects.DeviceOperator,
  164. ExternalKeySet = KeySet.ExternalKeySet
  165. };
  166. FsServer = new FileSystemServer(fsServerConfig);
  167. }
  168. public void LoadCart(string exeFsDir, string romFsFile = null)
  169. {
  170. if (romFsFile != null)
  171. {
  172. Device.FileSystem.LoadRomFs(romFsFile);
  173. }
  174. LocalFileSystem codeFs = new LocalFileSystem(exeFsDir);
  175. LoadExeFs(codeFs, out _);
  176. }
  177. public void LoadXci(string xciFile)
  178. {
  179. FileStream file = new FileStream(xciFile, FileMode.Open, FileAccess.Read);
  180. Xci xci = new Xci(KeySet, file.AsStorage());
  181. (Nca mainNca, Nca patchNca, Nca controlNca) = GetXciGameData(xci);
  182. if (mainNca == null)
  183. {
  184. Logger.PrintError(LogClass.Loader, "Unable to load XCI");
  185. return;
  186. }
  187. ContentManager.LoadEntries();
  188. LoadNca(mainNca, patchNca, controlNca);
  189. }
  190. public void LoadKip(string kipFile)
  191. {
  192. using (FileStream fs = new FileStream(kipFile, FileMode.Open))
  193. {
  194. ProgramLoader.LoadKernelInitalProcess(this, new KernelInitialProcess(fs));
  195. }
  196. }
  197. private (Nca Main, Nca patch, Nca Control) GetXciGameData(Xci xci)
  198. {
  199. if (!xci.HasPartition(XciPartitionType.Secure))
  200. {
  201. throw new InvalidDataException("Could not find XCI secure partition");
  202. }
  203. Nca mainNca = null;
  204. Nca patchNca = null;
  205. Nca controlNca = null;
  206. XciPartition securePartition = xci.OpenPartition(XciPartitionType.Secure);
  207. foreach (DirectoryEntryEx ticketEntry in securePartition.EnumerateEntries("/", "*.tik"))
  208. {
  209. Result result = securePartition.OpenFile(out IFile ticketFile, ticketEntry.FullPath, OpenMode.Read);
  210. if (result.IsSuccess())
  211. {
  212. Ticket ticket = new Ticket(ticketFile.AsStream());
  213. KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(KeySet)));
  214. }
  215. }
  216. foreach (DirectoryEntryEx fileEntry in securePartition.EnumerateEntries("/", "*.nca"))
  217. {
  218. Result result = securePartition.OpenFile(out IFile ncaFile, fileEntry.FullPath, OpenMode.Read);
  219. if (result.IsFailure())
  220. {
  221. continue;
  222. }
  223. Nca nca = new Nca(KeySet, ncaFile.AsStorage());
  224. if (nca.Header.ContentType == NcaContentType.Program)
  225. {
  226. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  227. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  228. {
  229. patchNca = nca;
  230. }
  231. else
  232. {
  233. mainNca = nca;
  234. }
  235. }
  236. else if (nca.Header.ContentType == NcaContentType.Control)
  237. {
  238. controlNca = nca;
  239. }
  240. }
  241. if (mainNca == null)
  242. {
  243. Logger.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided XCI file");
  244. }
  245. if (controlNca != null)
  246. {
  247. ReadControlData(controlNca);
  248. }
  249. return (mainNca, patchNca, controlNca);
  250. }
  251. public void ReadControlData(Nca controlNca)
  252. {
  253. IFileSystem controlFs = controlNca.OpenFileSystem(NcaSectionType.Data, FsIntegrityCheckLevel);
  254. Result result = controlFs.OpenFile(out IFile controlFile, "/control.nacp", OpenMode.Read);
  255. if (result.IsSuccess())
  256. {
  257. ControlData = new Nacp(controlFile.AsStream());
  258. TitleName = CurrentTitle = ControlData.Descriptions[(int) State.DesiredTitleLanguage].Title;
  259. }
  260. }
  261. public void LoadNca(string ncaFile)
  262. {
  263. FileStream file = new FileStream(ncaFile, FileMode.Open, FileAccess.Read);
  264. Nca nca = new Nca(KeySet, file.AsStorage(false));
  265. LoadNca(nca, null, null);
  266. }
  267. public void LoadNsp(string nspFile)
  268. {
  269. FileStream file = new FileStream(nspFile, FileMode.Open, FileAccess.Read);
  270. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  271. foreach (DirectoryEntryEx ticketEntry in nsp.EnumerateEntries("/", "*.tik"))
  272. {
  273. Result result = nsp.OpenFile(out IFile ticketFile, ticketEntry.FullPath, OpenMode.Read);
  274. if (result.IsSuccess())
  275. {
  276. Ticket ticket = new Ticket(ticketFile.AsStream());
  277. KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(KeySet)));
  278. }
  279. }
  280. Nca mainNca = null;
  281. Nca patchNca = null;
  282. Nca controlNca = null;
  283. foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
  284. {
  285. nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath, OpenMode.Read).ThrowIfFailure();
  286. Nca nca = new Nca(KeySet, ncaFile.AsStorage());
  287. if (nca.Header.ContentType == NcaContentType.Program)
  288. {
  289. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  290. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  291. {
  292. patchNca = nca;
  293. }
  294. else
  295. {
  296. mainNca = nca;
  297. }
  298. }
  299. else if (nca.Header.ContentType == NcaContentType.Control)
  300. {
  301. controlNca = nca;
  302. }
  303. }
  304. if (mainNca != null)
  305. {
  306. LoadNca(mainNca, patchNca, controlNca);
  307. return;
  308. }
  309. // This is not a normal NSP, it's actually a ExeFS as a NSP
  310. LoadExeFs(nsp, out _);
  311. }
  312. public void LoadNca(Nca mainNca, Nca patchNca, Nca controlNca)
  313. {
  314. if (mainNca.Header.ContentType != NcaContentType.Program)
  315. {
  316. Logger.PrintError(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");
  317. return;
  318. }
  319. IStorage dataStorage = null;
  320. IFileSystem codeFs = null;
  321. if (patchNca == null)
  322. {
  323. if (mainNca.CanOpenSection(NcaSectionType.Data))
  324. {
  325. dataStorage = mainNca.OpenStorage(NcaSectionType.Data, FsIntegrityCheckLevel);
  326. }
  327. if (mainNca.CanOpenSection(NcaSectionType.Code))
  328. {
  329. codeFs = mainNca.OpenFileSystem(NcaSectionType.Code, FsIntegrityCheckLevel);
  330. }
  331. }
  332. else
  333. {
  334. if (patchNca.CanOpenSection(NcaSectionType.Data))
  335. {
  336. dataStorage = mainNca.OpenStorageWithPatch(patchNca, NcaSectionType.Data, FsIntegrityCheckLevel);
  337. }
  338. if (patchNca.CanOpenSection(NcaSectionType.Code))
  339. {
  340. codeFs = mainNca.OpenFileSystemWithPatch(patchNca, NcaSectionType.Code, FsIntegrityCheckLevel);
  341. }
  342. }
  343. if (codeFs == null)
  344. {
  345. Logger.PrintError(LogClass.Loader, "No ExeFS found in NCA");
  346. return;
  347. }
  348. if (dataStorage == null)
  349. {
  350. Logger.PrintWarning(LogClass.Loader, "No RomFS found in NCA");
  351. }
  352. else
  353. {
  354. Device.FileSystem.SetRomFs(dataStorage.AsStream(FileAccess.Read));
  355. }
  356. LoadExeFs(codeFs, out Npdm metaData);
  357. Nacp ReadControlData()
  358. {
  359. IFileSystem controlRomfs = controlNca.OpenFileSystem(NcaSectionType.Data, FsIntegrityCheckLevel);
  360. controlRomfs.OpenFile(out IFile controlFile, "/control.nacp", OpenMode.Read).ThrowIfFailure();
  361. Nacp controlData = new Nacp(controlFile.AsStream());
  362. TitleName = CurrentTitle = controlData.Descriptions[(int)State.DesiredTitleLanguage].Title;
  363. TitleID = metaData.Aci0.TitleId.ToString("x16");
  364. if (string.IsNullOrWhiteSpace(CurrentTitle))
  365. {
  366. TitleName = CurrentTitle = controlData.Descriptions.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Title)).Title;
  367. }
  368. return controlData;
  369. }
  370. if (controlNca != null)
  371. {
  372. ReadControlData();
  373. }
  374. else
  375. {
  376. TitleID = CurrentTitle = metaData.Aci0.TitleId.ToString("x16");
  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 = CurrentTitle = metaData.Aci0.TitleId.ToString("x16");
  407. LoadNso("rtld");
  408. LoadNso("main");
  409. LoadNso("subsdk");
  410. LoadNso("sdk");
  411. ContentManager.LoadEntries();
  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. using (MemoryStream stream = new MemoryStream(reader.ReadBytes((int)nacpSize)))
  449. {
  450. ControlData = new Nacp(stream);
  451. }
  452. metaData.TitleName = ControlData.Descriptions[(int)State.DesiredTitleLanguage].Title;
  453. if (string.IsNullOrWhiteSpace(metaData.TitleName))
  454. {
  455. metaData.TitleName = ControlData.Descriptions.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Title)).Title;
  456. }
  457. metaData.Aci0.TitleId = ControlData.PresenceGroupId;
  458. if (metaData.Aci0.TitleId == 0)
  459. {
  460. metaData.Aci0.TitleId = ControlData.SaveDataOwnerId;
  461. }
  462. if (metaData.Aci0.TitleId == 0)
  463. {
  464. metaData.Aci0.TitleId = ControlData.AddOnContentBaseId - 0x1000;
  465. }
  466. if (metaData.Aci0.TitleId.ToString("x16") == "fffffffffffff000")
  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();
  484. TitleName = CurrentTitle = metaData.TitleName;
  485. TitleID = metaData.Aci0.TitleId.ToString("x16");
  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. public void LoadKeySet()
  497. {
  498. string keyFile = null;
  499. string titleKeyFile = null;
  500. string consoleKeyFile = null;
  501. string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
  502. LoadSetAtPath(Path.Combine(home, ".switch"));
  503. LoadSetAtPath(Device.FileSystem.GetSystemPath());
  504. KeySet = ExternalKeyReader.ReadKeyFile(keyFile, titleKeyFile, consoleKeyFile);
  505. void LoadSetAtPath(string basePath)
  506. {
  507. string localKeyFile = Path.Combine(basePath, "prod.keys");
  508. string localTitleKeyFile = Path.Combine(basePath, "title.keys");
  509. string localConsoleKeyFile = Path.Combine(basePath, "console.keys");
  510. if (File.Exists(localKeyFile))
  511. {
  512. keyFile = localKeyFile;
  513. }
  514. if (File.Exists(localTitleKeyFile))
  515. {
  516. titleKeyFile = localTitleKeyFile;
  517. }
  518. if (File.Exists(localConsoleKeyFile))
  519. {
  520. consoleKeyFile = localConsoleKeyFile;
  521. }
  522. }
  523. }
  524. public void SignalVsync()
  525. {
  526. VsyncEvent.ReadableEvent.Signal();
  527. }
  528. internal long GetThreadUid()
  529. {
  530. return Interlocked.Increment(ref _threadUid) - 1;
  531. }
  532. internal long GetKipId()
  533. {
  534. return Interlocked.Increment(ref _kipId) - 1;
  535. }
  536. internal long GetProcessId()
  537. {
  538. return Interlocked.Increment(ref _processId) - 1;
  539. }
  540. public void EnableMultiCoreScheduling()
  541. {
  542. if (!_hasStarted)
  543. {
  544. Scheduler.MultiCoreScheduling = true;
  545. }
  546. }
  547. public void DisableMultiCoreScheduling()
  548. {
  549. if (!_hasStarted)
  550. {
  551. Scheduler.MultiCoreScheduling = false;
  552. }
  553. }
  554. public void Dispose()
  555. {
  556. Dispose(true);
  557. }
  558. protected virtual void Dispose(bool disposing)
  559. {
  560. if (disposing)
  561. {
  562. // Force all threads to exit.
  563. lock (Processes)
  564. {
  565. foreach (KProcess process in Processes.Values)
  566. {
  567. process.StopAllThreads();
  568. }
  569. }
  570. // It's only safe to release resources once all threads
  571. // have exited.
  572. ThreadCounter.Signal();
  573. //ThreadCounter.Wait(); // FIXME: Uncomment this
  574. // BODY: Right now, guest processes don't exit properly because the logic waits for them to exit.
  575. // BODY: However, this doesn't happen when you close the main window so we need to find a way to make them exit gracefully
  576. Scheduler.Dispose();
  577. TimeManager.Dispose();
  578. Device.Unload();
  579. }
  580. }
  581. }
  582. }