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. 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. : 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. }