IRoInterface.cs 18 KB

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