ModLoader.cs 21 KB

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