Horizon.cs 20 KB

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