ModLoader.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. using LibHac.Common;
  2. using LibHac.Fs;
  3. using LibHac.FsSystem;
  4. using LibHac.FsSystem.RomFs;
  5. using Ryujinx.Common.Configuration;
  6. using Ryujinx.Common.Logging;
  7. using Ryujinx.HLE.Loaders.Mods;
  8. using Ryujinx.HLE.Loaders.Executables;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Collections.Specialized;
  12. using System.Linq;
  13. using System.IO;
  14. namespace Ryujinx.HLE.HOS
  15. {
  16. public class ModLoader
  17. {
  18. private const string RomfsDir = "romfs";
  19. private const string ExefsDir = "exefs";
  20. private const string RomfsContainer = "romfs.bin";
  21. private const string ExefsContainer = "exefs.nsp";
  22. private const string StubExtension = ".stub";
  23. private const string AmsContentsDir = "contents";
  24. private const string AmsNsoPatchDir = "exefs_patches";
  25. private const string AmsNroPatchDir = "nro_patches";
  26. private const string AmsKipPatchDir = "kip_patches";
  27. public struct Mod<T> where T : FileSystemInfo
  28. {
  29. public readonly string Name;
  30. public readonly T Path;
  31. public Mod(string name, T path)
  32. {
  33. Name = name;
  34. Path = path;
  35. }
  36. }
  37. // Title dependent mods
  38. public class ModCache
  39. {
  40. public List<Mod<FileInfo>> RomfsContainers { get; }
  41. public List<Mod<FileInfo>> ExefsContainers { get; }
  42. public List<Mod<DirectoryInfo>> RomfsDirs { get; }
  43. public List<Mod<DirectoryInfo>> ExefsDirs { get; }
  44. public ModCache()
  45. {
  46. RomfsContainers = new List<Mod<FileInfo>>();
  47. ExefsContainers = new List<Mod<FileInfo>>();
  48. RomfsDirs = new List<Mod<DirectoryInfo>>();
  49. ExefsDirs = new List<Mod<DirectoryInfo>>();
  50. }
  51. }
  52. // Title independent mods
  53. public class PatchCache
  54. {
  55. public List<Mod<DirectoryInfo>> NsoPatches { get; }
  56. public List<Mod<DirectoryInfo>> NroPatches { get; }
  57. public List<Mod<DirectoryInfo>> KipPatches { get; }
  58. public HashSet<string> SearchedDirs { get; }
  59. public PatchCache()
  60. {
  61. NsoPatches = new List<Mod<DirectoryInfo>>();
  62. NroPatches = new List<Mod<DirectoryInfo>>();
  63. KipPatches = new List<Mod<DirectoryInfo>>();
  64. SearchedDirs = new HashSet<string>();
  65. }
  66. }
  67. public Dictionary<ulong, ModCache> AppMods; // key is TitleId
  68. public PatchCache Patches;
  69. private static readonly EnumerationOptions _dirEnumOptions;
  70. static ModLoader()
  71. {
  72. _dirEnumOptions = new EnumerationOptions
  73. {
  74. MatchCasing = MatchCasing.CaseInsensitive,
  75. MatchType = MatchType.Simple,
  76. RecurseSubdirectories = false,
  77. ReturnSpecialDirectories = false
  78. };
  79. }
  80. public ModLoader()
  81. {
  82. AppMods = new Dictionary<ulong, ModCache>();
  83. Patches = new PatchCache();
  84. }
  85. public void Clear()
  86. {
  87. AppMods.Clear();
  88. Patches = new PatchCache();
  89. }
  90. private static bool StrEquals(string s1, string s2) => string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase);
  91. public string GetModsBasePath() => EnsureBaseDirStructure(AppDataManager.GetModsPath());
  92. private string EnsureBaseDirStructure(string modsBasePath)
  93. {
  94. var modsDir = new DirectoryInfo(modsBasePath);
  95. modsDir.CreateSubdirectory(AmsContentsDir);
  96. modsDir.CreateSubdirectory(AmsNsoPatchDir);
  97. modsDir.CreateSubdirectory(AmsNroPatchDir);
  98. // modsDir.CreateSubdirectory(AmsKipPatchDir); // uncomment when KIPs are supported
  99. return modsDir.FullName;
  100. }
  101. private static DirectoryInfo FindTitleDir(DirectoryInfo contentsDir, string titleId)
  102. => contentsDir.EnumerateDirectories($"{titleId}*", _dirEnumOptions).FirstOrDefault();
  103. public string GetTitleDir(string modsBasePath, string titleId)
  104. {
  105. var contentsDir = new DirectoryInfo(Path.Combine(modsBasePath, AmsContentsDir));
  106. var titleModsPath = FindTitleDir(contentsDir, titleId);
  107. if (titleModsPath == null)
  108. {
  109. Logger.Info?.Print(LogClass.ModLoader, $"Creating mods dir for Title {titleId.ToUpper()}");
  110. titleModsPath = contentsDir.CreateSubdirectory(titleId);
  111. }
  112. return titleModsPath.FullName;
  113. }
  114. // Static Query Methods
  115. public static void QueryPatchDirs(PatchCache cache, DirectoryInfo patchDir, DirectoryInfo searchDir)
  116. {
  117. if (!patchDir.Exists || cache.SearchedDirs.Contains(searchDir.FullName)) return;
  118. var patches = cache.KipPatches;
  119. string type = null;
  120. if (StrEquals(AmsNsoPatchDir, patchDir.Name)) { patches = cache.NsoPatches; type = "NSO"; }
  121. else if (StrEquals(AmsNroPatchDir, patchDir.Name)) { patches = cache.NroPatches; type = "NRO"; }
  122. else if (StrEquals(AmsKipPatchDir, patchDir.Name)) { patches = cache.KipPatches; type = "KIP"; }
  123. else return;
  124. foreach (var modDir in patchDir.EnumerateDirectories())
  125. {
  126. patches.Add(new Mod<DirectoryInfo>(modDir.Name, modDir));
  127. Logger.Info?.Print(LogClass.ModLoader, $"Found {type} patch '{modDir.Name}'");
  128. }
  129. }
  130. public static void QueryTitleDir(ModCache mods, DirectoryInfo titleDir)
  131. {
  132. if (!titleDir.Exists) return;
  133. var fsFile = new FileInfo(Path.Combine(titleDir.FullName, RomfsContainer));
  134. if (fsFile.Exists)
  135. {
  136. mods.RomfsContainers.Add(new Mod<FileInfo>($"<{titleDir.Name} RomFs>", fsFile));
  137. }
  138. fsFile = new FileInfo(Path.Combine(titleDir.FullName, ExefsContainer));
  139. if (fsFile.Exists)
  140. {
  141. mods.ExefsContainers.Add(new Mod<FileInfo>($"<{titleDir.Name} ExeFs>", fsFile));
  142. }
  143. System.Text.StringBuilder types = new System.Text.StringBuilder(5);
  144. foreach (var modDir in titleDir.EnumerateDirectories())
  145. {
  146. types.Clear();
  147. Mod<DirectoryInfo> mod = new Mod<DirectoryInfo>("", null);
  148. if (StrEquals(RomfsDir, modDir.Name))
  149. {
  150. mods.RomfsDirs.Add(mod = new Mod<DirectoryInfo>($"<{titleDir.Name} RomFs>", modDir));
  151. types.Append('R');
  152. }
  153. else if (StrEquals(ExefsDir, modDir.Name))
  154. {
  155. mods.ExefsDirs.Add(mod = new Mod<DirectoryInfo>($"<{titleDir.Name} ExeFs>", modDir));
  156. types.Append('E');
  157. }
  158. else
  159. {
  160. var romfs = new DirectoryInfo(Path.Combine(modDir.FullName, RomfsDir));
  161. var exefs = new DirectoryInfo(Path.Combine(modDir.FullName, ExefsDir));
  162. if (romfs.Exists)
  163. {
  164. mods.RomfsDirs.Add(mod = new Mod<DirectoryInfo>(modDir.Name, romfs));
  165. types.Append('R');
  166. }
  167. if (exefs.Exists)
  168. {
  169. mods.ExefsDirs.Add(mod = new Mod<DirectoryInfo>(modDir.Name, exefs));
  170. types.Append('E');
  171. }
  172. }
  173. if (types.Length > 0) Logger.Info?.Print(LogClass.ModLoader, $"Found mod '{mod.Name}' [{types}]");
  174. }
  175. }
  176. public static void QueryContentsDir(ModCache mods, DirectoryInfo contentsDir, ulong titleId)
  177. {
  178. if (!contentsDir.Exists) return;
  179. Logger.Info?.Print(LogClass.ModLoader, $"Searching mods for Title {titleId:X16}");
  180. var titleDir = FindTitleDir(contentsDir, $"{titleId:x16}");
  181. if (titleDir != null)
  182. {
  183. QueryTitleDir(mods, titleDir);
  184. }
  185. }
  186. public static void CollectMods(ModCache mods, PatchCache patches, ulong? titleId, params string[] searchDirPaths)
  187. {
  188. static bool IsPatchesDir(string name) => StrEquals(AmsNsoPatchDir, name) ||
  189. StrEquals(AmsNroPatchDir, name) ||
  190. StrEquals(AmsKipPatchDir, name);
  191. static bool TryQuery(ModCache mods, PatchCache patches, ulong? titleId, DirectoryInfo dir, DirectoryInfo searchDir)
  192. {
  193. if (StrEquals(AmsContentsDir, dir.Name))
  194. {
  195. if (titleId.HasValue)
  196. {
  197. QueryContentsDir(mods, dir, (ulong)titleId);
  198. return true;
  199. }
  200. }
  201. else if (IsPatchesDir(dir.Name))
  202. {
  203. QueryPatchDirs(patches, dir, searchDir);
  204. return true;
  205. }
  206. return false;
  207. }
  208. foreach (var path in searchDirPaths)
  209. {
  210. var dir = new DirectoryInfo(path);
  211. if (!dir.Exists)
  212. {
  213. Logger.Warning?.Print(LogClass.ModLoader, $"Mod Search Dir '{dir.FullName}' doesn't exist");
  214. continue;
  215. }
  216. if (!TryQuery(mods, patches, titleId, dir, dir))
  217. {
  218. foreach (var subdir in dir.EnumerateDirectories())
  219. {
  220. TryQuery(mods, patches, titleId, subdir, dir);
  221. }
  222. }
  223. patches.SearchedDirs.Add(dir.FullName);
  224. }
  225. }
  226. public void CollectMods(ulong titleId, params string[] searchDirPaths)
  227. {
  228. if (!AppMods.TryGetValue(titleId, out ModCache mods))
  229. {
  230. mods = new ModCache();
  231. AppMods[titleId] = mods;
  232. }
  233. CollectMods(mods, Patches, titleId, searchDirPaths);
  234. }
  235. internal IStorage ApplyRomFsMods(ulong titleId, IStorage baseStorage)
  236. {
  237. if (!AppMods.TryGetValue(titleId, out ModCache mods) || mods.RomfsDirs.Count + mods.RomfsContainers.Count == 0)
  238. {
  239. return baseStorage;
  240. }
  241. var fileSet = new HashSet<string>();
  242. var builder = new RomFsBuilder();
  243. int count = 0;
  244. Logger.Info?.Print(LogClass.ModLoader, $"Applying RomFS mods for Title {titleId:X16}");
  245. // Prioritize loose files first
  246. foreach (var mod in mods.RomfsDirs)
  247. {
  248. using (IFileSystem fs = new LocalFileSystem(mod.Path.FullName))
  249. {
  250. AddFiles(fs, mod.Name, fileSet, builder);
  251. }
  252. count++;
  253. }
  254. // Then files inside images
  255. foreach (var mod in mods.RomfsContainers)
  256. {
  257. Logger.Info?.Print(LogClass.ModLoader, $"Found 'romfs.bin' for Title {titleId:X16}");
  258. using (IFileSystem fs = new RomFsFileSystem(mod.Path.OpenRead().AsStorage()))
  259. {
  260. AddFiles(fs, mod.Name, fileSet, builder);
  261. }
  262. count++;
  263. }
  264. if (fileSet.Count == 0)
  265. {
  266. Logger.Info?.Print(LogClass.ModLoader, "No files found. Using base RomFS");
  267. return baseStorage;
  268. }
  269. Logger.Info?.Print(LogClass.ModLoader, $"Replaced {fileSet.Count} file(s) over {count} mod(s). Processing base storage...");
  270. // And finally, the base romfs
  271. var baseRom = new RomFsFileSystem(baseStorage);
  272. foreach (var entry in baseRom.EnumerateEntries()
  273. .Where(f => f.Type == DirectoryEntryType.File && !fileSet.Contains(f.FullPath))
  274. .OrderBy(f => f.FullPath, StringComparer.Ordinal))
  275. {
  276. baseRom.OpenFile(out IFile file, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  277. builder.AddFile(entry.FullPath, file);
  278. }
  279. Logger.Info?.Print(LogClass.ModLoader, "Building new RomFS...");
  280. IStorage newStorage = builder.Build();
  281. Logger.Info?.Print(LogClass.ModLoader, "Using modded RomFS");
  282. return newStorage;
  283. }
  284. private static void AddFiles(IFileSystem fs, string modName, HashSet<string> fileSet, RomFsBuilder builder)
  285. {
  286. foreach (var entry in fs.EnumerateEntries()
  287. .Where(f => f.Type == DirectoryEntryType.File)
  288. .OrderBy(f => f.FullPath, StringComparer.Ordinal))
  289. {
  290. fs.OpenFile(out IFile file, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  291. if (fileSet.Add(entry.FullPath))
  292. {
  293. builder.AddFile(entry.FullPath, file);
  294. }
  295. else
  296. {
  297. Logger.Warning?.Print(LogClass.ModLoader, $" Skipped duplicate file '{entry.FullPath}' from '{modName}'", "ApplyRomFsMods");
  298. }
  299. }
  300. }
  301. internal bool ReplaceExefsPartition(ulong titleId, ref IFileSystem exefs)
  302. {
  303. if (!AppMods.TryGetValue(titleId, out ModCache mods) || mods.ExefsContainers.Count == 0)
  304. {
  305. return false;
  306. }
  307. if (mods.ExefsContainers.Count > 1)
  308. {
  309. Logger.Warning?.Print(LogClass.ModLoader, "Multiple ExeFS partition replacements detected");
  310. }
  311. Logger.Info?.Print(LogClass.ModLoader, $"Using replacement ExeFS partition");
  312. exefs = new PartitionFileSystem(mods.ExefsContainers[0].Path.OpenRead().AsStorage());
  313. return true;
  314. }
  315. internal bool ApplyExefsMods(ulong titleId, List<NsoExecutable> nsos)
  316. {
  317. if (!AppMods.TryGetValue(titleId, out ModCache mods) || mods.ExefsDirs.Count == 0)
  318. {
  319. return false;
  320. }
  321. bool replaced = false;
  322. if (nsos.Count > 32)
  323. {
  324. throw new ArgumentOutOfRangeException("NSO Count is more than 32");
  325. }
  326. var exeMods = mods.ExefsDirs;
  327. BitVector32 stubs = new BitVector32();
  328. BitVector32 repls = new BitVector32();
  329. foreach (var mod in exeMods)
  330. {
  331. for (int i = 0; i < nsos.Count; ++i)
  332. {
  333. var nso = nsos[i];
  334. var nsoName = nso.Name;
  335. FileInfo nsoFile = new FileInfo(Path.Combine(mod.Path.FullName, nsoName));
  336. if (nsoFile.Exists)
  337. {
  338. if (repls[1 << i])
  339. {
  340. Logger.Warning?.Print(LogClass.ModLoader, $"Multiple replacements to '{nsoName}'");
  341. continue;
  342. }
  343. repls[1 << i] = true;
  344. nsos[i] = new NsoExecutable(nsoFile.OpenRead().AsStorage(), nsoName);
  345. Logger.Info?.Print(LogClass.ModLoader, $"NSO '{nsoName}' replaced");
  346. replaced = true;
  347. continue;
  348. }
  349. stubs[1 << i] |= File.Exists(Path.Combine(mod.Path.FullName, nsoName + StubExtension));
  350. }
  351. }
  352. for (int i = nsos.Count - 1; i >= 0; --i)
  353. {
  354. if (stubs[1 << i] && !repls[1 << i]) // Prioritizes replacements over stubs
  355. {
  356. Logger.Info?.Print(LogClass.ModLoader, $" NSO '{nsos[i].Name}' stubbed");
  357. nsos.RemoveAt(i);
  358. replaced = true;
  359. }
  360. }
  361. return replaced;
  362. }
  363. internal void ApplyNroPatches(NroExecutable nro)
  364. {
  365. var nroPatches = Patches.NroPatches;
  366. if (nroPatches.Count == 0) return;
  367. // NRO patches aren't offset relative to header unlike NSO
  368. // according to Atmosphere's ro patcher module
  369. ApplyProgramPatches(nroPatches, 0, nro);
  370. }
  371. internal bool ApplyNsoPatches(ulong titleId, params IExecutable[] programs)
  372. {
  373. IEnumerable<Mod<DirectoryInfo>> nsoMods = Patches.NsoPatches;
  374. if (AppMods.TryGetValue(titleId, out ModCache mods))
  375. {
  376. nsoMods = nsoMods.Concat(mods.ExefsDirs);
  377. }
  378. // NSO patches are created with offset 0 according to Atmosphere's patcher module
  379. // But `Program` doesn't contain the header which is 0x100 bytes. So, we adjust for that here
  380. return ApplyProgramPatches(nsoMods, 0x100, programs);
  381. }
  382. private static bool ApplyProgramPatches(IEnumerable<Mod<DirectoryInfo>> mods, int protectedOffset, params IExecutable[] programs)
  383. {
  384. int count = 0;
  385. MemPatch[] patches = new MemPatch[programs.Length];
  386. for (int i = 0; i < patches.Length; ++i)
  387. {
  388. patches[i] = new MemPatch();
  389. }
  390. var buildIds = programs.Select(p => p switch
  391. {
  392. NsoExecutable nso => BitConverter.ToString(nso.BuildId.Bytes.ToArray()).Replace("-", "").TrimEnd('0'),
  393. NroExecutable nro => BitConverter.ToString(nro.Header.BuildId).Replace("-", "").TrimEnd('0'),
  394. _ => string.Empty
  395. }).ToList();
  396. int GetIndex(string buildId) => buildIds.FindIndex(id => id == buildId); // O(n) but list is small
  397. // Collect patches
  398. foreach (var mod in mods)
  399. {
  400. var patchDir = mod.Path;
  401. foreach (var patchFile in patchDir.EnumerateFiles())
  402. {
  403. if (StrEquals(".ips", patchFile.Extension)) // IPS|IPS32
  404. {
  405. string filename = Path.GetFileNameWithoutExtension(patchFile.FullName).Split('.')[0];
  406. string buildId = filename.TrimEnd('0');
  407. int index = GetIndex(buildId);
  408. if (index == -1)
  409. {
  410. continue;
  411. }
  412. Logger.Info?.Print(LogClass.ModLoader, $"Matching IPS patch '{patchFile.Name}' in '{mod.Name}' bid={buildId}");
  413. using var fs = patchFile.OpenRead();
  414. using var reader = new BinaryReader(fs);
  415. var patcher = new IpsPatcher(reader);
  416. patcher.AddPatches(patches[index]);
  417. }
  418. else if (StrEquals(".pchtxt", patchFile.Extension)) // IPSwitch
  419. {
  420. using var fs = patchFile.OpenRead();
  421. using var reader = new StreamReader(fs);
  422. var patcher = new IPSwitchPatcher(reader);
  423. int index = GetIndex(patcher.BuildId);
  424. if (index == -1)
  425. {
  426. continue;
  427. }
  428. Logger.Info?.Print(LogClass.ModLoader, $"Matching IPSwitch patch '{patchFile.Name}' in '{mod.Name}' bid={patcher.BuildId}");
  429. patcher.AddPatches(patches[index]);
  430. }
  431. }
  432. }
  433. // Apply patches
  434. for (int i = 0; i < programs.Length; ++i)
  435. {
  436. count += patches[i].Patch(programs[i].Program, protectedOffset);
  437. }
  438. return count > 0;
  439. }
  440. }
  441. }