ApplicationLoader.cs 31 KB

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