IRoInterface.cs 18 KB

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