IRoInterface.cs 18 KB

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