ApplicationLoader.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. using LibHac;
  2. using LibHac.Account;
  3. using LibHac.Common;
  4. using LibHac.Fs;
  5. using LibHac.FsSystem;
  6. using LibHac.FsSystem.NcaUtils;
  7. using LibHac.Ncm;
  8. using LibHac.Ns;
  9. using LibHac.Spl;
  10. using Ryujinx.Common.Configuration;
  11. using Ryujinx.Common.Logging;
  12. using Ryujinx.HLE.FileSystem;
  13. using Ryujinx.HLE.FileSystem.Content;
  14. using Ryujinx.HLE.Loaders.Executables;
  15. using Ryujinx.HLE.Loaders.Npdm;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Reflection;
  21. using static LibHac.Fs.ApplicationSaveDataManagement;
  22. namespace Ryujinx.HLE.HOS
  23. {
  24. using JsonHelper = Common.Utilities.JsonHelper;
  25. public class ApplicationLoader
  26. {
  27. private readonly Switch _device;
  28. private readonly ContentManager _contentManager;
  29. private readonly VirtualFileSystem _fileSystem;
  30. public IntegrityCheckLevel FsIntegrityCheckLevel => _device.System.FsIntegrityCheckLevel;
  31. public ulong TitleId { get; private set; }
  32. public string TitleIdText => TitleId.ToString("x16");
  33. public string TitleName { get; private set; }
  34. public string TitleVersionString { get; private set; }
  35. public bool TitleIs64Bit { get; private set; }
  36. public BlitStruct<ApplicationControlProperty> ControlData { get; set; }
  37. public ApplicationLoader(Switch device, VirtualFileSystem fileSystem, ContentManager contentManager)
  38. {
  39. _device = device;
  40. _contentManager = contentManager;
  41. _fileSystem = fileSystem;
  42. ControlData = new BlitStruct<ApplicationControlProperty>(1);
  43. }
  44. public void LoadCart(string exeFsDir, string romFsFile = null)
  45. {
  46. if (romFsFile != null)
  47. {
  48. _fileSystem.LoadRomFs(romFsFile);
  49. }
  50. LocalFileSystem codeFs = new LocalFileSystem(exeFsDir);
  51. LoadExeFs(codeFs, out _);
  52. if (TitleId != 0)
  53. {
  54. EnsureSaveData(new TitleId(TitleId));
  55. }
  56. }
  57. private (Nca Main, Nca Patch, Nca Control) GetGameData(PartitionFileSystem pfs)
  58. {
  59. Nca mainNca = null;
  60. Nca patchNca = null;
  61. Nca controlNca = null;
  62. _fileSystem.ImportTickets(pfs);
  63. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  64. {
  65. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  66. Nca nca = new Nca(_fileSystem.KeySet, ncaFile.AsStorage());
  67. if (nca.Header.ContentType == NcaContentType.Program)
  68. {
  69. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  70. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  71. {
  72. patchNca = nca;
  73. }
  74. else
  75. {
  76. mainNca = nca;
  77. }
  78. }
  79. else if (nca.Header.ContentType == NcaContentType.Control)
  80. {
  81. controlNca = nca;
  82. }
  83. }
  84. return (mainNca, patchNca, controlNca);
  85. }
  86. public void LoadXci(string xciFile)
  87. {
  88. FileStream file = new FileStream(xciFile, FileMode.Open, FileAccess.Read);
  89. Xci xci = new Xci(_fileSystem.KeySet, file.AsStorage());
  90. if (!xci.HasPartition(XciPartitionType.Secure))
  91. {
  92. Logger.PrintError(LogClass.Loader, "Unable to load XCI: Could not find XCI secure partition");
  93. return;
  94. }
  95. PartitionFileSystem securePartition = xci.OpenPartition(XciPartitionType.Secure);
  96. Nca mainNca = null;
  97. Nca patchNca = null;
  98. Nca controlNca = null;
  99. try
  100. {
  101. (mainNca, patchNca, controlNca) = GetGameData(securePartition);
  102. }
  103. catch (Exception e)
  104. {
  105. Logger.PrintError(LogClass.Loader, $"Unable to load XCI: {e.Message}");
  106. return;
  107. }
  108. if (mainNca == null)
  109. {
  110. Logger.PrintError(LogClass.Loader, "Unable to load XCI: Could not find Main NCA");
  111. return;
  112. }
  113. _contentManager.LoadEntries(_device);
  114. LoadNca(mainNca, patchNca, controlNca);
  115. }
  116. public void LoadNsp(string nspFile)
  117. {
  118. FileStream file = new FileStream(nspFile, FileMode.Open, FileAccess.Read);
  119. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  120. Nca mainNca = null;
  121. Nca patchNca = null;
  122. Nca controlNca = null;
  123. try
  124. {
  125. (mainNca, patchNca, controlNca) = GetGameData(nsp);
  126. }
  127. catch (Exception e)
  128. {
  129. Logger.PrintError(LogClass.Loader, $"Unable to load NSP: {e.Message}");
  130. return;
  131. }
  132. if (mainNca == null)
  133. {
  134. Logger.PrintError(LogClass.Loader, "Unable to load NSP: Could not find Main NCA");
  135. return;
  136. }
  137. if (mainNca != null)
  138. {
  139. LoadNca(mainNca, patchNca, controlNca);
  140. return;
  141. }
  142. // This is not a normal NSP, it's actually a ExeFS as a NSP
  143. LoadExeFs(nsp, out _);
  144. }
  145. public void LoadNca(string ncaFile)
  146. {
  147. FileStream file = new FileStream(ncaFile, FileMode.Open, FileAccess.Read);
  148. Nca nca = new Nca(_fileSystem.KeySet, file.AsStorage(false));
  149. LoadNca(nca, null, null);
  150. }
  151. private void LoadNca(Nca mainNca, Nca patchNca, Nca controlNca)
  152. {
  153. if (mainNca.Header.ContentType != NcaContentType.Program)
  154. {
  155. Logger.PrintError(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");
  156. return;
  157. }
  158. IStorage dataStorage = null;
  159. IFileSystem codeFs = null;
  160. string titleUpdateMetadataPath = System.IO.Path.Combine(_fileSystem.GetBasePath(), "games", mainNca.Header.TitleId.ToString("x16"), "updates.json");
  161. if (File.Exists(titleUpdateMetadataPath))
  162. {
  163. string updatePath = JsonHelper.DeserializeFromFile<TitleUpdateMetadata>(titleUpdateMetadataPath).Selected;
  164. if (File.Exists(updatePath))
  165. {
  166. FileStream file = new FileStream(updatePath, FileMode.Open, FileAccess.Read);
  167. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  168. _fileSystem.ImportTickets(nsp);
  169. foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
  170. {
  171. nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  172. Nca nca = new Nca(_fileSystem.KeySet, ncaFile.AsStorage());
  173. if ($"{nca.Header.TitleId.ToString("x16")[..^3]}000" != mainNca.Header.TitleId.ToString("x16"))
  174. {
  175. break;
  176. }
  177. if (nca.Header.ContentType == NcaContentType.Program)
  178. {
  179. patchNca = nca;
  180. }
  181. else if (nca.Header.ContentType == NcaContentType.Control)
  182. {
  183. controlNca = nca;
  184. }
  185. }
  186. }
  187. }
  188. if (patchNca == null)
  189. {
  190. if (mainNca.CanOpenSection(NcaSectionType.Data))
  191. {
  192. dataStorage = mainNca.OpenStorage(NcaSectionType.Data, FsIntegrityCheckLevel);
  193. }
  194. if (mainNca.CanOpenSection(NcaSectionType.Code))
  195. {
  196. codeFs = mainNca.OpenFileSystem(NcaSectionType.Code, FsIntegrityCheckLevel);
  197. }
  198. }
  199. else
  200. {
  201. if (patchNca.CanOpenSection(NcaSectionType.Data))
  202. {
  203. dataStorage = mainNca.OpenStorageWithPatch(patchNca, NcaSectionType.Data, FsIntegrityCheckLevel);
  204. }
  205. if (patchNca.CanOpenSection(NcaSectionType.Code))
  206. {
  207. codeFs = mainNca.OpenFileSystemWithPatch(patchNca, NcaSectionType.Code, FsIntegrityCheckLevel);
  208. }
  209. }
  210. if (codeFs == null)
  211. {
  212. Logger.PrintError(LogClass.Loader, "No ExeFS found in NCA");
  213. return;
  214. }
  215. if (dataStorage == null)
  216. {
  217. Logger.PrintWarning(LogClass.Loader, "No RomFS found in NCA");
  218. }
  219. else
  220. {
  221. _fileSystem.SetRomFs(dataStorage.AsStream(FileAccess.Read));
  222. }
  223. LoadExeFs(codeFs, out Npdm metaData);
  224. TitleId = metaData.Aci0.TitleId;
  225. TitleIs64Bit = metaData.Is64Bit;
  226. if (controlNca != null)
  227. {
  228. ReadControlData(controlNca);
  229. }
  230. else
  231. {
  232. ControlData.ByteSpan.Clear();
  233. }
  234. if (TitleId != 0)
  235. {
  236. EnsureSaveData(new TitleId(TitleId));
  237. }
  238. Logger.PrintInfo(LogClass.Loader, $"Application Loaded: {TitleName} v{TitleVersionString} [{TitleIdText}] [{(TitleIs64Bit ? "64-bit" : "32-bit")}]");
  239. }
  240. public void ReadControlData(Nca controlNca)
  241. {
  242. IFileSystem controlFs = controlNca.OpenFileSystem(NcaSectionType.Data, FsIntegrityCheckLevel);
  243. Result result = controlFs.OpenFile(out IFile controlFile, "/control.nacp".ToU8Span(), OpenMode.Read);
  244. if (result.IsSuccess())
  245. {
  246. result = controlFile.Read(out long bytesRead, 0, ControlData.ByteSpan, ReadOption.None);
  247. if (result.IsSuccess() && bytesRead == ControlData.ByteSpan.Length)
  248. {
  249. TitleName = ControlData.Value
  250. .Titles[(int)_device.System.State.DesiredTitleLanguage].Name.ToString();
  251. if (string.IsNullOrWhiteSpace(TitleName))
  252. {
  253. TitleName = ControlData.Value.Titles.ToArray()
  254. .FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  255. }
  256. TitleVersionString = ControlData.Value.DisplayVersion.ToString();
  257. }
  258. }
  259. else
  260. {
  261. ControlData.ByteSpan.Clear();
  262. }
  263. }
  264. private void LoadExeFs(IFileSystem codeFs, out Npdm metaData)
  265. {
  266. Result result = codeFs.OpenFile(out IFile npdmFile, "/main.npdm".ToU8Span(), OpenMode.Read);
  267. if (ResultFs.PathNotFound.Includes(result))
  268. {
  269. Logger.PrintWarning(LogClass.Loader, "NPDM file not found, using default values!");
  270. metaData = GetDefaultNpdm();
  271. }
  272. else
  273. {
  274. metaData = new Npdm(npdmFile.AsStream());
  275. }
  276. List<IExecutable> nsos = new List<IExecutable>();
  277. void LoadNso(string filename)
  278. {
  279. foreach (DirectoryEntryEx file in codeFs.EnumerateEntries("/", $"{filename}*"))
  280. {
  281. if (Path.GetExtension(file.Name) != string.Empty)
  282. {
  283. continue;
  284. }
  285. Logger.PrintInfo(LogClass.Loader, $"Loading {file.Name}...");
  286. codeFs.OpenFile(out IFile nsoFile, file.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  287. NsoExecutable nso = new NsoExecutable(nsoFile.AsStorage());
  288. nsos.Add(nso);
  289. }
  290. }
  291. TitleId = metaData.Aci0.TitleId;
  292. TitleIs64Bit = metaData.Is64Bit;
  293. LoadNso("rtld");
  294. LoadNso("main");
  295. LoadNso("subsdk");
  296. LoadNso("sdk");
  297. _contentManager.LoadEntries(_device);
  298. ProgramLoader.LoadNsos(_device.System.KernelContext, metaData, executables: nsos.ToArray());
  299. }
  300. public void LoadProgram(string filePath)
  301. {
  302. Npdm metaData = GetDefaultNpdm();
  303. bool isNro = Path.GetExtension(filePath).ToLower() == ".nro";
  304. IExecutable nro;
  305. if (isNro)
  306. {
  307. FileStream input = new FileStream(filePath, FileMode.Open);
  308. NroExecutable obj = new NroExecutable(input);
  309. nro = obj;
  310. // homebrew NRO can actually have some data after the actual NRO
  311. if (input.Length > obj.FileSize)
  312. {
  313. input.Position = obj.FileSize;
  314. BinaryReader reader = new BinaryReader(input);
  315. uint asetMagic = reader.ReadUInt32();
  316. if (asetMagic == 0x54455341)
  317. {
  318. uint asetVersion = reader.ReadUInt32();
  319. if (asetVersion == 0)
  320. {
  321. ulong iconOffset = reader.ReadUInt64();
  322. ulong iconSize = reader.ReadUInt64();
  323. ulong nacpOffset = reader.ReadUInt64();
  324. ulong nacpSize = reader.ReadUInt64();
  325. ulong romfsOffset = reader.ReadUInt64();
  326. ulong romfsSize = reader.ReadUInt64();
  327. if (romfsSize != 0)
  328. {
  329. _fileSystem.SetRomFs(new HomebrewRomFsStream(input, obj.FileSize + (long)romfsOffset));
  330. }
  331. if (nacpSize != 0)
  332. {
  333. input.Seek(obj.FileSize + (long)nacpOffset, SeekOrigin.Begin);
  334. reader.Read(ControlData.ByteSpan);
  335. ref ApplicationControlProperty nacp = ref ControlData.Value;
  336. metaData.TitleName = nacp.Titles[(int)_device.System.State.DesiredTitleLanguage].Name.ToString();
  337. if (string.IsNullOrWhiteSpace(metaData.TitleName))
  338. {
  339. metaData.TitleName = nacp.Titles.ToArray().FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  340. }
  341. if (nacp.PresenceGroupId != 0)
  342. {
  343. metaData.Aci0.TitleId = nacp.PresenceGroupId;
  344. }
  345. else if (nacp.SaveDataOwnerId.Value != 0)
  346. {
  347. metaData.Aci0.TitleId = nacp.SaveDataOwnerId.Value;
  348. }
  349. else if (nacp.AddOnContentBaseId != 0)
  350. {
  351. metaData.Aci0.TitleId = nacp.AddOnContentBaseId - 0x1000;
  352. }
  353. else
  354. {
  355. metaData.Aci0.TitleId = 0000000000000000;
  356. }
  357. }
  358. }
  359. else
  360. {
  361. Logger.PrintWarning(LogClass.Loader, $"Unsupported ASET header version found \"{asetVersion}\"");
  362. }
  363. }
  364. }
  365. }
  366. else
  367. {
  368. nro = new NsoExecutable(new LocalStorage(filePath, FileAccess.Read));
  369. }
  370. _contentManager.LoadEntries(_device);
  371. TitleName = metaData.TitleName;
  372. TitleId = metaData.Aci0.TitleId;
  373. TitleIs64Bit = metaData.Is64Bit;
  374. ProgramLoader.LoadNsos(_device.System.KernelContext, metaData, executables: nro);
  375. }
  376. private Npdm GetDefaultNpdm()
  377. {
  378. Assembly asm = Assembly.GetCallingAssembly();
  379. using (Stream npdmStream = asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm"))
  380. {
  381. return new Npdm(npdmStream);
  382. }
  383. }
  384. private Result EnsureSaveData(TitleId titleId)
  385. {
  386. Logger.PrintInfo(LogClass.Application, "Ensuring required savedata exists.");
  387. Uid user = _device.System.State.Account.LastOpenedUser.UserId.ToLibHacUid();
  388. ref ApplicationControlProperty control = ref ControlData.Value;
  389. if (Util.IsEmpty(ControlData.ByteSpan))
  390. {
  391. // If the current application doesn't have a loaded control property, create a dummy one
  392. // and set the savedata sizes so a user savedata will be created.
  393. control = ref new BlitStruct<ApplicationControlProperty>(1).Value;
  394. // The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
  395. control.UserAccountSaveDataSize = 0x4000;
  396. control.UserAccountSaveDataJournalSize = 0x4000;
  397. Logger.PrintWarning(LogClass.Application,
  398. "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games.");
  399. }
  400. FileSystemClient fs = _fileSystem.FsClient;
  401. Result rc = fs.EnsureApplicationCacheStorage(out _, titleId, ref control);
  402. if (rc.IsFailure())
  403. {
  404. Logger.PrintError(LogClass.Application, $"Error calling EnsureApplicationCacheStorage. Result code {rc.ToStringWithName()}");
  405. return rc;
  406. }
  407. rc = EnsureApplicationSaveData(fs, out _, titleId, ref control, ref user);
  408. if (rc.IsFailure())
  409. {
  410. Logger.PrintError(LogClass.Application, $"Error calling EnsureApplicationSaveData. Result code {rc.ToStringWithName()}");
  411. }
  412. return rc;
  413. }
  414. }
  415. }