Horizon.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. using LibHac;
  2. using LibHac.Fs;
  3. using LibHac.Fs.NcaUtils;
  4. using Ryujinx.Common.Logging;
  5. using Ryujinx.HLE.FileSystem.Content;
  6. using Ryujinx.HLE.HOS.Font;
  7. using Ryujinx.HLE.HOS.Kernel.Common;
  8. using Ryujinx.HLE.HOS.Kernel.Memory;
  9. using Ryujinx.HLE.HOS.Kernel.Process;
  10. using Ryujinx.HLE.HOS.Kernel.Threading;
  11. using Ryujinx.HLE.HOS.Services.Sm;
  12. using Ryujinx.HLE.HOS.SystemState;
  13. using Ryujinx.HLE.Loaders.Executables;
  14. using Ryujinx.HLE.Loaders.Npdm;
  15. using System;
  16. using System.Collections.Concurrent;
  17. using System.Collections.Generic;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Reflection;
  21. using System.Threading;
  22. using NxStaticObject = Ryujinx.HLE.Loaders.Executables.NxStaticObject;
  23. namespace Ryujinx.HLE.HOS
  24. {
  25. public class Horizon : IDisposable
  26. {
  27. internal const int InitialKipId = 1;
  28. internal const int InitialProcessId = 0x51;
  29. internal const int HidSize = 0x40000;
  30. internal const int FontSize = 0x1100000;
  31. internal const int IirsSize = 0x8000;
  32. private const int MemoryBlockAllocatorSize = 0x2710;
  33. private const ulong UserSlabHeapBase = DramMemoryMap.SlabHeapBase;
  34. private const ulong UserSlabHeapItemSize = KMemoryManager.PageSize;
  35. private const ulong UserSlabHeapSize = 0x3de000;
  36. internal long PrivilegedProcessLowestId { get; set; } = 1;
  37. internal long PrivilegedProcessHighestId { get; set; } = 8;
  38. internal Switch Device { get; private set; }
  39. public SystemStateMgr State { get; private set; }
  40. internal bool KernelInitialized { get; private set; }
  41. internal KResourceLimit ResourceLimit { get; private set; }
  42. internal KMemoryRegionManager[] MemoryRegions { get; private set; }
  43. internal KMemoryBlockAllocator LargeMemoryBlockAllocator { get; private set; }
  44. internal KMemoryBlockAllocator SmallMemoryBlockAllocator { get; private set; }
  45. internal KSlabHeap UserSlabHeapPages { get; private set; }
  46. internal KCriticalSection CriticalSection { get; private set; }
  47. internal KScheduler Scheduler { get; private set; }
  48. internal KTimeManager TimeManager { get; private set; }
  49. internal KSynchronization Synchronization { get; private set; }
  50. internal KContextIdManager ContextIdManager { get; private set; }
  51. private long _kipId;
  52. private long _processId;
  53. private long _threadUid;
  54. internal CountdownEvent ThreadCounter;
  55. internal SortedDictionary<long, KProcess> Processes;
  56. internal ConcurrentDictionary<string, KAutoObject> AutoObjectNames;
  57. internal bool EnableVersionChecks { get; private set; }
  58. internal AppletStateMgr AppletState { get; private set; }
  59. internal KSharedMemory HidSharedMem { get; private set; }
  60. internal KSharedMemory FontSharedMem { get; private set; }
  61. internal KSharedMemory IirsSharedMem { get; private set; }
  62. internal SharedFontManager Font { get; private set; }
  63. internal ContentManager ContentManager { get; private set; }
  64. internal KEvent VsyncEvent { get; private set; }
  65. internal Keyset KeySet { get; private set; }
  66. private bool _hasStarted;
  67. public Nacp ControlData { get; set; }
  68. public string CurrentTitle { get; private set; }
  69. public string TitleName { get; private set; }
  70. public string TitleID { get; private set; }
  71. public IntegrityCheckLevel FsIntegrityCheckLevel { get; set; }
  72. internal long HidBaseAddress { get; private set; }
  73. public Horizon(Switch device)
  74. {
  75. ControlData = new Nacp();
  76. Device = device;
  77. State = new SystemStateMgr();
  78. ResourceLimit = new KResourceLimit(this);
  79. KernelInit.InitializeResourceLimit(ResourceLimit);
  80. MemoryRegions = KernelInit.GetMemoryRegions();
  81. LargeMemoryBlockAllocator = new KMemoryBlockAllocator(MemoryBlockAllocatorSize * 2);
  82. SmallMemoryBlockAllocator = new KMemoryBlockAllocator(MemoryBlockAllocatorSize);
  83. UserSlabHeapPages = new KSlabHeap(
  84. UserSlabHeapBase,
  85. UserSlabHeapItemSize,
  86. UserSlabHeapSize);
  87. CriticalSection = new KCriticalSection(this);
  88. Scheduler = new KScheduler(this);
  89. TimeManager = new KTimeManager();
  90. Synchronization = new KSynchronization(this);
  91. ContextIdManager = new KContextIdManager();
  92. _kipId = InitialKipId;
  93. _processId = InitialProcessId;
  94. Scheduler.StartAutoPreemptionThread();
  95. KernelInitialized = true;
  96. ThreadCounter = new CountdownEvent(1);
  97. Processes = new SortedDictionary<long, KProcess>();
  98. AutoObjectNames = new ConcurrentDictionary<string, KAutoObject>();
  99. //Note: This is not really correct, but with HLE of services, the only memory
  100. //region used that is used is Application, so we can use the other ones for anything.
  101. KMemoryRegionManager region = MemoryRegions[(int)MemoryRegion.NvServices];
  102. ulong hidPa = region.Address;
  103. ulong fontPa = region.Address + HidSize;
  104. ulong iirsPa = region.Address + HidSize + FontSize;
  105. HidBaseAddress = (long)(hidPa - DramMemoryMap.DramBase);
  106. KPageList hidPageList = new KPageList();
  107. KPageList fontPageList = new KPageList();
  108. KPageList iirsPageList = new KPageList();
  109. hidPageList .AddRange(hidPa, HidSize / KMemoryManager.PageSize);
  110. fontPageList.AddRange(fontPa, FontSize / KMemoryManager.PageSize);
  111. iirsPageList.AddRange(iirsPa, IirsSize / KMemoryManager.PageSize);
  112. HidSharedMem = new KSharedMemory(this, hidPageList, 0, 0, MemoryPermission.Read);
  113. FontSharedMem = new KSharedMemory(this, fontPageList, 0, 0, MemoryPermission.Read);
  114. IirsSharedMem = new KSharedMemory(this, iirsPageList, 0, 0, MemoryPermission.Read);
  115. AppletState = new AppletStateMgr(this);
  116. AppletState.SetFocus(true);
  117. Font = new SharedFontManager(device, (long)(fontPa - DramMemoryMap.DramBase));
  118. IUserInterface.InitializePort(this);
  119. VsyncEvent = new KEvent(this);
  120. LoadKeySet();
  121. ContentManager = new ContentManager(device);
  122. }
  123. public void LoadCart(string exeFsDir, string romFsFile = null)
  124. {
  125. if (romFsFile != null)
  126. {
  127. Device.FileSystem.LoadRomFs(romFsFile);
  128. }
  129. LocalFileSystem codeFs = new LocalFileSystem(exeFsDir);
  130. LoadExeFs(codeFs, out _);
  131. }
  132. public void LoadXci(string xciFile)
  133. {
  134. FileStream file = new FileStream(xciFile, FileMode.Open, FileAccess.Read);
  135. Xci xci = new Xci(KeySet, file.AsStorage());
  136. (Nca mainNca, Nca patchNca, Nca controlNca) = GetXciGameData(xci);
  137. if (mainNca == null)
  138. {
  139. Logger.PrintError(LogClass.Loader, "Unable to load XCI");
  140. return;
  141. }
  142. ContentManager.LoadEntries();
  143. LoadNca(mainNca, patchNca, controlNca);
  144. }
  145. public void LoadKip(string kipFile)
  146. {
  147. using (FileStream fs = new FileStream(kipFile, FileMode.Open))
  148. {
  149. ProgramLoader.LoadKernelInitalProcess(this, new KernelInitialProcess(fs));
  150. }
  151. }
  152. private (Nca Main, Nca patch, Nca Control) GetXciGameData(Xci xci)
  153. {
  154. if (!xci.HasPartition(XciPartitionType.Secure))
  155. {
  156. throw new InvalidDataException("Could not find XCI secure partition");
  157. }
  158. Nca mainNca = null;
  159. Nca patchNca = null;
  160. Nca controlNca = null;
  161. XciPartition securePartition = xci.OpenPartition(XciPartitionType.Secure);
  162. foreach (DirectoryEntry ticketEntry in securePartition.EnumerateEntries("*.tik"))
  163. {
  164. Ticket ticket = new Ticket(securePartition.OpenFile(ticketEntry.FullPath, OpenMode.Read).AsStream());
  165. if (!KeySet.TitleKeys.ContainsKey(ticket.RightsId))
  166. {
  167. KeySet.TitleKeys.Add(ticket.RightsId, ticket.GetTitleKey(KeySet));
  168. }
  169. }
  170. foreach (DirectoryEntry fileEntry in securePartition.EnumerateEntries("*.nca"))
  171. {
  172. IStorage ncaStorage = securePartition.OpenFile(fileEntry.FullPath, OpenMode.Read).AsStorage();
  173. Nca nca = new Nca(KeySet, ncaStorage);
  174. if (nca.Header.ContentType == ContentType.Program)
  175. {
  176. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, ContentType.Program);
  177. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  178. {
  179. patchNca = nca;
  180. }
  181. else
  182. {
  183. mainNca = nca;
  184. }
  185. }
  186. else if (nca.Header.ContentType == ContentType.Control)
  187. {
  188. controlNca = nca;
  189. }
  190. }
  191. if (mainNca == null)
  192. {
  193. Logger.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided XCI file");
  194. }
  195. if (controlNca != null)
  196. {
  197. ReadControlData(controlNca);
  198. }
  199. return (mainNca, patchNca, controlNca);
  200. }
  201. public void ReadControlData(Nca controlNca)
  202. {
  203. IFileSystem controlFs = controlNca.OpenFileSystem(NcaSectionType.Data, FsIntegrityCheckLevel);
  204. IFile controlFile = controlFs.OpenFile("/control.nacp", OpenMode.Read);
  205. ControlData = new Nacp(controlFile.AsStream());
  206. TitleName = CurrentTitle = ControlData.Descriptions[(int)State.DesiredTitleLanguage].Title;
  207. }
  208. public void LoadNca(string ncaFile)
  209. {
  210. FileStream file = new FileStream(ncaFile, FileMode.Open, FileAccess.Read);
  211. Nca nca = new Nca(KeySet, file.AsStorage(false));
  212. LoadNca(nca, null, null);
  213. }
  214. public void LoadNsp(string nspFile)
  215. {
  216. FileStream file = new FileStream(nspFile, FileMode.Open, FileAccess.Read);
  217. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  218. foreach (DirectoryEntry ticketEntry in nsp.EnumerateEntries("*.tik"))
  219. {
  220. Ticket ticket = new Ticket(nsp.OpenFile(ticketEntry.FullPath, OpenMode.Read).AsStream());
  221. if (!KeySet.TitleKeys.ContainsKey(ticket.RightsId))
  222. {
  223. KeySet.TitleKeys.Add(ticket.RightsId, ticket.GetTitleKey(KeySet));
  224. }
  225. }
  226. Nca mainNca = null;
  227. Nca patchNca = null;
  228. Nca controlNca = null;
  229. foreach (DirectoryEntry fileEntry in nsp.EnumerateEntries("*.nca"))
  230. {
  231. IStorage ncaStorage = nsp.OpenFile(fileEntry.FullPath, OpenMode.Read).AsStorage();
  232. Nca nca = new Nca(KeySet, ncaStorage);
  233. if (nca.Header.ContentType == ContentType.Program)
  234. {
  235. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, ContentType.Program);
  236. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  237. {
  238. patchNca = nca;
  239. }
  240. else
  241. {
  242. mainNca = nca;
  243. }
  244. }
  245. else if (nca.Header.ContentType == ContentType.Control)
  246. {
  247. controlNca = nca;
  248. }
  249. }
  250. if (mainNca != null)
  251. {
  252. LoadNca(mainNca, patchNca, controlNca);
  253. return;
  254. }
  255. // This is not a normal NSP, it's actually a ExeFS as a NSP
  256. LoadExeFs(nsp, out _);
  257. }
  258. public void LoadNca(Nca mainNca, Nca patchNca, Nca controlNca)
  259. {
  260. if (mainNca.Header.ContentType != ContentType.Program)
  261. {
  262. Logger.PrintError(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");
  263. return;
  264. }
  265. IStorage dataStorage = null;
  266. IFileSystem codeFs = null;
  267. if (patchNca == null)
  268. {
  269. if (mainNca.CanOpenSection(NcaSectionType.Data))
  270. {
  271. dataStorage = mainNca.OpenStorage(NcaSectionType.Data, FsIntegrityCheckLevel);
  272. }
  273. if (mainNca.CanOpenSection(NcaSectionType.Code))
  274. {
  275. codeFs = mainNca.OpenFileSystem(NcaSectionType.Code, FsIntegrityCheckLevel);
  276. }
  277. }
  278. else
  279. {
  280. if (patchNca.CanOpenSection(NcaSectionType.Data))
  281. {
  282. dataStorage = mainNca.OpenStorageWithPatch(patchNca, NcaSectionType.Data, FsIntegrityCheckLevel);
  283. }
  284. if (patchNca.CanOpenSection(NcaSectionType.Code))
  285. {
  286. codeFs = mainNca.OpenFileSystemWithPatch(patchNca, NcaSectionType.Code, FsIntegrityCheckLevel);
  287. }
  288. }
  289. if (codeFs == null)
  290. {
  291. Logger.PrintError(LogClass.Loader, "No ExeFS found in NCA");
  292. return;
  293. }
  294. if (dataStorage == null)
  295. {
  296. Logger.PrintWarning(LogClass.Loader, "No RomFS found in NCA");
  297. }
  298. else
  299. {
  300. Device.FileSystem.SetRomFs(dataStorage.AsStream(FileAccess.Read));
  301. }
  302. LoadExeFs(codeFs, out Npdm metaData);
  303. Nacp ReadControlData()
  304. {
  305. IFileSystem controlRomfs = controlNca.OpenFileSystem(NcaSectionType.Data, FsIntegrityCheckLevel);
  306. IFile controlFile = controlRomfs.OpenFile("/control.nacp", OpenMode.Read);
  307. Nacp controlData = new Nacp(controlFile.AsStream());
  308. TitleName = CurrentTitle = controlData.Descriptions[(int)State.DesiredTitleLanguage].Title;
  309. TitleID = metaData.Aci0.TitleId.ToString("x16");
  310. CurrentTitle = controlData.Descriptions[(int)State.DesiredTitleLanguage].Title;
  311. if (string.IsNullOrWhiteSpace(CurrentTitle))
  312. {
  313. TitleName = CurrentTitle = controlData.Descriptions.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Title)).Title;
  314. }
  315. return controlData;
  316. }
  317. if (controlNca != null)
  318. {
  319. ReadControlData();
  320. }
  321. else
  322. {
  323. TitleID = CurrentTitle = metaData.Aci0.TitleId.ToString("x16");
  324. }
  325. }
  326. private void LoadExeFs(IFileSystem codeFs, out Npdm metaData)
  327. {
  328. if (codeFs.FileExists("/main.npdm"))
  329. {
  330. Logger.PrintInfo(LogClass.Loader, "Loading main.npdm...");
  331. metaData = new Npdm(codeFs.OpenFile("/main.npdm", OpenMode.Read).AsStream());
  332. }
  333. else
  334. {
  335. Logger.PrintWarning(LogClass.Loader, "NPDM file not found, using default values!");
  336. metaData = GetDefaultNpdm();
  337. }
  338. List<IExecutable> staticObjects = new List<IExecutable>();
  339. void LoadNso(string filename)
  340. {
  341. foreach (DirectoryEntry file in codeFs.EnumerateEntries($"{filename}*"))
  342. {
  343. if (Path.GetExtension(file.Name) != string.Empty)
  344. {
  345. continue;
  346. }
  347. Logger.PrintInfo(LogClass.Loader, $"Loading {file.Name}...");
  348. NxStaticObject staticObject = new NxStaticObject(codeFs.OpenFile(file.FullPath, OpenMode.Read).AsStream());
  349. staticObjects.Add(staticObject);
  350. }
  351. }
  352. TitleID = CurrentTitle = metaData.Aci0.TitleId.ToString("x16");
  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. FileStream input = new FileStream(filePath, FileMode.Open);
  365. IExecutable staticObject;
  366. if (isNro)
  367. {
  368. NxRelocatableObject obj = new NxRelocatableObject(input);
  369. staticObject = obj;
  370. // homebrew NRO can actually have some data after the actual NRO
  371. if (input.Length > obj.FileSize)
  372. {
  373. input.Position = obj.FileSize;
  374. BinaryReader reader = new BinaryReader(input);
  375. uint asetMagic = reader.ReadUInt32();
  376. if (asetMagic == 0x54455341)
  377. {
  378. uint asetVersion = reader.ReadUInt32();
  379. if (asetVersion == 0)
  380. {
  381. ulong iconOffset = reader.ReadUInt64();
  382. ulong iconSize = reader.ReadUInt64();
  383. ulong nacpOffset = reader.ReadUInt64();
  384. ulong nacpSize = reader.ReadUInt64();
  385. ulong romfsOffset = reader.ReadUInt64();
  386. ulong romfsSize = reader.ReadUInt64();
  387. if (romfsSize != 0)
  388. {
  389. Device.FileSystem.SetRomFs(new HomebrewRomFsStream(input, obj.FileSize + (long)romfsOffset));
  390. }
  391. }
  392. else
  393. {
  394. Logger.PrintWarning(LogClass.Loader, $"Unsupported ASET header version found \"{asetVersion}\"");
  395. }
  396. }
  397. }
  398. }
  399. else
  400. {
  401. staticObject = new NxStaticObject(input);
  402. }
  403. ContentManager.LoadEntries();
  404. TitleID = CurrentTitle = metaData.Aci0.TitleId.ToString("x16");
  405. TitleName = metaData.TitleName;
  406. ProgramLoader.LoadStaticObjects(this, metaData, new IExecutable[] { staticObject });
  407. }
  408. private Npdm GetDefaultNpdm()
  409. {
  410. Assembly asm = Assembly.GetCallingAssembly();
  411. using (Stream npdmStream = asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm"))
  412. {
  413. return new Npdm(npdmStream);
  414. }
  415. }
  416. public void LoadKeySet()
  417. {
  418. string keyFile = null;
  419. string titleKeyFile = null;
  420. string consoleKeyFile = null;
  421. string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
  422. LoadSetAtPath(Path.Combine(home, ".switch"));
  423. LoadSetAtPath(Device.FileSystem.GetSystemPath());
  424. KeySet = ExternalKeys.ReadKeyFile(keyFile, titleKeyFile, consoleKeyFile);
  425. void LoadSetAtPath(string basePath)
  426. {
  427. string localKeyFile = Path.Combine(basePath, "prod.keys");
  428. string localTitleKeyFile = Path.Combine(basePath, "title.keys");
  429. string localConsoleKeyFile = Path.Combine(basePath, "console.keys");
  430. if (File.Exists(localKeyFile))
  431. {
  432. keyFile = localKeyFile;
  433. }
  434. if (File.Exists(localTitleKeyFile))
  435. {
  436. titleKeyFile = localTitleKeyFile;
  437. }
  438. if (File.Exists(localConsoleKeyFile))
  439. {
  440. consoleKeyFile = localConsoleKeyFile;
  441. }
  442. }
  443. }
  444. public void SignalVsync()
  445. {
  446. VsyncEvent.ReadableEvent.Signal();
  447. }
  448. internal long GetThreadUid()
  449. {
  450. return Interlocked.Increment(ref _threadUid) - 1;
  451. }
  452. internal long GetKipId()
  453. {
  454. return Interlocked.Increment(ref _kipId) - 1;
  455. }
  456. internal long GetProcessId()
  457. {
  458. return Interlocked.Increment(ref _processId) - 1;
  459. }
  460. public void EnableMultiCoreScheduling()
  461. {
  462. if (!_hasStarted)
  463. {
  464. Scheduler.MultiCoreScheduling = true;
  465. }
  466. }
  467. public void DisableMultiCoreScheduling()
  468. {
  469. if (!_hasStarted)
  470. {
  471. Scheduler.MultiCoreScheduling = false;
  472. }
  473. }
  474. public void Dispose()
  475. {
  476. Dispose(true);
  477. }
  478. protected virtual void Dispose(bool disposing)
  479. {
  480. if (disposing)
  481. {
  482. //Force all threads to exit.
  483. lock (Processes)
  484. {
  485. foreach (KProcess process in Processes.Values)
  486. {
  487. process.StopAllThreads();
  488. }
  489. }
  490. //It's only safe to release resources once all threads
  491. //have exited.
  492. ThreadCounter.Signal();
  493. ThreadCounter.Wait();
  494. Scheduler.Dispose();
  495. TimeManager.Dispose();
  496. Device.Unload();
  497. }
  498. }
  499. }
  500. }