Horizon.cs 26 KB

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