Horizon.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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. internal 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. internal long HidBaseAddress { get; private set; }
  77. public Horizon(Switch device)
  78. {
  79. ControlData = new Nacp();
  80. Device = device;
  81. State = new SystemStateMgr();
  82. ResourceLimit = new KResourceLimit(this);
  83. KernelInit.InitializeResourceLimit(ResourceLimit);
  84. MemoryRegions = KernelInit.GetMemoryRegions();
  85. LargeMemoryBlockAllocator = new KMemoryBlockAllocator(MemoryBlockAllocatorSize * 2);
  86. SmallMemoryBlockAllocator = new KMemoryBlockAllocator(MemoryBlockAllocatorSize);
  87. UserSlabHeapPages = new KSlabHeap(
  88. UserSlabHeapBase,
  89. UserSlabHeapItemSize,
  90. UserSlabHeapSize);
  91. CriticalSection = new KCriticalSection(this);
  92. Scheduler = new KScheduler(this);
  93. TimeManager = new KTimeManager();
  94. Synchronization = new KSynchronization(this);
  95. ContextIdManager = new KContextIdManager();
  96. _kipId = InitialKipId;
  97. _processId = InitialProcessId;
  98. Scheduler.StartAutoPreemptionThread();
  99. KernelInitialized = true;
  100. ThreadCounter = new CountdownEvent(1);
  101. Processes = new SortedDictionary<long, KProcess>();
  102. AutoObjectNames = new ConcurrentDictionary<string, KAutoObject>();
  103. // Note: This is not really correct, but with HLE of services, the only memory
  104. // region used that is used is Application, so we can use the other ones for anything.
  105. KMemoryRegionManager region = MemoryRegions[(int)MemoryRegion.NvServices];
  106. ulong hidPa = region.Address;
  107. ulong fontPa = region.Address + HidSize;
  108. ulong iirsPa = region.Address + HidSize + FontSize;
  109. ulong timePa = region.Address + HidSize + FontSize + IirsSize;
  110. HidBaseAddress = (long)(hidPa - DramMemoryMap.DramBase);
  111. KPageList hidPageList = new KPageList();
  112. KPageList fontPageList = new KPageList();
  113. KPageList iirsPageList = new KPageList();
  114. KPageList timePageList = new KPageList();
  115. hidPageList .AddRange(hidPa, HidSize / KMemoryManager.PageSize);
  116. fontPageList.AddRange(fontPa, FontSize / KMemoryManager.PageSize);
  117. iirsPageList.AddRange(iirsPa, IirsSize / KMemoryManager.PageSize);
  118. timePageList.AddRange(timePa, TimeSize / KMemoryManager.PageSize);
  119. HidSharedMem = new KSharedMemory(this, hidPageList, 0, 0, MemoryPermission.Read);
  120. FontSharedMem = new KSharedMemory(this, fontPageList, 0, 0, MemoryPermission.Read);
  121. IirsSharedMem = new KSharedMemory(this, iirsPageList, 0, 0, MemoryPermission.Read);
  122. TimeSharedMem = new KSharedMemory(this, timePageList, 0, 0, MemoryPermission.Read);
  123. AppletState = new AppletStateMgr(this);
  124. AppletState.SetFocus(true);
  125. Font = new SharedFontManager(device, (long)(fontPa - DramMemoryMap.DramBase));
  126. IUserInterface.InitializePort(this);
  127. VsyncEvent = new KEvent(this);
  128. LoadKeySet();
  129. ContentManager = new ContentManager(device);
  130. // TODO: use set:sys (and set external clock source id from settings)
  131. // TODO: use "time!standard_steady_clock_rtc_update_interval_minutes" and implement a worker thread to be accurate.
  132. StandardSteadyClockCore.Instance.ConfigureSetupValue();
  133. if (Services.Set.NxSettings.Settings.TryGetValue("time!standard_network_clock_sufficient_accuracy_minutes", out object standardNetworkClockSufficientAccuracyMinutes))
  134. {
  135. TimeSpanType standardNetworkClockSufficientAccuracy = new TimeSpanType((int)standardNetworkClockSufficientAccuracyMinutes * 60000000000);
  136. StandardNetworkSystemClockCore.Instance.SetStandardNetworkClockSufficientAccuracy(standardNetworkClockSufficientAccuracy);
  137. }
  138. }
  139. public void LoadCart(string exeFsDir, string romFsFile = null)
  140. {
  141. if (romFsFile != null)
  142. {
  143. Device.FileSystem.LoadRomFs(romFsFile);
  144. }
  145. LocalFileSystem codeFs = new LocalFileSystem(exeFsDir);
  146. LoadExeFs(codeFs, out _);
  147. }
  148. public void LoadXci(string xciFile)
  149. {
  150. FileStream file = new FileStream(xciFile, FileMode.Open, FileAccess.Read);
  151. Xci xci = new Xci(KeySet, file.AsStorage());
  152. (Nca mainNca, Nca patchNca, Nca controlNca) = GetXciGameData(xci);
  153. if (mainNca == null)
  154. {
  155. Logger.PrintError(LogClass.Loader, "Unable to load XCI");
  156. return;
  157. }
  158. ContentManager.LoadEntries();
  159. LoadNca(mainNca, patchNca, controlNca);
  160. }
  161. public void LoadKip(string kipFile)
  162. {
  163. using (FileStream fs = new FileStream(kipFile, FileMode.Open))
  164. {
  165. ProgramLoader.LoadKernelInitalProcess(this, new KernelInitialProcess(fs));
  166. }
  167. }
  168. private (Nca Main, Nca patch, Nca Control) GetXciGameData(Xci xci)
  169. {
  170. if (!xci.HasPartition(XciPartitionType.Secure))
  171. {
  172. throw new InvalidDataException("Could not find XCI secure partition");
  173. }
  174. Nca mainNca = null;
  175. Nca patchNca = null;
  176. Nca controlNca = null;
  177. XciPartition securePartition = xci.OpenPartition(XciPartitionType.Secure);
  178. foreach (DirectoryEntry ticketEntry in securePartition.EnumerateEntries("*.tik"))
  179. {
  180. Ticket ticket = new Ticket(securePartition.OpenFile(ticketEntry.FullPath, OpenMode.Read).AsStream());
  181. if (!KeySet.TitleKeys.ContainsKey(ticket.RightsId))
  182. {
  183. KeySet.TitleKeys.Add(ticket.RightsId, ticket.GetTitleKey(KeySet));
  184. }
  185. }
  186. foreach (DirectoryEntry fileEntry in securePartition.EnumerateEntries("*.nca"))
  187. {
  188. IStorage ncaStorage = securePartition.OpenFile(fileEntry.FullPath, OpenMode.Read).AsStorage();
  189. Nca nca = new Nca(KeySet, ncaStorage);
  190. if (nca.Header.ContentType == ContentType.Program)
  191. {
  192. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, ContentType.Program);
  193. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  194. {
  195. patchNca = nca;
  196. }
  197. else
  198. {
  199. mainNca = nca;
  200. }
  201. }
  202. else if (nca.Header.ContentType == ContentType.Control)
  203. {
  204. controlNca = nca;
  205. }
  206. }
  207. if (mainNca == null)
  208. {
  209. Logger.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided XCI file");
  210. }
  211. if (controlNca != null)
  212. {
  213. ReadControlData(controlNca);
  214. }
  215. return (mainNca, patchNca, controlNca);
  216. }
  217. public void ReadControlData(Nca controlNca)
  218. {
  219. IFileSystem controlFs = controlNca.OpenFileSystem(NcaSectionType.Data, FsIntegrityCheckLevel);
  220. IFile controlFile = controlFs.OpenFile("/control.nacp", OpenMode.Read);
  221. ControlData = new Nacp(controlFile.AsStream());
  222. TitleName = CurrentTitle = ControlData.Descriptions[(int)State.DesiredTitleLanguage].Title;
  223. }
  224. public void LoadNca(string ncaFile)
  225. {
  226. FileStream file = new FileStream(ncaFile, FileMode.Open, FileAccess.Read);
  227. Nca nca = new Nca(KeySet, file.AsStorage(false));
  228. LoadNca(nca, null, null);
  229. }
  230. public void LoadNsp(string nspFile)
  231. {
  232. FileStream file = new FileStream(nspFile, FileMode.Open, FileAccess.Read);
  233. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  234. foreach (DirectoryEntry ticketEntry in nsp.EnumerateEntries("*.tik"))
  235. {
  236. Ticket ticket = new Ticket(nsp.OpenFile(ticketEntry.FullPath, OpenMode.Read).AsStream());
  237. if (!KeySet.TitleKeys.ContainsKey(ticket.RightsId))
  238. {
  239. KeySet.TitleKeys.Add(ticket.RightsId, ticket.GetTitleKey(KeySet));
  240. }
  241. }
  242. Nca mainNca = null;
  243. Nca patchNca = null;
  244. Nca controlNca = null;
  245. foreach (DirectoryEntry fileEntry in nsp.EnumerateEntries("*.nca"))
  246. {
  247. IStorage ncaStorage = nsp.OpenFile(fileEntry.FullPath, OpenMode.Read).AsStorage();
  248. Nca nca = new Nca(KeySet, ncaStorage);
  249. if (nca.Header.ContentType == ContentType.Program)
  250. {
  251. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, ContentType.Program);
  252. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  253. {
  254. patchNca = nca;
  255. }
  256. else
  257. {
  258. mainNca = nca;
  259. }
  260. }
  261. else if (nca.Header.ContentType == ContentType.Control)
  262. {
  263. controlNca = nca;
  264. }
  265. }
  266. if (mainNca != null)
  267. {
  268. LoadNca(mainNca, patchNca, controlNca);
  269. return;
  270. }
  271. // This is not a normal NSP, it's actually a ExeFS as a NSP
  272. LoadExeFs(nsp, out _);
  273. }
  274. public void LoadNca(Nca mainNca, Nca patchNca, Nca controlNca)
  275. {
  276. if (mainNca.Header.ContentType != ContentType.Program)
  277. {
  278. Logger.PrintError(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");
  279. return;
  280. }
  281. IStorage dataStorage = null;
  282. IFileSystem codeFs = null;
  283. if (patchNca == null)
  284. {
  285. if (mainNca.CanOpenSection(NcaSectionType.Data))
  286. {
  287. dataStorage = mainNca.OpenStorage(NcaSectionType.Data, FsIntegrityCheckLevel);
  288. }
  289. if (mainNca.CanOpenSection(NcaSectionType.Code))
  290. {
  291. codeFs = mainNca.OpenFileSystem(NcaSectionType.Code, FsIntegrityCheckLevel);
  292. }
  293. }
  294. else
  295. {
  296. if (patchNca.CanOpenSection(NcaSectionType.Data))
  297. {
  298. dataStorage = mainNca.OpenStorageWithPatch(patchNca, NcaSectionType.Data, FsIntegrityCheckLevel);
  299. }
  300. if (patchNca.CanOpenSection(NcaSectionType.Code))
  301. {
  302. codeFs = mainNca.OpenFileSystemWithPatch(patchNca, NcaSectionType.Code, FsIntegrityCheckLevel);
  303. }
  304. }
  305. if (codeFs == null)
  306. {
  307. Logger.PrintError(LogClass.Loader, "No ExeFS found in NCA");
  308. return;
  309. }
  310. if (dataStorage == null)
  311. {
  312. Logger.PrintWarning(LogClass.Loader, "No RomFS found in NCA");
  313. }
  314. else
  315. {
  316. Device.FileSystem.SetRomFs(dataStorage.AsStream(FileAccess.Read));
  317. }
  318. LoadExeFs(codeFs, out Npdm metaData);
  319. Nacp ReadControlData()
  320. {
  321. IFileSystem controlRomfs = controlNca.OpenFileSystem(NcaSectionType.Data, FsIntegrityCheckLevel);
  322. IFile controlFile = controlRomfs.OpenFile("/control.nacp", OpenMode.Read);
  323. Nacp controlData = new Nacp(controlFile.AsStream());
  324. TitleName = CurrentTitle = controlData.Descriptions[(int)State.DesiredTitleLanguage].Title;
  325. TitleID = metaData.Aci0.TitleId.ToString("x16");
  326. CurrentTitle = controlData.Descriptions[(int)State.DesiredTitleLanguage].Title;
  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. }
  408. else
  409. {
  410. Logger.PrintWarning(LogClass.Loader, $"Unsupported ASET header version found \"{asetVersion}\"");
  411. }
  412. }
  413. }
  414. }
  415. else
  416. {
  417. staticObject = new NxStaticObject(input);
  418. }
  419. ContentManager.LoadEntries();
  420. TitleID = CurrentTitle = metaData.Aci0.TitleId.ToString("x16");
  421. TitleName = metaData.TitleName;
  422. ProgramLoader.LoadStaticObjects(this, metaData, new IExecutable[] { staticObject });
  423. }
  424. private Npdm GetDefaultNpdm()
  425. {
  426. Assembly asm = Assembly.GetCallingAssembly();
  427. using (Stream npdmStream = asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm"))
  428. {
  429. return new Npdm(npdmStream);
  430. }
  431. }
  432. public void LoadKeySet()
  433. {
  434. string keyFile = null;
  435. string titleKeyFile = null;
  436. string consoleKeyFile = null;
  437. string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
  438. LoadSetAtPath(Path.Combine(home, ".switch"));
  439. LoadSetAtPath(Device.FileSystem.GetSystemPath());
  440. KeySet = ExternalKeys.ReadKeyFile(keyFile, titleKeyFile, consoleKeyFile);
  441. void LoadSetAtPath(string basePath)
  442. {
  443. string localKeyFile = Path.Combine(basePath, "prod.keys");
  444. string localTitleKeyFile = Path.Combine(basePath, "title.keys");
  445. string localConsoleKeyFile = Path.Combine(basePath, "console.keys");
  446. if (File.Exists(localKeyFile))
  447. {
  448. keyFile = localKeyFile;
  449. }
  450. if (File.Exists(localTitleKeyFile))
  451. {
  452. titleKeyFile = localTitleKeyFile;
  453. }
  454. if (File.Exists(localConsoleKeyFile))
  455. {
  456. consoleKeyFile = localConsoleKeyFile;
  457. }
  458. }
  459. }
  460. public void SignalVsync()
  461. {
  462. VsyncEvent.ReadableEvent.Signal();
  463. }
  464. internal long GetThreadUid()
  465. {
  466. return Interlocked.Increment(ref _threadUid) - 1;
  467. }
  468. internal long GetKipId()
  469. {
  470. return Interlocked.Increment(ref _kipId) - 1;
  471. }
  472. internal long GetProcessId()
  473. {
  474. return Interlocked.Increment(ref _processId) - 1;
  475. }
  476. public void EnableMultiCoreScheduling()
  477. {
  478. if (!_hasStarted)
  479. {
  480. Scheduler.MultiCoreScheduling = true;
  481. }
  482. }
  483. public void DisableMultiCoreScheduling()
  484. {
  485. if (!_hasStarted)
  486. {
  487. Scheduler.MultiCoreScheduling = false;
  488. }
  489. }
  490. public void Dispose()
  491. {
  492. Dispose(true);
  493. }
  494. protected virtual void Dispose(bool disposing)
  495. {
  496. if (disposing)
  497. {
  498. // Force all threads to exit.
  499. lock (Processes)
  500. {
  501. foreach (KProcess process in Processes.Values)
  502. {
  503. process.StopAllThreads();
  504. }
  505. }
  506. // It's only safe to release resources once all threads
  507. // have exited.
  508. ThreadCounter.Signal();
  509. ThreadCounter.Wait();
  510. Scheduler.Dispose();
  511. TimeManager.Dispose();
  512. Device.Unload();
  513. }
  514. }
  515. }
  516. }