ApplicationLoader.cs 21 KB

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