IRoInterface.cs 18 KB

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