Horizon.cs 23 KB

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