Horizon.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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. // NOTE: Now we set the default internal offset of the steady clock like Nintendo does... even if it's strange this is accurate.
  131. // TODO: use bpc:r and set:sys (and set external clock source id from settings)
  132. DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  133. SteadyClockCore.Instance.SetInternalOffset(new TimeSpanType(((ulong)(DateTime.Now.ToUniversalTime() - UnixEpoch).TotalSeconds) * 1000000000));
  134. }
  135. public void LoadCart(string exeFsDir, string romFsFile = null)
  136. {
  137. if (romFsFile != null)
  138. {
  139. Device.FileSystem.LoadRomFs(romFsFile);
  140. }
  141. LocalFileSystem codeFs = new LocalFileSystem(exeFsDir);
  142. LoadExeFs(codeFs, out _);
  143. }
  144. public void LoadXci(string xciFile)
  145. {
  146. FileStream file = new FileStream(xciFile, FileMode.Open, FileAccess.Read);
  147. Xci xci = new Xci(KeySet, file.AsStorage());
  148. (Nca mainNca, Nca patchNca, Nca controlNca) = GetXciGameData(xci);
  149. if (mainNca == null)
  150. {
  151. Logger.PrintError(LogClass.Loader, "Unable to load XCI");
  152. return;
  153. }
  154. ContentManager.LoadEntries();
  155. LoadNca(mainNca, patchNca, controlNca);
  156. }
  157. public void LoadKip(string kipFile)
  158. {
  159. using (FileStream fs = new FileStream(kipFile, FileMode.Open))
  160. {
  161. ProgramLoader.LoadKernelInitalProcess(this, new KernelInitialProcess(fs));
  162. }
  163. }
  164. private (Nca Main, Nca patch, Nca Control) GetXciGameData(Xci xci)
  165. {
  166. if (!xci.HasPartition(XciPartitionType.Secure))
  167. {
  168. throw new InvalidDataException("Could not find XCI secure partition");
  169. }
  170. Nca mainNca = null;
  171. Nca patchNca = null;
  172. Nca controlNca = null;
  173. XciPartition securePartition = xci.OpenPartition(XciPartitionType.Secure);
  174. foreach (DirectoryEntry ticketEntry in securePartition.EnumerateEntries("*.tik"))
  175. {
  176. Ticket ticket = new Ticket(securePartition.OpenFile(ticketEntry.FullPath, OpenMode.Read).AsStream());
  177. if (!KeySet.TitleKeys.ContainsKey(ticket.RightsId))
  178. {
  179. KeySet.TitleKeys.Add(ticket.RightsId, ticket.GetTitleKey(KeySet));
  180. }
  181. }
  182. foreach (DirectoryEntry fileEntry in securePartition.EnumerateEntries("*.nca"))
  183. {
  184. IStorage ncaStorage = securePartition.OpenFile(fileEntry.FullPath, OpenMode.Read).AsStorage();
  185. Nca nca = new Nca(KeySet, ncaStorage);
  186. if (nca.Header.ContentType == ContentType.Program)
  187. {
  188. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, ContentType.Program);
  189. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  190. {
  191. patchNca = nca;
  192. }
  193. else
  194. {
  195. mainNca = nca;
  196. }
  197. }
  198. else if (nca.Header.ContentType == ContentType.Control)
  199. {
  200. controlNca = nca;
  201. }
  202. }
  203. if (mainNca == null)
  204. {
  205. Logger.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided XCI file");
  206. }
  207. if (controlNca != null)
  208. {
  209. ReadControlData(controlNca);
  210. }
  211. return (mainNca, patchNca, controlNca);
  212. }
  213. public void ReadControlData(Nca controlNca)
  214. {
  215. IFileSystem controlFs = controlNca.OpenFileSystem(NcaSectionType.Data, FsIntegrityCheckLevel);
  216. IFile controlFile = controlFs.OpenFile("/control.nacp", OpenMode.Read);
  217. ControlData = new Nacp(controlFile.AsStream());
  218. TitleName = CurrentTitle = ControlData.Descriptions[(int)State.DesiredTitleLanguage].Title;
  219. }
  220. public void LoadNca(string ncaFile)
  221. {
  222. FileStream file = new FileStream(ncaFile, FileMode.Open, FileAccess.Read);
  223. Nca nca = new Nca(KeySet, file.AsStorage(false));
  224. LoadNca(nca, null, null);
  225. }
  226. public void LoadNsp(string nspFile)
  227. {
  228. FileStream file = new FileStream(nspFile, FileMode.Open, FileAccess.Read);
  229. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  230. foreach (DirectoryEntry ticketEntry in nsp.EnumerateEntries("*.tik"))
  231. {
  232. Ticket ticket = new Ticket(nsp.OpenFile(ticketEntry.FullPath, OpenMode.Read).AsStream());
  233. if (!KeySet.TitleKeys.ContainsKey(ticket.RightsId))
  234. {
  235. KeySet.TitleKeys.Add(ticket.RightsId, ticket.GetTitleKey(KeySet));
  236. }
  237. }
  238. Nca mainNca = null;
  239. Nca patchNca = null;
  240. Nca controlNca = null;
  241. foreach (DirectoryEntry fileEntry in nsp.EnumerateEntries("*.nca"))
  242. {
  243. IStorage ncaStorage = nsp.OpenFile(fileEntry.FullPath, OpenMode.Read).AsStorage();
  244. Nca nca = new Nca(KeySet, ncaStorage);
  245. if (nca.Header.ContentType == ContentType.Program)
  246. {
  247. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, ContentType.Program);
  248. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  249. {
  250. patchNca = nca;
  251. }
  252. else
  253. {
  254. mainNca = nca;
  255. }
  256. }
  257. else if (nca.Header.ContentType == ContentType.Control)
  258. {
  259. controlNca = nca;
  260. }
  261. }
  262. if (mainNca != null)
  263. {
  264. LoadNca(mainNca, patchNca, controlNca);
  265. return;
  266. }
  267. // This is not a normal NSP, it's actually a ExeFS as a NSP
  268. LoadExeFs(nsp, out _);
  269. }
  270. public void LoadNca(Nca mainNca, Nca patchNca, Nca controlNca)
  271. {
  272. if (mainNca.Header.ContentType != ContentType.Program)
  273. {
  274. Logger.PrintError(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");
  275. return;
  276. }
  277. IStorage dataStorage = null;
  278. IFileSystem codeFs = null;
  279. if (patchNca == null)
  280. {
  281. if (mainNca.CanOpenSection(NcaSectionType.Data))
  282. {
  283. dataStorage = mainNca.OpenStorage(NcaSectionType.Data, FsIntegrityCheckLevel);
  284. }
  285. if (mainNca.CanOpenSection(NcaSectionType.Code))
  286. {
  287. codeFs = mainNca.OpenFileSystem(NcaSectionType.Code, FsIntegrityCheckLevel);
  288. }
  289. }
  290. else
  291. {
  292. if (patchNca.CanOpenSection(NcaSectionType.Data))
  293. {
  294. dataStorage = mainNca.OpenStorageWithPatch(patchNca, NcaSectionType.Data, FsIntegrityCheckLevel);
  295. }
  296. if (patchNca.CanOpenSection(NcaSectionType.Code))
  297. {
  298. codeFs = mainNca.OpenFileSystemWithPatch(patchNca, NcaSectionType.Code, FsIntegrityCheckLevel);
  299. }
  300. }
  301. if (codeFs == null)
  302. {
  303. Logger.PrintError(LogClass.Loader, "No ExeFS found in NCA");
  304. return;
  305. }
  306. if (dataStorage == null)
  307. {
  308. Logger.PrintWarning(LogClass.Loader, "No RomFS found in NCA");
  309. }
  310. else
  311. {
  312. Device.FileSystem.SetRomFs(dataStorage.AsStream(FileAccess.Read));
  313. }
  314. LoadExeFs(codeFs, out Npdm metaData);
  315. Nacp ReadControlData()
  316. {
  317. IFileSystem controlRomfs = controlNca.OpenFileSystem(NcaSectionType.Data, FsIntegrityCheckLevel);
  318. IFile controlFile = controlRomfs.OpenFile("/control.nacp", OpenMode.Read);
  319. Nacp controlData = new Nacp(controlFile.AsStream());
  320. TitleName = CurrentTitle = controlData.Descriptions[(int)State.DesiredTitleLanguage].Title;
  321. TitleID = metaData.Aci0.TitleId.ToString("x16");
  322. CurrentTitle = controlData.Descriptions[(int)State.DesiredTitleLanguage].Title;
  323. if (string.IsNullOrWhiteSpace(CurrentTitle))
  324. {
  325. TitleName = CurrentTitle = controlData.Descriptions.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Title)).Title;
  326. }
  327. return controlData;
  328. }
  329. if (controlNca != null)
  330. {
  331. ReadControlData();
  332. }
  333. else
  334. {
  335. TitleID = CurrentTitle = metaData.Aci0.TitleId.ToString("x16");
  336. }
  337. }
  338. private void LoadExeFs(IFileSystem codeFs, out Npdm metaData)
  339. {
  340. if (codeFs.FileExists("/main.npdm"))
  341. {
  342. Logger.PrintInfo(LogClass.Loader, "Loading main.npdm...");
  343. metaData = new Npdm(codeFs.OpenFile("/main.npdm", OpenMode.Read).AsStream());
  344. }
  345. else
  346. {
  347. Logger.PrintWarning(LogClass.Loader, "NPDM file not found, using default values!");
  348. metaData = GetDefaultNpdm();
  349. }
  350. List<IExecutable> staticObjects = new List<IExecutable>();
  351. void LoadNso(string filename)
  352. {
  353. foreach (DirectoryEntry file in codeFs.EnumerateEntries($"{filename}*"))
  354. {
  355. if (Path.GetExtension(file.Name) != string.Empty)
  356. {
  357. continue;
  358. }
  359. Logger.PrintInfo(LogClass.Loader, $"Loading {file.Name}...");
  360. NxStaticObject staticObject = new NxStaticObject(codeFs.OpenFile(file.FullPath, OpenMode.Read).AsStream());
  361. staticObjects.Add(staticObject);
  362. }
  363. }
  364. TitleID = CurrentTitle = metaData.Aci0.TitleId.ToString("x16");
  365. LoadNso("rtld");
  366. LoadNso("main");
  367. LoadNso("subsdk");
  368. LoadNso("sdk");
  369. ContentManager.LoadEntries();
  370. ProgramLoader.LoadStaticObjects(this, metaData, staticObjects.ToArray());
  371. }
  372. public void LoadProgram(string filePath)
  373. {
  374. Npdm metaData = GetDefaultNpdm();
  375. bool isNro = Path.GetExtension(filePath).ToLower() == ".nro";
  376. FileStream input = new FileStream(filePath, FileMode.Open);
  377. IExecutable staticObject;
  378. if (isNro)
  379. {
  380. NxRelocatableObject obj = new NxRelocatableObject(input);
  381. staticObject = obj;
  382. // homebrew NRO can actually have some data after the actual NRO
  383. if (input.Length > obj.FileSize)
  384. {
  385. input.Position = obj.FileSize;
  386. BinaryReader reader = new BinaryReader(input);
  387. uint asetMagic = reader.ReadUInt32();
  388. if (asetMagic == 0x54455341)
  389. {
  390. uint asetVersion = reader.ReadUInt32();
  391. if (asetVersion == 0)
  392. {
  393. ulong iconOffset = reader.ReadUInt64();
  394. ulong iconSize = reader.ReadUInt64();
  395. ulong nacpOffset = reader.ReadUInt64();
  396. ulong nacpSize = reader.ReadUInt64();
  397. ulong romfsOffset = reader.ReadUInt64();
  398. ulong romfsSize = reader.ReadUInt64();
  399. if (romfsSize != 0)
  400. {
  401. Device.FileSystem.SetRomFs(new HomebrewRomFsStream(input, obj.FileSize + (long)romfsOffset));
  402. }
  403. }
  404. else
  405. {
  406. Logger.PrintWarning(LogClass.Loader, $"Unsupported ASET header version found \"{asetVersion}\"");
  407. }
  408. }
  409. }
  410. }
  411. else
  412. {
  413. staticObject = new NxStaticObject(input);
  414. }
  415. ContentManager.LoadEntries();
  416. TitleID = CurrentTitle = metaData.Aci0.TitleId.ToString("x16");
  417. TitleName = metaData.TitleName;
  418. ProgramLoader.LoadStaticObjects(this, metaData, new IExecutable[] { staticObject });
  419. }
  420. private Npdm GetDefaultNpdm()
  421. {
  422. Assembly asm = Assembly.GetCallingAssembly();
  423. using (Stream npdmStream = asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm"))
  424. {
  425. return new Npdm(npdmStream);
  426. }
  427. }
  428. public void LoadKeySet()
  429. {
  430. string keyFile = null;
  431. string titleKeyFile = null;
  432. string consoleKeyFile = null;
  433. string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
  434. LoadSetAtPath(Path.Combine(home, ".switch"));
  435. LoadSetAtPath(Device.FileSystem.GetSystemPath());
  436. KeySet = ExternalKeys.ReadKeyFile(keyFile, titleKeyFile, consoleKeyFile);
  437. void LoadSetAtPath(string basePath)
  438. {
  439. string localKeyFile = Path.Combine(basePath, "prod.keys");
  440. string localTitleKeyFile = Path.Combine(basePath, "title.keys");
  441. string localConsoleKeyFile = Path.Combine(basePath, "console.keys");
  442. if (File.Exists(localKeyFile))
  443. {
  444. keyFile = localKeyFile;
  445. }
  446. if (File.Exists(localTitleKeyFile))
  447. {
  448. titleKeyFile = localTitleKeyFile;
  449. }
  450. if (File.Exists(localConsoleKeyFile))
  451. {
  452. consoleKeyFile = localConsoleKeyFile;
  453. }
  454. }
  455. }
  456. public void SignalVsync()
  457. {
  458. VsyncEvent.ReadableEvent.Signal();
  459. }
  460. internal long GetThreadUid()
  461. {
  462. return Interlocked.Increment(ref _threadUid) - 1;
  463. }
  464. internal long GetKipId()
  465. {
  466. return Interlocked.Increment(ref _kipId) - 1;
  467. }
  468. internal long GetProcessId()
  469. {
  470. return Interlocked.Increment(ref _processId) - 1;
  471. }
  472. public void EnableMultiCoreScheduling()
  473. {
  474. if (!_hasStarted)
  475. {
  476. Scheduler.MultiCoreScheduling = true;
  477. }
  478. }
  479. public void DisableMultiCoreScheduling()
  480. {
  481. if (!_hasStarted)
  482. {
  483. Scheduler.MultiCoreScheduling = false;
  484. }
  485. }
  486. public void Dispose()
  487. {
  488. Dispose(true);
  489. }
  490. protected virtual void Dispose(bool disposing)
  491. {
  492. if (disposing)
  493. {
  494. // Force all threads to exit.
  495. lock (Processes)
  496. {
  497. foreach (KProcess process in Processes.Values)
  498. {
  499. process.StopAllThreads();
  500. }
  501. }
  502. // It's only safe to release resources once all threads
  503. // have exited.
  504. ThreadCounter.Signal();
  505. ThreadCounter.Wait();
  506. Scheduler.Dispose();
  507. TimeManager.Dispose();
  508. Device.Unload();
  509. }
  510. }
  511. }
  512. }