ApplicationLoader.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. using ARMeilleure.Translation.PTC;
  2. using LibHac;
  3. using LibHac.Account;
  4. using LibHac.Common;
  5. using LibHac.Fs;
  6. using LibHac.Fs.Fsa;
  7. using LibHac.FsSystem;
  8. using LibHac.FsSystem.NcaUtils;
  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.Globalization;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Reflection;
  22. using static LibHac.Fs.ApplicationSaveDataManagement;
  23. using static Ryujinx.HLE.HOS.ModLoader;
  24. using ApplicationId = LibHac.Ncm.ApplicationId;
  25. namespace Ryujinx.HLE.HOS
  26. {
  27. using JsonHelper = Common.Utilities.JsonHelper;
  28. public class ApplicationLoader
  29. {
  30. // Binaries from exefs are loaded into mem in this order. Do not change.
  31. internal static readonly string[] ExeFsPrefixes =
  32. {
  33. "rtld",
  34. "main",
  35. "subsdk0",
  36. "subsdk1",
  37. "subsdk2",
  38. "subsdk3",
  39. "subsdk4",
  40. "subsdk5",
  41. "subsdk6",
  42. "subsdk7",
  43. "subsdk8",
  44. "subsdk9",
  45. "sdk"
  46. };
  47. private readonly Switch _device;
  48. private readonly ContentManager _contentManager;
  49. private readonly VirtualFileSystem _fileSystem;
  50. private string _titleName;
  51. private string _displayVersion;
  52. private BlitStruct<ApplicationControlProperty> _controlData;
  53. public BlitStruct<ApplicationControlProperty> ControlData => _controlData;
  54. public string TitleName => _titleName;
  55. public string DisplayVersion => _displayVersion;
  56. public ulong TitleId { get; private set; }
  57. public bool TitleIs64Bit { get; private set; }
  58. public string TitleIdText => TitleId.ToString("x16");
  59. public ApplicationLoader(Switch device, VirtualFileSystem fileSystem, ContentManager contentManager)
  60. {
  61. _device = device;
  62. _contentManager = contentManager;
  63. _fileSystem = fileSystem;
  64. _controlData = new BlitStruct<ApplicationControlProperty>(1);
  65. }
  66. public void LoadCart(string exeFsDir, string romFsFile = null)
  67. {
  68. if (romFsFile != null)
  69. {
  70. _fileSystem.LoadRomFs(romFsFile);
  71. }
  72. LocalFileSystem codeFs = new LocalFileSystem(exeFsDir);
  73. Npdm metaData = ReadNpdm(codeFs);
  74. _fileSystem.ModLoader.CollectMods(new[] { TitleId }, _fileSystem.ModLoader.GetModsBasePath());
  75. if (TitleId != 0)
  76. {
  77. EnsureSaveData(new ApplicationId(TitleId));
  78. }
  79. LoadExeFs(codeFs, metaData);
  80. }
  81. public static (Nca main, Nca patch, Nca control) GetGameData(VirtualFileSystem fileSystem, PartitionFileSystem pfs, int programIndex)
  82. {
  83. Nca mainNca = null;
  84. Nca patchNca = null;
  85. Nca controlNca = null;
  86. fileSystem.ImportTickets(pfs);
  87. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  88. {
  89. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  90. Nca nca = new Nca(fileSystem.KeySet, ncaFile.AsStorage());
  91. int ncaProgramIndex = (int)(nca.Header.TitleId & 0xF);
  92. if (ncaProgramIndex != programIndex)
  93. {
  94. continue;
  95. }
  96. if (nca.Header.ContentType == NcaContentType.Program)
  97. {
  98. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  99. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  100. {
  101. patchNca = nca;
  102. }
  103. else
  104. {
  105. mainNca = nca;
  106. }
  107. }
  108. else if (nca.Header.ContentType == NcaContentType.Control)
  109. {
  110. controlNca = nca;
  111. }
  112. }
  113. return (mainNca, patchNca, controlNca);
  114. }
  115. public static (Nca patch, Nca control) GetGameUpdateDataFromPartition(VirtualFileSystem fileSystem, PartitionFileSystem pfs, string titleId, int programIndex)
  116. {
  117. Nca patchNca = null;
  118. Nca controlNca = null;
  119. fileSystem.ImportTickets(pfs);
  120. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  121. {
  122. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  123. Nca nca = new Nca(fileSystem.KeySet, ncaFile.AsStorage());
  124. int ncaProgramIndex = (int)(nca.Header.TitleId & 0xF);
  125. if (ncaProgramIndex != programIndex)
  126. {
  127. continue;
  128. }
  129. if ($"{nca.Header.TitleId.ToString("x16")[..^3]}000" != titleId)
  130. {
  131. break;
  132. }
  133. if (nca.Header.ContentType == NcaContentType.Program)
  134. {
  135. patchNca = nca;
  136. }
  137. else if (nca.Header.ContentType == NcaContentType.Control)
  138. {
  139. controlNca = nca;
  140. }
  141. }
  142. return (patchNca, controlNca);
  143. }
  144. public static (Nca patch, Nca control) GetGameUpdateData(VirtualFileSystem fileSystem, string titleId, int programIndex, out string updatePath)
  145. {
  146. updatePath = null;
  147. if (ulong.TryParse(titleId, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong titleIdBase))
  148. {
  149. // Clear the program index part.
  150. titleIdBase &= 0xFFFFFFFFFFFFFFF0;
  151. // Load update informations if existing.
  152. string titleUpdateMetadataPath = Path.Combine(AppDataManager.GamesDirPath, titleIdBase.ToString("x16"), "updates.json");
  153. if (File.Exists(titleUpdateMetadataPath))
  154. {
  155. updatePath = JsonHelper.DeserializeFromFile<TitleUpdateMetadata>(titleUpdateMetadataPath).Selected;
  156. if (File.Exists(updatePath))
  157. {
  158. FileStream file = new FileStream(updatePath, FileMode.Open, FileAccess.Read);
  159. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  160. return GetGameUpdateDataFromPartition(fileSystem, nsp, titleIdBase.ToString("x16"), programIndex);
  161. }
  162. }
  163. }
  164. return (null, null);
  165. }
  166. public void LoadXci(string xciFile)
  167. {
  168. FileStream file = new FileStream(xciFile, FileMode.Open, FileAccess.Read);
  169. Xci xci = new Xci(_fileSystem.KeySet, file.AsStorage());
  170. if (!xci.HasPartition(XciPartitionType.Secure))
  171. {
  172. Logger.Error?.Print(LogClass.Loader, "Unable to load XCI: Could not find XCI secure partition");
  173. return;
  174. }
  175. PartitionFileSystem securePartition = xci.OpenPartition(XciPartitionType.Secure);
  176. Nca mainNca;
  177. Nca patchNca;
  178. Nca controlNca;
  179. try
  180. {
  181. (mainNca, patchNca, controlNca) = GetGameData(_fileSystem, securePartition, _device.UserChannelPersistence.Index);
  182. }
  183. catch (Exception e)
  184. {
  185. Logger.Error?.Print(LogClass.Loader, $"Unable to load XCI: {e.Message}");
  186. return;
  187. }
  188. if (mainNca == null)
  189. {
  190. Logger.Error?.Print(LogClass.Loader, "Unable to load XCI: Could not find Main NCA");
  191. return;
  192. }
  193. _contentManager.LoadEntries(_device);
  194. _contentManager.ClearAocData();
  195. _contentManager.AddAocData(securePartition, xciFile, mainNca.Header.TitleId);
  196. LoadNca(mainNca, patchNca, controlNca);
  197. }
  198. public void LoadNsp(string nspFile)
  199. {
  200. FileStream file = new FileStream(nspFile, FileMode.Open, FileAccess.Read);
  201. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  202. Nca mainNca;
  203. Nca patchNca;
  204. Nca controlNca;
  205. try
  206. {
  207. (mainNca, patchNca, controlNca) = GetGameData(_fileSystem, nsp, _device.UserChannelPersistence.Index);
  208. }
  209. catch (Exception e)
  210. {
  211. Logger.Error?.Print(LogClass.Loader, $"Unable to load NSP: {e.Message}");
  212. return;
  213. }
  214. if (mainNca == null)
  215. {
  216. Logger.Error?.Print(LogClass.Loader, "Unable to load NSP: Could not find Main NCA");
  217. return;
  218. }
  219. if (mainNca != null)
  220. {
  221. _contentManager.ClearAocData();
  222. _contentManager.AddAocData(nsp, nspFile, mainNca.Header.TitleId);
  223. LoadNca(mainNca, patchNca, controlNca);
  224. return;
  225. }
  226. // This is not a normal NSP, it's actually a ExeFS as a NSP
  227. LoadExeFs(nsp);
  228. }
  229. public void LoadNca(string ncaFile)
  230. {
  231. FileStream file = new FileStream(ncaFile, FileMode.Open, FileAccess.Read);
  232. Nca nca = new Nca(_fileSystem.KeySet, file.AsStorage(false));
  233. LoadNca(nca, null, null);
  234. }
  235. private void LoadNca(Nca mainNca, Nca patchNca, Nca controlNca)
  236. {
  237. if (mainNca.Header.ContentType != NcaContentType.Program)
  238. {
  239. Logger.Error?.Print(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");
  240. return;
  241. }
  242. IStorage dataStorage = null;
  243. IFileSystem codeFs = null;
  244. (Nca updatePatchNca, Nca updateControlNca) = GetGameUpdateData(_fileSystem, mainNca.Header.TitleId.ToString("x16"), _device.UserChannelPersistence.Index, out _);
  245. if (updatePatchNca != null)
  246. {
  247. patchNca = updatePatchNca;
  248. }
  249. if (updateControlNca != null)
  250. {
  251. controlNca = updateControlNca;
  252. }
  253. // Load program 0 control NCA as we are going to need it for display version.
  254. (_, Nca updateProgram0ControlNca) = GetGameUpdateData(_fileSystem, mainNca.Header.TitleId.ToString("x16"), 0, out _);
  255. // Load Aoc
  256. string titleAocMetadataPath = Path.Combine(AppDataManager.GamesDirPath, mainNca.Header.TitleId.ToString("x16"), "dlc.json");
  257. if (File.Exists(titleAocMetadataPath))
  258. {
  259. List<DlcContainer> dlcContainerList = JsonHelper.DeserializeFromFile<List<DlcContainer>>(titleAocMetadataPath);
  260. foreach (DlcContainer dlcContainer in dlcContainerList)
  261. {
  262. foreach (DlcNca dlcNca in dlcContainer.DlcNcaList)
  263. {
  264. _contentManager.AddAocItem(dlcNca.TitleId, dlcContainer.Path, dlcNca.Path, dlcNca.Enabled);
  265. }
  266. }
  267. }
  268. if (patchNca == null)
  269. {
  270. if (mainNca.CanOpenSection(NcaSectionType.Data))
  271. {
  272. dataStorage = mainNca.OpenStorage(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);
  273. }
  274. if (mainNca.CanOpenSection(NcaSectionType.Code))
  275. {
  276. codeFs = mainNca.OpenFileSystem(NcaSectionType.Code, _device.System.FsIntegrityCheckLevel);
  277. }
  278. }
  279. else
  280. {
  281. if (patchNca.CanOpenSection(NcaSectionType.Data))
  282. {
  283. dataStorage = mainNca.OpenStorageWithPatch(patchNca, NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);
  284. }
  285. if (patchNca.CanOpenSection(NcaSectionType.Code))
  286. {
  287. codeFs = mainNca.OpenFileSystemWithPatch(patchNca, NcaSectionType.Code, _device.System.FsIntegrityCheckLevel);
  288. }
  289. }
  290. if (codeFs == null)
  291. {
  292. Logger.Error?.Print(LogClass.Loader, "No ExeFS found in NCA");
  293. return;
  294. }
  295. Npdm metaData = ReadNpdm(codeFs);
  296. _fileSystem.ModLoader.CollectMods(_contentManager.GetAocTitleIds().Prepend(TitleId), _fileSystem.ModLoader.GetModsBasePath());
  297. if (controlNca != null)
  298. {
  299. ReadControlData(_device, controlNca, ref _controlData, ref _titleName, ref _displayVersion);
  300. }
  301. else
  302. {
  303. ControlData.ByteSpan.Clear();
  304. }
  305. // NOTE: Nintendo doesn't guarantee that the display version will be updated on sub programs when updating a multi program application.
  306. // BODY: As such, to avoid PTC cache confusion, we only trust the the program 0 display version when launching a sub program.
  307. if (updateProgram0ControlNca != null && _device.UserChannelPersistence.Index != 0)
  308. {
  309. string dummyTitleName = "";
  310. BlitStruct<ApplicationControlProperty> dummyControl = new BlitStruct<ApplicationControlProperty>(1);
  311. ReadControlData(_device, updateProgram0ControlNca, ref dummyControl, ref dummyTitleName, ref _displayVersion);
  312. }
  313. if (dataStorage == null)
  314. {
  315. Logger.Warning?.Print(LogClass.Loader, "No RomFS found in NCA");
  316. }
  317. else
  318. {
  319. IStorage newStorage = _fileSystem.ModLoader.ApplyRomFsMods(TitleId, dataStorage);
  320. _fileSystem.SetRomFs(newStorage.AsStream(FileAccess.Read));
  321. }
  322. if (TitleId != 0)
  323. {
  324. EnsureSaveData(new ApplicationId(TitleId));
  325. }
  326. LoadExeFs(codeFs, metaData);
  327. Logger.Info?.Print(LogClass.Loader, $"Application Loaded: {TitleName} v{DisplayVersion} [{TitleIdText}] [{(TitleIs64Bit ? "64-bit" : "32-bit")}]");
  328. }
  329. // Sets TitleId, so be sure to call before using it
  330. private Npdm ReadNpdm(IFileSystem fs)
  331. {
  332. Result result = fs.OpenFile(out IFile npdmFile, "/main.npdm".ToU8Span(), OpenMode.Read);
  333. Npdm metaData;
  334. if (ResultFs.PathNotFound.Includes(result))
  335. {
  336. Logger.Warning?.Print(LogClass.Loader, "NPDM file not found, using default values!");
  337. metaData = GetDefaultNpdm();
  338. }
  339. else
  340. {
  341. metaData = new Npdm(npdmFile.AsStream());
  342. }
  343. TitleId = metaData.Aci0.TitleId;
  344. TitleIs64Bit = metaData.Is64Bit;
  345. return metaData;
  346. }
  347. private static void ReadControlData(Switch device, Nca controlNca, ref BlitStruct<ApplicationControlProperty> controlData, ref string titleName, ref string displayVersion)
  348. {
  349. IFileSystem controlFs = controlNca.OpenFileSystem(NcaSectionType.Data, device.System.FsIntegrityCheckLevel);
  350. Result result = controlFs.OpenFile(out IFile controlFile, "/control.nacp".ToU8Span(), OpenMode.Read);
  351. if (result.IsSuccess())
  352. {
  353. result = controlFile.Read(out long bytesRead, 0, controlData.ByteSpan, ReadOption.None);
  354. if (result.IsSuccess() && bytesRead == controlData.ByteSpan.Length)
  355. {
  356. titleName = controlData.Value.Titles[(int)device.System.State.DesiredTitleLanguage].Name.ToString();
  357. if (string.IsNullOrWhiteSpace(titleName))
  358. {
  359. titleName = controlData.Value.Titles.ToArray().FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  360. }
  361. displayVersion = controlData.Value.DisplayVersion.ToString();
  362. }
  363. }
  364. else
  365. {
  366. controlData.ByteSpan.Clear();
  367. }
  368. }
  369. private void LoadExeFs(IFileSystem codeFs, Npdm metaData = null)
  370. {
  371. if (_fileSystem.ModLoader.ReplaceExefsPartition(TitleId, ref codeFs))
  372. {
  373. metaData = null; //TODO: Check if we should retain old npdm
  374. }
  375. metaData ??= ReadNpdm(codeFs);
  376. NsoExecutable[] nsos = new NsoExecutable[ExeFsPrefixes.Length];
  377. for (int i = 0; i < nsos.Length; i++)
  378. {
  379. string name = ExeFsPrefixes[i];
  380. if (!codeFs.FileExists($"/{name}"))
  381. {
  382. continue; // file doesn't exist, skip
  383. }
  384. Logger.Info?.Print(LogClass.Loader, $"Loading {name}...");
  385. codeFs.OpenFile(out IFile nsoFile, $"/{name}".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  386. nsos[i] = new NsoExecutable(nsoFile.AsStorage(), name);
  387. }
  388. // ExeFs file replacements
  389. ModLoadResult modLoadResult = _fileSystem.ModLoader.ApplyExefsMods(TitleId, nsos);
  390. // collect the nsos, ignoring ones that aren't used
  391. NsoExecutable[] programs = nsos.Where(x => x != null).ToArray();
  392. // take the npdm from mods if present
  393. if (modLoadResult.Npdm != null)
  394. {
  395. metaData = modLoadResult.Npdm;
  396. }
  397. bool hasPatches = _fileSystem.ModLoader.ApplyNsoPatches(TitleId, programs);
  398. _contentManager.LoadEntries(_device);
  399. bool usePtc = _device.System.EnablePtc;
  400. // don't use PTC if exefs files have been replaced
  401. usePtc &= !modLoadResult.Modified;
  402. // don't use PTC if exefs files have been patched
  403. usePtc &= !hasPatches;
  404. if (_device.System.EnablePtc && !usePtc)
  405. {
  406. Logger.Warning?.Print(LogClass.Ptc, $"Detected exefs modifications. PPTC disabled.");
  407. }
  408. Graphics.Gpu.GraphicsConfig.TitleId = TitleIdText;
  409. _device.Gpu.HostInitalized.Set();
  410. Ptc.Initialize(TitleIdText, DisplayVersion, usePtc);
  411. ProgramLoader.LoadNsos(_device.System.KernelContext, metaData, executables: programs);
  412. }
  413. public void LoadProgram(string filePath)
  414. {
  415. Npdm metaData = GetDefaultNpdm();
  416. bool isNro = Path.GetExtension(filePath).ToLower() == ".nro";
  417. IExecutable executable;
  418. if (isNro)
  419. {
  420. FileStream input = new FileStream(filePath, FileMode.Open);
  421. NroExecutable obj = new NroExecutable(input.AsStorage());
  422. executable = obj;
  423. // homebrew NRO can actually have some data after the actual NRO
  424. if (input.Length > obj.FileSize)
  425. {
  426. input.Position = obj.FileSize;
  427. BinaryReader reader = new BinaryReader(input);
  428. uint asetMagic = reader.ReadUInt32();
  429. if (asetMagic == 0x54455341)
  430. {
  431. uint asetVersion = reader.ReadUInt32();
  432. if (asetVersion == 0)
  433. {
  434. ulong iconOffset = reader.ReadUInt64();
  435. ulong iconSize = reader.ReadUInt64();
  436. ulong nacpOffset = reader.ReadUInt64();
  437. ulong nacpSize = reader.ReadUInt64();
  438. ulong romfsOffset = reader.ReadUInt64();
  439. ulong romfsSize = reader.ReadUInt64();
  440. if (romfsSize != 0)
  441. {
  442. _fileSystem.SetRomFs(new HomebrewRomFsStream(input, obj.FileSize + (long)romfsOffset));
  443. }
  444. if (nacpSize != 0)
  445. {
  446. input.Seek(obj.FileSize + (long)nacpOffset, SeekOrigin.Begin);
  447. reader.Read(ControlData.ByteSpan);
  448. ref ApplicationControlProperty nacp = ref ControlData.Value;
  449. metaData.TitleName = nacp.Titles[(int)_device.System.State.DesiredTitleLanguage].Name.ToString();
  450. if (string.IsNullOrWhiteSpace(metaData.TitleName))
  451. {
  452. metaData.TitleName = nacp.Titles.ToArray().FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  453. }
  454. if (nacp.PresenceGroupId != 0)
  455. {
  456. metaData.Aci0.TitleId = nacp.PresenceGroupId;
  457. }
  458. else if (nacp.SaveDataOwnerId.Value != 0)
  459. {
  460. metaData.Aci0.TitleId = nacp.SaveDataOwnerId.Value;
  461. }
  462. else if (nacp.AddOnContentBaseId != 0)
  463. {
  464. metaData.Aci0.TitleId = nacp.AddOnContentBaseId - 0x1000;
  465. }
  466. else
  467. {
  468. metaData.Aci0.TitleId = 0000000000000000;
  469. }
  470. }
  471. }
  472. else
  473. {
  474. Logger.Warning?.Print(LogClass.Loader, $"Unsupported ASET header version found \"{asetVersion}\"");
  475. }
  476. }
  477. }
  478. }
  479. else
  480. {
  481. executable = new NsoExecutable(new LocalStorage(filePath, FileAccess.Read), Path.GetFileNameWithoutExtension(filePath));
  482. }
  483. _contentManager.LoadEntries(_device);
  484. _titleName = metaData.TitleName;
  485. TitleId = metaData.Aci0.TitleId;
  486. TitleIs64Bit = metaData.Is64Bit;
  487. // Explicitly null titleid to disable the shader cache
  488. Graphics.Gpu.GraphicsConfig.TitleId = null;
  489. _device.Gpu.HostInitalized.Set();
  490. ProgramLoader.LoadNsos(_device.System.KernelContext, metaData, executables: executable);
  491. }
  492. private Npdm GetDefaultNpdm()
  493. {
  494. Assembly asm = Assembly.GetCallingAssembly();
  495. using (Stream npdmStream = asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm"))
  496. {
  497. return new Npdm(npdmStream);
  498. }
  499. }
  500. private Result EnsureSaveData(ApplicationId applicationId)
  501. {
  502. Logger.Info?.Print(LogClass.Application, "Ensuring required savedata exists.");
  503. Uid user = _device.System.State.Account.LastOpenedUser.UserId.ToLibHacUid();
  504. ref ApplicationControlProperty control = ref ControlData.Value;
  505. if (LibHac.Utilities.IsEmpty(ControlData.ByteSpan))
  506. {
  507. // If the current application doesn't have a loaded control property, create a dummy one
  508. // and set the savedata sizes so a user savedata will be created.
  509. control = ref new BlitStruct<ApplicationControlProperty>(1).Value;
  510. // The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
  511. control.UserAccountSaveDataSize = 0x4000;
  512. control.UserAccountSaveDataJournalSize = 0x4000;
  513. Logger.Warning?.Print(LogClass.Application,
  514. "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games.");
  515. }
  516. FileSystemClient fileSystem = _fileSystem.FsClient;
  517. Result resultCode = fileSystem.EnsureApplicationCacheStorage(out _, applicationId, ref control);
  518. if (resultCode.IsFailure())
  519. {
  520. Logger.Error?.Print(LogClass.Application, $"Error calling EnsureApplicationCacheStorage. Result code {resultCode.ToStringWithName()}");
  521. return resultCode;
  522. }
  523. resultCode = EnsureApplicationSaveData(fileSystem, out _, applicationId, ref control, ref user);
  524. if (resultCode.IsFailure())
  525. {
  526. Logger.Error?.Print(LogClass.Application, $"Error calling EnsureApplicationSaveData. Result code {resultCode.ToStringWithName()}");
  527. }
  528. return resultCode;
  529. }
  530. }
  531. }