Process.cs 12 KB

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