Process.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. using ChocolArm64;
  2. using ChocolArm64.Events;
  3. using ChocolArm64.Memory;
  4. using Ryujinx.Core.Loaders;
  5. using Ryujinx.Core.Loaders.Executables;
  6. using Ryujinx.Core.OsHle.Exceptions;
  7. using Ryujinx.Core.OsHle.Handles;
  8. using Ryujinx.Core.OsHle.Services.Nv;
  9. using Ryujinx.Core.OsHle.Svc;
  10. using System;
  11. using System.Collections.Concurrent;
  12. using System.Collections.Generic;
  13. namespace Ryujinx.Core.OsHle
  14. {
  15. class Process : IDisposable
  16. {
  17. private const int TlsSize = 0x200;
  18. private const int TotalTlsSlots = (int)MemoryRegions.TlsPagesSize / TlsSize;
  19. private const int TickFreq = 19_200_000;
  20. private Switch Ns;
  21. public bool NeedsHbAbi { get; private set; }
  22. public long HbAbiDataPosition { get; private set; }
  23. public int ProcessId { get; private set; }
  24. private ATranslator Translator;
  25. public AMemory Memory { get; private set; }
  26. public KProcessScheduler Scheduler { get; private set; }
  27. public KProcessHandleTable HandleTable { get; private set; }
  28. public AppletStateMgr AppletState { get; private set; }
  29. private SvcHandler SvcHandler;
  30. private ConcurrentDictionary<int, AThread> TlsSlots;
  31. private ConcurrentDictionary<long, KThread> ThreadsByTpidr;
  32. private List<Executable> Executables;
  33. private KThread MainThread;
  34. private long ImageBase;
  35. private bool ShouldDispose;
  36. private bool Disposed;
  37. public Process(Switch Ns, int ProcessId)
  38. {
  39. this.Ns = Ns;
  40. this.ProcessId = ProcessId;
  41. Memory = new AMemory();
  42. HandleTable = new KProcessHandleTable();
  43. Scheduler = new KProcessScheduler();
  44. AppletState = new AppletStateMgr();
  45. SvcHandler = new SvcHandler(Ns, this);
  46. TlsSlots = new ConcurrentDictionary<int, AThread>();
  47. ThreadsByTpidr = new ConcurrentDictionary<long, KThread>();
  48. Executables = new List<Executable>();
  49. ImageBase = MemoryRegions.AddrSpaceStart;
  50. MapRWMemRegion(
  51. MemoryRegions.TlsPagesAddress,
  52. MemoryRegions.TlsPagesSize,
  53. MemoryType.ThreadLocal);
  54. }
  55. public void LoadProgram(IExecutable Program)
  56. {
  57. if (Disposed)
  58. {
  59. throw new ObjectDisposedException(nameof(Process));
  60. }
  61. Logging.Info(LogClass.Loader, $"Image base at 0x{ImageBase:x16}.");
  62. Executable Executable = new Executable(Program, Memory, ImageBase);
  63. Executables.Add(Executable);
  64. ImageBase = AMemoryHelper.PageRoundUp(Executable.ImageEnd);
  65. }
  66. public void SetEmptyArgs()
  67. {
  68. //TODO: This should be part of Run.
  69. ImageBase += AMemoryMgr.PageSize;
  70. }
  71. public bool Run(bool NeedsHbAbi = false)
  72. {
  73. if (Disposed)
  74. {
  75. throw new ObjectDisposedException(nameof(Process));
  76. }
  77. this.NeedsHbAbi = NeedsHbAbi;
  78. if (Executables.Count == 0)
  79. {
  80. return false;
  81. }
  82. MapRWMemRegion(
  83. MemoryRegions.MainStackAddress,
  84. MemoryRegions.MainStackSize,
  85. MemoryType.Normal);
  86. long StackTop = MemoryRegions.MainStackAddress + MemoryRegions.MainStackSize;
  87. int Handle = MakeThread(Executables[0].ImageBase, StackTop, 0, 0, 0);
  88. if (Handle == -1)
  89. {
  90. return false;
  91. }
  92. MainThread = HandleTable.GetData<KThread>(Handle);
  93. if (NeedsHbAbi)
  94. {
  95. HbAbiDataPosition = AMemoryHelper.PageRoundUp(Executables[0].ImageEnd);
  96. Homebrew.WriteHbAbiData(Memory, HbAbiDataPosition, Handle);
  97. MainThread.Thread.ThreadState.X0 = (ulong)HbAbiDataPosition;
  98. MainThread.Thread.ThreadState.X1 = ulong.MaxValue;
  99. }
  100. Scheduler.StartThread(MainThread);
  101. return true;
  102. }
  103. private void MapRWMemRegion(long Position, long Size, MemoryType Type)
  104. {
  105. Memory.Manager.Map(Position, Size, (int)Type, AMemoryPerm.RW);
  106. }
  107. public void StopAllThreadsAsync()
  108. {
  109. if (Disposed)
  110. {
  111. throw new ObjectDisposedException(nameof(Process));
  112. }
  113. if (MainThread != null)
  114. {
  115. MainThread.Thread.StopExecution();
  116. }
  117. foreach (AThread Thread in TlsSlots.Values)
  118. {
  119. Thread.StopExecution();
  120. }
  121. }
  122. public int MakeThread(
  123. long EntryPoint,
  124. long StackTop,
  125. long ArgsPtr,
  126. int Priority,
  127. int ProcessorId)
  128. {
  129. if (Disposed)
  130. {
  131. throw new ObjectDisposedException(nameof(Process));
  132. }
  133. AThread Thread = new AThread(GetTranslator(), Memory, EntryPoint);
  134. KThread ThreadHnd = new KThread(Thread, ProcessorId, Priority);
  135. int Handle = HandleTable.OpenHandle(ThreadHnd);
  136. int ThreadId = GetFreeTlsSlot(Thread);
  137. long Tpidr = MemoryRegions.TlsPagesAddress + ThreadId * TlsSize;
  138. Thread.ThreadState.Break += BreakHandler;
  139. Thread.ThreadState.SvcCall += SvcHandler.SvcCall;
  140. Thread.ThreadState.Undefined += UndefinedHandler;
  141. Thread.ThreadState.ProcessId = ProcessId;
  142. Thread.ThreadState.ThreadId = ThreadId;
  143. Thread.ThreadState.CntfrqEl0 = TickFreq;
  144. Thread.ThreadState.Tpidr = Tpidr;
  145. Thread.ThreadState.X0 = (ulong)ArgsPtr;
  146. Thread.ThreadState.X1 = (ulong)Handle;
  147. Thread.ThreadState.X31 = (ulong)StackTop;
  148. Thread.WorkFinished += ThreadFinished;
  149. ThreadsByTpidr.TryAdd(Thread.ThreadState.Tpidr, ThreadHnd);
  150. return Handle;
  151. }
  152. private void BreakHandler(object sender, AInstExceptionEventArgs e)
  153. {
  154. throw new GuestBrokeExecutionException();
  155. }
  156. private void UndefinedHandler(object sender, AInstUndefinedEventArgs e)
  157. {
  158. throw new UndefinedInstructionException(e.Position, e.RawOpCode);
  159. }
  160. private ATranslator GetTranslator()
  161. {
  162. if (Translator == null)
  163. {
  164. Dictionary<long, string> SymbolTable = new Dictionary<long, string>();
  165. foreach (Executable Exe in Executables)
  166. {
  167. foreach (KeyValuePair<long, string> KV in Exe.SymbolTable)
  168. {
  169. SymbolTable.TryAdd(Exe.ImageBase + KV.Key, KV.Value);
  170. }
  171. }
  172. Translator = new ATranslator(SymbolTable);
  173. Translator.CpuTrace += CpuTraceHandler;
  174. }
  175. return Translator;
  176. }
  177. private void CpuTraceHandler(object sender, ACpuTraceEventArgs e)
  178. {
  179. string NsoName = string.Empty;
  180. for (int Index = Executables.Count - 1; Index >= 0; Index--)
  181. {
  182. if (e.Position >= Executables[Index].ImageBase)
  183. {
  184. NsoName = $"{(e.Position - Executables[Index].ImageBase):x16}";
  185. break;
  186. }
  187. }
  188. Logging.Trace(LogClass.Loader, $"Executing at 0x{e.Position:x16} {e.SubName} {NsoName}");
  189. }
  190. public void EnableCpuTracing()
  191. {
  192. Translator.EnableCpuTrace = true;
  193. }
  194. public void DisableCpuTracing()
  195. {
  196. Translator.EnableCpuTrace = false;
  197. }
  198. private int GetFreeTlsSlot(AThread Thread)
  199. {
  200. for (int Index = 1; Index < TotalTlsSlots; Index++)
  201. {
  202. if (TlsSlots.TryAdd(Index, Thread))
  203. {
  204. return Index;
  205. }
  206. }
  207. throw new InvalidOperationException();
  208. }
  209. private void ThreadFinished(object sender, EventArgs e)
  210. {
  211. if (sender is AThread Thread)
  212. {
  213. Logging.Info(LogClass.KernelScheduler, $"Thread {Thread.ThreadId} exiting...");
  214. TlsSlots.TryRemove(GetTlsSlot(Thread.ThreadState.Tpidr), out _);
  215. }
  216. if (TlsSlots.Count == 0)
  217. {
  218. if (ShouldDispose)
  219. {
  220. Dispose();
  221. }
  222. Logging.Info(LogClass.KernelScheduler, $"No threads running, now exiting Process {ProcessId}...");
  223. Ns.Os.ExitProcess(ProcessId);
  224. }
  225. }
  226. private int GetTlsSlot(long Position)
  227. {
  228. return (int)((Position - MemoryRegions.TlsPagesAddress) / TlsSize);
  229. }
  230. public KThread GetThread(long Tpidr)
  231. {
  232. if (!ThreadsByTpidr.TryGetValue(Tpidr, out KThread Thread))
  233. {
  234. Logging.Error(LogClass.KernelScheduler, $"Thread with TPIDR 0x{Tpidr:x16} not found!");
  235. }
  236. return Thread;
  237. }
  238. public void Dispose()
  239. {
  240. Dispose(true);
  241. }
  242. protected virtual void Dispose(bool Disposing)
  243. {
  244. if (Disposing && !Disposed)
  245. {
  246. //If there is still some thread running, disposing the objects is not
  247. //safe as the thread may try to access those resources. Instead, we set
  248. //the flag to have the Process disposed when all threads finishes.
  249. //Note: This may not happen if the guest code gets stuck on a infinite loop.
  250. if (TlsSlots.Count > 0)
  251. {
  252. ShouldDispose = true;
  253. Logging.Info(LogClass.KernelScheduler, $"Process {ProcessId} waiting all threads terminate...");
  254. return;
  255. }
  256. Disposed = true;
  257. foreach (object Obj in HandleTable.Clear())
  258. {
  259. if (Obj is KSession Session)
  260. {
  261. Session.Dispose();
  262. }
  263. }
  264. INvDrvServices.Fds.DeleteProcess(this);
  265. INvDrvServices.NvMaps .DeleteProcess(this);
  266. INvDrvServices.NvMapsById.DeleteProcess(this);
  267. INvDrvServices.NvMapsFb .DeleteProcess(this);
  268. Scheduler.Dispose();
  269. AppletState.Dispose();
  270. SvcHandler.Dispose();
  271. Memory.Dispose();
  272. Logging.Info(LogClass.KernelScheduler, $"Process {ProcessId} exiting...");
  273. }
  274. }
  275. }
  276. }