ApplicationLoader.cs 25 KB

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