ModLoader.cs 28 KB

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