ApplicationLoader.cs 35 KB

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