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 KThread ThreadArbiterList { get; set; }
  28. public KProcessHandleTable HandleTable { get; private set; }
  29. public AppletStateMgr AppletState { get; private set; }
  30. private SvcHandler SvcHandler;
  31. private ConcurrentDictionary<int, AThread> TlsSlots;
  32. private ConcurrentDictionary<long, KThread> Threads;
  33. private List<Executable> Executables;
  34. private KThread MainThread;
  35. private long ImageBase;
  36. private bool ShouldDispose;
  37. private bool Disposed;
  38. public Process(Switch Ns, KProcessScheduler Scheduler, int ProcessId)
  39. {
  40. this.Ns = Ns;
  41. this.Scheduler = Scheduler;
  42. this.ProcessId = ProcessId;
  43. Memory = new AMemory();
  44. HandleTable = new KProcessHandleTable();
  45. AppletState = new AppletStateMgr();
  46. SvcHandler = new SvcHandler(Ns, this);
  47. TlsSlots = new ConcurrentDictionary<int, AThread>();
  48. Threads = new ConcurrentDictionary<long, KThread>();
  49. Executables = new List<Executable>();
  50. ImageBase = MemoryRegions.AddrSpaceStart;
  51. MapRWMemRegion(
  52. MemoryRegions.TlsPagesAddress,
  53. MemoryRegions.TlsPagesSize,
  54. MemoryType.ThreadLocal);
  55. }
  56. public void LoadProgram(IExecutable Program)
  57. {
  58. if (Disposed)
  59. {
  60. throw new ObjectDisposedException(nameof(Process));
  61. }
  62. Logging.Info(LogClass.Loader, $"Image base at 0x{ImageBase:x16}.");
  63. Executable Executable = new Executable(Program, Memory, ImageBase);
  64. Executables.Add(Executable);
  65. ImageBase = AMemoryHelper.PageRoundUp(Executable.ImageEnd);
  66. }
  67. public void SetEmptyArgs()
  68. {
  69. //TODO: This should be part of Run.
  70. ImageBase += AMemoryMgr.PageSize;
  71. }
  72. public bool Run(bool NeedsHbAbi = false)
  73. {
  74. if (Disposed)
  75. {
  76. throw new ObjectDisposedException(nameof(Process));
  77. }
  78. this.NeedsHbAbi = NeedsHbAbi;
  79. if (Executables.Count == 0)
  80. {
  81. return false;
  82. }
  83. MapRWMemRegion(
  84. MemoryRegions.MainStackAddress,
  85. MemoryRegions.MainStackSize,
  86. MemoryType.Normal);
  87. long StackTop = MemoryRegions.MainStackAddress + MemoryRegions.MainStackSize;
  88. int Handle = MakeThread(Executables[0].ImageBase, StackTop, 0, 44, 0);
  89. if (Handle == -1)
  90. {
  91. return false;
  92. }
  93. MainThread = HandleTable.GetData<KThread>(Handle);
  94. if (NeedsHbAbi)
  95. {
  96. HbAbiDataPosition = AMemoryHelper.PageRoundUp(Executables[0].ImageEnd);
  97. Homebrew.WriteHbAbiData(Memory, HbAbiDataPosition, Handle);
  98. MainThread.Thread.ThreadState.X0 = (ulong)HbAbiDataPosition;
  99. MainThread.Thread.ThreadState.X1 = ulong.MaxValue;
  100. }
  101. Scheduler.StartThread(MainThread);
  102. return true;
  103. }
  104. private void MapRWMemRegion(long Position, long Size, MemoryType Type)
  105. {
  106. Memory.Manager.Map(Position, Size, (int)Type, AMemoryPerm.RW);
  107. }
  108. public void StopAllThreadsAsync()
  109. {
  110. if (Disposed)
  111. {
  112. throw new ObjectDisposedException(nameof(Process));
  113. }
  114. if (MainThread != null)
  115. {
  116. MainThread.Thread.StopExecution();
  117. }
  118. foreach (AThread Thread in TlsSlots.Values)
  119. {
  120. Thread.StopExecution();
  121. }
  122. }
  123. public int MakeThread(
  124. long EntryPoint,
  125. long StackTop,
  126. long ArgsPtr,
  127. int Priority,
  128. int ProcessorId)
  129. {
  130. if (Disposed)
  131. {
  132. throw new ObjectDisposedException(nameof(Process));
  133. }
  134. AThread CpuThread = new AThread(GetTranslator(), Memory, EntryPoint);
  135. KThread Thread = new KThread(CpuThread, ProcessorId, Priority);
  136. int Handle = HandleTable.OpenHandle(Thread);
  137. int ThreadId = GetFreeTlsSlot(CpuThread);
  138. long Tpidr = MemoryRegions.TlsPagesAddress + ThreadId * TlsSize;
  139. CpuThread.ThreadState.ProcessId = ProcessId;
  140. CpuThread.ThreadState.ThreadId = ThreadId;
  141. CpuThread.ThreadState.CntfrqEl0 = TickFreq;
  142. CpuThread.ThreadState.Tpidr = Tpidr;
  143. CpuThread.ThreadState.X0 = (ulong)ArgsPtr;
  144. CpuThread.ThreadState.X1 = (ulong)Handle;
  145. CpuThread.ThreadState.X31 = (ulong)StackTop;
  146. CpuThread.ThreadState.Break += BreakHandler;
  147. CpuThread.ThreadState.SvcCall += SvcHandler.SvcCall;
  148. CpuThread.ThreadState.Undefined += UndefinedHandler;
  149. CpuThread.WorkFinished += ThreadFinished;
  150. Threads.TryAdd(CpuThread.ThreadState.Tpidr, Thread);
  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 (!Threads.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. }