Horizon.cs 28 KB

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