ApplicationLoader.cs 19 KB

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