IRoInterface.cs 18 KB

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