ApplicationLoader.cs 31 KB

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