ApplicationLoader.cs 31 KB

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