ModLoader.cs 28 KB

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