ApplicationLoader.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. using LibHac;
  2. using LibHac.Account;
  3. using LibHac.Common;
  4. using LibHac.Fs;
  5. using LibHac.Fs.Fsa;
  6. using LibHac.Fs.Shim;
  7. using LibHac.FsSystem;
  8. using LibHac.Loader;
  9. using LibHac.Ncm;
  10. using LibHac.Ns;
  11. using LibHac.Tools.Fs;
  12. using LibHac.Tools.FsSystem;
  13. using LibHac.Tools.FsSystem.NcaUtils;
  14. using Ryujinx.Common.Configuration;
  15. using Ryujinx.Common.Logging;
  16. using Ryujinx.Cpu;
  17. using Ryujinx.HLE.FileSystem;
  18. using Ryujinx.HLE.Loaders.Executables;
  19. using Ryujinx.Memory;
  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 System.Text;
  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 IDiskCacheLoadState DiskCacheLoadState { get; private set; }
  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. LocalFileSystem codeFs = new LocalFileSystem(exeFsDir);
  71. MetaLoader metaData = ReadNpdm(codeFs);
  72. _device.Configuration.VirtualFileSystem.ModLoader.CollectMods(
  73. new[] { TitleId },
  74. _device.Configuration.VirtualFileSystem.ModLoader.GetModsBasePath(),
  75. _device.Configuration.VirtualFileSystem.ModLoader.GetSdModsBasePath());
  76. if (TitleId != 0)
  77. {
  78. EnsureSaveData(new ApplicationId(TitleId));
  79. }
  80. ulong pid = LoadExeFs(codeFs, string.Empty, metaData);
  81. if (romFsFile != null)
  82. {
  83. _device.Configuration.VirtualFileSystem.LoadRomFs(pid, romFsFile);
  84. }
  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. _device.Configuration.ContentManager.ClearAocData();
  226. _device.Configuration.ContentManager.AddAocData(nsp, nspFile, mainNca.Header.TitleId, _device.Configuration.FsIntegrityCheckLevel);
  227. LoadNca(mainNca, patchNca, controlNca);
  228. return;
  229. }
  230. // This is not a normal NSP, it's actually a ExeFS as a NSP
  231. LoadExeFs(nsp, null, isHomebrew: true);
  232. }
  233. public void LoadNca(string ncaFile)
  234. {
  235. FileStream file = new FileStream(ncaFile, FileMode.Open, FileAccess.Read);
  236. Nca nca = new Nca(_device.Configuration.VirtualFileSystem.KeySet, file.AsStorage(false));
  237. LoadNca(nca, null, null);
  238. }
  239. public void LoadServiceNca(string ncaFile)
  240. {
  241. FileStream file = new FileStream(ncaFile, FileMode.Open, FileAccess.Read);
  242. Nca mainNca = new Nca(_device.Configuration.VirtualFileSystem.KeySet, file.AsStorage(false));
  243. if (mainNca.Header.ContentType != NcaContentType.Program)
  244. {
  245. Logger.Error?.Print(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");
  246. return;
  247. }
  248. IFileSystem codeFs = null;
  249. if (mainNca.CanOpenSection(NcaSectionType.Code))
  250. {
  251. codeFs = mainNca.OpenFileSystem(NcaSectionType.Code, _device.System.FsIntegrityCheckLevel);
  252. }
  253. if (codeFs == null)
  254. {
  255. Logger.Error?.Print(LogClass.Loader, "No ExeFS found in NCA");
  256. return;
  257. }
  258. using var npdmFile = new UniqueRef<IFile>();
  259. Result result = codeFs.OpenFile(ref npdmFile.Ref, "/main.npdm".ToU8Span(), OpenMode.Read);
  260. MetaLoader metaData;
  261. npdmFile.Get.GetSize(out long fileSize).ThrowIfFailure();
  262. var npdmBuffer = new byte[fileSize];
  263. npdmFile.Get.Read(out _, 0, npdmBuffer).ThrowIfFailure();
  264. metaData = new MetaLoader();
  265. metaData.Load(npdmBuffer).ThrowIfFailure();
  266. NsoExecutable[] nsos = new NsoExecutable[ExeFsPrefixes.Length];
  267. for (int i = 0; i < nsos.Length; i++)
  268. {
  269. string name = ExeFsPrefixes[i];
  270. if (!codeFs.FileExists($"/{name}"))
  271. {
  272. continue; // File doesn't exist, skip.
  273. }
  274. Logger.Info?.Print(LogClass.Loader, $"Loading {name}...");
  275. using var nsoFile = new UniqueRef<IFile>();
  276. codeFs.OpenFile(ref nsoFile.Ref, $"/{name}".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  277. nsos[i] = new NsoExecutable(nsoFile.Release().AsStorage(), name);
  278. }
  279. // Collect the nsos, ignoring ones that aren't used.
  280. NsoExecutable[] programs = nsos.Where(x => x != null).ToArray();
  281. string displayVersion = _device.System.ContentManager.GetCurrentFirmwareVersion().VersionString;
  282. bool usePtc = _device.System.EnablePtc;
  283. metaData.GetNpdm(out Npdm npdm).ThrowIfFailure();
  284. ProgramInfo programInfo = new ProgramInfo(in npdm, displayVersion, usePtc, allowCodeMemoryForJit: false);
  285. ProgramLoader.LoadNsos(_device.System.KernelContext, metaData, programInfo, executables: programs);
  286. string titleIdText = npdm.Aci.ProgramId.Value.ToString("x16");
  287. bool titleIs64Bit = (npdm.Meta.Flags & 1) != 0;
  288. string programName = Encoding.ASCII.GetString(npdm.Meta.ProgramName).TrimEnd('\0');
  289. Logger.Info?.Print(LogClass.Loader, $"Service Loaded: {programName} [{titleIdText}] [{(titleIs64Bit ? "64-bit" : "32-bit")}]");
  290. }
  291. private void LoadNca(Nca mainNca, Nca patchNca, Nca controlNca)
  292. {
  293. if (mainNca.Header.ContentType != NcaContentType.Program)
  294. {
  295. Logger.Error?.Print(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");
  296. return;
  297. }
  298. IStorage dataStorage = null;
  299. IFileSystem codeFs = null;
  300. (Nca updatePatchNca, Nca updateControlNca) = GetGameUpdateData(_device.Configuration.VirtualFileSystem, mainNca.Header.TitleId.ToString("x16"), _device.Configuration.UserChannelPersistence.Index, out _);
  301. if (updatePatchNca != null)
  302. {
  303. patchNca = updatePatchNca;
  304. }
  305. if (updateControlNca != null)
  306. {
  307. controlNca = updateControlNca;
  308. }
  309. // Load program 0 control NCA as we are going to need it for display version.
  310. (_, Nca updateProgram0ControlNca) = GetGameUpdateData(_device.Configuration.VirtualFileSystem, mainNca.Header.TitleId.ToString("x16"), 0, out _);
  311. // Load Aoc
  312. string titleAocMetadataPath = Path.Combine(AppDataManager.GamesDirPath, mainNca.Header.TitleId.ToString("x16"), "dlc.json");
  313. if (File.Exists(titleAocMetadataPath))
  314. {
  315. List<DownloadableContentContainer> dlcContainerList = JsonHelper.DeserializeFromFile<List<DownloadableContentContainer>>(titleAocMetadataPath);
  316. foreach (DownloadableContentContainer downloadableContentContainer in dlcContainerList)
  317. {
  318. foreach (DownloadableContentNca downloadableContentNca in downloadableContentContainer.DownloadableContentNcaList)
  319. {
  320. if (File.Exists(downloadableContentContainer.ContainerPath) && downloadableContentNca.Enabled)
  321. {
  322. _device.Configuration.ContentManager.AddAocItem(downloadableContentNca.TitleId, downloadableContentContainer.ContainerPath, downloadableContentNca.FullPath);
  323. }
  324. else
  325. {
  326. Logger.Warning?.Print(LogClass.Application, $"Cannot find AddOnContent file {downloadableContentContainer.ContainerPath}. It may have been moved or renamed.");
  327. }
  328. }
  329. }
  330. }
  331. if (patchNca == null)
  332. {
  333. if (mainNca.CanOpenSection(NcaSectionType.Data))
  334. {
  335. dataStorage = mainNca.OpenStorage(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);
  336. }
  337. if (mainNca.CanOpenSection(NcaSectionType.Code))
  338. {
  339. codeFs = mainNca.OpenFileSystem(NcaSectionType.Code, _device.System.FsIntegrityCheckLevel);
  340. }
  341. }
  342. else
  343. {
  344. if (patchNca.CanOpenSection(NcaSectionType.Data))
  345. {
  346. dataStorage = mainNca.OpenStorageWithPatch(patchNca, NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);
  347. }
  348. if (patchNca.CanOpenSection(NcaSectionType.Code))
  349. {
  350. codeFs = mainNca.OpenFileSystemWithPatch(patchNca, NcaSectionType.Code, _device.System.FsIntegrityCheckLevel);
  351. }
  352. }
  353. if (codeFs == null)
  354. {
  355. Logger.Error?.Print(LogClass.Loader, "No ExeFS found in NCA");
  356. return;
  357. }
  358. MetaLoader metaData = ReadNpdm(codeFs);
  359. _device.Configuration.VirtualFileSystem.ModLoader.CollectMods(
  360. _device.Configuration.ContentManager.GetAocTitleIds().Prepend(TitleId),
  361. _device.Configuration.VirtualFileSystem.ModLoader.GetModsBasePath(),
  362. _device.Configuration.VirtualFileSystem.ModLoader.GetSdModsBasePath());
  363. string displayVersion = string.Empty;
  364. if (controlNca != null)
  365. {
  366. ReadControlData(_device, controlNca, ref _controlData, ref _titleName, ref displayVersion);
  367. }
  368. else
  369. {
  370. ControlData.ByteSpan.Clear();
  371. }
  372. // NOTE: Nintendo doesn't guarantee that the display version will be updated on sub programs when updating a multi program application.
  373. // BODY: As such, to avoid PTC cache confusion, we only trust the the program 0 display version when launching a sub program.
  374. if (updateProgram0ControlNca != null && _device.Configuration.UserChannelPersistence.Index != 0)
  375. {
  376. string dummyTitleName = "";
  377. BlitStruct<ApplicationControlProperty> dummyControl = new BlitStruct<ApplicationControlProperty>(1);
  378. ReadControlData(_device, updateProgram0ControlNca, ref dummyControl, ref dummyTitleName, ref displayVersion);
  379. }
  380. _displayVersion = displayVersion;
  381. ulong pid = LoadExeFs(codeFs, displayVersion, metaData);
  382. if (dataStorage == null)
  383. {
  384. Logger.Warning?.Print(LogClass.Loader, "No RomFS found in NCA");
  385. }
  386. else
  387. {
  388. IStorage newStorage = _device.Configuration.VirtualFileSystem.ModLoader.ApplyRomFsMods(TitleId, dataStorage);
  389. _device.Configuration.VirtualFileSystem.SetRomFs(pid, newStorage.AsStream(FileAccess.Read));
  390. }
  391. // Don't create save data for system programs.
  392. if (TitleId != 0 && (TitleId < SystemProgramId.Start.Value || TitleId > SystemAppletId.End.Value))
  393. {
  394. // Multi-program applications can technically use any program ID for the main program, but in practice they always use 0 in the low nibble.
  395. // We'll know if this changes in the future because stuff will get errors when trying to mount the correct save.
  396. EnsureSaveData(new ApplicationId(TitleId & ~0xFul));
  397. }
  398. Logger.Info?.Print(LogClass.Loader, $"Application Loaded: {TitleName} v{DisplayVersion} [{TitleIdText}] [{(TitleIs64Bit ? "64-bit" : "32-bit")}]");
  399. }
  400. // Sets TitleId, so be sure to call before using it
  401. private MetaLoader ReadNpdm(IFileSystem fs)
  402. {
  403. using var npdmFile = new UniqueRef<IFile>();
  404. Result result = fs.OpenFile(ref npdmFile.Ref, "/main.npdm".ToU8Span(), OpenMode.Read);
  405. MetaLoader metaData;
  406. if (ResultFs.PathNotFound.Includes(result))
  407. {
  408. Logger.Warning?.Print(LogClass.Loader, "NPDM file not found, using default values!");
  409. metaData = GetDefaultNpdm();
  410. }
  411. else
  412. {
  413. npdmFile.Get.GetSize(out long fileSize).ThrowIfFailure();
  414. var npdmBuffer = new byte[fileSize];
  415. npdmFile.Get.Read(out _, 0, npdmBuffer).ThrowIfFailure();
  416. metaData = new MetaLoader();
  417. metaData.Load(npdmBuffer).ThrowIfFailure();
  418. }
  419. metaData.GetNpdm(out var npdm).ThrowIfFailure();
  420. TitleId = npdm.Aci.ProgramId.Value;
  421. TitleIs64Bit = (npdm.Meta.Flags & 1) != 0;
  422. _device.System.LibHacHorizonManager.ArpIReader.ApplicationId = new LibHac.ApplicationId(TitleId);
  423. return metaData;
  424. }
  425. private static void ReadControlData(Switch device, Nca controlNca, ref BlitStruct<ApplicationControlProperty> controlData, ref string titleName, ref string displayVersion)
  426. {
  427. using var controlFile = new UniqueRef<IFile>();
  428. IFileSystem controlFs = controlNca.OpenFileSystem(NcaSectionType.Data, device.System.FsIntegrityCheckLevel);
  429. Result result = controlFs.OpenFile(ref controlFile.Ref, "/control.nacp".ToU8Span(), OpenMode.Read);
  430. if (result.IsSuccess())
  431. {
  432. result = controlFile.Get.Read(out long bytesRead, 0, controlData.ByteSpan, ReadOption.None);
  433. if (result.IsSuccess() && bytesRead == controlData.ByteSpan.Length)
  434. {
  435. titleName = controlData.Value.Title[(int)device.System.State.DesiredTitleLanguage].NameString.ToString();
  436. if (string.IsNullOrWhiteSpace(titleName))
  437. {
  438. titleName = controlData.Value.Title.ItemsRo.ToArray().FirstOrDefault(x => x.Name[0] != 0).NameString.ToString();
  439. }
  440. displayVersion = controlData.Value.DisplayVersionString.ToString();
  441. }
  442. }
  443. else
  444. {
  445. controlData.ByteSpan.Clear();
  446. }
  447. }
  448. private ulong LoadExeFs(IFileSystem codeFs, string displayVersion, MetaLoader metaData = null, bool isHomebrew = false)
  449. {
  450. if (_device.Configuration.VirtualFileSystem.ModLoader.ReplaceExefsPartition(TitleId, ref codeFs))
  451. {
  452. metaData = null; // TODO: Check if we should retain old npdm.
  453. }
  454. metaData ??= ReadNpdm(codeFs);
  455. NsoExecutable[] nsos = new NsoExecutable[ExeFsPrefixes.Length];
  456. for (int i = 0; i < nsos.Length; i++)
  457. {
  458. string name = ExeFsPrefixes[i];
  459. if (!codeFs.FileExists($"/{name}"))
  460. {
  461. continue; // File doesn't exist, skip.
  462. }
  463. Logger.Info?.Print(LogClass.Loader, $"Loading {name}...");
  464. using var nsoFile = new UniqueRef<IFile>();
  465. codeFs.OpenFile(ref nsoFile.Ref, $"/{name}".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  466. nsos[i] = new NsoExecutable(nsoFile.Release().AsStorage(), name);
  467. }
  468. // ExeFs file replacements.
  469. ModLoadResult modLoadResult = _device.Configuration.VirtualFileSystem.ModLoader.ApplyExefsMods(TitleId, nsos);
  470. // Collect the nsos, ignoring ones that aren't used.
  471. NsoExecutable[] programs = nsos.Where(x => x != null).ToArray();
  472. // Take the npdm from mods if present.
  473. if (modLoadResult.Npdm != null)
  474. {
  475. metaData = modLoadResult.Npdm;
  476. }
  477. _device.Configuration.VirtualFileSystem.ModLoader.ApplyNsoPatches(TitleId, programs);
  478. _device.Configuration.ContentManager.LoadEntries(_device);
  479. bool usePtc = _device.System.EnablePtc;
  480. // Don't use PPTC if ExeFs files have been replaced.
  481. usePtc &= !modLoadResult.Modified;
  482. if (_device.System.EnablePtc && !usePtc)
  483. {
  484. Logger.Warning?.Print(LogClass.Ptc, $"Detected unsupported ExeFs modifications. PPTC disabled.");
  485. }
  486. Graphics.Gpu.GraphicsConfig.TitleId = TitleIdText;
  487. _device.Gpu.HostInitalized.Set();
  488. MemoryManagerMode memoryManagerMode = _device.Configuration.MemoryManagerMode;
  489. if (!MemoryBlock.SupportsFlags(MemoryAllocationFlags.ViewCompatible))
  490. {
  491. memoryManagerMode = MemoryManagerMode.SoftwarePageTable;
  492. }
  493. // We allow it for nx-hbloader because it can be used to launch homebrew.
  494. bool allowCodeMemoryForJit = TitleId == 0x010000000000100DUL || isHomebrew;
  495. metaData.GetNpdm(out Npdm npdm).ThrowIfFailure();
  496. ProgramInfo programInfo = new ProgramInfo(in npdm, displayVersion, usePtc, allowCodeMemoryForJit);
  497. ProgramLoadResult result = ProgramLoader.LoadNsos(_device.System.KernelContext, metaData, programInfo, executables: programs);
  498. DiskCacheLoadState = result.DiskCacheLoadState;
  499. _device.Configuration.VirtualFileSystem.ModLoader.LoadCheats(TitleId, result.TamperInfo, _device.TamperMachine);
  500. return result.ProcessId;
  501. }
  502. public void LoadProgram(string filePath)
  503. {
  504. MetaLoader metaData = GetDefaultNpdm();
  505. metaData.GetNpdm(out Npdm npdm).ThrowIfFailure();
  506. ProgramInfo programInfo = new ProgramInfo(in npdm, string.Empty, diskCacheEnabled: false, allowCodeMemoryForJit: true);
  507. bool isNro = Path.GetExtension(filePath).ToLower() == ".nro";
  508. IExecutable executable;
  509. Stream romfsStream = null;
  510. if (isNro)
  511. {
  512. FileStream input = new FileStream(filePath, FileMode.Open);
  513. NroExecutable obj = new NroExecutable(input.AsStorage());
  514. executable = obj;
  515. // Homebrew NRO can actually have some data after the actual NRO.
  516. if (input.Length > obj.FileSize)
  517. {
  518. input.Position = obj.FileSize;
  519. BinaryReader reader = new BinaryReader(input);
  520. uint asetMagic = reader.ReadUInt32();
  521. if (asetMagic == 0x54455341)
  522. {
  523. uint asetVersion = reader.ReadUInt32();
  524. if (asetVersion == 0)
  525. {
  526. ulong iconOffset = reader.ReadUInt64();
  527. ulong iconSize = reader.ReadUInt64();
  528. ulong nacpOffset = reader.ReadUInt64();
  529. ulong nacpSize = reader.ReadUInt64();
  530. ulong romfsOffset = reader.ReadUInt64();
  531. ulong romfsSize = reader.ReadUInt64();
  532. if (romfsSize != 0)
  533. {
  534. romfsStream = new HomebrewRomFsStream(input, obj.FileSize + (long)romfsOffset);
  535. }
  536. if (nacpSize != 0)
  537. {
  538. input.Seek(obj.FileSize + (long)nacpOffset, SeekOrigin.Begin);
  539. reader.Read(ControlData.ByteSpan);
  540. ref ApplicationControlProperty nacp = ref ControlData.Value;
  541. programInfo.Name = nacp.Title[(int)_device.System.State.DesiredTitleLanguage].NameString.ToString();
  542. if (string.IsNullOrWhiteSpace(programInfo.Name))
  543. {
  544. programInfo.Name = nacp.Title.ItemsRo.ToArray().FirstOrDefault(x => x.Name[0] != 0).NameString.ToString();
  545. }
  546. if (nacp.PresenceGroupId != 0)
  547. {
  548. programInfo.ProgramId = nacp.PresenceGroupId;
  549. }
  550. else if (nacp.SaveDataOwnerId != 0)
  551. {
  552. programInfo.ProgramId = nacp.SaveDataOwnerId;
  553. }
  554. else if (nacp.AddOnContentBaseId != 0)
  555. {
  556. programInfo.ProgramId = nacp.AddOnContentBaseId - 0x1000;
  557. }
  558. else
  559. {
  560. programInfo.ProgramId = 0000000000000000;
  561. }
  562. }
  563. }
  564. else
  565. {
  566. Logger.Warning?.Print(LogClass.Loader, $"Unsupported ASET header version found \"{asetVersion}\"");
  567. }
  568. }
  569. }
  570. }
  571. else
  572. {
  573. executable = new NsoExecutable(new LocalStorage(filePath, FileAccess.Read), Path.GetFileNameWithoutExtension(filePath));
  574. }
  575. _device.Configuration.ContentManager.LoadEntries(_device);
  576. _titleName = programInfo.Name;
  577. TitleId = programInfo.ProgramId;
  578. TitleIs64Bit = (npdm.Meta.Flags & 1) != 0;
  579. _device.System.LibHacHorizonManager.ArpIReader.ApplicationId = new LibHac.ApplicationId(TitleId);
  580. // Explicitly null titleid to disable the shader cache.
  581. Graphics.Gpu.GraphicsConfig.TitleId = null;
  582. _device.Gpu.HostInitalized.Set();
  583. ProgramLoadResult result = ProgramLoader.LoadNsos(_device.System.KernelContext, metaData, programInfo, executables: executable);
  584. if (romfsStream != null)
  585. {
  586. _device.Configuration.VirtualFileSystem.SetRomFs(result.ProcessId, romfsStream);
  587. }
  588. DiskCacheLoadState = result.DiskCacheLoadState;
  589. _device.Configuration.VirtualFileSystem.ModLoader.LoadCheats(TitleId, result.TamperInfo, _device.TamperMachine);
  590. }
  591. private MetaLoader GetDefaultNpdm()
  592. {
  593. Assembly asm = Assembly.GetCallingAssembly();
  594. using (Stream npdmStream = asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm"))
  595. {
  596. var npdmBuffer = new byte[npdmStream.Length];
  597. npdmStream.Read(npdmBuffer);
  598. var metaLoader = new MetaLoader();
  599. metaLoader.Load(npdmBuffer).ThrowIfFailure();
  600. return metaLoader;
  601. }
  602. }
  603. private static (ulong applicationId, int programCount) GetMultiProgramInfo(VirtualFileSystem fileSystem, PartitionFileSystem pfs)
  604. {
  605. ulong mainProgramId = 0;
  606. Span<bool> hasIndex = stackalloc bool[0x10];
  607. fileSystem.ImportTickets(pfs);
  608. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  609. {
  610. using var ncaFile = new UniqueRef<IFile>();
  611. pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  612. Nca nca = new Nca(fileSystem.KeySet, ncaFile.Release().AsStorage());
  613. if (nca.Header.ContentType != NcaContentType.Program)
  614. {
  615. continue;
  616. }
  617. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  618. if (nca.SectionExists(NcaSectionType.Data) && nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  619. {
  620. continue;
  621. }
  622. ulong currentProgramId = nca.Header.TitleId;
  623. ulong currentMainProgramId = currentProgramId & ~0xFFFul;
  624. if (mainProgramId == 0 && currentMainProgramId != 0)
  625. {
  626. mainProgramId = currentMainProgramId;
  627. }
  628. if (mainProgramId != currentMainProgramId)
  629. {
  630. // As far as I know there aren't any multi-application game cards containing multi-program applications,
  631. // so because multi-application game cards are the only way we should run into multiple applications
  632. // we'll just return that there's a single program.
  633. return (mainProgramId, 1);
  634. }
  635. hasIndex[(int)(currentProgramId & 0xF)] = true;
  636. }
  637. int programCount = 0;
  638. for (int i = 0; i < hasIndex.Length && hasIndex[i]; i++)
  639. {
  640. programCount++;
  641. }
  642. return (mainProgramId, programCount);
  643. }
  644. private Result RegisterProgramMapInfo(PartitionFileSystem pfs)
  645. {
  646. (ulong applicationId, int programCount) = GetMultiProgramInfo(_device.Configuration.VirtualFileSystem, pfs);
  647. if (programCount <= 0)
  648. return Result.Success;
  649. Span<ProgramIndexMapInfo> mapInfo = stackalloc ProgramIndexMapInfo[0x10];
  650. for (int i = 0; i < programCount; i++)
  651. {
  652. mapInfo[i].ProgramId = new ProgramId(applicationId + (uint)i);
  653. mapInfo[i].MainProgramId = new ApplicationId(applicationId);
  654. mapInfo[i].ProgramIndex = (byte)i;
  655. }
  656. return _device.System.LibHacHorizonManager.NsClient.Fs.RegisterProgramIndexMapInfo(mapInfo.Slice(0, programCount));
  657. }
  658. private Result EnsureSaveData(ApplicationId applicationId)
  659. {
  660. Logger.Info?.Print(LogClass.Application, "Ensuring required savedata exists.");
  661. Uid user = _device.System.AccountManager.LastOpenedUser.UserId.ToLibHacUid();
  662. ref ApplicationControlProperty control = ref ControlData.Value;
  663. if (LibHac.Common.Utilities.IsZeros(ControlData.ByteSpan))
  664. {
  665. // If the current application doesn't have a loaded control property, create a dummy one
  666. // and set the savedata sizes so a user savedata will be created.
  667. control = ref new BlitStruct<ApplicationControlProperty>(1).Value;
  668. // The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
  669. control.UserAccountSaveDataSize = 0x4000;
  670. control.UserAccountSaveDataJournalSize = 0x4000;
  671. control.SaveDataOwnerId = applicationId.Value;
  672. Logger.Warning?.Print(LogClass.Application,
  673. "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games.");
  674. }
  675. HorizonClient hos = _device.System.LibHacHorizonManager.RyujinxClient;
  676. Result resultCode = hos.Fs.EnsureApplicationCacheStorage(out _, out _, applicationId, in control);
  677. if (resultCode.IsFailure())
  678. {
  679. Logger.Error?.Print(LogClass.Application, $"Error calling EnsureApplicationCacheStorage. Result code {resultCode.ToStringWithName()}");
  680. return resultCode;
  681. }
  682. resultCode = hos.Fs.EnsureApplicationSaveData(out _, applicationId, in control, in user);
  683. if (resultCode.IsFailure())
  684. {
  685. Logger.Error?.Print(LogClass.Application, $"Error calling EnsureApplicationSaveData. Result code {resultCode.ToStringWithName()}");
  686. }
  687. return resultCode;
  688. }
  689. }
  690. }