Horizon.cs 22 KB

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