ModLoader.cs 27 KB

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