ModLoader.cs 27 KB

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