Process.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. using ChocolArm64;
  2. using ChocolArm64.Events;
  3. using ChocolArm64.Memory;
  4. using ChocolArm64.State;
  5. using LibHac;
  6. using Ryujinx.HLE.Exceptions;
  7. using Ryujinx.HLE.HOS.Diagnostics.Demangler;
  8. using Ryujinx.HLE.HOS.Kernel;
  9. using Ryujinx.HLE.HOS.Services.Nv;
  10. using Ryujinx.HLE.HOS.SystemState;
  11. using Ryujinx.HLE.Loaders;
  12. using Ryujinx.HLE.Loaders.Executables;
  13. using Ryujinx.HLE.Loaders.Npdm;
  14. using Ryujinx.HLE.Logging;
  15. using Ryujinx.HLE.Utilities;
  16. using System;
  17. using System.Collections.Concurrent;
  18. using System.Collections.Generic;
  19. using System.IO;
  20. using System.Text;
  21. namespace Ryujinx.HLE.HOS
  22. {
  23. class Process : IDisposable
  24. {
  25. private const int TickFreq = 19_200_000;
  26. public Switch Device { get; private set; }
  27. public bool NeedsHbAbi { get; private set; }
  28. public long HbAbiDataPosition { get; private set; }
  29. public int ProcessId { get; private set; }
  30. private ATranslator Translator;
  31. public AMemory Memory { get; private set; }
  32. public KMemoryManager MemoryManager { get; private set; }
  33. private List<KTlsPageManager> TlsPages;
  34. public Npdm MetaData { get; private set; }
  35. public Nacp ControlData { get; set; }
  36. public KProcessHandleTable HandleTable { get; private set; }
  37. public AppletStateMgr AppletState { get; private set; }
  38. private SvcHandler SvcHandler;
  39. private ConcurrentDictionary<long, KThread> Threads;
  40. private List<Executable> Executables;
  41. private long ImageBase;
  42. private bool Disposed;
  43. public Process(Switch Device, int ProcessId, Npdm MetaData)
  44. {
  45. this.Device = Device;
  46. this.MetaData = MetaData;
  47. this.ProcessId = ProcessId;
  48. Memory = new AMemory(Device.Memory.RamPointer);
  49. MemoryManager = new KMemoryManager(this);
  50. TlsPages = new List<KTlsPageManager>();
  51. HandleTable = new KProcessHandleTable();
  52. AppletState = new AppletStateMgr(Device.System);
  53. SvcHandler = new SvcHandler(Device, this);
  54. Threads = new ConcurrentDictionary<long, KThread>();
  55. Executables = new List<Executable>();
  56. ImageBase = MemoryManager.CodeRegionStart;
  57. }
  58. public void LoadProgram(IExecutable Program)
  59. {
  60. if (Disposed)
  61. {
  62. throw new ObjectDisposedException(nameof(Process));
  63. }
  64. Device.Log.PrintInfo(LogClass.Loader, $"Image base at 0x{ImageBase:x16}.");
  65. Executable Executable = new Executable(Program, MemoryManager, Memory, ImageBase);
  66. Executables.Add(Executable);
  67. ImageBase = IntUtils.AlignUp(Executable.ImageEnd, KMemoryManager.PageSize);
  68. }
  69. public void SetEmptyArgs()
  70. {
  71. //TODO: This should be part of Run.
  72. ImageBase += KMemoryManager.PageSize;
  73. }
  74. public bool Run(bool NeedsHbAbi = false)
  75. {
  76. if (Disposed)
  77. {
  78. throw new ObjectDisposedException(nameof(Process));
  79. }
  80. this.NeedsHbAbi = NeedsHbAbi;
  81. if (Executables.Count == 0)
  82. {
  83. return false;
  84. }
  85. long MainStackTop = MemoryManager.CodeRegionEnd - KMemoryManager.PageSize;
  86. long MainStackSize = 1 * 1024 * 1024;
  87. long MainStackBottom = MainStackTop - MainStackSize;
  88. MemoryManager.HleMapCustom(
  89. MainStackBottom,
  90. MainStackSize,
  91. MemoryState.MappedMemory,
  92. MemoryPermission.ReadAndWrite);
  93. int Handle = MakeThread(Executables[0].ImageBase, MainStackTop, 0, 44, 0);
  94. if (Handle == -1)
  95. {
  96. return false;
  97. }
  98. KThread MainThread = HandleTable.GetData<KThread>(Handle);
  99. if (NeedsHbAbi)
  100. {
  101. HbAbiDataPosition = IntUtils.AlignUp(Executables[0].ImageEnd, KMemoryManager.PageSize);
  102. const long HbAbiDataSize = KMemoryManager.PageSize;
  103. MemoryManager.HleMapCustom(
  104. HbAbiDataPosition,
  105. HbAbiDataSize,
  106. MemoryState.MappedMemory,
  107. MemoryPermission.ReadAndWrite);
  108. string SwitchPath = Device.FileSystem.SystemPathToSwitchPath(Executables[0].FilePath);
  109. Homebrew.WriteHbAbiData(Memory, HbAbiDataPosition, Handle, SwitchPath);
  110. MainThread.Context.ThreadState.X0 = (ulong)HbAbiDataPosition;
  111. MainThread.Context.ThreadState.X1 = ulong.MaxValue;
  112. }
  113. MainThread.TimeUp();
  114. return true;
  115. }
  116. private int ThreadIdCtr = 1;
  117. public int MakeThread(
  118. long EntryPoint,
  119. long StackTop,
  120. long ArgsPtr,
  121. int Priority,
  122. int ProcessorId)
  123. {
  124. if (Disposed)
  125. {
  126. throw new ObjectDisposedException(nameof(Process));
  127. }
  128. AThread CpuThread = new AThread(GetTranslator(), Memory, EntryPoint);
  129. long Tpidr = GetFreeTls();
  130. int ThreadId = ThreadIdCtr++; //(int)((Tpidr - MemoryManager.TlsIoRegionStart) / 0x200) + 1;
  131. KThread Thread = new KThread(CpuThread, this, Device.System, ProcessorId, Priority, ThreadId);
  132. Thread.LastPc = EntryPoint;
  133. int Handle = HandleTable.OpenHandle(Thread);
  134. CpuThread.ThreadState.CntfrqEl0 = TickFreq;
  135. CpuThread.ThreadState.Tpidr = Tpidr;
  136. CpuThread.ThreadState.X0 = (ulong)ArgsPtr;
  137. CpuThread.ThreadState.X1 = (ulong)Handle;
  138. CpuThread.ThreadState.X31 = (ulong)StackTop;
  139. CpuThread.ThreadState.Interrupt += InterruptHandler;
  140. CpuThread.ThreadState.Break += BreakHandler;
  141. CpuThread.ThreadState.SvcCall += SvcHandler.SvcCall;
  142. CpuThread.ThreadState.Undefined += UndefinedHandler;
  143. CpuThread.WorkFinished += ThreadFinished;
  144. Threads.TryAdd(CpuThread.ThreadState.Tpidr, Thread);
  145. return Handle;
  146. }
  147. private long GetFreeTls()
  148. {
  149. long Position;
  150. lock (TlsPages)
  151. {
  152. for (int Index = 0; Index < TlsPages.Count; Index++)
  153. {
  154. if (TlsPages[Index].TryGetFreeTlsAddr(out Position))
  155. {
  156. return Position;
  157. }
  158. }
  159. long PagePosition = MemoryManager.HleMapTlsPage();
  160. KTlsPageManager TlsPage = new KTlsPageManager(PagePosition);
  161. TlsPages.Add(TlsPage);
  162. TlsPage.TryGetFreeTlsAddr(out Position);
  163. }
  164. return Position;
  165. }
  166. private void InterruptHandler(object sender, EventArgs e)
  167. {
  168. Device.System.Scheduler.ContextSwitch();
  169. }
  170. private void BreakHandler(object sender, AInstExceptionEventArgs e)
  171. {
  172. throw new GuestBrokeExecutionException();
  173. }
  174. private void UndefinedHandler(object sender, AInstUndefinedEventArgs e)
  175. {
  176. throw new UndefinedInstructionException(e.Position, e.RawOpCode);
  177. }
  178. public void EnableCpuTracing()
  179. {
  180. Translator.EnableCpuTrace = true;
  181. }
  182. public void DisableCpuTracing()
  183. {
  184. Translator.EnableCpuTrace = false;
  185. }
  186. private void CpuTraceHandler(object sender, ACpuTraceEventArgs e)
  187. {
  188. Executable Exe = GetExecutable(e.Position);
  189. if (Exe == null)
  190. {
  191. return;
  192. }
  193. if (!TryGetSubName(Exe, e.Position, out string SubName))
  194. {
  195. SubName = string.Empty;
  196. }
  197. long Offset = e.Position - Exe.ImageBase;
  198. string ExeNameWithAddr = $"{Exe.Name}:0x{Offset:x8}";
  199. Device.Log.PrintDebug(LogClass.Cpu, ExeNameWithAddr + " " + SubName);
  200. }
  201. private ATranslator GetTranslator()
  202. {
  203. if (Translator == null)
  204. {
  205. Translator = new ATranslator();
  206. Translator.CpuTrace += CpuTraceHandler;
  207. }
  208. return Translator;
  209. }
  210. public void PrintStackTrace(AThreadState ThreadState)
  211. {
  212. StringBuilder Trace = new StringBuilder();
  213. Trace.AppendLine("Guest stack trace:");
  214. void AppendTrace(long Position)
  215. {
  216. Executable Exe = GetExecutable(Position);
  217. if (Exe == null)
  218. {
  219. return;
  220. }
  221. if (!TryGetSubName(Exe, Position, out string SubName))
  222. {
  223. SubName = $"Sub{Position:x16}";
  224. }
  225. else if (SubName.StartsWith("_Z"))
  226. {
  227. SubName = Demangler.Parse(SubName);
  228. }
  229. long Offset = Position - Exe.ImageBase;
  230. string ExeNameWithAddr = $"{Exe.Name}:0x{Offset:x8}";
  231. Trace.AppendLine(" " + ExeNameWithAddr + " " + SubName);
  232. }
  233. long FramePointer = (long)ThreadState.X29;
  234. while (FramePointer != 0)
  235. {
  236. AppendTrace(Memory.ReadInt64(FramePointer + 8));
  237. FramePointer = Memory.ReadInt64(FramePointer);
  238. }
  239. Device.Log.PrintInfo(LogClass.Cpu, Trace.ToString());
  240. }
  241. private bool TryGetSubName(Executable Exe, long Position, out string Name)
  242. {
  243. Position -= Exe.ImageBase;
  244. int Left = 0;
  245. int Right = Exe.SymbolTable.Count - 1;
  246. while (Left <= Right)
  247. {
  248. int Size = Right - Left;
  249. int Middle = Left + (Size >> 1);
  250. ElfSym Symbol = Exe.SymbolTable[Middle];
  251. long EndPosition = Symbol.Value + Symbol.Size;
  252. if ((ulong)Position >= (ulong)Symbol.Value && (ulong)Position < (ulong)EndPosition)
  253. {
  254. Name = Symbol.Name;
  255. return true;
  256. }
  257. if ((ulong)Position < (ulong)Symbol.Value)
  258. {
  259. Right = Middle - 1;
  260. }
  261. else
  262. {
  263. Left = Middle + 1;
  264. }
  265. }
  266. Name = null;
  267. return false;
  268. }
  269. private Executable GetExecutable(long Position)
  270. {
  271. string Name = string.Empty;
  272. for (int Index = Executables.Count - 1; Index >= 0; Index--)
  273. {
  274. if ((ulong)Position >= (ulong)Executables[Index].ImageBase)
  275. {
  276. return Executables[Index];
  277. }
  278. }
  279. return null;
  280. }
  281. private void ThreadFinished(object sender, EventArgs e)
  282. {
  283. if (sender is AThread Thread)
  284. {
  285. if (Threads.TryRemove(Thread.ThreadState.Tpidr, out KThread KernelThread))
  286. {
  287. Device.System.Scheduler.RemoveThread(KernelThread);
  288. }
  289. }
  290. if (Threads.Count == 0)
  291. {
  292. Device.System.ExitProcess(ProcessId);
  293. }
  294. }
  295. public KThread GetThread(long Tpidr)
  296. {
  297. if (!Threads.TryGetValue(Tpidr, out KThread Thread))
  298. {
  299. throw new InvalidOperationException();
  300. }
  301. return Thread;
  302. }
  303. private void Unload()
  304. {
  305. if (Disposed || Threads.Count > 0)
  306. {
  307. return;
  308. }
  309. Disposed = true;
  310. foreach (object Obj in HandleTable.Clear())
  311. {
  312. if (Obj is KSession Session)
  313. {
  314. Session.Dispose();
  315. }
  316. }
  317. INvDrvServices.UnloadProcess(this);
  318. if (NeedsHbAbi && Executables.Count > 0 && Executables[0].FilePath.EndsWith(Homebrew.TemporaryNroSuffix))
  319. {
  320. File.Delete(Executables[0].FilePath);
  321. }
  322. Device.Log.PrintInfo(LogClass.Loader, $"Process {ProcessId} exiting...");
  323. }
  324. public void Dispose()
  325. {
  326. Dispose(true);
  327. }
  328. protected virtual void Dispose(bool Disposing)
  329. {
  330. if (Disposing)
  331. {
  332. if (Threads.Count > 0)
  333. {
  334. foreach (KThread Thread in Threads.Values)
  335. {
  336. Device.System.Scheduler.StopThread(Thread);
  337. }
  338. }
  339. else
  340. {
  341. Unload();
  342. }
  343. }
  344. }
  345. }
  346. }