Horizon.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. using LibHac;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.HLE.FileSystem.Content;
  4. using Ryujinx.HLE.HOS.Font;
  5. using Ryujinx.HLE.HOS.Kernel;
  6. using Ryujinx.HLE.HOS.SystemState;
  7. using Ryujinx.HLE.Loaders.Executables;
  8. using Ryujinx.HLE.Loaders.Npdm;
  9. using System;
  10. using System.Collections.Concurrent;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Reflection;
  15. using System.Threading;
  16. using NxStaticObject = Ryujinx.HLE.Loaders.Executables.NxStaticObject;
  17. namespace Ryujinx.HLE.HOS
  18. {
  19. public class Horizon : IDisposable
  20. {
  21. internal const int InitialKipId = 1;
  22. internal const int InitialProcessId = 0x51;
  23. internal const int HidSize = 0x40000;
  24. internal const int FontSize = 0x1100000;
  25. private const int MemoryBlockAllocatorSize = 0x2710;
  26. private const ulong UserSlabHeapBase = DramMemoryMap.SlabHeapBase;
  27. private const ulong UserSlabHeapItemSize = KMemoryManager.PageSize;
  28. private const ulong UserSlabHeapSize = 0x3de000;
  29. internal long PrivilegedProcessLowestId { get; set; } = 1;
  30. internal long PrivilegedProcessHighestId { get; set; } = 8;
  31. internal Switch Device { get; private set; }
  32. public SystemStateMgr State { get; private set; }
  33. internal bool KernelInitialized { get; private set; }
  34. internal KResourceLimit ResourceLimit { get; private set; }
  35. internal KMemoryRegionManager[] MemoryRegions { get; private set; }
  36. internal KMemoryBlockAllocator LargeMemoryBlockAllocator { get; private set; }
  37. internal KMemoryBlockAllocator SmallMemoryBlockAllocator { get; private set; }
  38. internal KSlabHeap UserSlabHeapPages { get; private set; }
  39. internal KCriticalSection CriticalSection { get; private set; }
  40. internal KScheduler Scheduler { get; private set; }
  41. internal KTimeManager TimeManager { get; private set; }
  42. internal KSynchronization Synchronization { get; private set; }
  43. internal KContextIdManager ContextIdManager { get; private set; }
  44. private long KipId;
  45. private long ProcessId;
  46. private long ThreadUid;
  47. internal CountdownEvent ThreadCounter;
  48. internal SortedDictionary<long, KProcess> Processes;
  49. internal ConcurrentDictionary<string, KAutoObject> AutoObjectNames;
  50. internal bool EnableVersionChecks { get; private set; }
  51. internal AppletStateMgr AppletState { get; private set; }
  52. internal KSharedMemory HidSharedMem { get; private set; }
  53. internal KSharedMemory FontSharedMem { get; private set; }
  54. internal SharedFontManager Font { get; private set; }
  55. internal ContentManager ContentManager { get; private set; }
  56. internal KEvent VsyncEvent { get; private set; }
  57. internal Keyset KeySet { get; private set; }
  58. private bool HasStarted;
  59. public Nacp ControlData { get; set; }
  60. public string CurrentTitle { get; private set; }
  61. public IntegrityCheckLevel FsIntegrityCheckLevel { get; set; }
  62. internal long HidBaseAddress { get; private set; }
  63. public Horizon(Switch Device)
  64. {
  65. this.Device = Device;
  66. State = new SystemStateMgr();
  67. ResourceLimit = new KResourceLimit(this);
  68. KernelInit.InitializeResourceLimit(ResourceLimit);
  69. MemoryRegions = KernelInit.GetMemoryRegions();
  70. LargeMemoryBlockAllocator = new KMemoryBlockAllocator(MemoryBlockAllocatorSize * 2);
  71. SmallMemoryBlockAllocator = new KMemoryBlockAllocator(MemoryBlockAllocatorSize);
  72. UserSlabHeapPages = new KSlabHeap(
  73. UserSlabHeapBase,
  74. UserSlabHeapItemSize,
  75. UserSlabHeapSize);
  76. CriticalSection = new KCriticalSection(this);
  77. Scheduler = new KScheduler(this);
  78. TimeManager = new KTimeManager();
  79. Synchronization = new KSynchronization(this);
  80. ContextIdManager = new KContextIdManager();
  81. KipId = InitialKipId;
  82. ProcessId = InitialProcessId;
  83. Scheduler.StartAutoPreemptionThread();
  84. KernelInitialized = true;
  85. ThreadCounter = new CountdownEvent(1);
  86. Processes = new SortedDictionary<long, KProcess>();
  87. AutoObjectNames = new ConcurrentDictionary<string, KAutoObject>();
  88. //Note: This is not really correct, but with HLE of services, the only memory
  89. //region used that is used is Application, so we can use the other ones for anything.
  90. KMemoryRegionManager Region = MemoryRegions[(int)MemoryRegion.NvServices];
  91. ulong HidPa = Region.Address;
  92. ulong FontPa = Region.Address + HidSize;
  93. HidBaseAddress = (long)(HidPa - DramMemoryMap.DramBase);
  94. KPageList HidPageList = new KPageList();
  95. KPageList FontPageList = new KPageList();
  96. HidPageList .AddRange(HidPa, HidSize / KMemoryManager.PageSize);
  97. FontPageList.AddRange(FontPa, FontSize / KMemoryManager.PageSize);
  98. HidSharedMem = new KSharedMemory(HidPageList, 0, 0, MemoryPermission.Read);
  99. FontSharedMem = new KSharedMemory(FontPageList, 0, 0, MemoryPermission.Read);
  100. AppletState = new AppletStateMgr(this);
  101. AppletState.SetFocus(true);
  102. Font = new SharedFontManager(Device, (long)(FontPa - DramMemoryMap.DramBase));
  103. VsyncEvent = new KEvent(this);
  104. LoadKeySet();
  105. ContentManager = new ContentManager(Device);
  106. }
  107. public void LoadCart(string ExeFsDir, string RomFsFile = null)
  108. {
  109. if (RomFsFile != null)
  110. {
  111. Device.FileSystem.LoadRomFs(RomFsFile);
  112. }
  113. string NpdmFileName = Path.Combine(ExeFsDir, "main.npdm");
  114. Npdm MetaData = null;
  115. if (File.Exists(NpdmFileName))
  116. {
  117. Logger.PrintInfo(LogClass.Loader, $"Loading main.npdm...");
  118. using (FileStream Input = new FileStream(NpdmFileName, FileMode.Open))
  119. {
  120. MetaData = new Npdm(Input);
  121. }
  122. }
  123. else
  124. {
  125. Logger.PrintWarning(LogClass.Loader, $"NPDM file not found, using default values!");
  126. MetaData = GetDefaultNpdm();
  127. }
  128. List<IExecutable> StaticObjects = new List<IExecutable>();
  129. void LoadNso(string SearchPattern)
  130. {
  131. foreach (string File in Directory.GetFiles(ExeFsDir, SearchPattern))
  132. {
  133. if (Path.GetExtension(File) != string.Empty)
  134. {
  135. continue;
  136. }
  137. Logger.PrintInfo(LogClass.Loader, $"Loading {Path.GetFileNameWithoutExtension(File)}...");
  138. using (FileStream Input = new FileStream(File, FileMode.Open))
  139. {
  140. NxStaticObject StaticObject = new NxStaticObject(Input);
  141. StaticObjects.Add(StaticObject);
  142. }
  143. }
  144. }
  145. if (!MetaData.Is64Bits)
  146. {
  147. throw new NotImplementedException("32-bit titles are unsupported!");
  148. }
  149. CurrentTitle = MetaData.ACI0.TitleId.ToString("x16");
  150. LoadNso("rtld");
  151. LoadNso("main");
  152. LoadNso("subsdk*");
  153. LoadNso("sdk");
  154. ContentManager.LoadEntries();
  155. ProgramLoader.LoadStaticObjects(this, MetaData, StaticObjects.ToArray());
  156. }
  157. public void LoadXci(string XciFile)
  158. {
  159. FileStream File = new FileStream(XciFile, FileMode.Open, FileAccess.Read);
  160. Xci Xci = new Xci(KeySet, File);
  161. (Nca MainNca, Nca ControlNca) = GetXciGameData(Xci);
  162. if (MainNca == null)
  163. {
  164. Logger.PrintError(LogClass.Loader, "Unable to load XCI");
  165. return;
  166. }
  167. ContentManager.LoadEntries();
  168. LoadNca(MainNca, ControlNca);
  169. }
  170. private (Nca Main, Nca Control) GetXciGameData(Xci Xci)
  171. {
  172. if (Xci.SecurePartition == null)
  173. {
  174. throw new InvalidDataException("Could not find XCI secure partition");
  175. }
  176. Nca MainNca = null;
  177. Nca PatchNca = null;
  178. Nca ControlNca = null;
  179. foreach (PfsFileEntry TicketEntry in Xci.SecurePartition.Files.Where(x => x.Name.EndsWith(".tik")))
  180. {
  181. Ticket ticket = new Ticket(Xci.SecurePartition.OpenFile(TicketEntry));
  182. if (!KeySet.TitleKeys.ContainsKey(ticket.RightsId))
  183. {
  184. KeySet.TitleKeys.Add(ticket.RightsId, ticket.GetTitleKey(KeySet));
  185. }
  186. }
  187. foreach (PfsFileEntry FileEntry in Xci.SecurePartition.Files.Where(x => x.Name.EndsWith(".nca")))
  188. {
  189. Stream NcaStream = Xci.SecurePartition.OpenFile(FileEntry);
  190. Nca Nca = new Nca(KeySet, NcaStream, true);
  191. if (Nca.Header.ContentType == ContentType.Program)
  192. {
  193. if (Nca.Sections.Any(x => x?.Type == SectionType.Romfs))
  194. {
  195. MainNca = Nca;
  196. }
  197. else if (Nca.Sections.Any(x => x?.Type == SectionType.Bktr))
  198. {
  199. PatchNca = Nca;
  200. }
  201. }
  202. else if (Nca.Header.ContentType == ContentType.Control)
  203. {
  204. ControlNca = Nca;
  205. }
  206. }
  207. if (MainNca == null)
  208. {
  209. Logger.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided XCI file");
  210. }
  211. MainNca.SetBaseNca(PatchNca);
  212. if (ControlNca != null)
  213. {
  214. ReadControlData(ControlNca);
  215. }
  216. if (PatchNca != null)
  217. {
  218. PatchNca.SetBaseNca(MainNca);
  219. return (PatchNca, ControlNca);
  220. }
  221. return (MainNca, ControlNca);
  222. }
  223. public void ReadControlData(Nca ControlNca)
  224. {
  225. Romfs ControlRomfs = new Romfs(ControlNca.OpenSection(0, false, FsIntegrityCheckLevel));
  226. byte[] ControlFile = ControlRomfs.GetFile("/control.nacp");
  227. BinaryReader Reader = new BinaryReader(new MemoryStream(ControlFile));
  228. ControlData = new Nacp(Reader);
  229. }
  230. public void LoadNca(string NcaFile)
  231. {
  232. FileStream File = new FileStream(NcaFile, FileMode.Open, FileAccess.Read);
  233. Nca Nca = new Nca(KeySet, File, true);
  234. LoadNca(Nca, null);
  235. }
  236. public void LoadNsp(string NspFile)
  237. {
  238. FileStream File = new FileStream(NspFile, FileMode.Open, FileAccess.Read);
  239. Pfs Nsp = new Pfs(File);
  240. PfsFileEntry TicketFile = Nsp.Files.FirstOrDefault(x => x.Name.EndsWith(".tik"));
  241. // Load title key from the NSP's ticket in case the user doesn't have a title key file
  242. if (TicketFile != null)
  243. {
  244. Ticket Ticket = new Ticket(Nsp.OpenFile(TicketFile));
  245. KeySet.TitleKeys[Ticket.RightsId] = Ticket.GetTitleKey(KeySet);
  246. }
  247. Nca MainNca = null;
  248. Nca ControlNca = null;
  249. foreach (PfsFileEntry NcaFile in Nsp.Files.Where(x => x.Name.EndsWith(".nca")))
  250. {
  251. Nca Nca = new Nca(KeySet, Nsp.OpenFile(NcaFile), true);
  252. if (Nca.Header.ContentType == ContentType.Program)
  253. {
  254. MainNca = Nca;
  255. }
  256. else if (Nca.Header.ContentType == ContentType.Control)
  257. {
  258. ControlNca = Nca;
  259. }
  260. }
  261. if (MainNca != null)
  262. {
  263. LoadNca(MainNca, ControlNca);
  264. return;
  265. }
  266. Logger.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided NSP file");
  267. }
  268. public void LoadNca(Nca MainNca, Nca ControlNca)
  269. {
  270. if (MainNca.Header.ContentType != ContentType.Program)
  271. {
  272. Logger.PrintError(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");
  273. return;
  274. }
  275. Stream RomfsStream = MainNca.OpenSection(ProgramPartitionType.Data, false, FsIntegrityCheckLevel);
  276. Stream ExefsStream = MainNca.OpenSection(ProgramPartitionType.Code, false, FsIntegrityCheckLevel);
  277. if (ExefsStream == null)
  278. {
  279. Logger.PrintError(LogClass.Loader, "No ExeFS found in NCA");
  280. return;
  281. }
  282. if (RomfsStream == null)
  283. {
  284. Logger.PrintWarning(LogClass.Loader, "No RomFS found in NCA");
  285. }
  286. else
  287. {
  288. Device.FileSystem.SetRomFs(RomfsStream);
  289. }
  290. Pfs Exefs = new Pfs(ExefsStream);
  291. Npdm MetaData = null;
  292. if (Exefs.FileExists("main.npdm"))
  293. {
  294. Logger.PrintInfo(LogClass.Loader, "Loading main.npdm...");
  295. MetaData = new Npdm(Exefs.OpenFile("main.npdm"));
  296. }
  297. else
  298. {
  299. Logger.PrintWarning(LogClass.Loader, $"NPDM file not found, using default values!");
  300. MetaData = GetDefaultNpdm();
  301. }
  302. List<IExecutable> StaticObjects = new List<IExecutable>();
  303. void LoadNso(string Filename)
  304. {
  305. foreach (PfsFileEntry File in Exefs.Files.Where(x => x.Name.StartsWith(Filename)))
  306. {
  307. if (Path.GetExtension(File.Name) != string.Empty)
  308. {
  309. continue;
  310. }
  311. Logger.PrintInfo(LogClass.Loader, $"Loading {Filename}...");
  312. NxStaticObject StaticObject = new NxStaticObject(Exefs.OpenFile(File));
  313. StaticObjects.Add(StaticObject);
  314. }
  315. }
  316. Nacp ReadControlData()
  317. {
  318. Romfs ControlRomfs = new Romfs(ControlNca.OpenSection(0, false, FsIntegrityCheckLevel));
  319. byte[] ControlFile = ControlRomfs.GetFile("/control.nacp");
  320. BinaryReader Reader = new BinaryReader(new MemoryStream(ControlFile));
  321. Nacp ControlData = new Nacp(Reader);
  322. CurrentTitle = ControlData.Languages[(int)State.DesiredTitleLanguage].Title;
  323. if (string.IsNullOrWhiteSpace(CurrentTitle))
  324. {
  325. CurrentTitle = ControlData.Languages.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Title)).Title;
  326. }
  327. return ControlData;
  328. }
  329. if (ControlNca != null)
  330. {
  331. ReadControlData();
  332. }
  333. else
  334. {
  335. CurrentTitle = MetaData.ACI0.TitleId.ToString("x16");
  336. }
  337. if (!MetaData.Is64Bits)
  338. {
  339. throw new NotImplementedException("32-bit titles are not supported!");
  340. }
  341. LoadNso("rtld");
  342. LoadNso("main");
  343. LoadNso("subsdk");
  344. LoadNso("sdk");
  345. ContentManager.LoadEntries();
  346. ProgramLoader.LoadStaticObjects(this, MetaData, StaticObjects.ToArray());
  347. }
  348. public void LoadProgram(string FilePath)
  349. {
  350. Npdm MetaData = GetDefaultNpdm();
  351. bool IsNro = Path.GetExtension(FilePath).ToLower() == ".nro";
  352. using (FileStream Input = new FileStream(FilePath, FileMode.Open))
  353. {
  354. IExecutable StaticObject = IsNro
  355. ? (IExecutable)new NxRelocatableObject(Input)
  356. : (IExecutable)new NxStaticObject(Input);
  357. ProgramLoader.LoadStaticObjects(this, MetaData, new IExecutable[] { StaticObject });
  358. }
  359. }
  360. private Npdm GetDefaultNpdm()
  361. {
  362. Assembly Asm = Assembly.GetCallingAssembly();
  363. using (Stream NpdmStream = Asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm"))
  364. {
  365. return new Npdm(NpdmStream);
  366. }
  367. }
  368. public void LoadKeySet()
  369. {
  370. string KeyFile = null;
  371. string TitleKeyFile = null;
  372. string ConsoleKeyFile = null;
  373. string Home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
  374. LoadSetAtPath(Path.Combine(Home, ".switch"));
  375. LoadSetAtPath(Device.FileSystem.GetSystemPath());
  376. KeySet = ExternalKeys.ReadKeyFile(KeyFile, TitleKeyFile, ConsoleKeyFile);
  377. void LoadSetAtPath(string BasePath)
  378. {
  379. string LocalKeyFile = Path.Combine(BasePath, "prod.keys");
  380. string LocalTitleKeyFile = Path.Combine(BasePath, "title.keys");
  381. string LocalConsoleKeyFile = Path.Combine(BasePath, "console.keys");
  382. if (File.Exists(LocalKeyFile))
  383. {
  384. KeyFile = LocalKeyFile;
  385. }
  386. if (File.Exists(LocalTitleKeyFile))
  387. {
  388. TitleKeyFile = LocalTitleKeyFile;
  389. }
  390. if (File.Exists(LocalConsoleKeyFile))
  391. {
  392. ConsoleKeyFile = LocalConsoleKeyFile;
  393. }
  394. }
  395. }
  396. public void SignalVsync()
  397. {
  398. VsyncEvent.ReadableEvent.Signal();
  399. }
  400. internal long GetThreadUid()
  401. {
  402. return Interlocked.Increment(ref ThreadUid) - 1;
  403. }
  404. internal long GetKipId()
  405. {
  406. return Interlocked.Increment(ref KipId) - 1;
  407. }
  408. internal long GetProcessId()
  409. {
  410. return Interlocked.Increment(ref ProcessId) - 1;
  411. }
  412. public void EnableMultiCoreScheduling()
  413. {
  414. if (!HasStarted)
  415. {
  416. Scheduler.MultiCoreScheduling = true;
  417. }
  418. }
  419. public void DisableMultiCoreScheduling()
  420. {
  421. if (!HasStarted)
  422. {
  423. Scheduler.MultiCoreScheduling = false;
  424. }
  425. }
  426. public void Dispose()
  427. {
  428. Dispose(true);
  429. }
  430. protected virtual void Dispose(bool Disposing)
  431. {
  432. if (Disposing)
  433. {
  434. //Force all threads to exit.
  435. lock (Processes)
  436. {
  437. foreach (KProcess Process in Processes.Values)
  438. {
  439. Process.StopAllThreads();
  440. }
  441. }
  442. //It's only safe to release resources once all threads
  443. //have exited.
  444. ThreadCounter.Signal();
  445. ThreadCounter.Wait();
  446. Scheduler.Dispose();
  447. TimeManager.Dispose();
  448. Device.Unload();
  449. }
  450. }
  451. }
  452. }