Ryujinx/Ryujinx.Core/OsHle/Process.cs

425 lines
12 KiB
C#
Raw Normal View History

2018-02-05 00:08:20 +01:00
using ChocolArm64;
using ChocolArm64.Events;
2018-02-05 00:08:20 +01:00
using ChocolArm64.Memory;
using ChocolArm64.State;
using Ryujinx.Core.Loaders;
using Ryujinx.Core.Loaders.Executables;
2018-04-24 20:57:39 +02:00
using Ryujinx.Core.Logging;
using Ryujinx.Core.OsHle.Exceptions;
using Ryujinx.Core.OsHle.Handles;
using Ryujinx.Core.OsHle.Kernel;
2018-03-20 21:00:00 +01:00
using Ryujinx.Core.OsHle.Services.Nv;
2018-02-05 00:08:20 +01:00
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
2018-02-05 00:08:20 +01:00
namespace Ryujinx.Core.OsHle
2018-02-05 00:08:20 +01:00
{
class Process : IDisposable
2018-02-05 00:08:20 +01:00
{
2018-04-06 15:53:18 +02:00
private const int TlsSize = 0x200;
private const int TotalTlsSlots = (int)MemoryRegions.TlsPagesSize / TlsSize;
2018-02-05 00:08:20 +01:00
private const int TickFreq = 19_200_000;
2018-02-05 00:08:20 +01:00
private Switch Ns;
public bool NeedsHbAbi { get; private set; }
public long HbAbiDataPosition { get; private set; }
2018-02-05 00:08:20 +01:00
public int ProcessId { get; private set; }
private ATranslator Translator;
2018-02-05 00:08:20 +01:00
public AMemory Memory { get; private set; }
public KProcessScheduler Scheduler { get; private set; }
2018-02-05 00:08:20 +01:00
public KThread ThreadArbiterList { get; set; }
public KProcessHandleTable HandleTable { get; private set; }
public AppletStateMgr AppletState { get; private set; }
2018-02-14 06:43:21 +01:00
private SvcHandler SvcHandler;
2018-02-05 00:08:20 +01:00
private ConcurrentDictionary<int, AThread> TlsSlots;
private ConcurrentDictionary<long, KThread> Threads;
private KThread MainThread;
2018-02-05 00:08:20 +01:00
private List<Executable> Executables;
private Dictionary<long, string> SymbolTable;
2018-02-05 00:08:20 +01:00
private long ImageBase;
private bool ShouldDispose;
private bool Disposed;
public Process(Switch Ns, KProcessScheduler Scheduler, int ProcessId)
2018-02-05 00:08:20 +01:00
{
this.Ns = Ns;
this.Scheduler = Scheduler;
2018-02-05 00:08:20 +01:00
this.ProcessId = ProcessId;
Memory = new AMemory();
HandleTable = new KProcessHandleTable();
AppletState = new AppletStateMgr();
SvcHandler = new SvcHandler(Ns, this);
TlsSlots = new ConcurrentDictionary<int, AThread>();
Threads = new ConcurrentDictionary<long, KThread>();
2018-02-05 00:08:20 +01:00
Executables = new List<Executable>();
ImageBase = MemoryRegions.AddrSpaceStart;
2018-02-05 00:08:20 +01:00
MapRWMemRegion(
MemoryRegions.TlsPagesAddress,
MemoryRegions.TlsPagesSize,
MemoryType.ThreadLocal);
2018-02-05 00:08:20 +01:00
}
public void LoadProgram(IExecutable Program)
2018-02-05 00:08:20 +01:00
{
if (Disposed)
{
throw new ObjectDisposedException(nameof(Process));
}
2018-04-24 20:57:39 +02:00
Ns.Log.PrintInfo(LogClass.Loader, $"Image base at 0x{ImageBase:x16}.");
2018-02-05 00:08:20 +01:00
Executable Executable = new Executable(Program, Memory, ImageBase);
Executables.Add(Executable);
ImageBase = AMemoryHelper.PageRoundUp(Executable.ImageEnd);
}
public void SetEmptyArgs()
{
//TODO: This should be part of Run.
2018-02-05 00:08:20 +01:00
ImageBase += AMemoryMgr.PageSize;
}
public bool Run(bool NeedsHbAbi = false)
2018-02-05 00:08:20 +01:00
{
if (Disposed)
{
throw new ObjectDisposedException(nameof(Process));
}
this.NeedsHbAbi = NeedsHbAbi;
2018-02-05 00:08:20 +01:00
if (Executables.Count == 0)
{
return false;
}
MakeSymbolTable();
MapRWMemRegion(
MemoryRegions.MainStackAddress,
MemoryRegions.MainStackSize,
MemoryType.Normal);
2018-04-05 00:29:34 +02:00
long StackTop = MemoryRegions.MainStackAddress + MemoryRegions.MainStackSize;
2018-02-05 00:08:20 +01:00
int Handle = MakeThread(Executables[0].ImageBase, StackTop, 0, 44, 0);
2018-02-05 00:08:20 +01:00
if (Handle == -1)
{
return false;
}
MainThread = HandleTable.GetData<KThread>(Handle);
2018-02-05 00:08:20 +01:00
if (NeedsHbAbi)
{
HbAbiDataPosition = AMemoryHelper.PageRoundUp(Executables[0].ImageEnd);
Homebrew.WriteHbAbiData(Memory, HbAbiDataPosition, Handle);
MainThread.Thread.ThreadState.X0 = (ulong)HbAbiDataPosition;
MainThread.Thread.ThreadState.X1 = ulong.MaxValue;
}
Scheduler.StartThread(MainThread);
2018-02-05 00:08:20 +01:00
return true;
}
private void MapRWMemRegion(long Position, long Size, MemoryType Type)
{
Memory.Manager.Map(Position, Size, (int)Type, AMemoryPerm.RW);
}
public void StopAllThreadsAsync()
2018-02-05 00:08:20 +01:00
{
if (Disposed)
{
throw new ObjectDisposedException(nameof(Process));
}
2018-02-05 00:08:20 +01:00
if (MainThread != null)
{
MainThread.Thread.StopExecution();
2018-02-05 00:08:20 +01:00
}
foreach (AThread Thread in TlsSlots.Values)
{
Thread.StopExecution();
2018-02-05 00:08:20 +01:00
}
}
public int MakeThread(
long EntryPoint,
long StackTop,
long ArgsPtr,
int Priority,
int ProcessorId)
{
if (Disposed)
{
throw new ObjectDisposedException(nameof(Process));
}
AThread CpuThread = new AThread(GetTranslator(), Memory, EntryPoint);
KThread Thread = new KThread(CpuThread, ProcessorId, Priority);
2018-02-05 00:08:20 +01:00
int Handle = HandleTable.OpenHandle(Thread);
2018-02-05 00:08:20 +01:00
int ThreadId = GetFreeTlsSlot(CpuThread);
2018-02-05 00:08:20 +01:00
long Tpidr = MemoryRegions.TlsPagesAddress + ThreadId * TlsSize;
CpuThread.ThreadState.ProcessId = ProcessId;
CpuThread.ThreadState.ThreadId = ThreadId;
CpuThread.ThreadState.CntfrqEl0 = TickFreq;
CpuThread.ThreadState.Tpidr = Tpidr;
CpuThread.ThreadState.X0 = (ulong)ArgsPtr;
CpuThread.ThreadState.X1 = (ulong)Handle;
CpuThread.ThreadState.X31 = (ulong)StackTop;
CpuThread.ThreadState.Break += BreakHandler;
CpuThread.ThreadState.SvcCall += SvcHandler.SvcCall;
CpuThread.ThreadState.Undefined += UndefinedHandler;
2018-02-05 00:08:20 +01:00
CpuThread.WorkFinished += ThreadFinished;
2018-02-05 00:08:20 +01:00
Threads.TryAdd(CpuThread.ThreadState.Tpidr, Thread);
2018-02-05 00:08:20 +01:00
return Handle;
}
private void BreakHandler(object sender, AInstExceptionEventArgs e)
{
throw new GuestBrokeExecutionException();
}
private void UndefinedHandler(object sender, AInstUndefinedEventArgs e)
{
throw new UndefinedInstructionException(e.Position, e.RawOpCode);
}
private void MakeSymbolTable()
{
SymbolTable = new Dictionary<long, string>();
foreach (Executable Exe in Executables)
{
foreach (KeyValuePair<long, string> KV in Exe.SymbolTable)
{
SymbolTable.TryAdd(Exe.ImageBase + KV.Key, KV.Value);
}
}
}
private ATranslator GetTranslator()
{
if (Translator == null)
{
Translator = new ATranslator(SymbolTable);
Translator.CpuTrace += CpuTraceHandler;
}
return Translator;
}
public void EnableCpuTracing()
{
Translator.EnableCpuTrace = true;
}
public void DisableCpuTracing()
{
Translator.EnableCpuTrace = false;
}
private void CpuTraceHandler(object sender, ACpuTraceEventArgs e)
{
string NsoName = string.Empty;
for (int Index = Executables.Count - 1; Index >= 0; Index--)
{
if (e.Position >= Executables[Index].ImageBase)
{
NsoName = $"{(e.Position - Executables[Index].ImageBase):x16}";
2018-04-05 00:29:34 +02:00
break;
}
}
2018-04-24 20:57:39 +02:00
Ns.Log.PrintDebug(LogClass.Cpu, $"Executing at 0x{e.Position:x16} {e.SubName} {NsoName}");
}
public void PrintStackTrace(AThreadState ThreadState)
{
long[] Positions = ThreadState.GetCallStack();
StringBuilder Trace = new StringBuilder();
Trace.AppendLine("Guest stack trace:");
foreach (long Position in Positions)
{
if (!SymbolTable.TryGetValue(Position, out string SubName))
{
SubName = $"Sub{Position:x16}";
}
Trace.AppendLine(" " + SubName + " (" + GetNsoNameAndAddress(Position) + ")");
}
2018-04-24 20:57:39 +02:00
Ns.Log.PrintInfo(LogClass.Cpu, Trace.ToString());
}
private string GetNsoNameAndAddress(long Position)
{
string Name = string.Empty;
for (int Index = Executables.Count - 1; Index >= 0; Index--)
{
if (Position >= Executables[Index].ImageBase)
{
long Offset = Position - Executables[Index].ImageBase;
Name = $"{Executables[Index].Name}:{Offset:x8}";
break;
}
}
return Name;
}
2018-02-05 00:08:20 +01:00
private int GetFreeTlsSlot(AThread Thread)
{
for (int Index = 1; Index < TotalTlsSlots; Index++)
{
if (TlsSlots.TryAdd(Index, Thread))
{
return Index;
}
}
throw new InvalidOperationException();
2018-02-05 00:08:20 +01:00
}
private void ThreadFinished(object sender, EventArgs e)
{
if (sender is AThread Thread)
{
2018-02-18 20:28:07 +01:00
TlsSlots.TryRemove(GetTlsSlot(Thread.ThreadState.Tpidr), out _);
Threads.TryRemove(Thread.ThreadState.Tpidr, out KThread KernelThread);
Scheduler.RemoveThread(KernelThread);
KernelThread.WaitEvent.Set();
}
2018-02-05 00:08:20 +01:00
if (TlsSlots.Count == 0)
{
if (ShouldDispose)
{
Dispose();
}
Ns.Os.ExitProcess(ProcessId);
2018-02-05 00:08:20 +01:00
}
}
private int GetTlsSlot(long Position)
{
return (int)((Position - MemoryRegions.TlsPagesAddress) / TlsSize);
2018-02-05 00:08:20 +01:00
}
public KThread GetThread(long Tpidr)
{
if (!Threads.TryGetValue(Tpidr, out KThread Thread))
2018-02-19 20:37:13 +01:00
{
2018-04-24 20:57:39 +02:00
throw new InvalidOperationException();
2018-02-19 20:37:13 +01:00
}
return Thread;
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool Disposing)
{
if (Disposing && !Disposed)
{
//If there is still some thread running, disposing the objects is not
//safe as the thread may try to access those resources. Instead, we set
//the flag to have the Process disposed when all threads finishes.
//Note: This may not happen if the guest code gets stuck on a infinite loop.
if (TlsSlots.Count > 0)
{
ShouldDispose = true;
2018-04-24 20:57:39 +02:00
Ns.Log.PrintInfo(LogClass.Loader, $"Process {ProcessId} waiting all threads terminate...");
return;
}
Disposed = true;
foreach (object Obj in HandleTable.Clear())
{
if (Obj is KSession Session)
{
Session.Dispose();
}
}
INvDrvServices.UnloadProcess(this);
AppletState.Dispose();
SvcHandler.Dispose();
Memory.Dispose();
2018-04-24 20:57:39 +02:00
Ns.Log.PrintInfo(LogClass.Loader, $"Process {ProcessId} exiting...");
}
}
2018-02-05 00:08:20 +01:00
}
}