ApplicationLoader.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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.Fs.Shim;
  8. using LibHac.FsSystem;
  9. using LibHac.FsSystem.NcaUtils;
  10. using LibHac.Loader;
  11. using LibHac.Ncm;
  12. using LibHac.Ns;
  13. using Ryujinx.Common.Configuration;
  14. using Ryujinx.Common.Logging;
  15. using Ryujinx.HLE.FileSystem;
  16. using Ryujinx.HLE.HOS.Kernel.Process;
  17. using Ryujinx.HLE.Loaders.Executables;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.Globalization;
  21. using System.IO;
  22. using System.Linq;
  23. using System.Reflection;
  24. using static LibHac.Fs.ApplicationSaveDataManagement;
  25. using static Ryujinx.HLE.HOS.ModLoader;
  26. using ApplicationId = LibHac.Ncm.ApplicationId;
  27. namespace Ryujinx.HLE.HOS
  28. {
  29. using JsonHelper = Common.Utilities.JsonHelper;
  30. public class ApplicationLoader
  31. {
  32. // Binaries from exefs are loaded into mem in this order. Do not change.
  33. internal static readonly string[] ExeFsPrefixes =
  34. {
  35. "rtld",
  36. "main",
  37. "subsdk0",
  38. "subsdk1",
  39. "subsdk2",
  40. "subsdk3",
  41. "subsdk4",
  42. "subsdk5",
  43. "subsdk6",
  44. "subsdk7",
  45. "subsdk8",
  46. "subsdk9",
  47. "sdk"
  48. };
  49. private readonly Switch _device;
  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)
  60. {
  61. _device = device;
  62. _controlData = new BlitStruct<ApplicationControlProperty>(1);
  63. }
  64. public void LoadCart(string exeFsDir, string romFsFile = null)
  65. {
  66. if (romFsFile != null)
  67. {
  68. _device.Configuration.VirtualFileSystem.LoadRomFs(romFsFile);
  69. }
  70. LocalFileSystem codeFs = new LocalFileSystem(exeFsDir);
  71. MetaLoader metaData = ReadNpdm(codeFs);
  72. _device.Configuration.VirtualFileSystem.ModLoader.CollectMods(new[] { TitleId }, _device.Configuration.VirtualFileSystem.ModLoader.GetModsBasePath());
  73. if (TitleId != 0)
  74. {
  75. EnsureSaveData(new ApplicationId(TitleId));
  76. }
  77. LoadExeFs(codeFs, metaData);
  78. }
  79. public static (Nca main, Nca patch, Nca control) GetGameData(VirtualFileSystem fileSystem, PartitionFileSystem pfs, int programIndex)
  80. {
  81. Nca mainNca = null;
  82. Nca patchNca = null;
  83. Nca controlNca = null;
  84. fileSystem.ImportTickets(pfs);
  85. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  86. {
  87. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  88. Nca nca = new Nca(fileSystem.KeySet, ncaFile.AsStorage());
  89. int ncaProgramIndex = (int)(nca.Header.TitleId & 0xF);
  90. if (ncaProgramIndex != programIndex)
  91. {
  92. continue;
  93. }
  94. if (nca.Header.ContentType == NcaContentType.Program)
  95. {
  96. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  97. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  98. {
  99. patchNca = nca;
  100. }
  101. else
  102. {
  103. mainNca = nca;
  104. }
  105. }
  106. else if (nca.Header.ContentType == NcaContentType.Control)
  107. {
  108. controlNca = nca;
  109. }
  110. }
  111. return (mainNca, patchNca, controlNca);
  112. }
  113. public static (Nca patch, Nca control) GetGameUpdateDataFromPartition(VirtualFileSystem fileSystem, PartitionFileSystem pfs, string titleId, int programIndex)
  114. {
  115. Nca patchNca = null;
  116. Nca controlNca = null;
  117. fileSystem.ImportTickets(pfs);
  118. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  119. {
  120. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  121. Nca nca = new Nca(fileSystem.KeySet, ncaFile.AsStorage());
  122. int ncaProgramIndex = (int)(nca.Header.TitleId & 0xF);
  123. if (ncaProgramIndex != programIndex)
  124. {
  125. continue;
  126. }
  127. if ($"{nca.Header.TitleId.ToString("x16")[..^3]}000" != titleId)
  128. {
  129. break;
  130. }
  131. if (nca.Header.ContentType == NcaContentType.Program)
  132. {
  133. patchNca = nca;
  134. }
  135. else if (nca.Header.ContentType == NcaContentType.Control)
  136. {
  137. controlNca = nca;
  138. }
  139. }
  140. return (patchNca, controlNca);
  141. }
  142. public static (Nca patch, Nca control) GetGameUpdateData(VirtualFileSystem fileSystem, string titleId, int programIndex, out string updatePath)
  143. {
  144. updatePath = null;
  145. if (ulong.TryParse(titleId, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong titleIdBase))
  146. {
  147. // Clear the program index part.
  148. titleIdBase &= 0xFFFFFFFFFFFFFFF0;
  149. // Load update informations if existing.
  150. string titleUpdateMetadataPath = Path.Combine(AppDataManager.GamesDirPath, titleIdBase.ToString("x16"), "updates.json");
  151. if (File.Exists(titleUpdateMetadataPath))
  152. {
  153. updatePath = JsonHelper.DeserializeFromFile<TitleUpdateMetadata>(titleUpdateMetadataPath).Selected;
  154. if (File.Exists(updatePath))
  155. {
  156. FileStream file = new FileStream(updatePath, FileMode.Open, FileAccess.Read);
  157. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  158. return GetGameUpdateDataFromPartition(fileSystem, nsp, titleIdBase.ToString("x16"), programIndex);
  159. }
  160. }
  161. }
  162. return (null, null);
  163. }
  164. public void LoadXci(string xciFile)
  165. {
  166. FileStream file = new FileStream(xciFile, FileMode.Open, FileAccess.Read);
  167. Xci xci = new Xci(_device.Configuration.VirtualFileSystem.KeySet, file.AsStorage());
  168. if (!xci.HasPartition(XciPartitionType.Secure))
  169. {
  170. Logger.Error?.Print(LogClass.Loader, "Unable to load XCI: Could not find XCI secure partition");
  171. return;
  172. }
  173. PartitionFileSystem securePartition = xci.OpenPartition(XciPartitionType.Secure);
  174. Nca mainNca;
  175. Nca patchNca;
  176. Nca controlNca;
  177. try
  178. {
  179. (mainNca, patchNca, controlNca) = GetGameData(_device.Configuration.VirtualFileSystem, securePartition, _device.Configuration.UserChannelPersistence.Index);
  180. RegisterProgramMapInfo(securePartition).ThrowIfFailure();
  181. }
  182. catch (Exception e)
  183. {
  184. Logger.Error?.Print(LogClass.Loader, $"Unable to load XCI: {e.Message}");
  185. return;
  186. }
  187. if (mainNca == null)
  188. {
  189. Logger.Error?.Print(LogClass.Loader, "Unable to load XCI: Could not find Main NCA");
  190. return;
  191. }
  192. _device.Configuration.ContentManager.LoadEntries(_device);
  193. _device.Configuration.ContentManager.ClearAocData();
  194. _device.Configuration.ContentManager.AddAocData(securePartition, xciFile, mainNca.Header.TitleId, _device.Configuration.FsIntegrityCheckLevel);
  195. LoadNca(mainNca, patchNca, controlNca);
  196. }
  197. public void LoadNsp(string nspFile)
  198. {
  199. FileStream file = new FileStream(nspFile, FileMode.Open, FileAccess.Read);
  200. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  201. Nca mainNca;
  202. Nca patchNca;
  203. Nca controlNca;
  204. try
  205. {
  206. (mainNca, patchNca, controlNca) = GetGameData(_device.Configuration.VirtualFileSystem, nsp, _device.Configuration.UserChannelPersistence.Index);
  207. RegisterProgramMapInfo(nsp).ThrowIfFailure();
  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. _device.Configuration.ContentManager.ClearAocData();
  222. _device.Configuration.ContentManager.AddAocData(nsp, nspFile, mainNca.Header.TitleId, _device.Configuration.FsIntegrityCheckLevel);
  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(_device.Configuration.VirtualFileSystem.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(_device.Configuration.VirtualFileSystem, mainNca.Header.TitleId.ToString("x16"), _device.Configuration.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(_device.Configuration.VirtualFileSystem, 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. _device.Configuration.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. MetaLoader metaData = ReadNpdm(codeFs);
  296. _device.Configuration.VirtualFileSystem.ModLoader.CollectMods(_device.Configuration.ContentManager.GetAocTitleIds().Prepend(TitleId), _device.Configuration.VirtualFileSystem.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.Configuration.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 = _device.Configuration.VirtualFileSystem.ModLoader.ApplyRomFsMods(TitleId, dataStorage);
  320. _device.Configuration.VirtualFileSystem.SetRomFs(newStorage.AsStream(FileAccess.Read));
  321. }
  322. // Don't create save data for system programs.
  323. if (TitleId != 0 && (TitleId < SystemProgramId.Start.Value || TitleId > SystemAppletId.End.Value))
  324. {
  325. // Multi-program applications can technically use any program ID for the main program, but in practice they always use 0 in the low nibble.
  326. // We'll know if this changes in the future because stuff will get errors when trying to mount the correct save.
  327. EnsureSaveData(new ApplicationId(TitleId & ~0xFul));
  328. }
  329. LoadExeFs(codeFs, metaData);
  330. Logger.Info?.Print(LogClass.Loader, $"Application Loaded: {TitleName} v{DisplayVersion} [{TitleIdText}] [{(TitleIs64Bit ? "64-bit" : "32-bit")}]");
  331. }
  332. // Sets TitleId, so be sure to call before using it
  333. private MetaLoader ReadNpdm(IFileSystem fs)
  334. {
  335. Result result = fs.OpenFile(out IFile npdmFile, "/main.npdm".ToU8Span(), OpenMode.Read);
  336. MetaLoader metaData;
  337. if (ResultFs.PathNotFound.Includes(result))
  338. {
  339. Logger.Warning?.Print(LogClass.Loader, "NPDM file not found, using default values!");
  340. metaData = GetDefaultNpdm();
  341. }
  342. else
  343. {
  344. npdmFile.GetSize(out long fileSize).ThrowIfFailure();
  345. var npdmBuffer = new byte[fileSize];
  346. npdmFile.Read(out _, 0, npdmBuffer).ThrowIfFailure();
  347. metaData = new MetaLoader();
  348. metaData.Load(npdmBuffer).ThrowIfFailure();
  349. }
  350. metaData.GetNpdm(out var npdm).ThrowIfFailure();
  351. TitleId = npdm.Aci.Value.ProgramId.Value;
  352. TitleIs64Bit = (npdm.Meta.Value.Flags & 1) != 0;
  353. _device.System.LibHacHorizonManager.ArpIReader.ApplicationId = new LibHac.ApplicationId(TitleId);
  354. return metaData;
  355. }
  356. private static void ReadControlData(Switch device, Nca controlNca, ref BlitStruct<ApplicationControlProperty> controlData, ref string titleName, ref string displayVersion)
  357. {
  358. IFileSystem controlFs = controlNca.OpenFileSystem(NcaSectionType.Data, device.System.FsIntegrityCheckLevel);
  359. Result result = controlFs.OpenFile(out IFile controlFile, "/control.nacp".ToU8Span(), OpenMode.Read);
  360. if (result.IsSuccess())
  361. {
  362. result = controlFile.Read(out long bytesRead, 0, controlData.ByteSpan, ReadOption.None);
  363. if (result.IsSuccess() && bytesRead == controlData.ByteSpan.Length)
  364. {
  365. titleName = controlData.Value.Titles[(int)device.System.State.DesiredTitleLanguage].Name.ToString();
  366. if (string.IsNullOrWhiteSpace(titleName))
  367. {
  368. titleName = controlData.Value.Titles.ToArray().FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  369. }
  370. displayVersion = controlData.Value.DisplayVersion.ToString();
  371. }
  372. }
  373. else
  374. {
  375. controlData.ByteSpan.Clear();
  376. }
  377. }
  378. private void LoadExeFs(IFileSystem codeFs, MetaLoader metaData = null)
  379. {
  380. if (_device.Configuration.VirtualFileSystem.ModLoader.ReplaceExefsPartition(TitleId, ref codeFs))
  381. {
  382. metaData = null; //TODO: Check if we should retain old npdm
  383. }
  384. metaData ??= ReadNpdm(codeFs);
  385. NsoExecutable[] nsos = new NsoExecutable[ExeFsPrefixes.Length];
  386. for (int i = 0; i < nsos.Length; i++)
  387. {
  388. string name = ExeFsPrefixes[i];
  389. if (!codeFs.FileExists($"/{name}"))
  390. {
  391. continue; // file doesn't exist, skip
  392. }
  393. Logger.Info?.Print(LogClass.Loader, $"Loading {name}...");
  394. codeFs.OpenFile(out IFile nsoFile, $"/{name}".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  395. nsos[i] = new NsoExecutable(nsoFile.AsStorage(), name);
  396. }
  397. // ExeFs file replacements
  398. ModLoadResult modLoadResult = _device.Configuration.VirtualFileSystem.ModLoader.ApplyExefsMods(TitleId, nsos);
  399. // collect the nsos, ignoring ones that aren't used
  400. NsoExecutable[] programs = nsos.Where(x => x != null).ToArray();
  401. // take the npdm from mods if present
  402. if (modLoadResult.Npdm != null)
  403. {
  404. metaData = modLoadResult.Npdm;
  405. }
  406. _device.Configuration.VirtualFileSystem.ModLoader.ApplyNsoPatches(TitleId, programs);
  407. _device.Configuration.ContentManager.LoadEntries(_device);
  408. bool usePtc = _device.System.EnablePtc;
  409. // Don't use PPTC if ExeFs files have been replaced.
  410. usePtc &= !modLoadResult.Modified;
  411. if (_device.System.EnablePtc && !usePtc)
  412. {
  413. Logger.Warning?.Print(LogClass.Ptc, $"Detected unsupported ExeFs modifications. PPTC disabled.");
  414. }
  415. Graphics.Gpu.GraphicsConfig.TitleId = TitleIdText;
  416. _device.Gpu.HostInitalized.Set();
  417. Ptc.Initialize(TitleIdText, DisplayVersion, usePtc, _device.Configuration.MemoryManagerMode);
  418. metaData.GetNpdm(out Npdm npdm).ThrowIfFailure();
  419. ProgramLoader.LoadNsos(_device.System.KernelContext, out ProcessTamperInfo tamperInfo, metaData, new ProgramInfo(in npdm), executables: programs);
  420. _device.Configuration.VirtualFileSystem.ModLoader.LoadCheats(TitleId, tamperInfo, _device.TamperMachine);
  421. }
  422. public void LoadProgram(string filePath)
  423. {
  424. MetaLoader metaData = GetDefaultNpdm();
  425. metaData.GetNpdm(out Npdm npdm).ThrowIfFailure();
  426. ProgramInfo programInfo = new ProgramInfo(in npdm);
  427. bool isNro = Path.GetExtension(filePath).ToLower() == ".nro";
  428. IExecutable executable;
  429. if (isNro)
  430. {
  431. FileStream input = new FileStream(filePath, FileMode.Open);
  432. NroExecutable obj = new NroExecutable(input.AsStorage());
  433. executable = obj;
  434. // homebrew NRO can actually have some data after the actual NRO
  435. if (input.Length > obj.FileSize)
  436. {
  437. input.Position = obj.FileSize;
  438. BinaryReader reader = new BinaryReader(input);
  439. uint asetMagic = reader.ReadUInt32();
  440. if (asetMagic == 0x54455341)
  441. {
  442. uint asetVersion = reader.ReadUInt32();
  443. if (asetVersion == 0)
  444. {
  445. ulong iconOffset = reader.ReadUInt64();
  446. ulong iconSize = reader.ReadUInt64();
  447. ulong nacpOffset = reader.ReadUInt64();
  448. ulong nacpSize = reader.ReadUInt64();
  449. ulong romfsOffset = reader.ReadUInt64();
  450. ulong romfsSize = reader.ReadUInt64();
  451. if (romfsSize != 0)
  452. {
  453. _device.Configuration.VirtualFileSystem.SetRomFs(new HomebrewRomFsStream(input, obj.FileSize + (long)romfsOffset));
  454. }
  455. if (nacpSize != 0)
  456. {
  457. input.Seek(obj.FileSize + (long)nacpOffset, SeekOrigin.Begin);
  458. reader.Read(ControlData.ByteSpan);
  459. ref ApplicationControlProperty nacp = ref ControlData.Value;
  460. programInfo.Name = nacp.Titles[(int)_device.System.State.DesiredTitleLanguage].Name.ToString();
  461. if (string.IsNullOrWhiteSpace(programInfo.Name))
  462. {
  463. programInfo.Name = nacp.Titles.ToArray().FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  464. }
  465. if (nacp.PresenceGroupId != 0)
  466. {
  467. programInfo.ProgramId = nacp.PresenceGroupId;
  468. }
  469. else if (nacp.SaveDataOwnerId.Value != 0)
  470. {
  471. programInfo.ProgramId = nacp.SaveDataOwnerId.Value;
  472. }
  473. else if (nacp.AddOnContentBaseId != 0)
  474. {
  475. programInfo.ProgramId = nacp.AddOnContentBaseId - 0x1000;
  476. }
  477. else
  478. {
  479. programInfo.ProgramId = 0000000000000000;
  480. }
  481. }
  482. }
  483. else
  484. {
  485. Logger.Warning?.Print(LogClass.Loader, $"Unsupported ASET header version found \"{asetVersion}\"");
  486. }
  487. }
  488. }
  489. }
  490. else
  491. {
  492. executable = new NsoExecutable(new LocalStorage(filePath, FileAccess.Read), Path.GetFileNameWithoutExtension(filePath));
  493. }
  494. _device.Configuration.ContentManager.LoadEntries(_device);
  495. _titleName = programInfo.Name;
  496. TitleId = programInfo.ProgramId;
  497. TitleIs64Bit = (npdm.Meta.Value.Flags & 1) != 0;
  498. _device.System.LibHacHorizonManager.ArpIReader.ApplicationId = new LibHac.ApplicationId(TitleId);
  499. // Explicitly null titleid to disable the shader cache
  500. Graphics.Gpu.GraphicsConfig.TitleId = null;
  501. _device.Gpu.HostInitalized.Set();
  502. ProgramLoader.LoadNsos(_device.System.KernelContext, out ProcessTamperInfo tamperInfo, metaData, programInfo, executables: executable);
  503. _device.Configuration.VirtualFileSystem.ModLoader.LoadCheats(TitleId, tamperInfo, _device.TamperMachine);
  504. }
  505. private MetaLoader GetDefaultNpdm()
  506. {
  507. Assembly asm = Assembly.GetCallingAssembly();
  508. using (Stream npdmStream = asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm"))
  509. {
  510. var npdmBuffer = new byte[npdmStream.Length];
  511. npdmStream.Read(npdmBuffer);
  512. var metaLoader = new MetaLoader();
  513. metaLoader.Load(npdmBuffer).ThrowIfFailure();
  514. return metaLoader;
  515. }
  516. }
  517. private static (ulong applicationId, int programCount) GetMultiProgramInfo(VirtualFileSystem fileSystem, PartitionFileSystem pfs)
  518. {
  519. ulong mainProgramId = 0;
  520. Span<bool> hasIndex = stackalloc bool[0x10];
  521. fileSystem.ImportTickets(pfs);
  522. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  523. {
  524. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  525. Nca nca = new Nca(fileSystem.KeySet, ncaFile.AsStorage());
  526. if (nca.Header.ContentType != NcaContentType.Program)
  527. {
  528. continue;
  529. }
  530. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  531. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  532. {
  533. continue;
  534. }
  535. ulong currentProgramId = nca.Header.TitleId;
  536. ulong currentMainProgramId = currentProgramId & ~0xFFFul;
  537. if (mainProgramId == 0 && currentMainProgramId != 0)
  538. {
  539. mainProgramId = currentMainProgramId;
  540. }
  541. if (mainProgramId != currentMainProgramId)
  542. {
  543. // As far as I know there aren't any multi-application game cards containing multi-program applications,
  544. // so because multi-application game cards are the only way we should run into multiple applications
  545. // we'll just return that there's a single program.
  546. return (mainProgramId, 1);
  547. }
  548. hasIndex[(int)(currentProgramId & 0xF)] = true;
  549. }
  550. int programCount = 0;
  551. for (int i = 0; i < hasIndex.Length && hasIndex[i]; i++)
  552. {
  553. programCount++;
  554. }
  555. return (mainProgramId, programCount);
  556. }
  557. private Result RegisterProgramMapInfo(PartitionFileSystem pfs)
  558. {
  559. (ulong applicationId, int programCount) = GetMultiProgramInfo(_device.Configuration.VirtualFileSystem, pfs);
  560. if (programCount <= 0)
  561. return Result.Success;
  562. Span<ProgramIndexMapInfo> mapInfo = stackalloc ProgramIndexMapInfo[0x10];
  563. for (int i = 0; i < programCount; i++)
  564. {
  565. mapInfo[i].ProgramId = new ProgramId(applicationId + (uint)i);
  566. mapInfo[i].MainProgramId = new ProgramId(applicationId);
  567. mapInfo[i].ProgramIndex = (byte)i;
  568. }
  569. return _device.System.LibHacHorizonManager.NsClient.Fs.RegisterProgramIndexMapInfo(mapInfo.Slice(0, programCount));
  570. }
  571. private Result EnsureSaveData(ApplicationId applicationId)
  572. {
  573. Logger.Info?.Print(LogClass.Application, "Ensuring required savedata exists.");
  574. Uid user = _device.System.AccountManager.LastOpenedUser.UserId.ToLibHacUid();
  575. ref ApplicationControlProperty control = ref ControlData.Value;
  576. if (LibHac.Utilities.IsZeros(ControlData.ByteSpan))
  577. {
  578. // If the current application doesn't have a loaded control property, create a dummy one
  579. // and set the savedata sizes so a user savedata will be created.
  580. control = ref new BlitStruct<ApplicationControlProperty>(1).Value;
  581. // The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
  582. control.UserAccountSaveDataSize = 0x4000;
  583. control.UserAccountSaveDataJournalSize = 0x4000;
  584. Logger.Warning?.Print(LogClass.Application,
  585. "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games.");
  586. }
  587. HorizonClient hos = _device.System.LibHacHorizonManager.RyujinxClient;
  588. Result resultCode = hos.Fs.EnsureApplicationCacheStorage(out _, out _, applicationId, ref control);
  589. if (resultCode.IsFailure())
  590. {
  591. Logger.Error?.Print(LogClass.Application, $"Error calling EnsureApplicationCacheStorage. Result code {resultCode.ToStringWithName()}");
  592. return resultCode;
  593. }
  594. resultCode = EnsureApplicationSaveData(hos.Fs, out _, applicationId, ref control, ref user);
  595. if (resultCode.IsFailure())
  596. {
  597. Logger.Error?.Print(LogClass.Application, $"Error calling EnsureApplicationSaveData. Result code {resultCode.ToStringWithName()}");
  598. }
  599. return resultCode;
  600. }
  601. }
  602. }