ApplicationLoader.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. using ARMeilleure.Translation.PTC;
  2. using LibHac;
  3. using LibHac.Account;
  4. using LibHac.Common;
  5. using LibHac.Fs;
  6. using LibHac.FsSystem;
  7. using LibHac.FsSystem.NcaUtils;
  8. using LibHac.Ncm;
  9. using LibHac.Ns;
  10. using Ryujinx.Common.Configuration;
  11. using Ryujinx.Common.Logging;
  12. using Ryujinx.HLE.FileSystem;
  13. using Ryujinx.HLE.FileSystem.Content;
  14. using Ryujinx.HLE.Loaders.Executables;
  15. using Ryujinx.HLE.Loaders.Npdm;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Reflection;
  21. using static LibHac.Fs.ApplicationSaveDataManagement;
  22. namespace Ryujinx.HLE.HOS
  23. {
  24. using JsonHelper = Common.Utilities.JsonHelper;
  25. public class ApplicationLoader
  26. {
  27. private readonly Switch _device;
  28. private readonly ContentManager _contentManager;
  29. private readonly VirtualFileSystem _fileSystem;
  30. public BlitStruct<ApplicationControlProperty> ControlData { get; set; }
  31. public string TitleName { get; private set; }
  32. public string DisplayVersion { get; private set; }
  33. public ulong TitleId { get; private set; }
  34. public string TitleIdText => TitleId.ToString("x16");
  35. public bool TitleIs64Bit { get; private set; }
  36. public bool EnablePtc => _device.System.EnablePtc;
  37. // Binaries from exefs are loaded into mem in this order. Do not change.
  38. private static readonly string[] ExeFsPrefixes = { "rtld", "main", "subsdk*", "sdk" };
  39. public ApplicationLoader(Switch device, VirtualFileSystem fileSystem, ContentManager contentManager)
  40. {
  41. _device = device;
  42. _contentManager = contentManager;
  43. _fileSystem = fileSystem;
  44. ControlData = new BlitStruct<ApplicationControlProperty>(1);
  45. // Clear Mods cache
  46. _fileSystem.ModLoader.Clear();
  47. }
  48. public void LoadCart(string exeFsDir, string romFsFile = null)
  49. {
  50. if (romFsFile != null)
  51. {
  52. _fileSystem.LoadRomFs(romFsFile);
  53. }
  54. LocalFileSystem codeFs = new LocalFileSystem(exeFsDir);
  55. Npdm metaData = ReadNpdm(codeFs);
  56. _fileSystem.ModLoader.CollectMods(TitleId, _fileSystem.GetBaseModsPath());
  57. if (TitleId != 0)
  58. {
  59. EnsureSaveData(new TitleId(TitleId));
  60. }
  61. LoadExeFs(codeFs, metaData);
  62. }
  63. private (Nca main, Nca patch, Nca control) GetGameData(PartitionFileSystem pfs)
  64. {
  65. Nca mainNca = null;
  66. Nca patchNca = null;
  67. Nca controlNca = null;
  68. _fileSystem.ImportTickets(pfs);
  69. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  70. {
  71. pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  72. Nca nca = new Nca(_fileSystem.KeySet, ncaFile.AsStorage());
  73. if (nca.Header.ContentType == NcaContentType.Program)
  74. {
  75. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  76. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  77. {
  78. patchNca = nca;
  79. }
  80. else
  81. {
  82. mainNca = nca;
  83. }
  84. }
  85. else if (nca.Header.ContentType == NcaContentType.Control)
  86. {
  87. controlNca = nca;
  88. }
  89. }
  90. return (mainNca, patchNca, controlNca);
  91. }
  92. public void LoadXci(string xciFile)
  93. {
  94. FileStream file = new FileStream(xciFile, FileMode.Open, FileAccess.Read);
  95. Xci xci = new Xci(_fileSystem.KeySet, file.AsStorage());
  96. if (!xci.HasPartition(XciPartitionType.Secure))
  97. {
  98. Logger.PrintError(LogClass.Loader, "Unable to load XCI: Could not find XCI secure partition");
  99. return;
  100. }
  101. PartitionFileSystem securePartition = xci.OpenPartition(XciPartitionType.Secure);
  102. Nca mainNca = null;
  103. Nca patchNca = null;
  104. Nca controlNca = null;
  105. try
  106. {
  107. (mainNca, patchNca, controlNca) = GetGameData(securePartition);
  108. }
  109. catch (Exception e)
  110. {
  111. Logger.PrintError(LogClass.Loader, $"Unable to load XCI: {e.Message}");
  112. return;
  113. }
  114. if (mainNca == null)
  115. {
  116. Logger.PrintError(LogClass.Loader, "Unable to load XCI: Could not find Main NCA");
  117. return;
  118. }
  119. _contentManager.LoadEntries(_device);
  120. _contentManager.ClearAocData();
  121. _contentManager.AddAocData(securePartition, xciFile, mainNca.Header.TitleId);
  122. LoadNca(mainNca, patchNca, controlNca);
  123. }
  124. public void LoadNsp(string nspFile)
  125. {
  126. FileStream file = new FileStream(nspFile, FileMode.Open, FileAccess.Read);
  127. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  128. Nca mainNca = null;
  129. Nca patchNca = null;
  130. Nca controlNca = null;
  131. try
  132. {
  133. (mainNca, patchNca, controlNca) = GetGameData(nsp);
  134. }
  135. catch (Exception e)
  136. {
  137. Logger.PrintError(LogClass.Loader, $"Unable to load NSP: {e.Message}");
  138. return;
  139. }
  140. if (mainNca == null)
  141. {
  142. Logger.PrintError(LogClass.Loader, "Unable to load NSP: Could not find Main NCA");
  143. return;
  144. }
  145. if (mainNca != null)
  146. {
  147. _contentManager.ClearAocData();
  148. _contentManager.AddAocData(nsp, nspFile, mainNca.Header.TitleId);
  149. LoadNca(mainNca, patchNca, controlNca);
  150. return;
  151. }
  152. // This is not a normal NSP, it's actually a ExeFS as a NSP
  153. LoadExeFs(nsp);
  154. }
  155. public void LoadNca(string ncaFile)
  156. {
  157. FileStream file = new FileStream(ncaFile, FileMode.Open, FileAccess.Read);
  158. Nca nca = new Nca(_fileSystem.KeySet, file.AsStorage(false));
  159. LoadNca(nca, null, null);
  160. }
  161. private void LoadNca(Nca mainNca, Nca patchNca, Nca controlNca)
  162. {
  163. if (mainNca.Header.ContentType != NcaContentType.Program)
  164. {
  165. Logger.PrintError(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");
  166. return;
  167. }
  168. IStorage dataStorage = null;
  169. IFileSystem codeFs = null;
  170. // Load Update
  171. string titleUpdateMetadataPath = Path.Combine(_fileSystem.GetBasePath(), "games", mainNca.Header.TitleId.ToString("x16"), "updates.json");
  172. if (File.Exists(titleUpdateMetadataPath))
  173. {
  174. string updatePath = JsonHelper.DeserializeFromFile<TitleUpdateMetadata>(titleUpdateMetadataPath).Selected;
  175. if (File.Exists(updatePath))
  176. {
  177. FileStream file = new FileStream(updatePath, FileMode.Open, FileAccess.Read);
  178. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  179. _fileSystem.ImportTickets(nsp);
  180. foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
  181. {
  182. nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  183. Nca nca = new Nca(_fileSystem.KeySet, ncaFile.AsStorage());
  184. if ($"{nca.Header.TitleId.ToString("x16")[..^3]}000" != mainNca.Header.TitleId.ToString("x16"))
  185. {
  186. break;
  187. }
  188. if (nca.Header.ContentType == NcaContentType.Program)
  189. {
  190. patchNca = nca;
  191. }
  192. else if (nca.Header.ContentType == NcaContentType.Control)
  193. {
  194. controlNca = nca;
  195. }
  196. }
  197. }
  198. }
  199. // Load Aoc
  200. string titleAocMetadataPath = Path.Combine(_fileSystem.GetBasePath(), "games", mainNca.Header.TitleId.ToString("x16"), "dlc.json");
  201. if (File.Exists(titleAocMetadataPath))
  202. {
  203. List<DlcContainer> dlcContainerList = JsonHelper.DeserializeFromFile<List<DlcContainer>>(titleAocMetadataPath);
  204. foreach (DlcContainer dlcContainer in dlcContainerList)
  205. {
  206. foreach (DlcNca dlcNca in dlcContainer.DlcNcaList)
  207. {
  208. _contentManager.AddAocItem(dlcNca.TitleId, dlcContainer.Path, dlcNca.Path, dlcNca.Enabled);
  209. }
  210. }
  211. }
  212. if (patchNca == null)
  213. {
  214. if (mainNca.CanOpenSection(NcaSectionType.Data))
  215. {
  216. dataStorage = mainNca.OpenStorage(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);
  217. }
  218. if (mainNca.CanOpenSection(NcaSectionType.Code))
  219. {
  220. codeFs = mainNca.OpenFileSystem(NcaSectionType.Code, _device.System.FsIntegrityCheckLevel);
  221. }
  222. }
  223. else
  224. {
  225. if (patchNca.CanOpenSection(NcaSectionType.Data))
  226. {
  227. dataStorage = mainNca.OpenStorageWithPatch(patchNca, NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);
  228. }
  229. if (patchNca.CanOpenSection(NcaSectionType.Code))
  230. {
  231. codeFs = mainNca.OpenFileSystemWithPatch(patchNca, NcaSectionType.Code, _device.System.FsIntegrityCheckLevel);
  232. }
  233. }
  234. if (codeFs == null)
  235. {
  236. Logger.PrintError(LogClass.Loader, "No ExeFS found in NCA");
  237. return;
  238. }
  239. Npdm metaData = ReadNpdm(codeFs);
  240. _fileSystem.ModLoader.CollectMods(TitleId, _fileSystem.GetBaseModsPath());
  241. if (controlNca != null)
  242. {
  243. ReadControlData(controlNca);
  244. }
  245. else
  246. {
  247. ControlData.ByteSpan.Clear();
  248. }
  249. if (dataStorage == null)
  250. {
  251. Logger.PrintWarning(LogClass.Loader, "No RomFS found in NCA");
  252. }
  253. else
  254. {
  255. IStorage newStorage = _fileSystem.ModLoader.ApplyRomFsMods(TitleId, dataStorage);
  256. _fileSystem.SetRomFs(newStorage.AsStream(FileAccess.Read));
  257. }
  258. if (TitleId != 0)
  259. {
  260. EnsureSaveData(new TitleId(TitleId));
  261. }
  262. LoadExeFs(codeFs, metaData);
  263. Logger.PrintInfo(LogClass.Loader, $"Application Loaded: {TitleName} v{DisplayVersion} [{TitleIdText}] [{(TitleIs64Bit ? "64-bit" : "32-bit")}]");
  264. }
  265. // Sets TitleId, so be sure to call before using it
  266. private Npdm ReadNpdm(IFileSystem fs)
  267. {
  268. Result result = fs.OpenFile(out IFile npdmFile, "/main.npdm".ToU8Span(), OpenMode.Read);
  269. Npdm metaData;
  270. if (ResultFs.PathNotFound.Includes(result))
  271. {
  272. Logger.PrintWarning(LogClass.Loader, "NPDM file not found, using default values!");
  273. metaData = GetDefaultNpdm();
  274. }
  275. else
  276. {
  277. metaData = new Npdm(npdmFile.AsStream());
  278. }
  279. TitleId = metaData.Aci0.TitleId;
  280. TitleIs64Bit = metaData.Is64Bit;
  281. return metaData;
  282. }
  283. private void ReadControlData(Nca controlNca)
  284. {
  285. IFileSystem controlFs = controlNca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);
  286. Result result = controlFs.OpenFile(out IFile controlFile, "/control.nacp".ToU8Span(), OpenMode.Read);
  287. if (result.IsSuccess())
  288. {
  289. result = controlFile.Read(out long bytesRead, 0, ControlData.ByteSpan, ReadOption.None);
  290. if (result.IsSuccess() && bytesRead == ControlData.ByteSpan.Length)
  291. {
  292. TitleName = ControlData.Value
  293. .Titles[(int)_device.System.State.DesiredTitleLanguage].Name.ToString();
  294. if (string.IsNullOrWhiteSpace(TitleName))
  295. {
  296. TitleName = ControlData.Value.Titles.ToArray()
  297. .FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  298. }
  299. DisplayVersion = ControlData.Value.DisplayVersion.ToString();
  300. }
  301. }
  302. else
  303. {
  304. ControlData.ByteSpan.Clear();
  305. }
  306. }
  307. private void LoadExeFs(IFileSystem codeFs, Npdm metaData = null)
  308. {
  309. if (_fileSystem.ModLoader.ReplaceExefsPartition(TitleId, ref codeFs))
  310. {
  311. metaData = null; //TODO: Check if we should retain old npdm
  312. }
  313. metaData ??= ReadNpdm(codeFs);
  314. List<NsoExecutable> nsos = new List<NsoExecutable>();
  315. foreach (string exePrefix in ExeFsPrefixes) // Load binaries with standard prefixes
  316. {
  317. foreach (DirectoryEntryEx file in codeFs.EnumerateEntries("/", exePrefix))
  318. {
  319. if (Path.GetExtension(file.Name) != string.Empty)
  320. {
  321. continue;
  322. }
  323. Logger.PrintInfo(LogClass.Loader, $"Loading {file.Name}...");
  324. codeFs.OpenFile(out IFile nsoFile, file.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  325. NsoExecutable nso = new NsoExecutable(nsoFile.AsStorage(), file.Name);
  326. nsos.Add(nso);
  327. }
  328. }
  329. // ExeFs file replacements
  330. bool modified = _fileSystem.ModLoader.ApplyExefsMods(TitleId, nsos);
  331. var programs = nsos.ToArray();
  332. modified |= _fileSystem.ModLoader.ApplyNsoPatches(TitleId, programs);
  333. _contentManager.LoadEntries(_device);
  334. if (EnablePtc && modified)
  335. {
  336. Logger.PrintWarning(LogClass.Ptc, $"Detected exefs modifications. PPTC disabled.");
  337. }
  338. Ptc.Initialize(TitleIdText, DisplayVersion, EnablePtc && !modified);
  339. ProgramLoader.LoadNsos(_device.System.KernelContext, metaData, executables: programs);
  340. }
  341. public void LoadProgram(string filePath)
  342. {
  343. Npdm metaData = GetDefaultNpdm();
  344. bool isNro = Path.GetExtension(filePath).ToLower() == ".nro";
  345. IExecutable executable;
  346. if (isNro)
  347. {
  348. FileStream input = new FileStream(filePath, FileMode.Open);
  349. NroExecutable obj = new NroExecutable(input.AsStorage());
  350. executable = obj;
  351. // homebrew NRO can actually have some data after the actual NRO
  352. if (input.Length > obj.FileSize)
  353. {
  354. input.Position = obj.FileSize;
  355. BinaryReader reader = new BinaryReader(input);
  356. uint asetMagic = reader.ReadUInt32();
  357. if (asetMagic == 0x54455341)
  358. {
  359. uint asetVersion = reader.ReadUInt32();
  360. if (asetVersion == 0)
  361. {
  362. ulong iconOffset = reader.ReadUInt64();
  363. ulong iconSize = reader.ReadUInt64();
  364. ulong nacpOffset = reader.ReadUInt64();
  365. ulong nacpSize = reader.ReadUInt64();
  366. ulong romfsOffset = reader.ReadUInt64();
  367. ulong romfsSize = reader.ReadUInt64();
  368. if (romfsSize != 0)
  369. {
  370. _fileSystem.SetRomFs(new HomebrewRomFsStream(input, obj.FileSize + (long)romfsOffset));
  371. }
  372. if (nacpSize != 0)
  373. {
  374. input.Seek(obj.FileSize + (long)nacpOffset, SeekOrigin.Begin);
  375. reader.Read(ControlData.ByteSpan);
  376. ref ApplicationControlProperty nacp = ref ControlData.Value;
  377. metaData.TitleName = nacp.Titles[(int)_device.System.State.DesiredTitleLanguage].Name.ToString();
  378. if (string.IsNullOrWhiteSpace(metaData.TitleName))
  379. {
  380. metaData.TitleName = nacp.Titles.ToArray().FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  381. }
  382. if (nacp.PresenceGroupId != 0)
  383. {
  384. metaData.Aci0.TitleId = nacp.PresenceGroupId;
  385. }
  386. else if (nacp.SaveDataOwnerId.Value != 0)
  387. {
  388. metaData.Aci0.TitleId = nacp.SaveDataOwnerId.Value;
  389. }
  390. else if (nacp.AddOnContentBaseId != 0)
  391. {
  392. metaData.Aci0.TitleId = nacp.AddOnContentBaseId - 0x1000;
  393. }
  394. else
  395. {
  396. metaData.Aci0.TitleId = 0000000000000000;
  397. }
  398. }
  399. }
  400. else
  401. {
  402. Logger.PrintWarning(LogClass.Loader, $"Unsupported ASET header version found \"{asetVersion}\"");
  403. }
  404. }
  405. }
  406. }
  407. else
  408. {
  409. executable = new NsoExecutable(new LocalStorage(filePath, FileAccess.Read), Path.GetFileNameWithoutExtension(filePath));
  410. }
  411. _contentManager.LoadEntries(_device);
  412. TitleName = metaData.TitleName;
  413. TitleId = metaData.Aci0.TitleId;
  414. TitleIs64Bit = metaData.Is64Bit;
  415. ProgramLoader.LoadNsos(_device.System.KernelContext, metaData, executables: executable);
  416. }
  417. private Npdm GetDefaultNpdm()
  418. {
  419. Assembly asm = Assembly.GetCallingAssembly();
  420. using (Stream npdmStream = asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm"))
  421. {
  422. return new Npdm(npdmStream);
  423. }
  424. }
  425. private Result EnsureSaveData(TitleId titleId)
  426. {
  427. Logger.PrintInfo(LogClass.Application, "Ensuring required savedata exists.");
  428. Uid user = _device.System.State.Account.LastOpenedUser.UserId.ToLibHacUid();
  429. ref ApplicationControlProperty control = ref ControlData.Value;
  430. if (Util.IsEmpty(ControlData.ByteSpan))
  431. {
  432. // If the current application doesn't have a loaded control property, create a dummy one
  433. // and set the savedata sizes so a user savedata will be created.
  434. control = ref new BlitStruct<ApplicationControlProperty>(1).Value;
  435. // The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
  436. control.UserAccountSaveDataSize = 0x4000;
  437. control.UserAccountSaveDataJournalSize = 0x4000;
  438. Logger.PrintWarning(LogClass.Application,
  439. "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games.");
  440. }
  441. FileSystemClient fs = _fileSystem.FsClient;
  442. Result rc = fs.EnsureApplicationCacheStorage(out _, titleId, ref control);
  443. if (rc.IsFailure())
  444. {
  445. Logger.PrintError(LogClass.Application, $"Error calling EnsureApplicationCacheStorage. Result code {rc.ToStringWithName()}");
  446. return rc;
  447. }
  448. rc = EnsureApplicationSaveData(fs, out _, titleId, ref control, ref user);
  449. if (rc.IsFailure())
  450. {
  451. Logger.PrintError(LogClass.Application, $"Error calling EnsureApplicationSaveData. Result code {rc.ToStringWithName()}");
  452. }
  453. return rc;
  454. }
  455. }
  456. }