IRoInterface.cs 18 KB

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