Horizon.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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.SystemState;
  11. using Ryujinx.HLE.Loaders.Executables;
  12. using Ryujinx.HLE.Loaders.Npdm;
  13. using System;
  14. using System.Collections.Concurrent;
  15. using System.Collections.Generic;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Reflection;
  19. using System.Threading;
  20. using NxStaticObject = Ryujinx.HLE.Loaders.Executables.NxStaticObject;
  21. namespace Ryujinx.HLE.HOS
  22. {
  23. public class Horizon : IDisposable
  24. {
  25. internal const int InitialKipId = 1;
  26. internal const int InitialProcessId = 0x51;
  27. internal const int HidSize = 0x40000;
  28. internal const int FontSize = 0x1100000;
  29. private const int MemoryBlockAllocatorSize = 0x2710;
  30. private const ulong UserSlabHeapBase = DramMemoryMap.SlabHeapBase;
  31. private const ulong UserSlabHeapItemSize = KMemoryManager.PageSize;
  32. private const ulong UserSlabHeapSize = 0x3de000;
  33. internal long PrivilegedProcessLowestId { get; set; } = 1;
  34. internal long PrivilegedProcessHighestId { get; set; } = 8;
  35. internal Switch Device { get; private set; }
  36. public SystemStateMgr State { get; private set; }
  37. internal bool KernelInitialized { get; private set; }
  38. internal KResourceLimit ResourceLimit { get; private set; }
  39. internal KMemoryRegionManager[] MemoryRegions { get; private set; }
  40. internal KMemoryBlockAllocator LargeMemoryBlockAllocator { get; private set; }
  41. internal KMemoryBlockAllocator SmallMemoryBlockAllocator { get; private set; }
  42. internal KSlabHeap UserSlabHeapPages { get; private set; }
  43. internal KCriticalSection CriticalSection { get; private set; }
  44. internal KScheduler Scheduler { get; private set; }
  45. internal KTimeManager TimeManager { get; private set; }
  46. internal KSynchronization Synchronization { get; private set; }
  47. internal KContextIdManager ContextIdManager { get; private set; }
  48. private long _kipId;
  49. private long _processId;
  50. private long _threadUid;
  51. internal CountdownEvent ThreadCounter;
  52. internal SortedDictionary<long, KProcess> Processes;
  53. internal ConcurrentDictionary<string, KAutoObject> AutoObjectNames;
  54. internal bool EnableVersionChecks { get; private set; }
  55. internal AppletStateMgr AppletState { get; private set; }
  56. internal KSharedMemory HidSharedMem { get; private set; }
  57. internal KSharedMemory FontSharedMem { get; private set; }
  58. internal SharedFontManager Font { get; private set; }
  59. internal ContentManager ContentManager { get; private set; }
  60. internal KEvent VsyncEvent { get; private set; }
  61. internal Keyset KeySet { get; private set; }
  62. private bool _hasStarted;
  63. public Nacp ControlData { get; set; }
  64. public string CurrentTitle { get; private set; }
  65. public IntegrityCheckLevel FsIntegrityCheckLevel { get; set; }
  66. internal long HidBaseAddress { get; private set; }
  67. public Horizon(Switch device)
  68. {
  69. Device = device;
  70. State = new SystemStateMgr();
  71. ResourceLimit = new KResourceLimit(this);
  72. KernelInit.InitializeResourceLimit(ResourceLimit);
  73. MemoryRegions = KernelInit.GetMemoryRegions();
  74. LargeMemoryBlockAllocator = new KMemoryBlockAllocator(MemoryBlockAllocatorSize * 2);
  75. SmallMemoryBlockAllocator = new KMemoryBlockAllocator(MemoryBlockAllocatorSize);
  76. UserSlabHeapPages = new KSlabHeap(
  77. UserSlabHeapBase,
  78. UserSlabHeapItemSize,
  79. UserSlabHeapSize);
  80. CriticalSection = new KCriticalSection(this);
  81. Scheduler = new KScheduler(this);
  82. TimeManager = new KTimeManager();
  83. Synchronization = new KSynchronization(this);
  84. ContextIdManager = new KContextIdManager();
  85. _kipId = InitialKipId;
  86. _processId = InitialProcessId;
  87. Scheduler.StartAutoPreemptionThread();
  88. KernelInitialized = true;
  89. ThreadCounter = new CountdownEvent(1);
  90. Processes = new SortedDictionary<long, KProcess>();
  91. AutoObjectNames = new ConcurrentDictionary<string, KAutoObject>();
  92. //Note: This is not really correct, but with HLE of services, the only memory
  93. //region used that is used is Application, so we can use the other ones for anything.
  94. KMemoryRegionManager region = MemoryRegions[(int)MemoryRegion.NvServices];
  95. ulong hidPa = region.Address;
  96. ulong fontPa = region.Address + HidSize;
  97. HidBaseAddress = (long)(hidPa - DramMemoryMap.DramBase);
  98. KPageList hidPageList = new KPageList();
  99. KPageList fontPageList = new KPageList();
  100. hidPageList .AddRange(hidPa, HidSize / KMemoryManager.PageSize);
  101. fontPageList.AddRange(fontPa, FontSize / KMemoryManager.PageSize);
  102. HidSharedMem = new KSharedMemory(hidPageList, 0, 0, MemoryPermission.Read);
  103. FontSharedMem = new KSharedMemory(fontPageList, 0, 0, MemoryPermission.Read);
  104. AppletState = new AppletStateMgr(this);
  105. AppletState.SetFocus(true);
  106. Font = new SharedFontManager(device, (long)(fontPa - DramMemoryMap.DramBase));
  107. VsyncEvent = new KEvent(this);
  108. LoadKeySet();
  109. ContentManager = new ContentManager(device);
  110. }
  111. public void LoadCart(string exeFsDir, string romFsFile = null)
  112. {
  113. if (romFsFile != null)
  114. {
  115. Device.FileSystem.LoadRomFs(romFsFile);
  116. }
  117. string npdmFileName = Path.Combine(exeFsDir, "main.npdm");
  118. Npdm metaData = null;
  119. if (File.Exists(npdmFileName))
  120. {
  121. Logger.PrintInfo(LogClass.Loader, $"Loading main.npdm...");
  122. using (FileStream input = new FileStream(npdmFileName, FileMode.Open))
  123. {
  124. metaData = new Npdm(input);
  125. }
  126. }
  127. else
  128. {
  129. Logger.PrintWarning(LogClass.Loader, $"NPDM file not found, using default values!");
  130. metaData = GetDefaultNpdm();
  131. }
  132. List<IExecutable> staticObjects = new List<IExecutable>();
  133. void LoadNso(string searchPattern)
  134. {
  135. foreach (string file in Directory.GetFiles(exeFsDir, searchPattern))
  136. {
  137. if (Path.GetExtension(file) != string.Empty)
  138. {
  139. continue;
  140. }
  141. Logger.PrintInfo(LogClass.Loader, $"Loading {Path.GetFileNameWithoutExtension(file)}...");
  142. using (FileStream input = new FileStream(file, FileMode.Open))
  143. {
  144. NxStaticObject staticObject = new NxStaticObject(input);
  145. staticObjects.Add(staticObject);
  146. }
  147. }
  148. }
  149. if (!metaData.Is64Bits)
  150. {
  151. throw new NotImplementedException("32-bit titles are unsupported!");
  152. }
  153. CurrentTitle = metaData.Aci0.TitleId.ToString("x16");
  154. LoadNso("rtld");
  155. LoadNso("main");
  156. LoadNso("subsdk*");
  157. LoadNso("sdk");
  158. ContentManager.LoadEntries();
  159. ProgramLoader.LoadStaticObjects(this, metaData, staticObjects.ToArray());
  160. }
  161. public void LoadXci(string xciFile)
  162. {
  163. FileStream file = new FileStream(xciFile, FileMode.Open, FileAccess.Read);
  164. Xci xci = new Xci(KeySet, file.AsStorage());
  165. (Nca mainNca, Nca controlNca) = GetXciGameData(xci);
  166. if (mainNca == null)
  167. {
  168. Logger.PrintError(LogClass.Loader, "Unable to load XCI");
  169. return;
  170. }
  171. ContentManager.LoadEntries();
  172. LoadNca(mainNca, controlNca);
  173. }
  174. private (Nca Main, Nca Control) GetXciGameData(Xci xci)
  175. {
  176. if (xci.SecurePartition == null)
  177. {
  178. throw new InvalidDataException("Could not find XCI secure partition");
  179. }
  180. Nca mainNca = null;
  181. Nca patchNca = null;
  182. Nca controlNca = null;
  183. foreach (PfsFileEntry ticketEntry in xci.SecurePartition.Files.Where(x => x.Name.EndsWith(".tik")))
  184. {
  185. Ticket ticket = new Ticket(xci.SecurePartition.OpenFile(ticketEntry).AsStream());
  186. if (!KeySet.TitleKeys.ContainsKey(ticket.RightsId))
  187. {
  188. KeySet.TitleKeys.Add(ticket.RightsId, ticket.GetTitleKey(KeySet));
  189. }
  190. }
  191. foreach (PfsFileEntry fileEntry in xci.SecurePartition.Files.Where(x => x.Name.EndsWith(".nca")))
  192. {
  193. IStorage ncaStorage = xci.SecurePartition.OpenFile(fileEntry);
  194. Nca nca = new Nca(KeySet, ncaStorage, true);
  195. if (nca.Header.ContentType == ContentType.Program)
  196. {
  197. if (nca.Sections.Any(x => x?.Type == SectionType.Romfs))
  198. {
  199. mainNca = nca;
  200. }
  201. else if (nca.Sections.Any(x => x?.Type == SectionType.Bktr))
  202. {
  203. patchNca = nca;
  204. }
  205. }
  206. else if (nca.Header.ContentType == ContentType.Control)
  207. {
  208. controlNca = nca;
  209. }
  210. }
  211. if (mainNca == null)
  212. {
  213. Logger.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided XCI file");
  214. }
  215. mainNca.SetBaseNca(patchNca);
  216. if (controlNca != null)
  217. {
  218. ReadControlData(controlNca);
  219. }
  220. if (patchNca != null)
  221. {
  222. patchNca.SetBaseNca(mainNca);
  223. return (patchNca, controlNca);
  224. }
  225. return (mainNca, controlNca);
  226. }
  227. public void ReadControlData(Nca controlNca)
  228. {
  229. Romfs controlRomfs = new Romfs(controlNca.OpenSection(0, false, FsIntegrityCheckLevel, true));
  230. IStorage controlFile = controlRomfs.OpenFile("/control.nacp");
  231. ControlData = new Nacp(controlFile.AsStream());
  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.AsStorage(false), false);
  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.AsStorage(false));
  243. foreach (PfsFileEntry ticketEntry in nsp.Files.Where(x => x.Name.EndsWith(".tik")))
  244. {
  245. Ticket ticket = new Ticket(nsp.OpenFile(ticketEntry).AsStream());
  246. if (!KeySet.TitleKeys.ContainsKey(ticket.RightsId))
  247. {
  248. KeySet.TitleKeys.Add(ticket.RightsId, ticket.GetTitleKey(KeySet));
  249. }
  250. }
  251. Nca mainNca = null;
  252. Nca controlNca = null;
  253. foreach (PfsFileEntry ncaFile in nsp.Files.Where(x => x.Name.EndsWith(".nca")))
  254. {
  255. Nca nca = new Nca(KeySet, nsp.OpenFile(ncaFile), true);
  256. if (nca.Header.ContentType == ContentType.Program)
  257. {
  258. mainNca = nca;
  259. }
  260. else if (nca.Header.ContentType == ContentType.Control)
  261. {
  262. controlNca = nca;
  263. }
  264. }
  265. if (mainNca != null)
  266. {
  267. LoadNca(mainNca, controlNca);
  268. return;
  269. }
  270. Logger.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided NSP file");
  271. }
  272. public void LoadNca(Nca mainNca, Nca controlNca)
  273. {
  274. if (mainNca.Header.ContentType != ContentType.Program)
  275. {
  276. Logger.PrintError(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");
  277. return;
  278. }
  279. IStorage romfsStorage = mainNca.OpenSection(ProgramPartitionType.Data, false, FsIntegrityCheckLevel, false);
  280. IStorage exefsStorage = mainNca.OpenSection(ProgramPartitionType.Code, false, FsIntegrityCheckLevel, true);
  281. if (exefsStorage == null)
  282. {
  283. Logger.PrintError(LogClass.Loader, "No ExeFS found in NCA");
  284. return;
  285. }
  286. if (romfsStorage == null)
  287. {
  288. Logger.PrintWarning(LogClass.Loader, "No RomFS found in NCA");
  289. }
  290. else
  291. {
  292. Device.FileSystem.SetRomFs(romfsStorage.AsStream(false));
  293. }
  294. Pfs exefs = new Pfs(exefsStorage);
  295. Npdm metaData = null;
  296. if (exefs.FileExists("main.npdm"))
  297. {
  298. Logger.PrintInfo(LogClass.Loader, "Loading main.npdm...");
  299. metaData = new Npdm(exefs.OpenFile("main.npdm").AsStream());
  300. }
  301. else
  302. {
  303. Logger.PrintWarning(LogClass.Loader, $"NPDM file not found, using default values!");
  304. metaData = GetDefaultNpdm();
  305. }
  306. List<IExecutable> staticObjects = new List<IExecutable>();
  307. void LoadNso(string filename)
  308. {
  309. foreach (PfsFileEntry file in exefs.Files.Where(x => x.Name.StartsWith(filename)))
  310. {
  311. if (Path.GetExtension(file.Name) != string.Empty)
  312. {
  313. continue;
  314. }
  315. Logger.PrintInfo(LogClass.Loader, $"Loading {filename}...");
  316. NxStaticObject staticObject = new NxStaticObject(exefs.OpenFile(file).AsStream());
  317. staticObjects.Add(staticObject);
  318. }
  319. }
  320. Nacp ReadControlData()
  321. {
  322. Romfs controlRomfs = new Romfs(controlNca.OpenSection(0, false, FsIntegrityCheckLevel, true));
  323. IStorage controlFile = controlRomfs.OpenFile("/control.nacp");
  324. Nacp controlData = new Nacp(controlFile.AsStream());
  325. CurrentTitle = controlData.Descriptions[(int)State.DesiredTitleLanguage].Title;
  326. if (string.IsNullOrWhiteSpace(CurrentTitle))
  327. {
  328. CurrentTitle = controlData.Descriptions.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. }