ModLoader.cs 20 KB

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