Horizon.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. using LibHac;
  2. using Ryujinx.HLE.HOS.Font;
  3. using Ryujinx.HLE.HOS.Kernel;
  4. using Ryujinx.HLE.HOS.SystemState;
  5. using Ryujinx.HLE.Loaders.Executables;
  6. using Ryujinx.HLE.Loaders.Npdm;
  7. using Ryujinx.HLE.Logging;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. namespace Ryujinx.HLE.HOS
  14. {
  15. public class Horizon : IDisposable
  16. {
  17. internal const int HidSize = 0x40000;
  18. internal const int FontSize = 0x1100000;
  19. private Switch Device;
  20. private ConcurrentDictionary<int, Process> Processes;
  21. public SystemStateMgr State { get; private set; }
  22. internal KRecursiveLock CriticalSectionLock { get; private set; }
  23. internal KScheduler Scheduler { get; private set; }
  24. internal KTimeManager TimeManager { get; private set; }
  25. internal KAddressArbiter AddressArbiter { get; private set; }
  26. internal KSynchronization Synchronization { get; private set; }
  27. internal LinkedList<KThread> Withholders { get; private set; }
  28. internal KSharedMemory HidSharedMem { get; private set; }
  29. internal KSharedMemory FontSharedMem { get; private set; }
  30. internal SharedFontManager Font { get; private set; }
  31. internal KEvent VsyncEvent { get; private set; }
  32. internal Keyset KeySet { get; private set; }
  33. private bool HasStarted;
  34. public Nacp ControlData { get; set; }
  35. public string CurrentTitle { get; private set; }
  36. public Horizon(Switch Device)
  37. {
  38. this.Device = Device;
  39. Processes = new ConcurrentDictionary<int, Process>();
  40. State = new SystemStateMgr();
  41. CriticalSectionLock = new KRecursiveLock(this);
  42. Scheduler = new KScheduler(this);
  43. TimeManager = new KTimeManager();
  44. AddressArbiter = new KAddressArbiter(this);
  45. Synchronization = new KSynchronization(this);
  46. Withholders = new LinkedList<KThread>();
  47. if (!Device.Memory.Allocator.TryAllocate(HidSize, out long HidPA) ||
  48. !Device.Memory.Allocator.TryAllocate(FontSize, out long FontPA))
  49. {
  50. throw new InvalidOperationException();
  51. }
  52. HidSharedMem = new KSharedMemory(HidPA, HidSize);
  53. FontSharedMem = new KSharedMemory(FontPA, FontSize);
  54. Font = new SharedFontManager(Device, FontSharedMem.PA);
  55. VsyncEvent = new KEvent(this);
  56. LoadKeySet();
  57. }
  58. public void LoadCart(string ExeFsDir, string RomFsFile = null)
  59. {
  60. if (RomFsFile != null)
  61. {
  62. Device.FileSystem.LoadRomFs(RomFsFile);
  63. }
  64. string NpdmFileName = Path.Combine(ExeFsDir, "main.npdm");
  65. Npdm MetaData = null;
  66. if (File.Exists(NpdmFileName))
  67. {
  68. Device.Log.PrintInfo(LogClass.Loader, $"Loading main.npdm...");
  69. using (FileStream Input = new FileStream(NpdmFileName, FileMode.Open))
  70. {
  71. MetaData = new Npdm(Input);
  72. }
  73. }
  74. else
  75. {
  76. Device.Log.PrintWarning(LogClass.Loader, $"NPDM file not found, using default values!");
  77. }
  78. Process MainProcess = MakeProcess(MetaData);
  79. void LoadNso(string FileName)
  80. {
  81. foreach (string File in Directory.GetFiles(ExeFsDir, FileName))
  82. {
  83. if (Path.GetExtension(File) != string.Empty)
  84. {
  85. continue;
  86. }
  87. Device.Log.PrintInfo(LogClass.Loader, $"Loading {Path.GetFileNameWithoutExtension(File)}...");
  88. using (FileStream Input = new FileStream(File, FileMode.Open))
  89. {
  90. string Name = Path.GetFileNameWithoutExtension(File);
  91. Nso Program = new Nso(Input, Name);
  92. MainProcess.LoadProgram(Program);
  93. }
  94. }
  95. }
  96. if (!(MainProcess.MetaData?.Is64Bits ?? true))
  97. {
  98. throw new NotImplementedException("32-bit titles are unsupported!");
  99. }
  100. CurrentTitle = MainProcess.MetaData.ACI0.TitleId.ToString("x16");
  101. LoadNso("rtld");
  102. MainProcess.SetEmptyArgs();
  103. LoadNso("main");
  104. LoadNso("subsdk*");
  105. LoadNso("sdk");
  106. MainProcess.Run();
  107. }
  108. public void LoadXci(string XciFile)
  109. {
  110. FileStream File = new FileStream(XciFile, FileMode.Open, FileAccess.Read);
  111. Xci Xci = new Xci(KeySet, File);
  112. (Nca MainNca, Nca ControlNca) = GetXciGameData(Xci);
  113. if (MainNca == null)
  114. {
  115. Device.Log.PrintError(LogClass.Loader, "Unable to load XCI");
  116. return;
  117. }
  118. LoadNca(MainNca, ControlNca);
  119. }
  120. private (Nca Main, Nca Control) GetXciGameData(Xci Xci)
  121. {
  122. if (Xci.SecurePartition == null)
  123. {
  124. throw new InvalidDataException("Could not find XCI secure partition");
  125. }
  126. Nca MainNca = null;
  127. Nca PatchNca = null;
  128. Nca ControlNca = null;
  129. foreach (PfsFileEntry FileEntry in Xci.SecurePartition.Files.Where(x => x.Name.EndsWith(".nca")))
  130. {
  131. Stream NcaStream = Xci.SecurePartition.OpenFile(FileEntry);
  132. Nca Nca = new Nca(KeySet, NcaStream, true);
  133. if (Nca.Header.ContentType == ContentType.Program)
  134. {
  135. if (Nca.Sections.Any(x => x?.Type == SectionType.Romfs))
  136. {
  137. MainNca = Nca;
  138. }
  139. else if (Nca.Sections.Any(x => x?.Type == SectionType.Bktr))
  140. {
  141. PatchNca = Nca;
  142. }
  143. }
  144. else if (Nca.Header.ContentType == ContentType.Control)
  145. {
  146. ControlNca = Nca;
  147. }
  148. }
  149. if (MainNca == null)
  150. {
  151. Device.Log.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided XCI file");
  152. }
  153. MainNca.SetBaseNca(PatchNca);
  154. if (ControlNca != null)
  155. {
  156. ReadControlData(ControlNca);
  157. }
  158. return (MainNca, ControlNca);
  159. }
  160. public void ReadControlData(Nca ControlNca)
  161. {
  162. Romfs ControlRomfs = new Romfs(ControlNca.OpenSection(0, false));
  163. byte[] ControlFile = ControlRomfs.GetFile("/control.nacp");
  164. BinaryReader Reader = new BinaryReader(new MemoryStream(ControlFile));
  165. ControlData = new Nacp(Reader);
  166. }
  167. public void LoadNca(string NcaFile)
  168. {
  169. FileStream File = new FileStream(NcaFile, FileMode.Open, FileAccess.Read);
  170. Nca Nca = new Nca(KeySet, File, true);
  171. LoadNca(Nca, null);
  172. }
  173. public void LoadNsp(string NspFile)
  174. {
  175. FileStream File = new FileStream(NspFile, FileMode.Open, FileAccess.Read);
  176. Pfs Nsp = new Pfs(File);
  177. PfsFileEntry TicketFile = Nsp.Files.FirstOrDefault(x => x.Name.EndsWith(".tik"));
  178. // Load title key from the NSP's ticket in case the user doesn't have a title key file
  179. if (TicketFile != null)
  180. {
  181. // todo Change when Ticket(Stream) overload is added
  182. Ticket Ticket = new Ticket(new BinaryReader(Nsp.OpenFile(TicketFile)));
  183. KeySet.TitleKeys[Ticket.RightsId] = Ticket.GetTitleKey(KeySet);
  184. }
  185. Nca MainNca = null;
  186. Nca ControlNca = null;
  187. foreach (PfsFileEntry NcaFile in Nsp.Files.Where(x => x.Name.EndsWith(".nca")))
  188. {
  189. Nca Nca = new Nca(KeySet, Nsp.OpenFile(NcaFile), true);
  190. if (Nca.Header.ContentType == ContentType.Program)
  191. {
  192. MainNca = Nca;
  193. }
  194. else if (Nca.Header.ContentType == ContentType.Control)
  195. {
  196. ControlNca = Nca;
  197. }
  198. }
  199. if (MainNca != null)
  200. {
  201. LoadNca(MainNca, ControlNca);
  202. return;
  203. }
  204. Device.Log.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided NSP file");
  205. }
  206. public void LoadNca(Nca MainNca, Nca ControlNca)
  207. {
  208. NcaSection RomfsSection = MainNca.Sections.FirstOrDefault(x => x?.Type == SectionType.Romfs);
  209. NcaSection ExefsSection = MainNca.Sections.FirstOrDefault(x => x?.IsExefs == true);
  210. if (ExefsSection == null)
  211. {
  212. Device.Log.PrintError(LogClass.Loader, "No ExeFS found in NCA");
  213. return;
  214. }
  215. if (RomfsSection == null)
  216. {
  217. Device.Log.PrintError(LogClass.Loader, "No RomFS found in NCA");
  218. return;
  219. }
  220. Stream RomfsStream = MainNca.OpenSection(RomfsSection.SectionNum, false);
  221. Device.FileSystem.SetRomFs(RomfsStream);
  222. Stream ExefsStream = MainNca.OpenSection(ExefsSection.SectionNum, false);
  223. Pfs Exefs = new Pfs(ExefsStream);
  224. Npdm MetaData = null;
  225. if (Exefs.FileExists("main.npdm"))
  226. {
  227. Device.Log.PrintInfo(LogClass.Loader, "Loading main.npdm...");
  228. MetaData = new Npdm(Exefs.OpenFile("main.npdm"));
  229. }
  230. else
  231. {
  232. Device.Log.PrintWarning(LogClass.Loader, $"NPDM file not found, using default values!");
  233. }
  234. Process MainProcess = MakeProcess(MetaData);
  235. void LoadNso(string Filename)
  236. {
  237. foreach (PfsFileEntry File in Exefs.Files.Where(x => x.Name.StartsWith(Filename)))
  238. {
  239. if (Path.GetExtension(File.Name) != string.Empty)
  240. {
  241. continue;
  242. }
  243. Device.Log.PrintInfo(LogClass.Loader, $"Loading {Filename}...");
  244. string Name = Path.GetFileNameWithoutExtension(File.Name);
  245. Nso Program = new Nso(Exefs.OpenFile(File), Name);
  246. MainProcess.LoadProgram(Program);
  247. }
  248. }
  249. Nacp ReadControlData()
  250. {
  251. Romfs ControlRomfs = new Romfs(ControlNca.OpenSection(0, false));
  252. byte[] ControlFile = ControlRomfs.GetFile("/control.nacp");
  253. BinaryReader Reader = new BinaryReader(new MemoryStream(ControlFile));
  254. Nacp ControlData = new Nacp(Reader);
  255. CurrentTitle = ControlData.Languages[(int)State.DesiredTitleLanguage].Title;
  256. if (string.IsNullOrWhiteSpace(CurrentTitle))
  257. {
  258. CurrentTitle = ControlData.Languages.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Title)).Title;
  259. }
  260. return ControlData;
  261. }
  262. if (ControlNca != null)
  263. {
  264. MainProcess.ControlData = ReadControlData();
  265. }
  266. else
  267. {
  268. CurrentTitle = MainProcess.MetaData.ACI0.TitleId.ToString("x16");
  269. }
  270. if (!MainProcess.MetaData.Is64Bits)
  271. {
  272. throw new NotImplementedException("32-bit titles are unsupported!");
  273. }
  274. LoadNso("rtld");
  275. MainProcess.SetEmptyArgs();
  276. LoadNso("main");
  277. LoadNso("subsdk");
  278. LoadNso("sdk");
  279. MainProcess.Run();
  280. }
  281. public void LoadProgram(string FilePath)
  282. {
  283. bool IsNro = Path.GetExtension(FilePath).ToLower() == ".nro";
  284. string Name = Path.GetFileNameWithoutExtension(FilePath);
  285. string SwitchFilePath = Device.FileSystem.SystemPathToSwitchPath(FilePath);
  286. if (IsNro && (SwitchFilePath == null || !SwitchFilePath.StartsWith("sdmc:/")))
  287. {
  288. string SwitchPath = $"sdmc:/switch/{Name}{Homebrew.TemporaryNroSuffix}";
  289. string TempPath = Device.FileSystem.SwitchPathToSystemPath(SwitchPath);
  290. string SwitchDir = Path.GetDirectoryName(TempPath);
  291. if (!Directory.Exists(SwitchDir))
  292. {
  293. Directory.CreateDirectory(SwitchDir);
  294. }
  295. File.Copy(FilePath, TempPath, true);
  296. FilePath = TempPath;
  297. }
  298. Process MainProcess = MakeProcess();
  299. using (FileStream Input = new FileStream(FilePath, FileMode.Open))
  300. {
  301. MainProcess.LoadProgram(IsNro
  302. ? (IExecutable)new Nro(Input, FilePath)
  303. : (IExecutable)new Nso(Input, FilePath));
  304. }
  305. MainProcess.SetEmptyArgs();
  306. MainProcess.Run(IsNro);
  307. }
  308. public void LoadKeySet()
  309. {
  310. string KeyFile = null;
  311. string TitleKeyFile = null;
  312. string ConsoleKeyFile = null;
  313. string Home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
  314. LoadSetAtPath(Path.Combine(Home, ".switch"));
  315. LoadSetAtPath(Device.FileSystem.GetSystemPath());
  316. KeySet = ExternalKeys.ReadKeyFile(KeyFile, TitleKeyFile, ConsoleKeyFile);
  317. void LoadSetAtPath(string BasePath)
  318. {
  319. string LocalKeyFile = Path.Combine(BasePath, "prod.keys");
  320. string LocalTitleKeyFile = Path.Combine(BasePath, "title.keys");
  321. string LocalConsoleKeyFile = Path.Combine(BasePath, "console.keys");
  322. if (File.Exists(LocalKeyFile))
  323. {
  324. KeyFile = LocalKeyFile;
  325. }
  326. if (File.Exists(LocalTitleKeyFile))
  327. {
  328. TitleKeyFile = LocalTitleKeyFile;
  329. }
  330. if (File.Exists(LocalConsoleKeyFile))
  331. {
  332. ConsoleKeyFile = LocalConsoleKeyFile;
  333. }
  334. }
  335. }
  336. public void SignalVsync()
  337. {
  338. VsyncEvent.Signal();
  339. }
  340. private Process MakeProcess(Npdm MetaData = null)
  341. {
  342. HasStarted = true;
  343. Process Process;
  344. lock (Processes)
  345. {
  346. int ProcessId = 0;
  347. while (Processes.ContainsKey(ProcessId))
  348. {
  349. ProcessId++;
  350. }
  351. Process = new Process(Device, ProcessId, MetaData);
  352. Processes.TryAdd(ProcessId, Process);
  353. }
  354. InitializeProcess(Process);
  355. return Process;
  356. }
  357. private void InitializeProcess(Process Process)
  358. {
  359. Process.AppletState.SetFocus(true);
  360. }
  361. internal void ExitProcess(int ProcessId)
  362. {
  363. if (Processes.TryRemove(ProcessId, out Process Process))
  364. {
  365. Process.Dispose();
  366. if (Processes.Count == 0)
  367. {
  368. Scheduler.Dispose();
  369. TimeManager.Dispose();
  370. Device.Unload();
  371. }
  372. }
  373. }
  374. public void EnableMultiCoreScheduling()
  375. {
  376. if (!HasStarted)
  377. {
  378. Scheduler.MultiCoreScheduling = true;
  379. }
  380. }
  381. public void DisableMultiCoreScheduling()
  382. {
  383. if (!HasStarted)
  384. {
  385. Scheduler.MultiCoreScheduling = false;
  386. }
  387. }
  388. public void Dispose()
  389. {
  390. Dispose(true);
  391. }
  392. protected virtual void Dispose(bool Disposing)
  393. {
  394. if (Disposing)
  395. {
  396. foreach (Process Process in Processes.Values)
  397. {
  398. Process.Dispose();
  399. }
  400. }
  401. }
  402. }
  403. }