Horizon.cs 23 KB

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