Process.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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.Kernel;
  9. using Ryujinx.Core.OsHle.Services.Nv;
  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, KProcessScheduler Scheduler, int ProcessId)
  38. {
  39. this.Ns = Ns;
  40. this.Scheduler = Scheduler;
  41. this.ProcessId = ProcessId;
  42. Memory = new AMemory();
  43. HandleTable = new KProcessHandleTable();
  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, 44, 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 KernelThread = new KThread(Thread, ProcessorId, Priority);
  135. int Handle = HandleTable.OpenHandle(KernelThread);
  136. KernelThread.Handle = Handle;
  137. int ThreadId = GetFreeTlsSlot(Thread);
  138. long Tpidr = MemoryRegions.TlsPagesAddress + ThreadId * TlsSize;
  139. Thread.ThreadState.ProcessId = ProcessId;
  140. Thread.ThreadState.ThreadId = ThreadId;
  141. Thread.ThreadState.CntfrqEl0 = TickFreq;
  142. Thread.ThreadState.Tpidr = Tpidr;
  143. Thread.ThreadState.X0 = (ulong)ArgsPtr;
  144. Thread.ThreadState.X1 = (ulong)Handle;
  145. Thread.ThreadState.X31 = (ulong)StackTop;
  146. Thread.ThreadState.Break += BreakHandler;
  147. Thread.ThreadState.SvcCall += SvcHandler.SvcCall;
  148. Thread.ThreadState.Undefined += UndefinedHandler;
  149. Thread.WorkFinished += ThreadFinished;
  150. ThreadsByTpidr.TryAdd(Thread.ThreadState.Tpidr, KernelThread);
  151. return Handle;
  152. }
  153. private void BreakHandler(object sender, AInstExceptionEventArgs e)
  154. {
  155. throw new GuestBrokeExecutionException();
  156. }
  157. private void UndefinedHandler(object sender, AInstUndefinedEventArgs e)
  158. {
  159. throw new UndefinedInstructionException(e.Position, e.RawOpCode);
  160. }
  161. private ATranslator GetTranslator()
  162. {
  163. if (Translator == null)
  164. {
  165. Dictionary<long, string> SymbolTable = new Dictionary<long, string>();
  166. foreach (Executable Exe in Executables)
  167. {
  168. foreach (KeyValuePair<long, string> KV in Exe.SymbolTable)
  169. {
  170. SymbolTable.TryAdd(Exe.ImageBase + KV.Key, KV.Value);
  171. }
  172. }
  173. Translator = new ATranslator(SymbolTable);
  174. Translator.CpuTrace += CpuTraceHandler;
  175. }
  176. return Translator;
  177. }
  178. private void CpuTraceHandler(object sender, ACpuTraceEventArgs e)
  179. {
  180. string NsoName = string.Empty;
  181. for (int Index = Executables.Count - 1; Index >= 0; Index--)
  182. {
  183. if (e.Position >= Executables[Index].ImageBase)
  184. {
  185. NsoName = $"{(e.Position - Executables[Index].ImageBase):x16}";
  186. break;
  187. }
  188. }
  189. Logging.Trace(LogClass.Loader, $"Executing at 0x{e.Position:x16} {e.SubName} {NsoName}");
  190. }
  191. public void EnableCpuTracing()
  192. {
  193. Translator.EnableCpuTrace = true;
  194. }
  195. public void DisableCpuTracing()
  196. {
  197. Translator.EnableCpuTrace = false;
  198. }
  199. private int GetFreeTlsSlot(AThread Thread)
  200. {
  201. for (int Index = 1; Index < TotalTlsSlots; Index++)
  202. {
  203. if (TlsSlots.TryAdd(Index, Thread))
  204. {
  205. return Index;
  206. }
  207. }
  208. throw new InvalidOperationException();
  209. }
  210. private void ThreadFinished(object sender, EventArgs e)
  211. {
  212. if (sender is AThread Thread)
  213. {
  214. Logging.Info(LogClass.KernelScheduler, $"Thread {Thread.ThreadId} exiting...");
  215. TlsSlots.TryRemove(GetTlsSlot(Thread.ThreadState.Tpidr), out _);
  216. KThread KernelThread = GetThread(Thread.ThreadState.Tpidr);
  217. Scheduler.RemoveThread(KernelThread);
  218. KernelThread.WaitEvent.Set();
  219. }
  220. if (TlsSlots.Count == 0)
  221. {
  222. if (ShouldDispose)
  223. {
  224. Dispose();
  225. }
  226. Logging.Info(LogClass.KernelScheduler, $"No threads running, now exiting Process {ProcessId}...");
  227. Ns.Os.ExitProcess(ProcessId);
  228. }
  229. }
  230. private int GetTlsSlot(long Position)
  231. {
  232. return (int)((Position - MemoryRegions.TlsPagesAddress) / TlsSize);
  233. }
  234. public KThread GetThread(long Tpidr)
  235. {
  236. if (!ThreadsByTpidr.TryGetValue(Tpidr, out KThread Thread))
  237. {
  238. Logging.Error(LogClass.KernelScheduler, $"Thread with TPIDR 0x{Tpidr:x16} not found!");
  239. }
  240. return Thread;
  241. }
  242. public void Dispose()
  243. {
  244. Dispose(true);
  245. }
  246. protected virtual void Dispose(bool Disposing)
  247. {
  248. if (Disposing && !Disposed)
  249. {
  250. //If there is still some thread running, disposing the objects is not
  251. //safe as the thread may try to access those resources. Instead, we set
  252. //the flag to have the Process disposed when all threads finishes.
  253. //Note: This may not happen if the guest code gets stuck on a infinite loop.
  254. if (TlsSlots.Count > 0)
  255. {
  256. ShouldDispose = true;
  257. Logging.Info(LogClass.KernelScheduler, $"Process {ProcessId} waiting all threads terminate...");
  258. return;
  259. }
  260. Disposed = true;
  261. foreach (object Obj in HandleTable.Clear())
  262. {
  263. if (Obj is KSession Session)
  264. {
  265. Session.Dispose();
  266. }
  267. }
  268. INvDrvServices.Fds.DeleteProcess(this);
  269. INvDrvServices.NvMaps .DeleteProcess(this);
  270. INvDrvServices.NvMapsById.DeleteProcess(this);
  271. INvDrvServices.NvMapsFb .DeleteProcess(this);
  272. AppletState.Dispose();
  273. SvcHandler.Dispose();
  274. Memory.Dispose();
  275. Logging.Info(LogClass.KernelScheduler, $"Process {ProcessId} exiting...");
  276. }
  277. }
  278. }
  279. }