Process.cs 10 KB

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