ApplicationLoader.cs 25 KB

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