Process.cs 10.0 KB

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