ApplicationLoader.cs 35 KB

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