Horizon.cs 25 KB

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