Horizon.cs 21 KB

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