Horizon.cs 19 KB

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