Horizon.cs 22 KB

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