Horizon.cs 27 KB

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