ApplicationLoader.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  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. if (File.Exists(dlcContainer.Path))
  265. {
  266. _device.Configuration.ContentManager.AddAocItem(dlcNca.TitleId, dlcContainer.Path, dlcNca.Path, dlcNca.Enabled);
  267. }
  268. else
  269. {
  270. Logger.Warning?.Print(LogClass.Application, $"Cannot find AddOnContent file {dlcContainer.Path}. It may have been moved or renamed.");
  271. }
  272. }
  273. }
  274. }
  275. if (patchNca == null)
  276. {
  277. if (mainNca.CanOpenSection(NcaSectionType.Data))
  278. {
  279. dataStorage = mainNca.OpenStorage(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);
  280. }
  281. if (mainNca.CanOpenSection(NcaSectionType.Code))
  282. {
  283. codeFs = mainNca.OpenFileSystem(NcaSectionType.Code, _device.System.FsIntegrityCheckLevel);
  284. }
  285. }
  286. else
  287. {
  288. if (patchNca.CanOpenSection(NcaSectionType.Data))
  289. {
  290. dataStorage = mainNca.OpenStorageWithPatch(patchNca, NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);
  291. }
  292. if (patchNca.CanOpenSection(NcaSectionType.Code))
  293. {
  294. codeFs = mainNca.OpenFileSystemWithPatch(patchNca, NcaSectionType.Code, _device.System.FsIntegrityCheckLevel);
  295. }
  296. }
  297. if (codeFs == null)
  298. {
  299. Logger.Error?.Print(LogClass.Loader, "No ExeFS found in NCA");
  300. return;
  301. }
  302. MetaLoader metaData = ReadNpdm(codeFs);
  303. _device.Configuration.VirtualFileSystem.ModLoader.CollectMods(_device.Configuration.ContentManager.GetAocTitleIds().Prepend(TitleId), _device.Configuration.VirtualFileSystem.ModLoader.GetModsBasePath());
  304. if (controlNca != null)
  305. {
  306. ReadControlData(_device, controlNca, ref _controlData, ref _titleName, ref _displayVersion);
  307. }
  308. else
  309. {
  310. ControlData.ByteSpan.Clear();
  311. }
  312. // NOTE: Nintendo doesn't guarantee that the display version will be updated on sub programs when updating a multi program application.
  313. // BODY: As such, to avoid PTC cache confusion, we only trust the the program 0 display version when launching a sub program.
  314. if (updateProgram0ControlNca != null && _device.Configuration.UserChannelPersistence.Index != 0)
  315. {
  316. string dummyTitleName = "";
  317. BlitStruct<ApplicationControlProperty> dummyControl = new BlitStruct<ApplicationControlProperty>(1);
  318. ReadControlData(_device, updateProgram0ControlNca, ref dummyControl, ref dummyTitleName, ref _displayVersion);
  319. }
  320. if (dataStorage == null)
  321. {
  322. Logger.Warning?.Print(LogClass.Loader, "No RomFS found in NCA");
  323. }
  324. else
  325. {
  326. IStorage newStorage = _device.Configuration.VirtualFileSystem.ModLoader.ApplyRomFsMods(TitleId, dataStorage);
  327. _device.Configuration.VirtualFileSystem.SetRomFs(newStorage.AsStream(FileAccess.Read));
  328. }
  329. // Don't create save data for system programs.
  330. if (TitleId != 0 && (TitleId < SystemProgramId.Start.Value || TitleId > SystemAppletId.End.Value))
  331. {
  332. // Multi-program applications can technically use any program ID for the main program, but in practice they always use 0 in the low nibble.
  333. // We'll know if this changes in the future because stuff will get errors when trying to mount the correct save.
  334. EnsureSaveData(new ApplicationId(TitleId & ~0xFul));
  335. }
  336. LoadExeFs(codeFs, metaData);
  337. Logger.Info?.Print(LogClass.Loader, $"Application Loaded: {TitleName} v{DisplayVersion} [{TitleIdText}] [{(TitleIs64Bit ? "64-bit" : "32-bit")}]");
  338. }
  339. // Sets TitleId, so be sure to call before using it
  340. private MetaLoader ReadNpdm(IFileSystem fs)
  341. {
  342. Result result = fs.OpenFile(out IFile npdmFile, "/main.npdm".ToU8Span(), OpenMode.Read);
  343. MetaLoader metaData;
  344. if (ResultFs.PathNotFound.Includes(result))
  345. {
  346. Logger.Warning?.Print(LogClass.Loader, "NPDM file not found, using default values!");
  347. metaData = GetDefaultNpdm();
  348. }
  349. else
  350. {
  351. npdmFile.GetSize(out long fileSize).ThrowIfFailure();
  352. var npdmBuffer = new byte[fileSize];
  353. npdmFile.Read(out _, 0, npdmBuffer).ThrowIfFailure();
  354. metaData = new MetaLoader();
  355. metaData.Load(npdmBuffer).ThrowIfFailure();
  356. }
  357. metaData.GetNpdm(out var npdm).ThrowIfFailure();
  358. TitleId = npdm.Aci.Value.ProgramId.Value;
  359. TitleIs64Bit = (npdm.Meta.Value.Flags & 1) != 0;
  360. _device.System.LibHacHorizonManager.ArpIReader.ApplicationId = new LibHac.ApplicationId(TitleId);
  361. return metaData;
  362. }
  363. private static void ReadControlData(Switch device, Nca controlNca, ref BlitStruct<ApplicationControlProperty> controlData, ref string titleName, ref string displayVersion)
  364. {
  365. IFileSystem controlFs = controlNca.OpenFileSystem(NcaSectionType.Data, device.System.FsIntegrityCheckLevel);
  366. Result result = controlFs.OpenFile(out IFile controlFile, "/control.nacp".ToU8Span(), OpenMode.Read);
  367. if (result.IsSuccess())
  368. {
  369. result = controlFile.Read(out long bytesRead, 0, controlData.ByteSpan, ReadOption.None);
  370. if (result.IsSuccess() && bytesRead == controlData.ByteSpan.Length)
  371. {
  372. titleName = controlData.Value.Titles[(int)device.System.State.DesiredTitleLanguage].Name.ToString();
  373. if (string.IsNullOrWhiteSpace(titleName))
  374. {
  375. titleName = controlData.Value.Titles.ToArray().FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  376. }
  377. displayVersion = controlData.Value.DisplayVersion.ToString();
  378. }
  379. }
  380. else
  381. {
  382. controlData.ByteSpan.Clear();
  383. }
  384. }
  385. private void LoadExeFs(IFileSystem codeFs, MetaLoader metaData = null)
  386. {
  387. if (_device.Configuration.VirtualFileSystem.ModLoader.ReplaceExefsPartition(TitleId, ref codeFs))
  388. {
  389. metaData = null; //TODO: Check if we should retain old npdm
  390. }
  391. metaData ??= ReadNpdm(codeFs);
  392. NsoExecutable[] nsos = new NsoExecutable[ExeFsPrefixes.Length];
  393. for (int i = 0; i < nsos.Length; i++)
  394. {
  395. string name = ExeFsPrefixes[i];
  396. if (!codeFs.FileExists($"/{name}"))
  397. {
  398. continue; // file doesn't exist, skip
  399. }
  400. Logger.Info?.Print(LogClass.Loader, $"Loading {name}...");
  401. codeFs.OpenFile(out IFile nsoFile, $"/{name}".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  402. nsos[i] = new NsoExecutable(nsoFile.AsStorage(), name);
  403. }
  404. // ExeFs file replacements
  405. ModLoadResult modLoadResult = _device.Configuration.VirtualFileSystem.ModLoader.ApplyExefsMods(TitleId, nsos);
  406. // collect the nsos, ignoring ones that aren't used
  407. NsoExecutable[] programs = nsos.Where(x => x != null).ToArray();
  408. // take the npdm from mods if present
  409. if (modLoadResult.Npdm != null)
  410. {
  411. metaData = modLoadResult.Npdm;
  412. }
  413. _device.Configuration.VirtualFileSystem.ModLoader.ApplyNsoPatches(TitleId, programs);
  414. _device.Configuration.ContentManager.LoadEntries(_device);
  415. bool usePtc = _device.System.EnablePtc;
  416. // Don't use PPTC if ExeFs files have been replaced.
  417. usePtc &= !modLoadResult.Modified;
  418. if (_device.System.EnablePtc && !usePtc)
  419. {
  420. Logger.Warning?.Print(LogClass.Ptc, $"Detected unsupported ExeFs modifications. PPTC disabled.");
  421. }
  422. Graphics.Gpu.GraphicsConfig.TitleId = TitleIdText;
  423. _device.Gpu.HostInitalized.Set();
  424. Ptc.Initialize(TitleIdText, DisplayVersion, usePtc, _device.Configuration.MemoryManagerMode);
  425. metaData.GetNpdm(out Npdm npdm).ThrowIfFailure();
  426. ProgramLoader.LoadNsos(_device.System.KernelContext, out ProcessTamperInfo tamperInfo, metaData, new ProgramInfo(in npdm), executables: programs);
  427. _device.Configuration.VirtualFileSystem.ModLoader.LoadCheats(TitleId, tamperInfo, _device.TamperMachine);
  428. }
  429. public void LoadProgram(string filePath)
  430. {
  431. MetaLoader metaData = GetDefaultNpdm();
  432. metaData.GetNpdm(out Npdm npdm).ThrowIfFailure();
  433. ProgramInfo programInfo = new ProgramInfo(in npdm);
  434. bool isNro = Path.GetExtension(filePath).ToLower() == ".nro";
  435. IExecutable executable;
  436. if (isNro)
  437. {
  438. FileStream input = new FileStream(filePath, FileMode.Open);
  439. NroExecutable obj = new NroExecutable(input.AsStorage());
  440. executable = obj;
  441. // homebrew NRO can actually have some data after the actual NRO
  442. if (input.Length > obj.FileSize)
  443. {
  444. input.Position = obj.FileSize;
  445. BinaryReader reader = new BinaryReader(input);
  446. uint asetMagic = reader.ReadUInt32();
  447. if (asetMagic == 0x54455341)
  448. {
  449. uint asetVersion = reader.ReadUInt32();
  450. if (asetVersion == 0)
  451. {
  452. ulong iconOffset = reader.ReadUInt64();
  453. ulong iconSize = reader.ReadUInt64();
  454. ulong nacpOffset = reader.ReadUInt64();
  455. ulong nacpSize = reader.ReadUInt64();
  456. ulong romfsOffset = reader.ReadUInt64();
  457. ulong romfsSize = reader.ReadUInt64();
  458. if (romfsSize != 0)
  459. {
  460. _device.Configuration.VirtualFileSystem.SetRomFs(new HomebrewRomFsStream(input, obj.FileSize + (long)romfsOffset));
  461. }
  462. if (nacpSize != 0)
  463. {
  464. input.Seek(obj.FileSize + (long)nacpOffset, SeekOrigin.Begin);
  465. reader.Read(ControlData.ByteSpan);
  466. ref ApplicationControlProperty nacp = ref ControlData.Value;
  467. programInfo.Name = nacp.Titles[(int)_device.System.State.DesiredTitleLanguage].Name.ToString();
  468. if (string.IsNullOrWhiteSpace(programInfo.Name))
  469. {
  470. programInfo.Name = nacp.Titles.ToArray().FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  471. }
  472. if (nacp.PresenceGroupId != 0)
  473. {
  474. programInfo.ProgramId = nacp.PresenceGroupId;
  475. }
  476. else if (nacp.SaveDataOwnerId.Value != 0)
  477. {
  478. programInfo.ProgramId = nacp.SaveDataOwnerId.Value;
  479. }
  480. else if (nacp.AddOnContentBaseId != 0)
  481. {
  482. programInfo.ProgramId = nacp.AddOnContentBaseId - 0x1000;
  483. }
  484. else
  485. {
  486. programInfo.ProgramId = 0000000000000000;
  487. }
  488. }
  489. }
  490. else
  491. {
  492. Logger.Warning?.Print(LogClass.Loader, $"Unsupported ASET header version found \"{asetVersion}\"");
  493. }
  494. }
  495. }
  496. }
  497. else
  498. {
  499. executable = new NsoExecutable(new LocalStorage(filePath, FileAccess.Read), Path.GetFileNameWithoutExtension(filePath));
  500. }
  501. _device.Configuration.ContentManager.LoadEntries(_device);
  502. _titleName = programInfo.Name;
  503. TitleId = programInfo.ProgramId;
  504. TitleIs64Bit = (npdm.Meta.Value.Flags & 1) != 0;
  505. _device.System.LibHacHorizonManager.ArpIReader.ApplicationId = new LibHac.ApplicationId(TitleId);
  506. // Explicitly null titleid to disable the shader cache
  507. Graphics.Gpu.GraphicsConfig.TitleId = null;
  508. _device.Gpu.HostInitalized.Set();
  509. ProgramLoader.LoadNsos(_device.System.KernelContext, out ProcessTamperInfo tamperInfo, metaData, programInfo, executables: executable);
  510. _device.Configuration.VirtualFileSystem.ModLoader.LoadCheats(TitleId, tamperInfo, _device.TamperMachine);
  511. }
  512. private MetaLoader GetDefaultNpdm()
  513. {
  514. Assembly asm = Assembly.GetCallingAssembly();
  515. using (Stream npdmStream = asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm"))
  516. {
  517. var npdmBuffer = new byte[npdmStream.Length];
  518. npdmStream.Read(npdmBuffer);
  519. var metaLoader = new MetaLoader();
  520. metaLoader.Load(npdmBuffer).ThrowIfFailure();
  521. return metaLoader;
  522. }
  523. }
  524. private static (ulong applicationId, int programCount) GetMultiProgramInfo(VirtualFileSystem fileSystem, PartitionFileSystem pfs)
  525. {
  526. ulong mainProgramId = 0;
  527. Span<bool> hasIndex = stackalloc bool[0x10];
  528. fileSystem.ImportTickets(pfs);
  529. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  530. {
  531. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  532. Nca nca = new Nca(fileSystem.KeySet, ncaFile.AsStorage());
  533. if (nca.Header.ContentType != NcaContentType.Program)
  534. {
  535. continue;
  536. }
  537. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  538. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  539. {
  540. continue;
  541. }
  542. ulong currentProgramId = nca.Header.TitleId;
  543. ulong currentMainProgramId = currentProgramId & ~0xFFFul;
  544. if (mainProgramId == 0 && currentMainProgramId != 0)
  545. {
  546. mainProgramId = currentMainProgramId;
  547. }
  548. if (mainProgramId != currentMainProgramId)
  549. {
  550. // As far as I know there aren't any multi-application game cards containing multi-program applications,
  551. // so because multi-application game cards are the only way we should run into multiple applications
  552. // we'll just return that there's a single program.
  553. return (mainProgramId, 1);
  554. }
  555. hasIndex[(int)(currentProgramId & 0xF)] = true;
  556. }
  557. int programCount = 0;
  558. for (int i = 0; i < hasIndex.Length && hasIndex[i]; i++)
  559. {
  560. programCount++;
  561. }
  562. return (mainProgramId, programCount);
  563. }
  564. private Result RegisterProgramMapInfo(PartitionFileSystem pfs)
  565. {
  566. (ulong applicationId, int programCount) = GetMultiProgramInfo(_device.Configuration.VirtualFileSystem, pfs);
  567. if (programCount <= 0)
  568. return Result.Success;
  569. Span<ProgramIndexMapInfo> mapInfo = stackalloc ProgramIndexMapInfo[0x10];
  570. for (int i = 0; i < programCount; i++)
  571. {
  572. mapInfo[i].ProgramId = new ProgramId(applicationId + (uint)i);
  573. mapInfo[i].MainProgramId = new ProgramId(applicationId);
  574. mapInfo[i].ProgramIndex = (byte)i;
  575. }
  576. return _device.System.LibHacHorizonManager.NsClient.Fs.RegisterProgramIndexMapInfo(mapInfo.Slice(0, programCount));
  577. }
  578. private Result EnsureSaveData(ApplicationId applicationId)
  579. {
  580. Logger.Info?.Print(LogClass.Application, "Ensuring required savedata exists.");
  581. Uid user = _device.System.AccountManager.LastOpenedUser.UserId.ToLibHacUid();
  582. ref ApplicationControlProperty control = ref ControlData.Value;
  583. if (LibHac.Utilities.IsZeros(ControlData.ByteSpan))
  584. {
  585. // If the current application doesn't have a loaded control property, create a dummy one
  586. // and set the savedata sizes so a user savedata will be created.
  587. control = ref new BlitStruct<ApplicationControlProperty>(1).Value;
  588. // The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
  589. control.UserAccountSaveDataSize = 0x4000;
  590. control.UserAccountSaveDataJournalSize = 0x4000;
  591. Logger.Warning?.Print(LogClass.Application,
  592. "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games.");
  593. }
  594. HorizonClient hos = _device.System.LibHacHorizonManager.RyujinxClient;
  595. Result resultCode = hos.Fs.EnsureApplicationCacheStorage(out _, out _, applicationId, ref control);
  596. if (resultCode.IsFailure())
  597. {
  598. Logger.Error?.Print(LogClass.Application, $"Error calling EnsureApplicationCacheStorage. Result code {resultCode.ToStringWithName()}");
  599. return resultCode;
  600. }
  601. resultCode = EnsureApplicationSaveData(hos.Fs, out _, applicationId, ref control, ref user);
  602. if (resultCode.IsFailure())
  603. {
  604. Logger.Error?.Print(LogClass.Application, $"Error calling EnsureApplicationSaveData. Result code {resultCode.ToStringWithName()}");
  605. }
  606. return resultCode;
  607. }
  608. }
  609. }