ApplicationLoader.cs 35 KB

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