ApplicationLoader.cs 35 KB

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