ModLoader.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. using LibHac.Common;
  2. using LibHac.Fs;
  3. using LibHac.Fs.Fsa;
  4. using LibHac.FsSystem;
  5. using LibHac.Loader;
  6. using LibHac.Tools.FsSystem;
  7. using LibHac.Tools.FsSystem.RomFs;
  8. using Ryujinx.Common.Configuration;
  9. using Ryujinx.Common.Logging;
  10. using Ryujinx.HLE.Loaders.Mods;
  11. using Ryujinx.HLE.Loaders.Executables;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Collections.Specialized;
  15. using System.Linq;
  16. using System.IO;
  17. using Ryujinx.HLE.HOS.Kernel.Process;
  18. using System.Globalization;
  19. using Path = System.IO.Path;
  20. namespace Ryujinx.HLE.HOS
  21. {
  22. public class ModLoader
  23. {
  24. private const string RomfsDir = "romfs";
  25. private const string ExefsDir = "exefs";
  26. private const string CheatDir = "cheats";
  27. private const string RomfsContainer = "romfs.bin";
  28. private const string ExefsContainer = "exefs.nsp";
  29. private const string StubExtension = ".stub";
  30. private const string CheatExtension = ".txt";
  31. private const string DefaultCheatName = "<default>";
  32. private const string AmsContentsDir = "contents";
  33. private const string AmsNsoPatchDir = "exefs_patches";
  34. private const string AmsNroPatchDir = "nro_patches";
  35. private const string AmsKipPatchDir = "kip_patches";
  36. public readonly struct Mod<T> where T : FileSystemInfo
  37. {
  38. public readonly string Name;
  39. public readonly T Path;
  40. public Mod(string name, T path)
  41. {
  42. Name = name;
  43. Path = path;
  44. }
  45. }
  46. public struct Cheat
  47. {
  48. // Atmosphere identifies the executables with the first 8 bytes
  49. // of the build id, which is equivalent to 16 hex digits.
  50. public const int CheatIdSize = 16;
  51. public readonly string Name;
  52. public readonly FileInfo Path;
  53. public readonly IEnumerable<String> Instructions;
  54. public Cheat(string name, FileInfo path, IEnumerable<String> instructions)
  55. {
  56. Name = name;
  57. Path = path;
  58. Instructions = instructions;
  59. }
  60. }
  61. // Title dependent mods
  62. public class ModCache
  63. {
  64. public List<Mod<FileInfo>> RomfsContainers { get; }
  65. public List<Mod<FileInfo>> ExefsContainers { get; }
  66. public List<Mod<DirectoryInfo>> RomfsDirs { get; }
  67. public List<Mod<DirectoryInfo>> ExefsDirs { get; }
  68. public List<Cheat> Cheats { get; }
  69. public ModCache()
  70. {
  71. RomfsContainers = new List<Mod<FileInfo>>();
  72. ExefsContainers = new List<Mod<FileInfo>>();
  73. RomfsDirs = new List<Mod<DirectoryInfo>>();
  74. ExefsDirs = new List<Mod<DirectoryInfo>>();
  75. Cheats = new List<Cheat>();
  76. }
  77. }
  78. // Title independent mods
  79. public class PatchCache
  80. {
  81. public List<Mod<DirectoryInfo>> NsoPatches { get; }
  82. public List<Mod<DirectoryInfo>> NroPatches { get; }
  83. public List<Mod<DirectoryInfo>> KipPatches { get; }
  84. internal bool Initialized { get; set; }
  85. public PatchCache()
  86. {
  87. NsoPatches = new List<Mod<DirectoryInfo>>();
  88. NroPatches = new List<Mod<DirectoryInfo>>();
  89. KipPatches = new List<Mod<DirectoryInfo>>();
  90. Initialized = false;
  91. }
  92. }
  93. public Dictionary<ulong, ModCache> AppMods; // key is TitleId
  94. public PatchCache Patches;
  95. private static readonly EnumerationOptions _dirEnumOptions;
  96. static ModLoader()
  97. {
  98. _dirEnumOptions = new EnumerationOptions
  99. {
  100. MatchCasing = MatchCasing.CaseInsensitive,
  101. MatchType = MatchType.Simple,
  102. RecurseSubdirectories = false,
  103. ReturnSpecialDirectories = false
  104. };
  105. }
  106. public ModLoader()
  107. {
  108. AppMods = new Dictionary<ulong, ModCache>();
  109. Patches = new PatchCache();
  110. }
  111. public void Clear()
  112. {
  113. AppMods.Clear();
  114. Patches = new PatchCache();
  115. }
  116. private static bool StrEquals(string s1, string s2) => string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase);
  117. public string GetModsBasePath() => EnsureBaseDirStructure(AppDataManager.GetModsPath());
  118. public string GetSdModsBasePath() => EnsureBaseDirStructure(AppDataManager.GetSdModsPath());
  119. private string EnsureBaseDirStructure(string modsBasePath)
  120. {
  121. var modsDir = new DirectoryInfo(modsBasePath);
  122. modsDir.CreateSubdirectory(AmsContentsDir);
  123. modsDir.CreateSubdirectory(AmsNsoPatchDir);
  124. modsDir.CreateSubdirectory(AmsNroPatchDir);
  125. // modsDir.CreateSubdirectory(AmsKipPatchDir); // uncomment when KIPs are supported
  126. return modsDir.FullName;
  127. }
  128. private static DirectoryInfo FindTitleDir(DirectoryInfo contentsDir, string titleId)
  129. => contentsDir.EnumerateDirectories($"{titleId}*", _dirEnumOptions).FirstOrDefault();
  130. public string GetTitleDir(string modsBasePath, string titleId)
  131. {
  132. var contentsDir = new DirectoryInfo(Path.Combine(modsBasePath, AmsContentsDir));
  133. var titleModsPath = FindTitleDir(contentsDir, titleId);
  134. if (titleModsPath == null)
  135. {
  136. Logger.Info?.Print(LogClass.ModLoader, $"Creating mods directory for Title {titleId.ToUpper()}");
  137. titleModsPath = contentsDir.CreateSubdirectory(titleId);
  138. }
  139. return titleModsPath.FullName;
  140. }
  141. // Static Query Methods
  142. public static void QueryPatchDirs(PatchCache cache, DirectoryInfo patchDir)
  143. {
  144. if (cache.Initialized || !patchDir.Exists) return;
  145. var patches = cache.KipPatches;
  146. string type = null;
  147. if (StrEquals(AmsNsoPatchDir, patchDir.Name)) { patches = cache.NsoPatches; type = "NSO"; }
  148. else if (StrEquals(AmsNroPatchDir, patchDir.Name)) { patches = cache.NroPatches; type = "NRO"; }
  149. else if (StrEquals(AmsKipPatchDir, patchDir.Name)) { patches = cache.KipPatches; type = "KIP"; }
  150. else return;
  151. foreach (var modDir in patchDir.EnumerateDirectories())
  152. {
  153. patches.Add(new Mod<DirectoryInfo>(modDir.Name, modDir));
  154. Logger.Info?.Print(LogClass.ModLoader, $"Found {type} patch '{modDir.Name}'");
  155. }
  156. }
  157. public static void QueryTitleDir(ModCache mods, DirectoryInfo titleDir)
  158. {
  159. if (!titleDir.Exists) return;
  160. var fsFile = new FileInfo(Path.Combine(titleDir.FullName, RomfsContainer));
  161. if (fsFile.Exists)
  162. {
  163. mods.RomfsContainers.Add(new Mod<FileInfo>($"<{titleDir.Name} RomFs>", fsFile));
  164. }
  165. fsFile = new FileInfo(Path.Combine(titleDir.FullName, ExefsContainer));
  166. if (fsFile.Exists)
  167. {
  168. mods.ExefsContainers.Add(new Mod<FileInfo>($"<{titleDir.Name} ExeFs>", fsFile));
  169. }
  170. System.Text.StringBuilder types = new System.Text.StringBuilder(5);
  171. foreach (var modDir in titleDir.EnumerateDirectories())
  172. {
  173. types.Clear();
  174. Mod<DirectoryInfo> mod = new Mod<DirectoryInfo>("", null);
  175. if (StrEquals(RomfsDir, modDir.Name))
  176. {
  177. mods.RomfsDirs.Add(mod = new Mod<DirectoryInfo>($"<{titleDir.Name} RomFs>", modDir));
  178. types.Append('R');
  179. }
  180. else if (StrEquals(ExefsDir, modDir.Name))
  181. {
  182. mods.ExefsDirs.Add(mod = new Mod<DirectoryInfo>($"<{titleDir.Name} ExeFs>", modDir));
  183. types.Append('E');
  184. }
  185. else if (StrEquals(CheatDir, modDir.Name))
  186. {
  187. for (int i = 0; i < QueryCheatsDir(mods, modDir); i++)
  188. {
  189. types.Append('C');
  190. }
  191. }
  192. else
  193. {
  194. var romfs = new DirectoryInfo(Path.Combine(modDir.FullName, RomfsDir));
  195. var exefs = new DirectoryInfo(Path.Combine(modDir.FullName, ExefsDir));
  196. var cheat = new DirectoryInfo(Path.Combine(modDir.FullName, CheatDir));
  197. if (romfs.Exists)
  198. {
  199. mods.RomfsDirs.Add(mod = new Mod<DirectoryInfo>(modDir.Name, romfs));
  200. types.Append('R');
  201. }
  202. if (exefs.Exists)
  203. {
  204. mods.ExefsDirs.Add(mod = new Mod<DirectoryInfo>(modDir.Name, exefs));
  205. types.Append('E');
  206. }
  207. if (cheat.Exists)
  208. {
  209. for (int i = 0; i < QueryCheatsDir(mods, cheat); i++)
  210. {
  211. types.Append('C');
  212. }
  213. }
  214. }
  215. if (types.Length > 0) Logger.Info?.Print(LogClass.ModLoader, $"Found mod '{mod.Name}' [{types}]");
  216. }
  217. }
  218. public static void QueryContentsDir(ModCache mods, DirectoryInfo contentsDir, ulong titleId)
  219. {
  220. if (!contentsDir.Exists) return;
  221. Logger.Info?.Print(LogClass.ModLoader, $"Searching mods for {((titleId & 0x1000) != 0 ? "DLC" : "Title")} {titleId:X16}");
  222. var titleDir = FindTitleDir(contentsDir, $"{titleId:x16}");
  223. if (titleDir != null)
  224. {
  225. QueryTitleDir(mods, titleDir);
  226. }
  227. }
  228. private static int QueryCheatsDir(ModCache mods, DirectoryInfo cheatsDir)
  229. {
  230. if (!cheatsDir.Exists)
  231. {
  232. return 0;
  233. }
  234. int numMods = 0;
  235. foreach (FileInfo file in cheatsDir.EnumerateFiles())
  236. {
  237. if (!StrEquals(CheatExtension, file.Extension))
  238. {
  239. continue;
  240. }
  241. string cheatId = Path.GetFileNameWithoutExtension(file.Name);
  242. if (cheatId.Length != Cheat.CheatIdSize)
  243. {
  244. continue;
  245. }
  246. if (!ulong.TryParse(cheatId, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _))
  247. {
  248. continue;
  249. }
  250. // A cheat file can contain several cheats for the same executable, so the file must be parsed in
  251. // order to properly enumerate them.
  252. mods.Cheats.AddRange(GetCheatsInFile(file));
  253. }
  254. return numMods;
  255. }
  256. private static IEnumerable<Cheat> GetCheatsInFile(FileInfo cheatFile)
  257. {
  258. string cheatName = DefaultCheatName;
  259. List<string> instructions = new List<string>();
  260. List<Cheat> cheats = new List<Cheat>();
  261. using (StreamReader cheatData = cheatFile.OpenText())
  262. {
  263. string line;
  264. while ((line = cheatData.ReadLine()) != null)
  265. {
  266. line = line.Trim();
  267. if (line.StartsWith('['))
  268. {
  269. // This line starts a new cheat section.
  270. if (!line.EndsWith(']') || line.Length < 3)
  271. {
  272. // Skip the entire file if there's any error while parsing the cheat file.
  273. Logger.Warning?.Print(LogClass.ModLoader, $"Ignoring cheat '{cheatFile.FullName}' because it is malformed");
  274. return new List<Cheat>();
  275. }
  276. // Add the previous section to the list.
  277. if (instructions.Count != 0)
  278. {
  279. cheats.Add(new Cheat($"<{cheatName} Cheat>", cheatFile, instructions));
  280. }
  281. // Start a new cheat section.
  282. cheatName = line.Substring(1, line.Length - 2);
  283. instructions = new List<string>();
  284. }
  285. else if (line.Length > 0)
  286. {
  287. // The line contains an instruction.
  288. instructions.Add(line);
  289. }
  290. }
  291. // Add the last section being processed.
  292. if (instructions.Count != 0)
  293. {
  294. cheats.Add(new Cheat($"<{cheatName} Cheat>", cheatFile, instructions));
  295. }
  296. }
  297. return cheats;
  298. }
  299. // Assumes searchDirPaths don't overlap
  300. public static void CollectMods(Dictionary<ulong, ModCache> modCaches, PatchCache patches, params string[] searchDirPaths)
  301. {
  302. static bool IsPatchesDir(string name) => StrEquals(AmsNsoPatchDir, name) ||
  303. StrEquals(AmsNroPatchDir, name) ||
  304. StrEquals(AmsKipPatchDir, name);
  305. static bool IsContentsDir(string name) => StrEquals(AmsContentsDir, name);
  306. static bool TryQuery(DirectoryInfo searchDir, PatchCache patches, Dictionary<ulong, ModCache> modCaches)
  307. {
  308. if (IsContentsDir(searchDir.Name))
  309. {
  310. foreach (var (titleId, cache) in modCaches)
  311. {
  312. QueryContentsDir(cache, searchDir, titleId);
  313. }
  314. return true;
  315. }
  316. else if (IsPatchesDir(searchDir.Name))
  317. {
  318. QueryPatchDirs(patches, searchDir);
  319. return true;
  320. }
  321. return false;
  322. }
  323. foreach (var path in searchDirPaths)
  324. {
  325. var searchDir = new DirectoryInfo(path);
  326. if (!searchDir.Exists)
  327. {
  328. Logger.Warning?.Print(LogClass.ModLoader, $"Mod Search Dir '{searchDir.FullName}' doesn't exist");
  329. continue;
  330. }
  331. if (!TryQuery(searchDir, patches, modCaches))
  332. {
  333. foreach (var subdir in searchDir.EnumerateDirectories())
  334. {
  335. TryQuery(subdir, patches, modCaches);
  336. }
  337. }
  338. }
  339. patches.Initialized = true;
  340. }
  341. public void CollectMods(IEnumerable<ulong> titles, params string[] searchDirPaths)
  342. {
  343. Clear();
  344. foreach (ulong titleId in titles)
  345. {
  346. AppMods[titleId] = new ModCache();
  347. }
  348. CollectMods(AppMods, Patches, searchDirPaths);
  349. }
  350. internal IStorage ApplyRomFsMods(ulong titleId, IStorage baseStorage)
  351. {
  352. if (!AppMods.TryGetValue(titleId, out ModCache mods) || mods.RomfsDirs.Count + mods.RomfsContainers.Count == 0)
  353. {
  354. return baseStorage;
  355. }
  356. var fileSet = new HashSet<string>();
  357. var builder = new RomFsBuilder();
  358. int count = 0;
  359. Logger.Info?.Print(LogClass.ModLoader, $"Applying RomFS mods for Title {titleId:X16}");
  360. // Prioritize loose files first
  361. foreach (var mod in mods.RomfsDirs)
  362. {
  363. using (IFileSystem fs = new LocalFileSystem(mod.Path.FullName))
  364. {
  365. AddFiles(fs, mod.Name, fileSet, builder);
  366. }
  367. count++;
  368. }
  369. // Then files inside images
  370. foreach (var mod in mods.RomfsContainers)
  371. {
  372. Logger.Info?.Print(LogClass.ModLoader, $"Found 'romfs.bin' for Title {titleId:X16}");
  373. using (IFileSystem fs = new RomFsFileSystem(mod.Path.OpenRead().AsStorage()))
  374. {
  375. AddFiles(fs, mod.Name, fileSet, builder);
  376. }
  377. count++;
  378. }
  379. if (fileSet.Count == 0)
  380. {
  381. Logger.Info?.Print(LogClass.ModLoader, "No files found. Using base RomFS");
  382. return baseStorage;
  383. }
  384. Logger.Info?.Print(LogClass.ModLoader, $"Replaced {fileSet.Count} file(s) over {count} mod(s). Processing base storage...");
  385. // And finally, the base romfs
  386. var baseRom = new RomFsFileSystem(baseStorage);
  387. foreach (var entry in baseRom.EnumerateEntries()
  388. .Where(f => f.Type == DirectoryEntryType.File && !fileSet.Contains(f.FullPath))
  389. .OrderBy(f => f.FullPath, StringComparer.Ordinal))
  390. {
  391. using var file = new UniqueRef<IFile>();
  392. baseRom.OpenFile(ref file.Ref(), entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  393. builder.AddFile(entry.FullPath, file.Release());
  394. }
  395. Logger.Info?.Print(LogClass.ModLoader, "Building new RomFS...");
  396. IStorage newStorage = builder.Build();
  397. Logger.Info?.Print(LogClass.ModLoader, "Using modded RomFS");
  398. return newStorage;
  399. }
  400. private static void AddFiles(IFileSystem fs, string modName, HashSet<string> fileSet, RomFsBuilder builder)
  401. {
  402. foreach (var entry in fs.EnumerateEntries()
  403. .Where(f => f.Type == DirectoryEntryType.File)
  404. .OrderBy(f => f.FullPath, StringComparer.Ordinal))
  405. {
  406. using var file = new UniqueRef<IFile>();
  407. fs.OpenFile(ref file.Ref(), entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  408. if (fileSet.Add(entry.FullPath))
  409. {
  410. builder.AddFile(entry.FullPath, file.Release());
  411. }
  412. else
  413. {
  414. Logger.Warning?.Print(LogClass.ModLoader, $" Skipped duplicate file '{entry.FullPath}' from '{modName}'", "ApplyRomFsMods");
  415. }
  416. }
  417. }
  418. internal bool ReplaceExefsPartition(ulong titleId, ref IFileSystem exefs)
  419. {
  420. if (!AppMods.TryGetValue(titleId, out ModCache mods) || mods.ExefsContainers.Count == 0)
  421. {
  422. return false;
  423. }
  424. if (mods.ExefsContainers.Count > 1)
  425. {
  426. Logger.Warning?.Print(LogClass.ModLoader, "Multiple ExeFS partition replacements detected");
  427. }
  428. Logger.Info?.Print(LogClass.ModLoader, $"Using replacement ExeFS partition");
  429. exefs = new PartitionFileSystem(mods.ExefsContainers[0].Path.OpenRead().AsStorage());
  430. return true;
  431. }
  432. public struct ModLoadResult
  433. {
  434. public BitVector32 Stubs;
  435. public BitVector32 Replaces;
  436. public MetaLoader Npdm;
  437. public bool Modified => (Stubs.Data | Replaces.Data) != 0;
  438. }
  439. internal ModLoadResult ApplyExefsMods(ulong titleId, NsoExecutable[] nsos)
  440. {
  441. ModLoadResult modLoadResult = new ModLoadResult
  442. {
  443. Stubs = new BitVector32(),
  444. Replaces = new BitVector32()
  445. };
  446. if (!AppMods.TryGetValue(titleId, out ModCache mods) || mods.ExefsDirs.Count == 0)
  447. {
  448. return modLoadResult;
  449. }
  450. if (nsos.Length != ApplicationLoader.ExeFsPrefixes.Length)
  451. {
  452. throw new ArgumentOutOfRangeException("NSO Count is incorrect");
  453. }
  454. var exeMods = mods.ExefsDirs;
  455. foreach (var mod in exeMods)
  456. {
  457. for (int i = 0; i < ApplicationLoader.ExeFsPrefixes.Length; ++i)
  458. {
  459. var nsoName = ApplicationLoader.ExeFsPrefixes[i];
  460. FileInfo nsoFile = new FileInfo(Path.Combine(mod.Path.FullName, nsoName));
  461. if (nsoFile.Exists)
  462. {
  463. if (modLoadResult.Replaces[1 << i])
  464. {
  465. Logger.Warning?.Print(LogClass.ModLoader, $"Multiple replacements to '{nsoName}'");
  466. continue;
  467. }
  468. modLoadResult.Replaces[1 << i] = true;
  469. nsos[i] = new NsoExecutable(nsoFile.OpenRead().AsStorage(), nsoName);
  470. Logger.Info?.Print(LogClass.ModLoader, $"NSO '{nsoName}' replaced");
  471. }
  472. modLoadResult.Stubs[1 << i] |= File.Exists(Path.Combine(mod.Path.FullName, nsoName + StubExtension));
  473. }
  474. FileInfo npdmFile = new FileInfo(Path.Combine(mod.Path.FullName, "main.npdm"));
  475. if (npdmFile.Exists)
  476. {
  477. if (modLoadResult.Npdm != null)
  478. {
  479. Logger.Warning?.Print(LogClass.ModLoader, "Multiple replacements to 'main.npdm'");
  480. continue;
  481. }
  482. modLoadResult.Npdm = new MetaLoader();
  483. modLoadResult.Npdm.Load(File.ReadAllBytes(npdmFile.FullName));
  484. Logger.Info?.Print(LogClass.ModLoader, "main.npdm replaced");
  485. }
  486. }
  487. for (int i = ApplicationLoader.ExeFsPrefixes.Length - 1; i >= 0; --i)
  488. {
  489. if (modLoadResult.Stubs[1 << i] && !modLoadResult.Replaces[1 << i]) // Prioritizes replacements over stubs
  490. {
  491. Logger.Info?.Print(LogClass.ModLoader, $" NSO '{nsos[i].Name}' stubbed");
  492. nsos[i] = null;
  493. }
  494. }
  495. return modLoadResult;
  496. }
  497. internal void ApplyNroPatches(NroExecutable nro)
  498. {
  499. var nroPatches = Patches.NroPatches;
  500. if (nroPatches.Count == 0) return;
  501. // NRO patches aren't offset relative to header unlike NSO
  502. // according to Atmosphere's ro patcher module
  503. ApplyProgramPatches(nroPatches, 0, nro);
  504. }
  505. internal bool ApplyNsoPatches(ulong titleId, params IExecutable[] programs)
  506. {
  507. IEnumerable<Mod<DirectoryInfo>> nsoMods = Patches.NsoPatches;
  508. if (AppMods.TryGetValue(titleId, out ModCache mods))
  509. {
  510. nsoMods = nsoMods.Concat(mods.ExefsDirs);
  511. }
  512. // NSO patches are created with offset 0 according to Atmosphere's patcher module
  513. // But `Program` doesn't contain the header which is 0x100 bytes. So, we adjust for that here
  514. return ApplyProgramPatches(nsoMods, 0x100, programs);
  515. }
  516. internal void LoadCheats(ulong titleId, ProcessTamperInfo tamperInfo, TamperMachine tamperMachine)
  517. {
  518. if (tamperInfo == null || tamperInfo.BuildIds == null || tamperInfo.CodeAddresses == null)
  519. {
  520. Logger.Error?.Print(LogClass.ModLoader, "Unable to install cheat because the associated process is invalid");
  521. return;
  522. }
  523. Logger.Info?.Print(LogClass.ModLoader, $"Build ids found for title {titleId:X16}:\n {String.Join("\n ", tamperInfo.BuildIds)}");
  524. if (!AppMods.TryGetValue(titleId, out ModCache mods) || mods.Cheats.Count == 0)
  525. {
  526. return;
  527. }
  528. var cheats = mods.Cheats;
  529. var processExes = tamperInfo.BuildIds.Zip(tamperInfo.CodeAddresses, (k, v) => new { k, v })
  530. .ToDictionary(x => x.k.Substring(0, Math.Min(Cheat.CheatIdSize, x.k.Length)), x => x.v);
  531. foreach (var cheat in cheats)
  532. {
  533. string cheatId = Path.GetFileNameWithoutExtension(cheat.Path.Name).ToUpper();
  534. if (!processExes.TryGetValue(cheatId, out ulong exeAddress))
  535. {
  536. Logger.Warning?.Print(LogClass.ModLoader, $"Skipping cheat '{cheat.Name}' because no executable matches its BuildId {cheatId} (check if the game title and version are correct)");
  537. continue;
  538. }
  539. Logger.Info?.Print(LogClass.ModLoader, $"Installing cheat '{cheat.Name}'");
  540. tamperMachine.InstallAtmosphereCheat(cheat.Name, cheatId, cheat.Instructions, tamperInfo, exeAddress);
  541. }
  542. EnableCheats(titleId, tamperMachine);
  543. }
  544. internal void EnableCheats(ulong titleId, TamperMachine tamperMachine)
  545. {
  546. var contentDirectory = FindTitleDir(new DirectoryInfo(Path.Combine(GetModsBasePath(), AmsContentsDir)), $"{titleId:x16}");
  547. string enabledCheatsPath = Path.Combine(contentDirectory.FullName, CheatDir, "enabled.txt");
  548. if (File.Exists(enabledCheatsPath))
  549. {
  550. tamperMachine.EnableCheats(File.ReadAllLines(enabledCheatsPath));
  551. }
  552. }
  553. private static bool ApplyProgramPatches(IEnumerable<Mod<DirectoryInfo>> mods, int protectedOffset, params IExecutable[] programs)
  554. {
  555. int count = 0;
  556. MemPatch[] patches = new MemPatch[programs.Length];
  557. for (int i = 0; i < patches.Length; ++i)
  558. {
  559. patches[i] = new MemPatch();
  560. }
  561. var buildIds = programs.Select(p => p switch
  562. {
  563. NsoExecutable nso => BitConverter.ToString(nso.BuildId.ItemsRo.ToArray()).Replace("-", "").TrimEnd('0'),
  564. NroExecutable nro => BitConverter.ToString(nro.Header.BuildId).Replace("-", "").TrimEnd('0'),
  565. _ => string.Empty
  566. }).ToList();
  567. int GetIndex(string buildId) => buildIds.FindIndex(id => id == buildId); // O(n) but list is small
  568. // Collect patches
  569. foreach (var mod in mods)
  570. {
  571. var patchDir = mod.Path;
  572. foreach (var patchFile in patchDir.EnumerateFiles())
  573. {
  574. if (StrEquals(".ips", patchFile.Extension)) // IPS|IPS32
  575. {
  576. string filename = Path.GetFileNameWithoutExtension(patchFile.FullName).Split('.')[0];
  577. string buildId = filename.TrimEnd('0');
  578. int index = GetIndex(buildId);
  579. if (index == -1)
  580. {
  581. continue;
  582. }
  583. Logger.Info?.Print(LogClass.ModLoader, $"Matching IPS patch '{patchFile.Name}' in '{mod.Name}' bid={buildId}");
  584. using var fs = patchFile.OpenRead();
  585. using var reader = new BinaryReader(fs);
  586. var patcher = new IpsPatcher(reader);
  587. patcher.AddPatches(patches[index]);
  588. }
  589. else if (StrEquals(".pchtxt", patchFile.Extension)) // IPSwitch
  590. {
  591. using var fs = patchFile.OpenRead();
  592. using var reader = new StreamReader(fs);
  593. var patcher = new IPSwitchPatcher(reader);
  594. int index = GetIndex(patcher.BuildId);
  595. if (index == -1)
  596. {
  597. continue;
  598. }
  599. Logger.Info?.Print(LogClass.ModLoader, $"Matching IPSwitch patch '{patchFile.Name}' in '{mod.Name}' bid={patcher.BuildId}");
  600. patcher.AddPatches(patches[index]);
  601. }
  602. }
  603. }
  604. // Apply patches
  605. for (int i = 0; i < programs.Length; ++i)
  606. {
  607. count += patches[i].Patch(programs[i].Program, protectedOffset);
  608. }
  609. return count > 0;
  610. }
  611. }
  612. }