Horizon.cs 22 KB

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