ServerBase.cs 14 KB

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