IRoInterface.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. using ChocolArm64.Memory;
  2. using Ryujinx.Common;
  3. using Ryujinx.HLE.HOS.Ipc;
  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.Collections.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Runtime.InteropServices;
  13. using System.Security.Cryptography;
  14. using static Ryujinx.HLE.HOS.ErrorCode;
  15. namespace Ryujinx.HLE.HOS.Services.Ldr
  16. {
  17. [StructLayout(LayoutKind.Explicit, Size = 0x350)]
  18. unsafe struct NrrHeader
  19. {
  20. [FieldOffset(0)]
  21. public uint Magic;
  22. [FieldOffset(0x10)]
  23. public ulong TitleIdMask;
  24. [FieldOffset(0x18)]
  25. public ulong TitleIdPattern;
  26. [FieldOffset(0x30)]
  27. public fixed byte Modulus[0x100];
  28. [FieldOffset(0x130)]
  29. public fixed byte FixedKeySignature[0x100];
  30. [FieldOffset(0x230)]
  31. public fixed byte NrrSignature[0x100];
  32. [FieldOffset(0x330)]
  33. public ulong TitleIdMin;
  34. [FieldOffset(0x338)]
  35. public uint NrrSize;
  36. [FieldOffset(0x340)]
  37. public uint HashOffset;
  38. [FieldOffset(0x344)]
  39. public uint HashCount;
  40. }
  41. class NrrInfo
  42. {
  43. public NrrHeader Header { get; private set; }
  44. public List<byte[]> Hashes { get; private set; }
  45. public long NrrAddress { get; private set; }
  46. public NrrInfo(long nrrAddress, NrrHeader header, List<byte[]> hashes)
  47. {
  48. NrrAddress = nrrAddress;
  49. Header = header;
  50. Hashes = hashes;
  51. }
  52. }
  53. class NroInfo
  54. {
  55. public NxRelocatableObject Executable { get; private set; }
  56. public byte[] Hash { get; private set; }
  57. public ulong NroAddress { get; private set; }
  58. public ulong NroSize { get; private set; }
  59. public ulong BssAddress { get; private set; }
  60. public ulong BssSize { get; private set; }
  61. public ulong TotalSize { get; private set; }
  62. public ulong NroMappedAddress { get; set; }
  63. public NroInfo(
  64. NxRelocatableObject executable,
  65. byte[] hash,
  66. ulong nroAddress,
  67. ulong nroSize,
  68. ulong bssAddress,
  69. ulong bssSize,
  70. ulong totalSize)
  71. {
  72. Executable = executable;
  73. Hash = hash;
  74. NroAddress = nroAddress;
  75. NroSize = nroSize;
  76. BssAddress = bssAddress;
  77. BssSize = bssSize;
  78. TotalSize = totalSize;
  79. }
  80. }
  81. class IRoInterface : IpcService
  82. {
  83. private Dictionary<int, ServiceProcessRequest> _commands;
  84. public override IReadOnlyDictionary<int, ServiceProcessRequest> Commands => _commands;
  85. private const int MaxNrr = 0x40;
  86. private const int MaxNro = 0x40;
  87. private const uint NrrMagic = 0x3052524E;
  88. private const uint NroMagic = 0x304F524E;
  89. private List<NrrInfo> _nrrInfos;
  90. private List<NroInfo> _nroInfos;
  91. private bool _isInitialized;
  92. public IRoInterface()
  93. {
  94. _commands = new Dictionary<int, ServiceProcessRequest>
  95. {
  96. { 0, LoadNro },
  97. { 1, UnloadNro },
  98. { 2, LoadNrr },
  99. { 3, UnloadNrr },
  100. { 4, Initialize }
  101. };
  102. _nrrInfos = new List<NrrInfo>(MaxNrr);
  103. _nroInfos = new List<NroInfo>(MaxNro);
  104. }
  105. private long ParseNrr(out NrrInfo nrrInfo, ServiceCtx context, long nrrAddress, long nrrSize)
  106. {
  107. nrrInfo = null;
  108. if (nrrSize == 0 || nrrAddress + nrrSize <= nrrAddress || (nrrSize & 0xFFF) != 0)
  109. {
  110. return MakeError(ErrorModule.Loader, LoaderErr.BadSize);
  111. }
  112. else if ((nrrAddress & 0xFFF) != 0)
  113. {
  114. return MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress);
  115. }
  116. StructReader reader = new StructReader(context.Memory, nrrAddress);
  117. NrrHeader header = reader.Read<NrrHeader>();
  118. if (header.Magic != NrrMagic)
  119. {
  120. return MakeError(ErrorModule.Loader, LoaderErr.InvalidNrr);
  121. }
  122. else if (header.NrrSize != nrrSize)
  123. {
  124. return MakeError(ErrorModule.Loader, LoaderErr.BadSize);
  125. }
  126. List<byte[]> hashes = new List<byte[]>();
  127. for (int i = 0; i < header.HashCount; i++)
  128. {
  129. hashes.Add(context.Memory.ReadBytes(nrrAddress + header.HashOffset + (i * 0x20), 0x20));
  130. }
  131. nrrInfo = new NrrInfo(nrrAddress, header, hashes);
  132. return 0;
  133. }
  134. public bool IsNroHashPresent(byte[] nroHash)
  135. {
  136. foreach (NrrInfo info in _nrrInfos)
  137. {
  138. foreach (byte[] hash in info.Hashes)
  139. {
  140. if (hash.SequenceEqual(nroHash))
  141. {
  142. return true;
  143. }
  144. }
  145. }
  146. return false;
  147. }
  148. public bool IsNroLoaded(byte[] nroHash)
  149. {
  150. foreach (NroInfo info in _nroInfos)
  151. {
  152. if (info.Hash.SequenceEqual(nroHash))
  153. {
  154. return true;
  155. }
  156. }
  157. return false;
  158. }
  159. public long ParseNro(out NroInfo res, ServiceCtx context, ulong nroAddress, ulong nroSize, ulong bssAddress, ulong bssSize)
  160. {
  161. res = null;
  162. if (_nroInfos.Count >= MaxNro)
  163. {
  164. return MakeError(ErrorModule.Loader, LoaderErr.MaxNro);
  165. }
  166. else if (nroSize == 0 || nroAddress + nroSize <= nroAddress || (nroSize & 0xFFF) != 0)
  167. {
  168. return MakeError(ErrorModule.Loader, LoaderErr.BadSize);
  169. }
  170. else if (bssSize != 0 && bssAddress + bssSize <= bssAddress)
  171. {
  172. return MakeError(ErrorModule.Loader, LoaderErr.BadSize);
  173. }
  174. else if ((nroAddress & 0xFFF) != 0)
  175. {
  176. return MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress);
  177. }
  178. uint magic = context.Memory.ReadUInt32((long)nroAddress + 0x10);
  179. uint nroFileSize = context.Memory.ReadUInt32((long)nroAddress + 0x18);
  180. if (magic != NroMagic || nroSize != nroFileSize)
  181. {
  182. return MakeError(ErrorModule.Loader, LoaderErr.InvalidNro);
  183. }
  184. byte[] nroData = context.Memory.ReadBytes((long)nroAddress, (long)nroSize);
  185. byte[] nroHash = null;
  186. MemoryStream stream = new MemoryStream(nroData);
  187. using (SHA256 hasher = SHA256.Create())
  188. {
  189. nroHash = hasher.ComputeHash(stream);
  190. }
  191. if (!IsNroHashPresent(nroHash))
  192. {
  193. return MakeError(ErrorModule.Loader, LoaderErr.NroHashNotPresent);
  194. }
  195. if (IsNroLoaded(nroHash))
  196. {
  197. return MakeError(ErrorModule.Loader, LoaderErr.NroAlreadyLoaded);
  198. }
  199. stream.Position = 0;
  200. NxRelocatableObject executable = new NxRelocatableObject(stream, nroAddress, bssAddress);
  201. // check if everything is page align.
  202. if ((executable.Text.Length & 0xFFF) != 0 || (executable.Ro.Length & 0xFFF) != 0 ||
  203. (executable.Data.Length & 0xFFF) != 0 || (executable.BssSize & 0xFFF) != 0)
  204. {
  205. return MakeError(ErrorModule.Loader, LoaderErr.InvalidNro);
  206. }
  207. // check if everything is contiguous.
  208. if (executable.RoOffset != executable.TextOffset + executable.Text.Length ||
  209. executable.DataOffset != executable.RoOffset + executable.Ro.Length ||
  210. nroFileSize != executable.DataOffset + executable.Data.Length)
  211. {
  212. return MakeError(ErrorModule.Loader, LoaderErr.InvalidNro);
  213. }
  214. // finally check the bss size match.
  215. if ((ulong)executable.BssSize != bssSize)
  216. {
  217. return MakeError(ErrorModule.Loader, LoaderErr.InvalidNro);
  218. }
  219. int totalSize = executable.Text.Length + executable.Ro.Length + executable.Data.Length + executable.BssSize;
  220. res = new NroInfo(
  221. executable,
  222. nroHash,
  223. nroAddress,
  224. nroSize,
  225. bssAddress,
  226. bssSize,
  227. (ulong)totalSize);
  228. return 0;
  229. }
  230. private long MapNro(ServiceCtx context, NroInfo info, out ulong nroMappedAddress)
  231. {
  232. nroMappedAddress = 0;
  233. KMemoryManager memMgr = context.Process.MemoryManager;
  234. ulong targetAddress = memMgr.GetAddrSpaceBaseAddr();
  235. while (true)
  236. {
  237. if (targetAddress + info.TotalSize >= memMgr.AddrSpaceEnd)
  238. {
  239. return MakeError(ErrorModule.Loader, LoaderErr.InvalidMemoryState);
  240. }
  241. KMemoryInfo memInfo = memMgr.QueryMemory(targetAddress);
  242. if (memInfo.State == MemoryState.Unmapped && memInfo.Size >= info.TotalSize)
  243. {
  244. if (!memMgr.InsideHeapRegion (targetAddress, info.TotalSize) &&
  245. !memMgr.InsideAliasRegion(targetAddress, info.TotalSize))
  246. {
  247. break;
  248. }
  249. }
  250. targetAddress += memInfo.Size;
  251. }
  252. KernelResult result = memMgr.MapProcessCodeMemory(targetAddress, info.NroAddress, info.NroSize);
  253. if (result != KernelResult.Success)
  254. {
  255. return MakeError(ErrorModule.Loader, LoaderErr.InvalidMemoryState);
  256. }
  257. ulong bssTargetAddress = targetAddress + info.NroSize;
  258. if (info.BssSize != 0)
  259. {
  260. result = memMgr.MapProcessCodeMemory(bssTargetAddress, info.BssAddress, info.BssSize);
  261. if (result != KernelResult.Success)
  262. {
  263. memMgr.UnmapProcessCodeMemory(targetAddress, info.NroAddress, info.NroSize);
  264. return MakeError(ErrorModule.Loader, LoaderErr.InvalidMemoryState);
  265. }
  266. }
  267. result = LoadNroIntoMemory(context.Process, info.Executable, targetAddress);
  268. if (result != KernelResult.Success)
  269. {
  270. memMgr.UnmapProcessCodeMemory(targetAddress, info.NroAddress, info.NroSize);
  271. if (info.BssSize != 0)
  272. {
  273. memMgr.UnmapProcessCodeMemory(bssTargetAddress, info.BssAddress, info.BssSize);
  274. }
  275. return 0;
  276. }
  277. info.NroMappedAddress = targetAddress;
  278. nroMappedAddress = targetAddress;
  279. return 0;
  280. }
  281. private KernelResult LoadNroIntoMemory(KProcess process, IExecutable relocatableObject, ulong baseAddress)
  282. {
  283. ulong textStart = baseAddress + (ulong)relocatableObject.TextOffset;
  284. ulong roStart = baseAddress + (ulong)relocatableObject.RoOffset;
  285. ulong dataStart = baseAddress + (ulong)relocatableObject.DataOffset;
  286. ulong bssStart = dataStart + (ulong)relocatableObject.Data.Length;
  287. ulong bssEnd = BitUtils.AlignUp(bssStart + (ulong)relocatableObject.BssSize, KMemoryManager.PageSize);
  288. process.CpuMemory.WriteBytes((long)textStart, relocatableObject.Text);
  289. process.CpuMemory.WriteBytes((long)roStart, relocatableObject.Ro);
  290. process.CpuMemory.WriteBytes((long)dataStart, relocatableObject.Data);
  291. MemoryHelper.FillWithZeros(process.CpuMemory, (long)bssStart, (int)(bssEnd - bssStart));
  292. KernelResult result;
  293. result = process.MemoryManager.SetProcessMemoryPermission(textStart, roStart - textStart, MemoryPermission.ReadAndExecute);
  294. if (result != KernelResult.Success)
  295. {
  296. return result;
  297. }
  298. result = process.MemoryManager.SetProcessMemoryPermission(roStart, dataStart - roStart, MemoryPermission.Read);
  299. if (result != KernelResult.Success)
  300. {
  301. return result;
  302. }
  303. return process.MemoryManager.SetProcessMemoryPermission(dataStart, bssEnd - dataStart, MemoryPermission.ReadAndWrite);
  304. }
  305. private long RemoveNrrInfo(long nrrAddress)
  306. {
  307. foreach (NrrInfo info in _nrrInfos)
  308. {
  309. if (info.NrrAddress == nrrAddress)
  310. {
  311. _nrrInfos.Remove(info);
  312. return 0;
  313. }
  314. }
  315. return MakeError(ErrorModule.Loader, LoaderErr.BadNrrAddress);
  316. }
  317. private long RemoveNroInfo(ServiceCtx context, ulong nroMappedAddress)
  318. {
  319. foreach (NroInfo info in _nroInfos)
  320. {
  321. if (info.NroMappedAddress == nroMappedAddress)
  322. {
  323. _nroInfos.Remove(info);
  324. ulong textSize = (ulong)info.Executable.Text.Length;
  325. ulong roSize = (ulong)info.Executable.Ro.Length;
  326. ulong dataSize = (ulong)info.Executable.Data.Length;
  327. ulong bssSize = (ulong)info.Executable.BssSize;
  328. KernelResult result = KernelResult.Success;
  329. if (info.Executable.BssSize != 0)
  330. {
  331. result = context.Process.MemoryManager.UnmapProcessCodeMemory(
  332. info.NroMappedAddress + textSize + roSize + dataSize,
  333. info.Executable.BssAddress,
  334. bssSize);
  335. }
  336. if (result == KernelResult.Success)
  337. {
  338. result = context.Process.MemoryManager.UnmapProcessCodeMemory(
  339. info.NroMappedAddress + textSize + roSize,
  340. info.Executable.SourceAddress + textSize + roSize,
  341. dataSize);
  342. if (result == KernelResult.Success)
  343. {
  344. result = context.Process.MemoryManager.UnmapProcessCodeMemory(
  345. info.NroMappedAddress,
  346. info.Executable.SourceAddress,
  347. textSize + roSize);
  348. }
  349. }
  350. return (long)result;
  351. }
  352. }
  353. return MakeError(ErrorModule.Loader, LoaderErr.BadNroAddress);
  354. }
  355. // LoadNro(u64, u64, u64, u64, u64, pid) -> u64
  356. public long LoadNro(ServiceCtx context)
  357. {
  358. long result = MakeError(ErrorModule.Loader, LoaderErr.BadInitialization);
  359. // Zero
  360. context.RequestData.ReadUInt64();
  361. ulong nroHeapAddress = context.RequestData.ReadUInt64();
  362. ulong nroSize = context.RequestData.ReadUInt64();
  363. ulong bssHeapAddress = context.RequestData.ReadUInt64();
  364. ulong bssSize = context.RequestData.ReadUInt64();
  365. ulong nroMappedAddress = 0;
  366. if (_isInitialized)
  367. {
  368. NroInfo info;
  369. result = ParseNro(out info, context, nroHeapAddress, nroSize, bssHeapAddress, bssSize);
  370. if (result == 0)
  371. {
  372. result = MapNro(context, info, out nroMappedAddress);
  373. if (result == 0)
  374. {
  375. _nroInfos.Add(info);
  376. }
  377. }
  378. }
  379. context.ResponseData.Write(nroMappedAddress);
  380. return result;
  381. }
  382. // UnloadNro(u64, u64, pid)
  383. public long UnloadNro(ServiceCtx context)
  384. {
  385. long result = MakeError(ErrorModule.Loader, LoaderErr.BadInitialization);
  386. // Zero
  387. context.RequestData.ReadUInt64();
  388. ulong nroMappedAddress = context.RequestData.ReadUInt64();
  389. if (_isInitialized)
  390. {
  391. if ((nroMappedAddress & 0xFFF) != 0)
  392. {
  393. return MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress);
  394. }
  395. result = RemoveNroInfo(context, nroMappedAddress);
  396. }
  397. return result;
  398. }
  399. // LoadNrr(u64, u64, u64, pid)
  400. public long LoadNrr(ServiceCtx context)
  401. {
  402. long result = MakeError(ErrorModule.Loader, LoaderErr.BadInitialization);
  403. // Zero
  404. context.RequestData.ReadUInt64();
  405. long nrrAddress = context.RequestData.ReadInt64();
  406. long nrrSize = context.RequestData.ReadInt64();
  407. if (_isInitialized)
  408. {
  409. NrrInfo info;
  410. result = ParseNrr(out info, context, nrrAddress, nrrSize);
  411. if(result == 0)
  412. {
  413. if (_nrrInfos.Count >= MaxNrr)
  414. {
  415. result = MakeError(ErrorModule.Loader, LoaderErr.MaxNrr);
  416. }
  417. else
  418. {
  419. _nrrInfos.Add(info);
  420. }
  421. }
  422. }
  423. return result;
  424. }
  425. // UnloadNrr(u64, u64, pid)
  426. public long UnloadNrr(ServiceCtx context)
  427. {
  428. long result = MakeError(ErrorModule.Loader, LoaderErr.BadInitialization);
  429. // Zero
  430. context.RequestData.ReadUInt64();
  431. long nrrHeapAddress = context.RequestData.ReadInt64();
  432. if (_isInitialized)
  433. {
  434. if ((nrrHeapAddress & 0xFFF) != 0)
  435. {
  436. return MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress);
  437. }
  438. result = RemoveNrrInfo(nrrHeapAddress);
  439. }
  440. return result;
  441. }
  442. // Initialize(u64, pid, KObject)
  443. public long Initialize(ServiceCtx context)
  444. {
  445. // TODO: we actually ignore the pid and process handle receive, we will need to use them when we will have multi process support.
  446. _isInitialized = true;
  447. return 0;
  448. }
  449. }
  450. }