ServerBase.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. using Ryujinx.HLE.HOS.Ipc;
  2. using Ryujinx.HLE.HOS.Kernel;
  3. using Ryujinx.HLE.HOS.Kernel.Common;
  4. using Ryujinx.HLE.HOS.Kernel.Ipc;
  5. using Ryujinx.HLE.HOS.Kernel.Process;
  6. using Ryujinx.HLE.HOS.Kernel.Threading;
  7. using System;
  8. using System.Buffers.Binary;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Threading;
  12. namespace Ryujinx.HLE.HOS.Services
  13. {
  14. class ServerBase
  15. {
  16. // Must be the maximum value used by services (highest one know is the one used by nvservices = 0x8000).
  17. // Having a size that is too low will cause failures as data copy will fail if the receiving buffer is
  18. // not large enough.
  19. private const int PointerBufferSize = 0x8000;
  20. private readonly static int[] DefaultCapabilities = new int[]
  21. {
  22. 0x030363F7,
  23. 0x1FFFFFCF,
  24. 0x207FFFEF,
  25. 0x47E0060F,
  26. 0x0048BFFF,
  27. 0x01007FFF
  28. };
  29. private readonly KernelContext _context;
  30. private KProcess _selfProcess;
  31. private readonly List<int> _sessionHandles = new List<int>();
  32. private readonly List<int> _portHandles = new List<int>();
  33. private readonly Dictionary<int, IpcService> _sessions = new Dictionary<int, IpcService>();
  34. private readonly Dictionary<int, Func<IpcService>> _ports = new Dictionary<int, Func<IpcService>>();
  35. public ManualResetEvent InitDone { get; }
  36. public Func<IpcService> SmObjectFactory { get; set; }
  37. public string Name { get; }
  38. public ServerBase(KernelContext context, string name)
  39. {
  40. InitDone = new ManualResetEvent(false);
  41. Name = name;
  42. _context = context;
  43. const ProcessCreationFlags flags =
  44. ProcessCreationFlags.EnableAslr |
  45. ProcessCreationFlags.AddressSpace64Bit |
  46. ProcessCreationFlags.Is64Bit |
  47. ProcessCreationFlags.PoolPartitionSystem;
  48. ProcessCreationInfo creationInfo = new ProcessCreationInfo("Service", 1, 0, 0x8000000, 1, flags, 0, 0);
  49. KernelStatic.StartInitialProcess(context, creationInfo, DefaultCapabilities, 44, ServerLoop);
  50. }
  51. private void AddPort(int serverPortHandle, Func<IpcService> objectFactory)
  52. {
  53. _portHandles.Add(serverPortHandle);
  54. _ports.Add(serverPortHandle, objectFactory);
  55. }
  56. public void AddSessionObj(KServerSession serverSession, IpcService obj)
  57. {
  58. _selfProcess.HandleTable.GenerateHandle(serverSession, out int serverSessionHandle);
  59. AddSessionObj(serverSessionHandle, obj);
  60. }
  61. public void AddSessionObj(int serverSessionHandle, IpcService obj)
  62. {
  63. _sessionHandles.Add(serverSessionHandle);
  64. _sessions.Add(serverSessionHandle, obj);
  65. }
  66. private void ServerLoop()
  67. {
  68. _selfProcess = KernelStatic.GetCurrentProcess();
  69. if (SmObjectFactory != null)
  70. {
  71. _context.Syscall.ManageNamedPort("sm:", 50, out int serverPortHandle);
  72. AddPort(serverPortHandle, SmObjectFactory);
  73. InitDone.Set();
  74. }
  75. else
  76. {
  77. InitDone.Dispose();
  78. }
  79. KThread thread = KernelStatic.GetCurrentThread();
  80. ulong messagePtr = thread.TlsAddress;
  81. _context.Syscall.SetHeapSize(0x200000, out ulong heapAddr);
  82. _selfProcess.CpuMemory.Write(messagePtr + 0x0, 0);
  83. _selfProcess.CpuMemory.Write(messagePtr + 0x4, 2 << 10);
  84. _selfProcess.CpuMemory.Write(messagePtr + 0x8, heapAddr | ((ulong)PointerBufferSize << 48));
  85. int replyTargetHandle = 0;
  86. while (true)
  87. {
  88. int[] portHandles = _portHandles.ToArray();
  89. int[] sessionHandles = _sessionHandles.ToArray();
  90. int[] handles = new int[portHandles.Length + sessionHandles.Length];
  91. portHandles.CopyTo(handles, 0);
  92. sessionHandles.CopyTo(handles, portHandles.Length);
  93. // We still need a timeout here to allow the service to pick up and listen new sessions...
  94. var rc = _context.Syscall.ReplyAndReceive(handles, replyTargetHandle, 1000000L, out int signaledIndex);
  95. thread.HandlePostSyscall();
  96. if (!thread.Context.Running)
  97. {
  98. break;
  99. }
  100. replyTargetHandle = 0;
  101. if (rc == KernelResult.Success && signaledIndex >= portHandles.Length)
  102. {
  103. // We got a IPC request, process it, pass to the appropriate service if needed.
  104. int signaledHandle = handles[signaledIndex];
  105. if (Process(signaledHandle, heapAddr))
  106. {
  107. replyTargetHandle = signaledHandle;
  108. }
  109. }
  110. else
  111. {
  112. if (rc == KernelResult.Success)
  113. {
  114. // We got a new connection, accept the session to allow servicing future requests.
  115. if (_context.Syscall.AcceptSession(handles[signaledIndex], out int serverSessionHandle) == KernelResult.Success)
  116. {
  117. IpcService obj = _ports[handles[signaledIndex]].Invoke();
  118. AddSessionObj(serverSessionHandle, obj);
  119. }
  120. }
  121. _selfProcess.CpuMemory.Write(messagePtr + 0x0, 0);
  122. _selfProcess.CpuMemory.Write(messagePtr + 0x4, 2 << 10);
  123. _selfProcess.CpuMemory.Write(messagePtr + 0x8, heapAddr | ((ulong)PointerBufferSize << 48));
  124. }
  125. }
  126. }
  127. private bool Process(int serverSessionHandle, ulong recvListAddr)
  128. {
  129. KProcess process = KernelStatic.GetCurrentProcess();
  130. KThread thread = KernelStatic.GetCurrentThread();
  131. ulong messagePtr = thread.TlsAddress;
  132. ulong messageSize = 0x100;
  133. byte[] reqData = new byte[messageSize];
  134. process.CpuMemory.Read(messagePtr, reqData);
  135. IpcMessage request = new IpcMessage(reqData, (long)messagePtr);
  136. IpcMessage response = new IpcMessage();
  137. ulong tempAddr = recvListAddr;
  138. int sizesOffset = request.RawData.Length - ((request.RecvListBuff.Count * 2 + 3) & ~3);
  139. bool noReceive = true;
  140. for (int i = 0; i < request.ReceiveBuff.Count; i++)
  141. {
  142. noReceive &= (request.ReceiveBuff[i].Position == 0);
  143. }
  144. if (noReceive)
  145. {
  146. for (int i = 0; i < request.RecvListBuff.Count; i++)
  147. {
  148. ulong size = (ulong)BinaryPrimitives.ReadInt16LittleEndian(request.RawData.AsSpan().Slice(sizesOffset + i * 2, 2));
  149. response.PtrBuff.Add(new IpcPtrBuffDesc(tempAddr, (uint)i, size));
  150. request.RecvListBuff[i] = new IpcRecvListBuffDesc(tempAddr, size);
  151. tempAddr += size;
  152. }
  153. }
  154. bool shouldReply = true;
  155. bool isTipcCommunication = false;
  156. using (MemoryStream raw = new MemoryStream(request.RawData))
  157. {
  158. BinaryReader reqReader = new BinaryReader(raw);
  159. if (request.Type == IpcMessageType.HipcRequest ||
  160. request.Type == IpcMessageType.HipcRequestWithContext)
  161. {
  162. response.Type = IpcMessageType.HipcResponse;
  163. using (MemoryStream resMs = new MemoryStream())
  164. {
  165. BinaryWriter resWriter = new BinaryWriter(resMs);
  166. ServiceCtx context = new ServiceCtx(
  167. _context.Device,
  168. process,
  169. process.CpuMemory,
  170. thread,
  171. request,
  172. response,
  173. reqReader,
  174. resWriter);
  175. _sessions[serverSessionHandle].CallHipcMethod(context);
  176. response.RawData = resMs.ToArray();
  177. }
  178. }
  179. else if (request.Type == IpcMessageType.HipcControl ||
  180. request.Type == IpcMessageType.HipcControlWithContext)
  181. {
  182. uint magic = (uint)reqReader.ReadUInt64();
  183. uint cmdId = (uint)reqReader.ReadUInt64();
  184. switch (cmdId)
  185. {
  186. case 0:
  187. request = FillResponse(response, 0, _sessions[serverSessionHandle].ConvertToDomain());
  188. break;
  189. case 3:
  190. request = FillResponse(response, 0, PointerBufferSize);
  191. break;
  192. // TODO: Whats the difference between IpcDuplicateSession/Ex?
  193. case 2:
  194. case 4:
  195. int unknown = reqReader.ReadInt32();
  196. _context.Syscall.CreateSession(false, 0, out int dupServerSessionHandle, out int dupClientSessionHandle);
  197. AddSessionObj(dupServerSessionHandle, _sessions[serverSessionHandle]);
  198. response.HandleDesc = IpcHandleDesc.MakeMove(dupClientSessionHandle);
  199. request = FillResponse(response, 0);
  200. break;
  201. default: throw new NotImplementedException(cmdId.ToString());
  202. }
  203. }
  204. else if (request.Type == IpcMessageType.HipcCloseSession || request.Type == IpcMessageType.TipcCloseSession)
  205. {
  206. _context.Syscall.CloseHandle(serverSessionHandle);
  207. _sessionHandles.Remove(serverSessionHandle);
  208. IpcService service = _sessions[serverSessionHandle];
  209. if (service is IDisposable disposableObj)
  210. {
  211. disposableObj.Dispose();
  212. }
  213. _sessions.Remove(serverSessionHandle);
  214. shouldReply = false;
  215. }
  216. // If the type is past 0xF, we are using TIPC
  217. else if (request.Type > IpcMessageType.TipcCloseSession)
  218. {
  219. isTipcCommunication = true;
  220. // Response type is always the same as request on TIPC.
  221. response.Type = request.Type;
  222. using (MemoryStream resMs = new MemoryStream())
  223. {
  224. BinaryWriter resWriter = new BinaryWriter(resMs);
  225. ServiceCtx context = new ServiceCtx(
  226. _context.Device,
  227. process,
  228. process.CpuMemory,
  229. thread,
  230. request,
  231. response,
  232. reqReader,
  233. resWriter);
  234. _sessions[serverSessionHandle].CallTipcMethod(context);
  235. response.RawData = resMs.ToArray();
  236. }
  237. process.CpuMemory.Write(messagePtr, response.GetBytesTipc());
  238. }
  239. else
  240. {
  241. throw new NotImplementedException(request.Type.ToString());
  242. }
  243. if (!isTipcCommunication)
  244. {
  245. process.CpuMemory.Write(messagePtr, response.GetBytes((long)messagePtr, recvListAddr | ((ulong)PointerBufferSize << 48)));
  246. }
  247. return shouldReply;
  248. }
  249. }
  250. private static IpcMessage FillResponse(IpcMessage response, long result, params int[] values)
  251. {
  252. using (MemoryStream ms = new MemoryStream())
  253. {
  254. BinaryWriter writer = new BinaryWriter(ms);
  255. foreach (int value in values)
  256. {
  257. writer.Write(value);
  258. }
  259. return FillResponse(response, result, ms.ToArray());
  260. }
  261. }
  262. private static IpcMessage FillResponse(IpcMessage response, long result, byte[] data = null)
  263. {
  264. response.Type = IpcMessageType.HipcResponse;
  265. using (MemoryStream ms = new MemoryStream())
  266. {
  267. BinaryWriter writer = new BinaryWriter(ms);
  268. writer.Write(IpcMagic.Sfco);
  269. writer.Write(result);
  270. if (data != null)
  271. {
  272. writer.Write(data);
  273. }
  274. response.RawData = ms.ToArray();
  275. }
  276. return response;
  277. }
  278. }
  279. }