Horizon.cs 25 KB

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