IRoInterface.cs 18 KB

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