ModLoader.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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. internal bool Initialized { get; set; }
  61. public PatchCache()
  62. {
  63. NsoPatches = new List<Mod<DirectoryInfo>>();
  64. NroPatches = new List<Mod<DirectoryInfo>>();
  65. KipPatches = new List<Mod<DirectoryInfo>>();
  66. Initialized = false;
  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)
  118. {
  119. if (cache.Initialized || !patchDir.Exists) 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 {((titleId & 0x1000) != 0 ? "DLC" : "Title")} {titleId:X16}");
  182. var titleDir = FindTitleDir(contentsDir, $"{titleId:x16}");
  183. if (titleDir != null)
  184. {
  185. QueryTitleDir(mods, titleDir);
  186. }
  187. }
  188. // Assumes searchDirPaths don't overlap
  189. public static void CollectMods(Dictionary<ulong, ModCache> modCaches, PatchCache patches, params string[] searchDirPaths)
  190. {
  191. static bool IsPatchesDir(string name) => StrEquals(AmsNsoPatchDir, name) ||
  192. StrEquals(AmsNroPatchDir, name) ||
  193. StrEquals(AmsKipPatchDir, name);
  194. static bool IsContentsDir(string name) => StrEquals(AmsContentsDir, name);
  195. static bool TryQuery(DirectoryInfo searchDir, PatchCache patches, Dictionary<ulong, ModCache> modCaches)
  196. {
  197. if (IsContentsDir(searchDir.Name))
  198. {
  199. foreach (var (titleId, cache) in modCaches)
  200. {
  201. QueryContentsDir(cache, searchDir, titleId);
  202. }
  203. return true;
  204. }
  205. else if (IsPatchesDir(searchDir.Name))
  206. {
  207. QueryPatchDirs(patches, searchDir);
  208. return true;
  209. }
  210. return false;
  211. }
  212. foreach (var path in searchDirPaths)
  213. {
  214. var searchDir = new DirectoryInfo(path);
  215. if (!searchDir.Exists)
  216. {
  217. Logger.Warning?.Print(LogClass.ModLoader, $"Mod Search Dir '{searchDir.FullName}' doesn't exist");
  218. continue;
  219. }
  220. if (!TryQuery(searchDir, patches, modCaches))
  221. {
  222. foreach (var subdir in searchDir.EnumerateDirectories())
  223. {
  224. TryQuery(subdir, patches, modCaches);
  225. }
  226. }
  227. }
  228. patches.Initialized = true;
  229. }
  230. public void CollectMods(IEnumerable<ulong> titles, params string[] searchDirPaths)
  231. {
  232. Clear();
  233. foreach (ulong titleId in titles)
  234. {
  235. AppMods[titleId] = new ModCache();
  236. }
  237. CollectMods(AppMods, Patches, searchDirPaths);
  238. }
  239. internal IStorage ApplyRomFsMods(ulong titleId, IStorage baseStorage)
  240. {
  241. if (!AppMods.TryGetValue(titleId, out ModCache mods) || mods.RomfsDirs.Count + mods.RomfsContainers.Count == 0)
  242. {
  243. return baseStorage;
  244. }
  245. var fileSet = new HashSet<string>();
  246. var builder = new RomFsBuilder();
  247. int count = 0;
  248. Logger.Info?.Print(LogClass.ModLoader, $"Applying RomFS mods for Title {titleId:X16}");
  249. // Prioritize loose files first
  250. foreach (var mod in mods.RomfsDirs)
  251. {
  252. using (IFileSystem fs = new LocalFileSystem(mod.Path.FullName))
  253. {
  254. AddFiles(fs, mod.Name, fileSet, builder);
  255. }
  256. count++;
  257. }
  258. // Then files inside images
  259. foreach (var mod in mods.RomfsContainers)
  260. {
  261. Logger.Info?.Print(LogClass.ModLoader, $"Found 'romfs.bin' for Title {titleId:X16}");
  262. using (IFileSystem fs = new RomFsFileSystem(mod.Path.OpenRead().AsStorage()))
  263. {
  264. AddFiles(fs, mod.Name, fileSet, builder);
  265. }
  266. count++;
  267. }
  268. if (fileSet.Count == 0)
  269. {
  270. Logger.Info?.Print(LogClass.ModLoader, "No files found. Using base RomFS");
  271. return baseStorage;
  272. }
  273. Logger.Info?.Print(LogClass.ModLoader, $"Replaced {fileSet.Count} file(s) over {count} mod(s). Processing base storage...");
  274. // And finally, the base romfs
  275. var baseRom = new RomFsFileSystem(baseStorage);
  276. foreach (var entry in baseRom.EnumerateEntries()
  277. .Where(f => f.Type == DirectoryEntryType.File && !fileSet.Contains(f.FullPath))
  278. .OrderBy(f => f.FullPath, StringComparer.Ordinal))
  279. {
  280. baseRom.OpenFile(out IFile file, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  281. builder.AddFile(entry.FullPath, file);
  282. }
  283. Logger.Info?.Print(LogClass.ModLoader, "Building new RomFS...");
  284. IStorage newStorage = builder.Build();
  285. Logger.Info?.Print(LogClass.ModLoader, "Using modded RomFS");
  286. return newStorage;
  287. }
  288. private static void AddFiles(IFileSystem fs, string modName, HashSet<string> fileSet, RomFsBuilder builder)
  289. {
  290. foreach (var entry in fs.EnumerateEntries()
  291. .Where(f => f.Type == DirectoryEntryType.File)
  292. .OrderBy(f => f.FullPath, StringComparer.Ordinal))
  293. {
  294. fs.OpenFile(out IFile file, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  295. if (fileSet.Add(entry.FullPath))
  296. {
  297. builder.AddFile(entry.FullPath, file);
  298. }
  299. else
  300. {
  301. Logger.Warning?.Print(LogClass.ModLoader, $" Skipped duplicate file '{entry.FullPath}' from '{modName}'", "ApplyRomFsMods");
  302. }
  303. }
  304. }
  305. internal bool ReplaceExefsPartition(ulong titleId, ref IFileSystem exefs)
  306. {
  307. if (!AppMods.TryGetValue(titleId, out ModCache mods) || mods.ExefsContainers.Count == 0)
  308. {
  309. return false;
  310. }
  311. if (mods.ExefsContainers.Count > 1)
  312. {
  313. Logger.Warning?.Print(LogClass.ModLoader, "Multiple ExeFS partition replacements detected");
  314. }
  315. Logger.Info?.Print(LogClass.ModLoader, $"Using replacement ExeFS partition");
  316. exefs = new PartitionFileSystem(mods.ExefsContainers[0].Path.OpenRead().AsStorage());
  317. return true;
  318. }
  319. public struct ModLoadResult
  320. {
  321. public BitVector32 Stubs;
  322. public BitVector32 Replaces;
  323. public Npdm Npdm;
  324. public bool Modified => (Stubs.Data | Replaces.Data) != 0;
  325. }
  326. internal ModLoadResult ApplyExefsMods(ulong titleId, NsoExecutable[] nsos)
  327. {
  328. ModLoadResult modLoadResult = new ModLoadResult
  329. {
  330. Stubs = new BitVector32(),
  331. Replaces = new BitVector32()
  332. };
  333. if (!AppMods.TryGetValue(titleId, out ModCache mods) || mods.ExefsDirs.Count == 0)
  334. {
  335. return modLoadResult;
  336. }
  337. if (nsos.Length != ApplicationLoader.ExeFsPrefixes.Length)
  338. {
  339. throw new ArgumentOutOfRangeException("NSO Count is incorrect");
  340. }
  341. var exeMods = mods.ExefsDirs;
  342. foreach (var mod in exeMods)
  343. {
  344. for (int i = 0; i < ApplicationLoader.ExeFsPrefixes.Length; ++i)
  345. {
  346. var nsoName = ApplicationLoader.ExeFsPrefixes[i];
  347. FileInfo nsoFile = new FileInfo(Path.Combine(mod.Path.FullName, nsoName));
  348. if (nsoFile.Exists)
  349. {
  350. if (modLoadResult.Replaces[1 << i])
  351. {
  352. Logger.Warning?.Print(LogClass.ModLoader, $"Multiple replacements to '{nsoName}'");
  353. continue;
  354. }
  355. modLoadResult.Replaces[1 << i] = true;
  356. nsos[i] = new NsoExecutable(nsoFile.OpenRead().AsStorage(), nsoName);
  357. Logger.Info?.Print(LogClass.ModLoader, $"NSO '{nsoName}' replaced");
  358. }
  359. modLoadResult.Stubs[1 << i] |= File.Exists(Path.Combine(mod.Path.FullName, nsoName + StubExtension));
  360. }
  361. FileInfo npdmFile = new FileInfo(Path.Combine(mod.Path.FullName, "main.npdm"));
  362. if (npdmFile.Exists)
  363. {
  364. if (modLoadResult.Npdm != null)
  365. {
  366. Logger.Warning?.Print(LogClass.ModLoader, "Multiple replacements to 'main.npdm'");
  367. continue;
  368. }
  369. modLoadResult.Npdm = new Npdm(npdmFile.OpenRead());
  370. Logger.Info?.Print(LogClass.ModLoader, $"main.npdm replaced");
  371. }
  372. }
  373. for (int i = ApplicationLoader.ExeFsPrefixes.Length - 1; i >= 0; --i)
  374. {
  375. if (modLoadResult.Stubs[1 << i] && !modLoadResult.Replaces[1 << i]) // Prioritizes replacements over stubs
  376. {
  377. Logger.Info?.Print(LogClass.ModLoader, $" NSO '{nsos[i].Name}' stubbed");
  378. nsos[i] = null;
  379. }
  380. }
  381. return modLoadResult;
  382. }
  383. internal void ApplyNroPatches(NroExecutable nro)
  384. {
  385. var nroPatches = Patches.NroPatches;
  386. if (nroPatches.Count == 0) return;
  387. // NRO patches aren't offset relative to header unlike NSO
  388. // according to Atmosphere's ro patcher module
  389. ApplyProgramPatches(nroPatches, 0, nro);
  390. }
  391. internal bool ApplyNsoPatches(ulong titleId, params IExecutable[] programs)
  392. {
  393. IEnumerable<Mod<DirectoryInfo>> nsoMods = Patches.NsoPatches;
  394. if (AppMods.TryGetValue(titleId, out ModCache mods))
  395. {
  396. nsoMods = nsoMods.Concat(mods.ExefsDirs);
  397. }
  398. // NSO patches are created with offset 0 according to Atmosphere's patcher module
  399. // But `Program` doesn't contain the header which is 0x100 bytes. So, we adjust for that here
  400. return ApplyProgramPatches(nsoMods, 0x100, programs);
  401. }
  402. private static bool ApplyProgramPatches(IEnumerable<Mod<DirectoryInfo>> mods, int protectedOffset, params IExecutable[] programs)
  403. {
  404. int count = 0;
  405. MemPatch[] patches = new MemPatch[programs.Length];
  406. for (int i = 0; i < patches.Length; ++i)
  407. {
  408. patches[i] = new MemPatch();
  409. }
  410. var buildIds = programs.Select(p => p switch
  411. {
  412. NsoExecutable nso => BitConverter.ToString(nso.BuildId.Bytes.ToArray()).Replace("-", "").TrimEnd('0'),
  413. NroExecutable nro => BitConverter.ToString(nro.Header.BuildId).Replace("-", "").TrimEnd('0'),
  414. _ => string.Empty
  415. }).ToList();
  416. int GetIndex(string buildId) => buildIds.FindIndex(id => id == buildId); // O(n) but list is small
  417. // Collect patches
  418. foreach (var mod in mods)
  419. {
  420. var patchDir = mod.Path;
  421. foreach (var patchFile in patchDir.EnumerateFiles())
  422. {
  423. if (StrEquals(".ips", patchFile.Extension)) // IPS|IPS32
  424. {
  425. string filename = Path.GetFileNameWithoutExtension(patchFile.FullName).Split('.')[0];
  426. string buildId = filename.TrimEnd('0');
  427. int index = GetIndex(buildId);
  428. if (index == -1)
  429. {
  430. continue;
  431. }
  432. Logger.Info?.Print(LogClass.ModLoader, $"Matching IPS patch '{patchFile.Name}' in '{mod.Name}' bid={buildId}");
  433. using var fs = patchFile.OpenRead();
  434. using var reader = new BinaryReader(fs);
  435. var patcher = new IpsPatcher(reader);
  436. patcher.AddPatches(patches[index]);
  437. }
  438. else if (StrEquals(".pchtxt", patchFile.Extension)) // IPSwitch
  439. {
  440. using var fs = patchFile.OpenRead();
  441. using var reader = new StreamReader(fs);
  442. var patcher = new IPSwitchPatcher(reader);
  443. int index = GetIndex(patcher.BuildId);
  444. if (index == -1)
  445. {
  446. continue;
  447. }
  448. Logger.Info?.Print(LogClass.ModLoader, $"Matching IPSwitch patch '{patchFile.Name}' in '{mod.Name}' bid={patcher.BuildId}");
  449. patcher.AddPatches(patches[index]);
  450. }
  451. }
  452. }
  453. // Apply patches
  454. for (int i = 0; i < programs.Length; ++i)
  455. {
  456. count += patches[i].Patch(programs[i].Program, protectedOffset);
  457. }
  458. return count > 0;
  459. }
  460. }
  461. }