ServerBase.cs 14 KB

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