Horizon.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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. 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. CurrentTitle = controlData.Descriptions[(int)State.DesiredTitleLanguage].Title;
  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. }
  409. else
  410. {
  411. Logger.PrintWarning(LogClass.Loader, $"Unsupported ASET header version found \"{asetVersion}\"");
  412. }
  413. }
  414. }
  415. }
  416. else
  417. {
  418. staticObject = new NxStaticObject(input);
  419. }
  420. ContentManager.LoadEntries();
  421. TitleID = CurrentTitle = metaData.Aci0.TitleId.ToString("x16");
  422. TitleName = metaData.TitleName;
  423. ProgramLoader.LoadStaticObjects(this, metaData, new IExecutable[] { staticObject });
  424. }
  425. private Npdm GetDefaultNpdm()
  426. {
  427. Assembly asm = Assembly.GetCallingAssembly();
  428. using (Stream npdmStream = asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm"))
  429. {
  430. return new Npdm(npdmStream);
  431. }
  432. }
  433. public void LoadKeySet()
  434. {
  435. string keyFile = null;
  436. string titleKeyFile = null;
  437. string consoleKeyFile = null;
  438. string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
  439. LoadSetAtPath(Path.Combine(home, ".switch"));
  440. LoadSetAtPath(Device.FileSystem.GetSystemPath());
  441. KeySet = ExternalKeys.ReadKeyFile(keyFile, titleKeyFile, consoleKeyFile);
  442. void LoadSetAtPath(string basePath)
  443. {
  444. string localKeyFile = Path.Combine(basePath, "prod.keys");
  445. string localTitleKeyFile = Path.Combine(basePath, "title.keys");
  446. string localConsoleKeyFile = Path.Combine(basePath, "console.keys");
  447. if (File.Exists(localKeyFile))
  448. {
  449. keyFile = localKeyFile;
  450. }
  451. if (File.Exists(localTitleKeyFile))
  452. {
  453. titleKeyFile = localTitleKeyFile;
  454. }
  455. if (File.Exists(localConsoleKeyFile))
  456. {
  457. consoleKeyFile = localConsoleKeyFile;
  458. }
  459. }
  460. }
  461. public void SignalVsync()
  462. {
  463. VsyncEvent.ReadableEvent.Signal();
  464. }
  465. internal long GetThreadUid()
  466. {
  467. return Interlocked.Increment(ref _threadUid) - 1;
  468. }
  469. internal long GetKipId()
  470. {
  471. return Interlocked.Increment(ref _kipId) - 1;
  472. }
  473. internal long GetProcessId()
  474. {
  475. return Interlocked.Increment(ref _processId) - 1;
  476. }
  477. public void EnableMultiCoreScheduling()
  478. {
  479. if (!_hasStarted)
  480. {
  481. Scheduler.MultiCoreScheduling = true;
  482. }
  483. }
  484. public void DisableMultiCoreScheduling()
  485. {
  486. if (!_hasStarted)
  487. {
  488. Scheduler.MultiCoreScheduling = false;
  489. }
  490. }
  491. public void Dispose()
  492. {
  493. Dispose(true);
  494. }
  495. protected virtual void Dispose(bool disposing)
  496. {
  497. if (disposing)
  498. {
  499. // Force all threads to exit.
  500. lock (Processes)
  501. {
  502. foreach (KProcess process in Processes.Values)
  503. {
  504. process.StopAllThreads();
  505. }
  506. }
  507. // It's only safe to release resources once all threads
  508. // have exited.
  509. ThreadCounter.Signal();
  510. ThreadCounter.Wait();
  511. Scheduler.Dispose();
  512. TimeManager.Dispose();
  513. Device.Unload();
  514. }
  515. }
  516. }
  517. }