ApplicationLoader.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. LoadNca(mainNca, patchNca, controlNca);
  116. }
  117. public void LoadNsp(string nspFile)
  118. {
  119. FileStream file = new FileStream(nspFile, FileMode.Open, FileAccess.Read);
  120. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  121. Nca mainNca = null;
  122. Nca patchNca = null;
  123. Nca controlNca = null;
  124. try
  125. {
  126. (mainNca, patchNca, controlNca) = GetGameData(nsp);
  127. }
  128. catch (Exception e)
  129. {
  130. Logger.PrintError(LogClass.Loader, $"Unable to load NSP: {e.Message}");
  131. return;
  132. }
  133. if (mainNca == null)
  134. {
  135. Logger.PrintError(LogClass.Loader, "Unable to load NSP: Could not find Main NCA");
  136. return;
  137. }
  138. if (mainNca != null)
  139. {
  140. LoadNca(mainNca, patchNca, controlNca);
  141. return;
  142. }
  143. // This is not a normal NSP, it's actually a ExeFS as a NSP
  144. LoadExeFs(nsp, out _);
  145. }
  146. public void LoadNca(string ncaFile)
  147. {
  148. FileStream file = new FileStream(ncaFile, FileMode.Open, FileAccess.Read);
  149. Nca nca = new Nca(_fileSystem.KeySet, file.AsStorage(false));
  150. LoadNca(nca, null, null);
  151. }
  152. private void LoadNca(Nca mainNca, Nca patchNca, Nca controlNca)
  153. {
  154. if (mainNca.Header.ContentType != NcaContentType.Program)
  155. {
  156. Logger.PrintError(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");
  157. return;
  158. }
  159. IStorage dataStorage = null;
  160. IFileSystem codeFs = null;
  161. string titleUpdateMetadataPath = System.IO.Path.Combine(_fileSystem.GetBasePath(), "games", mainNca.Header.TitleId.ToString("x16"), "updates.json");
  162. if (File.Exists(titleUpdateMetadataPath))
  163. {
  164. string updatePath = JsonHelper.DeserializeFromFile<TitleUpdateMetadata>(titleUpdateMetadataPath).Selected;
  165. if (File.Exists(updatePath))
  166. {
  167. FileStream file = new FileStream(updatePath, FileMode.Open, FileAccess.Read);
  168. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  169. _fileSystem.ImportTickets(nsp);
  170. foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
  171. {
  172. nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  173. Nca nca = new Nca(_fileSystem.KeySet, ncaFile.AsStorage());
  174. if ($"{nca.Header.TitleId.ToString("x16")[..^3]}000" != mainNca.Header.TitleId.ToString("x16"))
  175. {
  176. break;
  177. }
  178. if (nca.Header.ContentType == NcaContentType.Program)
  179. {
  180. patchNca = nca;
  181. }
  182. else if (nca.Header.ContentType == NcaContentType.Control)
  183. {
  184. controlNca = nca;
  185. }
  186. }
  187. }
  188. }
  189. if (patchNca == null)
  190. {
  191. if (mainNca.CanOpenSection(NcaSectionType.Data))
  192. {
  193. dataStorage = mainNca.OpenStorage(NcaSectionType.Data, FsIntegrityCheckLevel);
  194. }
  195. if (mainNca.CanOpenSection(NcaSectionType.Code))
  196. {
  197. codeFs = mainNca.OpenFileSystem(NcaSectionType.Code, FsIntegrityCheckLevel);
  198. }
  199. }
  200. else
  201. {
  202. if (patchNca.CanOpenSection(NcaSectionType.Data))
  203. {
  204. dataStorage = mainNca.OpenStorageWithPatch(patchNca, NcaSectionType.Data, FsIntegrityCheckLevel);
  205. }
  206. if (patchNca.CanOpenSection(NcaSectionType.Code))
  207. {
  208. codeFs = mainNca.OpenFileSystemWithPatch(patchNca, NcaSectionType.Code, FsIntegrityCheckLevel);
  209. }
  210. }
  211. if (codeFs == null)
  212. {
  213. Logger.PrintError(LogClass.Loader, "No ExeFS found in NCA");
  214. return;
  215. }
  216. if (dataStorage == null)
  217. {
  218. Logger.PrintWarning(LogClass.Loader, "No RomFS found in NCA");
  219. }
  220. else
  221. {
  222. _fileSystem.SetRomFs(dataStorage.AsStream(FileAccess.Read));
  223. }
  224. if (controlNca != null)
  225. {
  226. ReadControlData(controlNca);
  227. }
  228. else
  229. {
  230. ControlData.ByteSpan.Clear();
  231. }
  232. LoadExeFs(codeFs, out _);
  233. if (TitleId != 0)
  234. {
  235. EnsureSaveData(new TitleId(TitleId));
  236. }
  237. Logger.PrintInfo(LogClass.Loader, $"Application Loaded: {TitleName} v{DisplayVersion} [{TitleIdText}] [{(TitleIs64Bit ? "64-bit" : "32-bit")}]");
  238. }
  239. public void ReadControlData(Nca controlNca)
  240. {
  241. IFileSystem controlFs = controlNca.OpenFileSystem(NcaSectionType.Data, FsIntegrityCheckLevel);
  242. Result result = controlFs.OpenFile(out IFile controlFile, "/control.nacp".ToU8Span(), OpenMode.Read);
  243. if (result.IsSuccess())
  244. {
  245. result = controlFile.Read(out long bytesRead, 0, ControlData.ByteSpan, ReadOption.None);
  246. if (result.IsSuccess() && bytesRead == ControlData.ByteSpan.Length)
  247. {
  248. TitleName = ControlData.Value
  249. .Titles[(int)_device.System.State.DesiredTitleLanguage].Name.ToString();
  250. if (string.IsNullOrWhiteSpace(TitleName))
  251. {
  252. TitleName = ControlData.Value.Titles.ToArray()
  253. .FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  254. }
  255. DisplayVersion = ControlData.Value.DisplayVersion.ToString();
  256. }
  257. }
  258. else
  259. {
  260. ControlData.ByteSpan.Clear();
  261. }
  262. }
  263. private void LoadExeFs(IFileSystem codeFs, out Npdm metaData)
  264. {
  265. Result result = codeFs.OpenFile(out IFile npdmFile, "/main.npdm".ToU8Span(), OpenMode.Read);
  266. if (ResultFs.PathNotFound.Includes(result))
  267. {
  268. Logger.PrintWarning(LogClass.Loader, "NPDM file not found, using default values!");
  269. metaData = GetDefaultNpdm();
  270. }
  271. else
  272. {
  273. metaData = new Npdm(npdmFile.AsStream());
  274. }
  275. List<IExecutable> nsos = new List<IExecutable>();
  276. void LoadNso(string filename)
  277. {
  278. foreach (DirectoryEntryEx file in codeFs.EnumerateEntries("/", $"{filename}*"))
  279. {
  280. if (Path.GetExtension(file.Name) != string.Empty)
  281. {
  282. continue;
  283. }
  284. Logger.PrintInfo(LogClass.Loader, $"Loading {file.Name}...");
  285. codeFs.OpenFile(out IFile nsoFile, file.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  286. NsoExecutable nso = new NsoExecutable(nsoFile.AsStorage());
  287. nsos.Add(nso);
  288. }
  289. }
  290. TitleId = metaData.Aci0.TitleId;
  291. TitleIs64Bit = metaData.Is64Bit;
  292. LoadNso("rtld");
  293. LoadNso("main");
  294. LoadNso("subsdk");
  295. LoadNso("sdk");
  296. _contentManager.LoadEntries(_device);
  297. Ptc.Initialize(TitleIdText, DisplayVersion, EnablePtc);
  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. }