ApplicationLoader.cs 20 KB

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