ServerBase.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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 Func<IpcService> SmObjectFactory { get; }
  37. public string Name { get; }
  38. public ServerBase(KernelContext context, string name, Func<IpcService> smObjectFactory = null)
  39. {
  40. InitDone = new ManualResetEvent(false);
  41. Name = name;
  42. SmObjectFactory = smObjectFactory;
  43. _context = context;
  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, ServerLoop);
  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 ServerLoop()
  70. {
  71. _selfProcess = KernelStatic.GetCurrentProcess();
  72. if (SmObjectFactory != null)
  73. {
  74. _context.Syscall.ManageNamedPort(out int serverPortHandle, "sm:", 50);
  75. AddPort(serverPortHandle, SmObjectFactory);
  76. }
  77. InitDone.Set();
  78. KThread thread = KernelStatic.GetCurrentThread();
  79. ulong messagePtr = thread.TlsAddress;
  80. _context.Syscall.SetHeapSize(out ulong heapAddr, 0x200000);
  81. _selfProcess.CpuMemory.Write(messagePtr + 0x0, 0);
  82. _selfProcess.CpuMemory.Write(messagePtr + 0x4, 2 << 10);
  83. _selfProcess.CpuMemory.Write(messagePtr + 0x8, heapAddr | ((ulong)PointerBufferSize << 48));
  84. int replyTargetHandle = 0;
  85. while (true)
  86. {
  87. int[] portHandles = _portHandles.ToArray();
  88. int[] sessionHandles = _sessionHandles.ToArray();
  89. int[] handles = new int[portHandles.Length + sessionHandles.Length];
  90. portHandles.CopyTo(handles, 0);
  91. sessionHandles.CopyTo(handles, portHandles.Length);
  92. // We still need a timeout here to allow the service to pick up and listen new sessions...
  93. var rc = _context.Syscall.ReplyAndReceive(out int signaledIndex, handles, replyTargetHandle, 1000000L);
  94. thread.HandlePostSyscall();
  95. if (!thread.Context.Running)
  96. {
  97. break;
  98. }
  99. replyTargetHandle = 0;
  100. if (rc == KernelResult.Success && signaledIndex >= portHandles.Length)
  101. {
  102. // We got a IPC request, process it, pass to the appropriate service if needed.
  103. int signaledHandle = handles[signaledIndex];
  104. if (Process(signaledHandle, heapAddr))
  105. {
  106. replyTargetHandle = signaledHandle;
  107. }
  108. }
  109. else
  110. {
  111. if (rc == KernelResult.Success)
  112. {
  113. // We got a new connection, accept the session to allow servicing future requests.
  114. if (_context.Syscall.AcceptSession(out int serverSessionHandle, handles[signaledIndex]) == KernelResult.Success)
  115. {
  116. IpcService obj = _ports[handles[signaledIndex]].Invoke();
  117. AddSessionObj(serverSessionHandle, obj);
  118. }
  119. }
  120. _selfProcess.CpuMemory.Write(messagePtr + 0x0, 0);
  121. _selfProcess.CpuMemory.Write(messagePtr + 0x4, 2 << 10);
  122. _selfProcess.CpuMemory.Write(messagePtr + 0x8, heapAddr | ((ulong)PointerBufferSize << 48));
  123. }
  124. }
  125. Dispose();
  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(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(out int dupServerSessionHandle, out int dupClientSessionHandle, false, 0);
  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. protected virtual void Dispose(bool disposing)
  279. {
  280. if (disposing)
  281. {
  282. foreach (IpcService service in _sessions.Values)
  283. {
  284. if (service is IDisposable disposableObj)
  285. {
  286. disposableObj.Dispose();
  287. }
  288. service.DestroyAtExit();
  289. }
  290. _sessions.Clear();
  291. InitDone.Dispose();
  292. }
  293. }
  294. public void Dispose()
  295. {
  296. Dispose(true);
  297. }
  298. }
  299. }