IRoInterface.cs 18 KB

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