IRoInterface.cs 19 KB

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