ApplicationLoader.cs 31 KB

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