IRoInterface.cs 18 KB

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