ModLoader.cs 20 KB

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