IRoInterface.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. using LibHac.Tools.FsSystem;
  2. using Ryujinx.Common;
  3. using Ryujinx.Cpu;
  4. using Ryujinx.HLE.HOS.Kernel.Memory;
  5. using Ryujinx.HLE.HOS.Kernel.Process;
  6. using Ryujinx.HLE.Loaders.Executables;
  7. using Ryujinx.Horizon.Common;
  8. using Ryujinx.Memory;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Security.Cryptography;
  14. namespace Ryujinx.HLE.HOS.Services.Ro
  15. {
  16. [Service("ldr:ro")]
  17. [Service("ro:1")] // 7.0.0+
  18. class IRoInterface : DisposableIpcService
  19. {
  20. private const int MaxNrr = 0x40;
  21. private const int MaxNro = 0x40;
  22. private const int MaxMapRetries = 0x200;
  23. private const int GuardPagesSize = 0x4000;
  24. private const uint NrrMagic = 0x3052524E;
  25. private const uint NroMagic = 0x304F524E;
  26. private List<NrrInfo> _nrrInfos;
  27. private List<NroInfo> _nroInfos;
  28. private KProcess _owner;
  29. private IVirtualMemoryManager _ownerMm;
  30. public IRoInterface(ServiceCtx context)
  31. {
  32. _nrrInfos = new List<NrrInfo>(MaxNrr);
  33. _nroInfos = new List<NroInfo>(MaxNro);
  34. _owner = null;
  35. _ownerMm = null;
  36. }
  37. private ResultCode ParseNrr(out NrrInfo nrrInfo, ServiceCtx context, ulong nrrAddress, ulong nrrSize)
  38. {
  39. nrrInfo = null;
  40. if (nrrSize == 0 || nrrAddress + nrrSize <= nrrAddress || (nrrSize & 0xFFF) != 0)
  41. {
  42. return ResultCode.InvalidSize;
  43. }
  44. else if ((nrrAddress & 0xFFF) != 0)
  45. {
  46. return ResultCode.InvalidAddress;
  47. }
  48. NrrHeader header = _owner.CpuMemory.Read<NrrHeader>(nrrAddress);
  49. if (header.Magic != NrrMagic)
  50. {
  51. return ResultCode.InvalidNrr;
  52. }
  53. else if (header.Size != nrrSize)
  54. {
  55. return ResultCode.InvalidSize;
  56. }
  57. List<byte[]> hashes = new List<byte[]>();
  58. for (int i = 0; i < header.HashesCount; i++)
  59. {
  60. byte[] hash = new byte[0x20];
  61. _owner.CpuMemory.Read(nrrAddress + header.HashesOffset + (uint)(i * 0x20), hash);
  62. hashes.Add(hash);
  63. }
  64. nrrInfo = new NrrInfo(nrrAddress, header, hashes);
  65. return ResultCode.Success;
  66. }
  67. public bool IsNroHashPresent(byte[] nroHash)
  68. {
  69. foreach (NrrInfo info in _nrrInfos)
  70. {
  71. foreach (byte[] hash in info.Hashes)
  72. {
  73. if (hash.SequenceEqual(nroHash))
  74. {
  75. return true;
  76. }
  77. }
  78. }
  79. return false;
  80. }
  81. public bool IsNroLoaded(byte[] nroHash)
  82. {
  83. foreach (NroInfo info in _nroInfos)
  84. {
  85. if (info.Hash.SequenceEqual(nroHash))
  86. {
  87. return true;
  88. }
  89. }
  90. return false;
  91. }
  92. public ResultCode ParseNro(out NroInfo res, ServiceCtx context, ulong nroAddress, ulong nroSize, ulong bssAddress, ulong bssSize)
  93. {
  94. res = null;
  95. if (_nroInfos.Count >= MaxNro)
  96. {
  97. return ResultCode.TooManyNro;
  98. }
  99. else if (nroSize == 0 || nroAddress + nroSize <= nroAddress || (nroSize & 0xFFF) != 0)
  100. {
  101. return ResultCode.InvalidSize;
  102. }
  103. else if (bssSize != 0 && bssAddress + bssSize <= bssAddress)
  104. {
  105. return ResultCode.InvalidSize;
  106. }
  107. else if ((nroAddress & 0xFFF) != 0)
  108. {
  109. return ResultCode.InvalidAddress;
  110. }
  111. uint magic = _owner.CpuMemory.Read<uint>(nroAddress + 0x10);
  112. uint nroFileSize = _owner.CpuMemory.Read<uint>(nroAddress + 0x18);
  113. if (magic != NroMagic || nroSize != nroFileSize)
  114. {
  115. return ResultCode.InvalidNro;
  116. }
  117. byte[] nroData = new byte[nroSize];
  118. _owner.CpuMemory.Read(nroAddress, nroData);
  119. MemoryStream stream = new MemoryStream(nroData);
  120. byte[] nroHash = SHA256.HashData(stream);
  121. if (!IsNroHashPresent(nroHash))
  122. {
  123. return ResultCode.NotRegistered;
  124. }
  125. if (IsNroLoaded(nroHash))
  126. {
  127. return ResultCode.AlreadyLoaded;
  128. }
  129. stream.Position = 0;
  130. NroExecutable nro = new NroExecutable(stream.AsStorage(), nroAddress, bssAddress);
  131. // Check if everything is page align.
  132. if ((nro.Text.Length & 0xFFF) != 0 || (nro.Ro.Length & 0xFFF) != 0 ||
  133. (nro.Data.Length & 0xFFF) != 0 || (nro.BssSize & 0xFFF) != 0)
  134. {
  135. return ResultCode.InvalidNro;
  136. }
  137. // Check if everything is contiguous.
  138. if (nro.RoOffset != nro.TextOffset + nro.Text.Length ||
  139. nro.DataOffset != nro.RoOffset + nro.Ro.Length ||
  140. nroFileSize != nro.DataOffset + nro.Data.Length)
  141. {
  142. return ResultCode.InvalidNro;
  143. }
  144. // Check the bss size match.
  145. if ((ulong)nro.BssSize != bssSize)
  146. {
  147. return ResultCode.InvalidNro;
  148. }
  149. uint totalSize = (uint)nro.Text.Length + (uint)nro.Ro.Length + (uint)nro.Data.Length + nro.BssSize;
  150. // Apply patches
  151. context.Device.FileSystem.ModLoader.ApplyNroPatches(nro);
  152. res = new NroInfo(
  153. nro,
  154. nroHash,
  155. nroAddress,
  156. nroSize,
  157. bssAddress,
  158. bssSize,
  159. (ulong)totalSize);
  160. return ResultCode.Success;
  161. }
  162. private ResultCode MapNro(KProcess process, NroInfo info, out ulong nroMappedAddress)
  163. {
  164. KPageTableBase memMgr = process.MemoryManager;
  165. int retryCount = 0;
  166. nroMappedAddress = 0;
  167. while (retryCount++ < MaxMapRetries)
  168. {
  169. ResultCode result = MapCodeMemoryInProcess(process, info.NroAddress, info.NroSize, out nroMappedAddress);
  170. if (result != ResultCode.Success)
  171. {
  172. return result;
  173. }
  174. if (info.BssSize > 0)
  175. {
  176. Result bssMappingResult = memMgr.MapProcessCodeMemory(nroMappedAddress + info.NroSize, info.BssAddress, info.BssSize);
  177. if (bssMappingResult == KernelResult.InvalidMemState)
  178. {
  179. memMgr.UnmapProcessCodeMemory(nroMappedAddress + info.NroSize, info.BssAddress, info.BssSize);
  180. memMgr.UnmapProcessCodeMemory(nroMappedAddress, info.NroAddress, info.NroSize);
  181. continue;
  182. }
  183. else if (bssMappingResult != Result.Success)
  184. {
  185. memMgr.UnmapProcessCodeMemory(nroMappedAddress + info.NroSize, info.BssAddress, info.BssSize);
  186. memMgr.UnmapProcessCodeMemory(nroMappedAddress, info.NroAddress, info.NroSize);
  187. return (ResultCode)bssMappingResult.ErrorCode;
  188. }
  189. }
  190. if (CanAddGuardRegionsInProcess(process, nroMappedAddress, info.TotalSize))
  191. {
  192. return ResultCode.Success;
  193. }
  194. }
  195. return ResultCode.InsufficientAddressSpace;
  196. }
  197. private bool CanAddGuardRegionsInProcess(KProcess process, ulong baseAddress, ulong size)
  198. {
  199. KPageTableBase memMgr = process.MemoryManager;
  200. KMemoryInfo memInfo = memMgr.QueryMemory(baseAddress - 1);
  201. if (memInfo.State == MemoryState.Unmapped && baseAddress - GuardPagesSize >= memInfo.Address)
  202. {
  203. memInfo = memMgr.QueryMemory(baseAddress + size);
  204. if (memInfo.State == MemoryState.Unmapped)
  205. {
  206. return baseAddress + size + GuardPagesSize <= memInfo.Address + memInfo.Size;
  207. }
  208. }
  209. return false;
  210. }
  211. private ResultCode MapCodeMemoryInProcess(KProcess process, ulong baseAddress, ulong size, out ulong targetAddress)
  212. {
  213. KPageTableBase memMgr = process.MemoryManager;
  214. targetAddress = 0;
  215. int retryCount;
  216. ulong addressSpacePageLimit = (memMgr.GetAddrSpaceSize() - size) >> 12;
  217. for (retryCount = 0; retryCount < MaxMapRetries; retryCount++)
  218. {
  219. while (true)
  220. {
  221. ulong randomOffset = (ulong)(uint)Random.Shared.Next(0, (int)addressSpacePageLimit) << 12;
  222. targetAddress = memMgr.GetAddrSpaceBaseAddr() + randomOffset;
  223. if (memMgr.InsideAddrSpace(targetAddress, size) && !memMgr.InsideHeapRegion(targetAddress, size) && !memMgr.InsideAliasRegion(targetAddress, size))
  224. {
  225. break;
  226. }
  227. }
  228. Result result = memMgr.MapProcessCodeMemory(targetAddress, baseAddress, size);
  229. if (result == KernelResult.InvalidMemState)
  230. {
  231. continue;
  232. }
  233. else if (result != Result.Success)
  234. {
  235. return (ResultCode)result.ErrorCode;
  236. }
  237. if (!CanAddGuardRegionsInProcess(process, targetAddress, size))
  238. {
  239. continue;
  240. }
  241. return ResultCode.Success;
  242. }
  243. if (retryCount == MaxMapRetries)
  244. {
  245. return ResultCode.InsufficientAddressSpace;
  246. }
  247. return ResultCode.Success;
  248. }
  249. private Result SetNroMemoryPermissions(KProcess process, IExecutable relocatableObject, ulong baseAddress)
  250. {
  251. ulong textStart = baseAddress + relocatableObject.TextOffset;
  252. ulong roStart = baseAddress + relocatableObject.RoOffset;
  253. ulong dataStart = baseAddress + relocatableObject.DataOffset;
  254. ulong bssStart = dataStart + (ulong)relocatableObject.Data.Length;
  255. ulong bssEnd = BitUtils.AlignUp<ulong>(bssStart + relocatableObject.BssSize, KPageTableBase.PageSize);
  256. process.CpuMemory.Write(textStart, relocatableObject.Text);
  257. process.CpuMemory.Write(roStart, relocatableObject.Ro);
  258. process.CpuMemory.Write(dataStart, relocatableObject.Data);
  259. MemoryHelper.FillWithZeros(process.CpuMemory, bssStart, (int)(bssEnd - bssStart));
  260. Result result;
  261. result = process.MemoryManager.SetProcessMemoryPermission(textStart, roStart - textStart, KMemoryPermission.ReadAndExecute);
  262. if (result != Result.Success)
  263. {
  264. return result;
  265. }
  266. result = process.MemoryManager.SetProcessMemoryPermission(roStart, dataStart - roStart, KMemoryPermission.Read);
  267. if (result != Result.Success)
  268. {
  269. return result;
  270. }
  271. return process.MemoryManager.SetProcessMemoryPermission(dataStart, bssEnd - dataStart, KMemoryPermission.ReadAndWrite);
  272. }
  273. private ResultCode RemoveNrrInfo(ulong nrrAddress)
  274. {
  275. foreach (NrrInfo info in _nrrInfos)
  276. {
  277. if (info.NrrAddress == nrrAddress)
  278. {
  279. _nrrInfos.Remove(info);
  280. return ResultCode.Success;
  281. }
  282. }
  283. return ResultCode.NotLoaded;
  284. }
  285. private ResultCode RemoveNroInfo(ulong nroMappedAddress)
  286. {
  287. foreach (NroInfo info in _nroInfos)
  288. {
  289. if (info.NroMappedAddress == nroMappedAddress)
  290. {
  291. _nroInfos.Remove(info);
  292. return UnmapNroFromInfo(info);
  293. }
  294. }
  295. return ResultCode.NotLoaded;
  296. }
  297. private ResultCode UnmapNroFromInfo(NroInfo info)
  298. {
  299. ulong textSize = (ulong)info.Executable.Text.Length;
  300. ulong roSize = (ulong)info.Executable.Ro.Length;
  301. ulong dataSize = (ulong)info.Executable.Data.Length;
  302. ulong bssSize = (ulong)info.Executable.BssSize;
  303. Result result = Result.Success;
  304. if (info.Executable.BssSize != 0)
  305. {
  306. result = _owner.MemoryManager.UnmapProcessCodeMemory(
  307. info.NroMappedAddress + textSize + roSize + dataSize,
  308. info.Executable.BssAddress,
  309. bssSize);
  310. }
  311. if (result == Result.Success)
  312. {
  313. result = _owner.MemoryManager.UnmapProcessCodeMemory(
  314. info.NroMappedAddress + textSize + roSize,
  315. info.Executable.SourceAddress + textSize + roSize,
  316. dataSize);
  317. if (result == Result.Success)
  318. {
  319. result = _owner.MemoryManager.UnmapProcessCodeMemory(
  320. info.NroMappedAddress,
  321. info.Executable.SourceAddress,
  322. textSize + roSize);
  323. }
  324. }
  325. return (ResultCode)result.ErrorCode;
  326. }
  327. private ResultCode IsInitialized(ulong pid)
  328. {
  329. if (_owner != null && _owner.Pid == pid)
  330. {
  331. return ResultCode.Success;
  332. }
  333. return ResultCode.InvalidProcess;
  334. }
  335. [CommandHipc(0)]
  336. // LoadNro(u64, u64, u64, u64, u64, pid) -> u64
  337. public ResultCode LoadNro(ServiceCtx context)
  338. {
  339. ResultCode result = IsInitialized(_owner.Pid);
  340. // Zero
  341. context.RequestData.ReadUInt64();
  342. ulong nroHeapAddress = context.RequestData.ReadUInt64();
  343. ulong nroSize = context.RequestData.ReadUInt64();
  344. ulong bssHeapAddress = context.RequestData.ReadUInt64();
  345. ulong bssSize = context.RequestData.ReadUInt64();
  346. ulong nroMappedAddress = 0;
  347. if (result == ResultCode.Success)
  348. {
  349. NroInfo info;
  350. result = ParseNro(out info, context, nroHeapAddress, nroSize, bssHeapAddress, bssSize);
  351. if (result == ResultCode.Success)
  352. {
  353. result = MapNro(_owner, info, out nroMappedAddress);
  354. if (result == ResultCode.Success)
  355. {
  356. result = (ResultCode)SetNroMemoryPermissions(_owner, info.Executable, nroMappedAddress).ErrorCode;
  357. if (result == ResultCode.Success)
  358. {
  359. info.NroMappedAddress = nroMappedAddress;
  360. _nroInfos.Add(info);
  361. }
  362. }
  363. }
  364. }
  365. context.ResponseData.Write(nroMappedAddress);
  366. return result;
  367. }
  368. [CommandHipc(1)]
  369. // UnloadNro(u64, u64, pid)
  370. public ResultCode UnloadNro(ServiceCtx context)
  371. {
  372. ResultCode result = IsInitialized(_owner.Pid);
  373. // Zero
  374. context.RequestData.ReadUInt64();
  375. ulong nroMappedAddress = context.RequestData.ReadUInt64();
  376. if (result == ResultCode.Success)
  377. {
  378. if ((nroMappedAddress & 0xFFF) != 0)
  379. {
  380. return ResultCode.InvalidAddress;
  381. }
  382. result = RemoveNroInfo(nroMappedAddress);
  383. }
  384. return result;
  385. }
  386. [CommandHipc(2)]
  387. // LoadNrr(u64, u64, u64, pid)
  388. public ResultCode LoadNrr(ServiceCtx context)
  389. {
  390. ResultCode result = IsInitialized(_owner.Pid);
  391. // pid placeholder, zero
  392. context.RequestData.ReadUInt64();
  393. ulong nrrAddress = context.RequestData.ReadUInt64();
  394. ulong nrrSize = context.RequestData.ReadUInt64();
  395. if (result == ResultCode.Success)
  396. {
  397. NrrInfo info;
  398. result = ParseNrr(out info, context, nrrAddress, nrrSize);
  399. if (result == ResultCode.Success)
  400. {
  401. if (_nrrInfos.Count >= MaxNrr)
  402. {
  403. result = ResultCode.NotLoaded;
  404. }
  405. else
  406. {
  407. _nrrInfos.Add(info);
  408. }
  409. }
  410. }
  411. return result;
  412. }
  413. [CommandHipc(3)]
  414. // UnloadNrr(u64, u64, pid)
  415. public ResultCode UnloadNrr(ServiceCtx context)
  416. {
  417. ResultCode result = IsInitialized(_owner.Pid);
  418. // pid placeholder, zero
  419. context.RequestData.ReadUInt64();
  420. ulong nrrHeapAddress = context.RequestData.ReadUInt64();
  421. if (result == ResultCode.Success)
  422. {
  423. if ((nrrHeapAddress & 0xFFF) != 0)
  424. {
  425. return ResultCode.InvalidAddress;
  426. }
  427. result = RemoveNrrInfo(nrrHeapAddress);
  428. }
  429. return result;
  430. }
  431. [CommandHipc(4)]
  432. // Initialize(u64, pid, KObject)
  433. public ResultCode Initialize(ServiceCtx context)
  434. {
  435. if (_owner != null)
  436. {
  437. return ResultCode.InvalidSession;
  438. }
  439. int processHandle = context.Request.HandleDesc.ToCopy[0];
  440. _owner = context.Process.HandleTable.GetKProcess(processHandle);
  441. _ownerMm = _owner?.CpuMemory;
  442. context.Device.System.KernelContext.Syscall.CloseHandle(processHandle);
  443. if (_ownerMm is IRefCounted rc)
  444. {
  445. rc.IncrementReferenceCount();
  446. }
  447. return ResultCode.Success;
  448. }
  449. [CommandHipc(10)]
  450. // LoadNrr2(u64, u64, u64, pid)
  451. public ResultCode LoadNrr2(ServiceCtx context)
  452. {
  453. context.Device.System.KernelContext.Syscall.CloseHandle(context.Request.HandleDesc.ToCopy[0]);
  454. return LoadNrr(context);
  455. }
  456. protected override void Dispose(bool isDisposing)
  457. {
  458. if (isDisposing)
  459. {
  460. foreach (NroInfo info in _nroInfos)
  461. {
  462. UnmapNroFromInfo(info);
  463. }
  464. _nroInfos.Clear();
  465. if (_ownerMm is IRefCounted rc)
  466. {
  467. rc.DecrementReferenceCount();
  468. }
  469. }
  470. }
  471. }
  472. }