Compare commits

..

25 Commits

Author SHA1 Message Date
Coxxs
0c165c3f62 Move ProcessInfo and Minidump to HleProcessDebugger (ryubing/ryujinx!187)
See merge request ryubing/ryujinx!187
2025-10-22 16:20:13 -05:00
GreemDev
91da244c02 gdb: some more cleanups 2025-10-22 15:04:03 -05:00
GreemDev
904d4a7eb0 gdb: Make waiting for a process to start more forgiving (200ms per poll 10x -> 500ms) 2025-10-22 01:07:19 -05:00
Coxxs
1248a054de gdb: Abort if unable to start GDB server (ryubing/ryujinx!186)
See merge request ryubing/ryujinx!186
2025-10-21 23:16:18 -05:00
GreemDev
1bb2af84ce gdb: Catch SocketException from TcpListener#Start 2025-10-21 22:15:14 -05:00
GreemDev
886981004d chore: I thought I removed these months ago lol 2025-10-21 20:33:35 -05:00
Coxxs
e551dda17e gdb: fix IsProcess32Bit throws exception if called too early (ryubing/ryujinx!185)
See merge request ryubing/ryujinx!185
2025-10-20 21:35:55 -05:00
GreemDev
ed67535227 chore: [si skip] fix in-code typos 2025-10-20 21:32:23 -05:00
GreemDev
7d65611b96 gdb: [ci skip] just had a brain wave 2025-10-20 21:20:41 -05:00
GreemDev
71eb844dd8 gdb: dynamic rcmd system & more cleanups 2025-10-20 21:18:16 -05:00
Coxxs
a0e5edf8ba gdb: Support qAttached; Add missing ReplyOK when detach (ryubing/ryujinx!184)
See merge request ryubing/ryujinx!184
2025-10-20 21:12:16 -05:00
Coxxs
6541ad0726 Implement IUserServiceCreator: 1 (CreateClientProcessMonitor) (ryubing/ryujinx!181)
See merge request ryubing/ryujinx!181
2025-10-20 19:14:42 -05:00
Coxxs
1c084373c9 Update LoadIdTokenCache for 19.0.0+ (ryubing/ryujinx!182)
See merge request ryubing/ryujinx!182
2025-10-20 17:37:16 -05:00
GreemDev
5b3b907fd2 [ci skip] chore: Fix usage of var 2025-10-20 02:42:57 -05:00
Hack茶ん
f46577af58 [ci skip] Update Korean translation (ryubing/ryujinx!174)
See merge request ryubing/ryujinx!174
2025-10-19 17:43:34 -05:00
Xam
0e218754f5 Fix duplicate volume and mode change events in AppHost (ryubing/ryujinx!176)
See merge request ryubing/ryujinx!176
2025-10-19 17:41:21 -05:00
Xam
0c6d4a07b9 Input: AvaloniaMouseDriver: fix native touch inputs (ryubing/ryujinx!178)
See merge request ryubing/ryujinx!178
2025-10-19 17:33:24 -05:00
Xam
8714b010f6 Horizon: Audio: HwopusIpcServer: fix random crashes regression in Pokemon Quest (ryubing/ryujinx!175)
See merge request ryubing/ryujinx!175
2025-10-19 17:17:46 -05:00
GreemDev
d1d4a735a6 docs: use the real repo in COMPILING.md 2025-10-19 14:48:41 -05:00
GreemDev
247e2e03d6 gdb: More cleanup changes
- Move the message handler into its debugger class part,
- Move all message types into one file and collapse 3 of the ones with no data into a generic, stateless message with a single property being its type,
- Add an Fpscr helper property on IExecutionContext along with a comment about what Fpscr is (similar to the other registers in there)
- Moved the Rcmd helpers (such as GetRegisters, GetMinidump, etc) into a dedicated Debugger class part,
- Fixed the double-collection (ToArray being called twice) in GetThreadUids & GetThread in KProcess
2025-10-19 04:26:12 -05:00
GreemDev
6058af5119 chore: cleanup unused usings in Ryujinx.HLE 2025-10-19 04:17:02 -05:00
GreemDev
e11eff0f41 gdb: more cleanups
- convert GdbRegisters utilities into extensions on IExecutionContext

- add a Write/Read Register helper on Debugger that handles 32/64 bit instead of doing that for every usage of register reading/writing
2025-10-18 03:01:21 -05:00
GreemDev
2a2ab523cb gdb: Code cleanup pass #2
Moved the reply functionality into the command processor, move the main debugger thread into a dedicated class part, and more
2025-10-17 00:09:51 -05:00
Coxxs
8e941e4a8f gdb: Cleanup (ryubing/ryujinx!171)
See merge request ryubing/ryujinx!171
2025-10-16 19:53:51 -05:00
Hack茶ん
9aacf9b37b Update Korean translation (ryubing/ryujinx!168)
See merge request ryubing/ryujinx!168
2025-10-16 19:45:14 -05:00
69 changed files with 969 additions and 1032 deletions

View File

@@ -10,7 +10,7 @@ Make sure your SDK version is higher or equal to the required version specified
### Step 2
Either use `git clone https://github.com/Ryubing/Ryujinx` on the command line to clone the repository or use Code --> Download zip button to get the files.
Either use `git clone https://git.ryujinx.app/ryubing/ryujinx.git` on the command line to clone the repository or use Code --> Download zip button to get the files.
### Step 3

View File

@@ -3629,7 +3629,7 @@
"he_IL": "ממשק קלאסי (הפעלה מחדש דרושה)",
"it_IT": "Interfaccia classica (Riavvio necessario)",
"ja_JP": "クラシックインターフェース(再起動必要)",
"ko_KR": "클래식 인터페이스 (재시작 필요)",
"ko_KR": "클래식 인터페이스(다시 시작 필요)",
"no_NO": "Klassisk grensesnitt (Krever omstart)",
"pl_PL": "Klasyczny interfejs (Wymaga restartu)",
"pt_BR": "Interface Clássica (Reinício necessário)",
@@ -6454,7 +6454,7 @@
"he_IL": "",
"it_IT": "Voglio ripristinare le mie impostazioni.",
"ja_JP": "",
"ko_KR": "설정을 초기화하고 싶습니다.",
"ko_KR": "설정을 초기화하고자 합니다.",
"no_NO": "Jeg vil tilbakestille innstillingene mine.",
"pl_PL": "",
"pt_BR": "Quero redefinir minhas configurações.",

View File

@@ -94,7 +94,7 @@ namespace Ryujinx.Common.Logging.Targets
return;
}
using var signal = new ManualResetEventSlim(false);
using ManualResetEventSlim signal = new ManualResetEventSlim(false);
try
{
_messageQueue.Add(new FlushEventArgs(signal));

View File

@@ -42,6 +42,11 @@ namespace Ryujinx.Cpu
/// </summary>
uint Fpsr { get; set; }
/// <summary>
/// Floating-point Status and Control Register.
/// </summary>
uint Fpscr => Fpsr | Fpcr;
/// <summary>
/// Indicates whenever the CPU is running 64-bit (AArch64 mode) or 32-bit (AArch32 mode) code.
/// </summary>

View File

@@ -205,7 +205,7 @@ namespace Ryujinx.Graphics.Gpu.Shader
GpuChannelComputeState computeState,
ulong gpuVa)
{
if (_cpPrograms.TryGetValue(gpuVa, out var cpShader) && IsShaderEqual(channel, poolState, computeState, cpShader, gpuVa))
if (_cpPrograms.TryGetValue(gpuVa, out CachedShaderProgram cpShader) && IsShaderEqual(channel, poolState, computeState, cpShader, gpuVa))
{
return cpShader;
}
@@ -252,8 +252,8 @@ namespace Ryujinx.Graphics.Gpu.Shader
{
channel.TextureManager.UpdateRenderTargets();
var rtControl = state.RtControl;
var msaaMode = state.RtMsaaMode;
RtControl rtControl = state.RtControl;
TextureMsaaMode msaaMode = state.RtMsaaMode;
pipeline.SamplesCount = msaaMode.SamplesInX() * msaaMode.SamplesInY();
@@ -267,7 +267,7 @@ namespace Ryujinx.Graphics.Gpu.Shader
{
int rtIndex = rtControl.UnpackPermutationIndex(index);
var colorState = rtColorStateSpan[rtIndex];
RtColorState colorState = rtColorStateSpan[rtIndex];
if (index >= count || colorState.Format == 0 || colorState.WidthOrStride == 0)
{
@@ -312,12 +312,12 @@ namespace Ryujinx.Graphics.Gpu.Shader
ref GpuChannelGraphicsState graphicsState,
ShaderAddresses addresses)
{
if (_gpPrograms.TryGetValue(addresses, out var gpShaders) && IsShaderEqual(channel, ref poolState, ref graphicsState, gpShaders, addresses))
if (_gpPrograms.TryGetValue(addresses, out CachedShaderProgram gpShaders) && IsShaderEqual(channel, ref poolState, ref graphicsState, gpShaders, addresses))
{
return gpShaders;
}
if (_graphicsShaderCache.TryFind(channel, ref poolState, ref graphicsState, addresses, out gpShaders, out var cachedGuestCode))
if (_graphicsShaderCache.TryFind(channel, ref poolState, ref graphicsState, addresses, out gpShaders, out CachedGraphicsGuestCode cachedGuestCode))
{
_gpPrograms[addresses] = gpShaders;
return gpShaders;
@@ -590,7 +590,7 @@ namespace Ryujinx.Graphics.Gpu.Shader
for (int i = 0; i < Constants.TotalTransformFeedbackBuffers; i++)
{
var tf = tfStateSpan[i];
TfState tf = tfStateSpan[i];
descs[i] = new TransformFeedbackDescriptor(
tf.BufferIndex,
@@ -696,7 +696,7 @@ namespace Ryujinx.Graphics.Gpu.Shader
/// <returns>The generated translator context</returns>
public static TranslatorContext DecodeComputeShader(IGpuAccessor gpuAccessor, TargetApi api, ulong gpuVa)
{
var options = CreateTranslationOptions(api, DefaultFlags | TranslationFlags.Compute);
TranslationOptions options = CreateTranslationOptions(api, DefaultFlags | TranslationFlags.Compute);
return Translator.CreateContext(gpuVa, gpuAccessor, options);
}
@@ -713,7 +713,7 @@ namespace Ryujinx.Graphics.Gpu.Shader
/// <returns>The generated translator context</returns>
public static TranslatorContext DecodeGraphicsShader(IGpuAccessor gpuAccessor, TargetApi api, TranslationFlags flags, ulong gpuVa)
{
var options = CreateTranslationOptions(api, flags);
TranslationOptions options = CreateTranslationOptions(api, flags);
return Translator.CreateContext(gpuVa, gpuAccessor, options);
}
@@ -739,7 +739,7 @@ namespace Ryujinx.Graphics.Gpu.Shader
{
ulong cb1DataAddress = channel.BufferManager.GetGraphicsUniformBufferAddress(0, 1);
var memoryManager = channel.MemoryManager;
MemoryManager memoryManager = channel.MemoryManager;
codeA ??= memoryManager.GetSpan(vertexA.Address, vertexA.Size).ToArray();
codeB ??= memoryManager.GetSpan(currentStage.Address, currentStage.Size).ToArray();
@@ -777,7 +777,7 @@ namespace Ryujinx.Graphics.Gpu.Shader
/// <returns>Compiled graphics shader code</returns>
private static TranslatedShader TranslateShader(ShaderDumper dumper, GpuChannel channel, TranslatorContext context, byte[] code, bool asCompute)
{
var memoryManager = channel.MemoryManager;
MemoryManager memoryManager = channel.MemoryManager;
ulong cb1DataAddress = context.Stage == ShaderStage.Compute
? channel.BufferManager.GetComputeUniformBufferAddress(1)

View File

@@ -1,22 +0,0 @@
using SharpMetal;
using SharpMetal.Foundation;
using SharpMetal.ObjectiveCCore;
using SharpMetal.QuartzCore;
using System.Runtime.Versioning;
// ReSharper disable InconsistentNaming
namespace Ryujinx.Graphics.Metal.SharpMetalExtensions
{
[SupportedOSPlatform("macOS")]
public static class CAMetalLayerExtensions
{
private static readonly Selector sel_developerHUDProperties = "developerHUDProperties";
private static readonly Selector sel_setDeveloperHUDProperties = "setDeveloperHUDProperties:";
public static NSDictionary GetDeveloperHudProperties(this CAMetalLayer metalLayer)
=> new(ObjectiveCRuntime.IntPtr_objc_msgSend(metalLayer.NativePtr, sel_developerHUDProperties));
public static void SetDeveloperHudProperties(this CAMetalLayer metalLayer, NSDictionary dictionary)
=> ObjectiveCRuntime.objc_msgSend(metalLayer.NativePtr, sel_setDeveloperHUDProperties, dictionary);
}
}

View File

@@ -1,32 +0,0 @@
using SharpMetal.Foundation;
using SharpMetal.ObjectiveCCore;
using System.Runtime.Versioning;
// ReSharper disable InconsistentNaming
namespace Ryujinx.Graphics.Metal.SharpMetalExtensions
{
[SupportedOSPlatform("macOS")]
public static class NSHelper
{
private static readonly Selector sel_getCStringMaxLengthEncoding = "getCString:maxLength:encoding:";
private static readonly Selector sel_stringWithUTF8String = "stringWithUTF8String:";
public static unsafe string ToDotNetString(this NSString source)
{
char[] sourceBuffer = new char[source.Length];
fixed (char* pSourceBuffer = sourceBuffer)
{
ObjectiveC.bool_objc_msgSend(source,
sel_getCStringMaxLengthEncoding,
pSourceBuffer,
source.MaximumLengthOfBytes(NSStringEncoding.UTF16) + 1,
(ulong)NSStringEncoding.UTF16);
}
return new string(sourceBuffer);
}
public static NSString ToNSString(this string source)
=> new(ObjectiveC.IntPtr_objc_msgSend(new ObjectiveCClass(nameof(NSString)), sel_stringWithUTF8String, source));
}
}

View File

@@ -1,11 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="SharpMetal" />
</ItemGroup>
</Project>

View File

@@ -93,7 +93,7 @@ namespace Ryujinx.Graphics.Shader.Translation
size = DefaultLocalMemorySize;
}
var lmem = new MemoryDefinition("local_memory", AggregateType.Array | AggregateType.U32, BitUtils.DivRoundUp(size, sizeof(uint)));
MemoryDefinition lmem = new MemoryDefinition("local_memory", AggregateType.Array | AggregateType.U32, BitUtils.DivRoundUp(size, sizeof(uint)));
LocalMemoryId = Properties.AddLocalMemory(lmem);
}
@@ -112,7 +112,7 @@ namespace Ryujinx.Graphics.Shader.Translation
size = DefaultSharedMemorySize;
}
var smem = new MemoryDefinition("shared_memory", AggregateType.Array | AggregateType.U32, BitUtils.DivRoundUp(size, sizeof(uint)));
MemoryDefinition smem = new MemoryDefinition("shared_memory", AggregateType.Array | AggregateType.U32, BitUtils.DivRoundUp(size, sizeof(uint)));
SharedMemoryId = Properties.AddSharedMemory(smem);
}
@@ -273,16 +273,16 @@ namespace Ryujinx.Graphics.Shader.Translation
bool coherent,
bool separate)
{
var dimensions = type == SamplerType.None ? 0 : type.GetDimensions();
var dict = isImage ? _usedImages : _usedTextures;
int dimensions = type == SamplerType.None ? 0 : type.GetDimensions();
Dictionary<TextureInfo, TextureMeta> dict = isImage ? _usedImages : _usedTextures;
var usageFlags = TextureUsageFlags.None;
TextureUsageFlags usageFlags = TextureUsageFlags.None;
if (intCoords)
{
usageFlags |= TextureUsageFlags.NeedsScaleValue;
var canScale = _stage.SupportsRenderScale() && arrayLength == 1 && !write && dimensions == 2;
bool canScale = _stage.SupportsRenderScale() && arrayLength == 1 && !write && dimensions == 2;
if (!canScale)
{
@@ -304,9 +304,9 @@ namespace Ryujinx.Graphics.Shader.Translation
// For array textures, we also want to use type as key,
// since we may have texture handles stores in the same buffer, but for textures with different types.
var keyType = arrayLength > 1 ? type : SamplerType.None;
var info = new TextureInfo(cbufSlot, handle, arrayLength, separate, keyType, format);
var meta = new TextureMeta()
SamplerType keyType = arrayLength > 1 ? type : SamplerType.None;
TextureInfo info = new TextureInfo(cbufSlot, handle, arrayLength, separate, keyType, format);
TextureMeta meta = new TextureMeta()
{
AccurateType = accurateType,
Type = type,
@@ -316,7 +316,7 @@ namespace Ryujinx.Graphics.Shader.Translation
int setIndex;
int binding;
if (dict.TryGetValue(info, out var existingMeta))
if (dict.TryGetValue(info, out TextureMeta existingMeta))
{
dict[info] = MergeTextureMeta(meta, existingMeta);
setIndex = existingMeta.Set;
@@ -373,7 +373,7 @@ namespace Ryujinx.Graphics.Shader.Translation
nameSuffix = cbufSlot < 0 ? $"{prefix}_tcb_{handle:X}" : $"{prefix}_cb{cbufSlot}_{handle:X}";
}
var definition = new TextureDefinition(
TextureDefinition definition = new TextureDefinition(
setIndex,
binding,
arrayLength,
@@ -433,8 +433,8 @@ namespace Ryujinx.Graphics.Shader.Translation
{
selectedMeta.UsageFlags |= TextureUsageFlags.NeedsScaleValue;
var dimensions = type.GetDimensions();
var canScale = _stage.SupportsRenderScale() && selectedInfo.ArrayLength == 1 && dimensions == 2;
int dimensions = type.GetDimensions();
bool canScale = _stage.SupportsRenderScale() && selectedInfo.ArrayLength == 1 && dimensions == 2;
if (!canScale)
{
@@ -454,7 +454,7 @@ namespace Ryujinx.Graphics.Shader.Translation
public BufferDescriptor[] GetConstantBufferDescriptors()
{
var descriptors = new BufferDescriptor[_usedConstantBufferBindings.Count];
BufferDescriptor[] descriptors = new BufferDescriptor[_usedConstantBufferBindings.Count];
int descriptorIndex = 0;
@@ -478,7 +478,7 @@ namespace Ryujinx.Graphics.Shader.Translation
public BufferDescriptor[] GetStorageBufferDescriptors()
{
var descriptors = new BufferDescriptor[_sbSlots.Count];
BufferDescriptor[] descriptors = new BufferDescriptor[_sbSlots.Count];
int descriptorIndex = 0;

View File

@@ -242,8 +242,8 @@ namespace Ryujinx.Graphics.Shader.Translation
usedFeatures |= FeatureFlags.VtgAsCompute;
}
var cfgs = new ControlFlowGraph[functions.Length];
var frus = new RegisterUsage.FunctionRegisterUsage[functions.Length];
ControlFlowGraph[] cfgs = new ControlFlowGraph[functions.Length];
RegisterUsage.FunctionRegisterUsage[] frus = new RegisterUsage.FunctionRegisterUsage[functions.Length];
for (int i = 0; i < functions.Length; i++)
{
@@ -266,14 +266,14 @@ namespace Ryujinx.Graphics.Shader.Translation
for (int i = 0; i < functions.Length; i++)
{
var cfg = cfgs[i];
ControlFlowGraph cfg = cfgs[i];
int inArgumentsCount = 0;
int outArgumentsCount = 0;
if (i != 0)
{
var fru = frus[i];
RegisterUsage.FunctionRegisterUsage fru = frus[i];
inArgumentsCount = fru.InArguments.Length;
outArgumentsCount = fru.OutArguments.Length;
@@ -325,7 +325,7 @@ namespace Ryujinx.Graphics.Shader.Translation
FeatureFlags usedFeatures,
byte clipDistancesWritten)
{
var sInfo = StructuredProgram.MakeStructuredProgram(
StructuredProgramInfo sInfo = StructuredProgram.MakeStructuredProgram(
funcs,
attributeUsage,
definitions,
@@ -340,7 +340,7 @@ namespace Ryujinx.Graphics.Shader.Translation
_ => 1
};
var info = new ShaderProgramInfo(
ShaderProgramInfo info = new ShaderProgramInfo(
resourceManager.GetConstantBufferDescriptors(),
resourceManager.GetStorageBufferDescriptors(),
resourceManager.GetTextureDescriptors(),
@@ -356,7 +356,7 @@ namespace Ryujinx.Graphics.Shader.Translation
clipDistancesWritten,
originalDefinitions.OmapTargets);
var hostCapabilities = new HostCapabilities(
HostCapabilities hostCapabilities = new HostCapabilities(
GpuAccessor.QueryHostReducedPrecision(),
GpuAccessor.QueryHostSupportsFragmentShaderInterlock(),
GpuAccessor.QueryHostSupportsFragmentShaderOrderingIntel(),
@@ -367,7 +367,7 @@ namespace Ryujinx.Graphics.Shader.Translation
GpuAccessor.QueryHostSupportsTextureShadowLod(),
GpuAccessor.QueryHostSupportsViewportMask());
var parameters = new CodeGenParameters(attributeUsage, definitions, resourceManager.Properties, hostCapabilities, GpuAccessor, Options.TargetApi);
CodeGenParameters parameters = new CodeGenParameters(attributeUsage, definitions, resourceManager.Properties, hostCapabilities, GpuAccessor, Options.TargetApi);
return Options.TargetLanguage switch
{
@@ -486,10 +486,10 @@ namespace Ryujinx.Graphics.Shader.Translation
public ShaderProgram GenerateVertexPassthroughForCompute()
{
var attributeUsage = new AttributeUsage(GpuAccessor);
var resourceManager = new ResourceManager(ShaderStage.Vertex, GpuAccessor);
AttributeUsage attributeUsage = new AttributeUsage(GpuAccessor);
ResourceManager resourceManager = new ResourceManager(ShaderStage.Vertex, GpuAccessor);
var reservations = GetResourceReservations();
ResourceReservations reservations = GetResourceReservations();
int vertexInfoCbBinding = reservations.VertexInfoConstantBufferBinding;
@@ -508,7 +508,7 @@ namespace Ryujinx.Graphics.Shader.Translation
BufferDefinition vertexOutputBuffer = new(BufferLayout.Std430, 1, vertexDataSbBinding, "vb_input", vertexInputStruct);
resourceManager.Properties.AddOrUpdateStorageBuffer(vertexOutputBuffer);
var context = new EmitterContext();
EmitterContext context = new EmitterContext();
Operand vertexIndex = Options.TargetApi == TargetApi.OpenGL
? context.Load(StorageKind.Input, IoVariable.VertexId)
@@ -553,13 +553,13 @@ namespace Ryujinx.Graphics.Shader.Translation
}
}
var operations = context.GetOperations();
var cfg = ControlFlowGraph.Create(operations);
var function = new Function(cfg.Blocks, "main", false, 0, 0);
Operation[] operations = context.GetOperations();
ControlFlowGraph cfg = ControlFlowGraph.Create(operations);
Function function = new Function(cfg.Blocks, "main", false, 0, 0);
var transformFeedbackOutputs = GetTransformFeedbackOutputs(GpuAccessor, out ulong transformFeedbackVecMap);
TransformFeedbackOutput[] transformFeedbackOutputs = GetTransformFeedbackOutputs(GpuAccessor, out ulong transformFeedbackVecMap);
var definitions = new ShaderDefinitions(ShaderStage.Vertex, transformFeedbackVecMap, transformFeedbackOutputs)
ShaderDefinitions definitions = new ShaderDefinitions(ShaderStage.Vertex, transformFeedbackVecMap, transformFeedbackOutputs)
{
LastInVertexPipeline = true
};
@@ -604,10 +604,10 @@ namespace Ryujinx.Graphics.Shader.Translation
break;
}
var attributeUsage = new AttributeUsage(GpuAccessor);
var resourceManager = new ResourceManager(ShaderStage.Geometry, GpuAccessor);
AttributeUsage attributeUsage = new AttributeUsage(GpuAccessor);
ResourceManager resourceManager = new ResourceManager(ShaderStage.Geometry, GpuAccessor);
var context = new EmitterContext();
EmitterContext context = new EmitterContext();
for (int v = 0; v < maxOutputVertices; v++)
{
@@ -648,11 +648,11 @@ namespace Ryujinx.Graphics.Shader.Translation
context.EndPrimitive();
var operations = context.GetOperations();
var cfg = ControlFlowGraph.Create(operations);
var function = new Function(cfg.Blocks, "main", false, 0, 0);
Operation[] operations = context.GetOperations();
ControlFlowGraph cfg = ControlFlowGraph.Create(operations);
Function function = new Function(cfg.Blocks, "main", false, 0, 0);
var definitions = new ShaderDefinitions(
ShaderDefinitions definitions = new ShaderDefinitions(
ShaderStage.Geometry,
GpuAccessor.QueryGraphicsState(),
false,

View File

@@ -904,8 +904,8 @@ namespace Ryujinx.Graphics.Vulkan
pattern.OffsetIndex.CopyTo(shaderParams[..pattern.OffsetIndex.Length]);
using var patternScoped = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize);
var patternBuffer = patternScoped.Holder;
using ScopedTemporaryBuffer patternScoped = gd.BufferManager.ReserveOrCreate(gd, cbs, ParamsBufferSize);
BufferHolder patternBuffer = patternScoped.Holder;
patternBuffer.SetDataUnchecked<int>(patternScoped.Offset, shaderParams);

View File

@@ -1,9 +1,7 @@
using Ryujinx.Common;
using Ryujinx.Common.Logging;
using Ryujinx.HLE.HOS.Kernel.Threading;
using Ryujinx.Memory;
using System.Collections.Concurrent;
using System.Linq;
using System.Collections.Generic;
namespace Ryujinx.HLE.Debugger
{
@@ -11,12 +9,9 @@ namespace Ryujinx.HLE.Debugger
{
public byte[] OriginalData { get; }
public bool IsStep { get; }
public Breakpoint(byte[] originalData, bool isStep)
public Breakpoint(byte[] originalData)
{
OriginalData = originalData;
IsStep = isStep;
}
}
@@ -28,9 +23,9 @@ namespace Ryujinx.HLE.Debugger
private readonly Debugger _debugger;
private readonly ConcurrentDictionary<ulong, Breakpoint> _breakpoints = new();
private static readonly byte[] _aarch64BreakInstruction = { 0x00, 0x00, 0x20, 0xD4 }; // BRK #0
private static readonly byte[] _aarch32BreakInstruction = { 0xFE, 0xDE, 0xFF, 0xE7 }; // TRAP
private static readonly byte[] _aarch32ThumbBreakInstruction = { 0x80, 0xB6 };
private static readonly byte[] _aarch64BreakInstruction = [0x00, 0x00, 0x20, 0xD4]; // BRK #0
private static readonly byte[] _aarch32BreakInstruction = [0xFE, 0xDE, 0xFF, 0xE7]; // TRAP
private static readonly byte[] _aarch32ThumbBreakInstruction = [0x80, 0xB6];
public BreakpointManager(Debugger debugger)
{
@@ -44,7 +39,7 @@ namespace Ryujinx.HLE.Debugger
/// <param name="length">The length of the instruction to replace.</param>
/// <param name="isStep">Indicates if this is a single-step breakpoint.</param>
/// <returns>True if the breakpoint was set successfully; otherwise, false.</returns>
public bool SetBreakPoint(ulong address, ulong length, bool isStep = false)
public bool SetBreakPoint(ulong address, ulong length)
{
if (_breakpoints.ContainsKey(address))
{
@@ -58,7 +53,7 @@ namespace Ryujinx.HLE.Debugger
return false;
}
var originalInstruction = new byte[length];
byte[] originalInstruction = new byte[length];
if (!ReadMemory(address, originalInstruction))
{
Logger.Error?.Print(LogClass.GdbStub, $"Failed to read memory at 0x{address:X16} to set breakpoint.");
@@ -71,7 +66,7 @@ namespace Ryujinx.HLE.Debugger
return false;
}
var breakpoint = new Breakpoint(originalInstruction, isStep);
Breakpoint breakpoint = new(originalInstruction);
if (_breakpoints.TryAdd(address, breakpoint))
{
Logger.Debug?.Print(LogClass.GdbStub, $"Breakpoint set at 0x{address:X16}");
@@ -112,7 +107,7 @@ namespace Ryujinx.HLE.Debugger
/// </summary>
public void ClearAll()
{
foreach (var bp in _breakpoints)
foreach (KeyValuePair<ulong, Breakpoint> bp in _breakpoints)
{
if (!WriteMemory(bp.Key, bp.Value.OriginalData))
{
@@ -124,33 +119,9 @@ namespace Ryujinx.HLE.Debugger
Logger.Debug?.Print(LogClass.GdbStub, "All breakpoints cleared.");
}
/// <summary>
/// Clears all currently set single-step software breakpoints.
/// </summary>
public void ClearAllStepBreakpoints()
{
var stepBreakpoints = _breakpoints.Where(p => p.Value.IsStep).ToList();
if (stepBreakpoints.Count == 0)
{
return;
}
foreach (var bp in stepBreakpoints)
{
if (_breakpoints.TryRemove(bp.Key, out Breakpoint removedBreakpoint))
{
WriteMemory(bp.Key, removedBreakpoint.OriginalData);
}
}
Logger.Debug?.Print(LogClass.GdbStub, "All step breakpoints cleared.");
}
private byte[] GetBreakInstruction(ulong length)
{
if (_debugger.IsProcessAarch32)
if (_debugger.IsProcess32Bit)
{
if (length == 2)
{

View File

@@ -0,0 +1,127 @@
using Ryujinx.Common.Logging;
using Ryujinx.HLE.Debugger.Gdb;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Ryujinx.HLE.Debugger
{
public partial class Debugger
{
private void MainLoop()
{
IPEndPoint endpoint = new(IPAddress.Any, GdbStubPort);
_listenerSocket = new TcpListener(endpoint);
try
{
_listenerSocket.Start();
}
catch (SocketException se)
{
Logger.Error?.Print(LogClass.GdbStub,
$"Failed to create TCP server on {endpoint} for GDB client: {Enum.GetName(se.SocketErrorCode)}");
throw;
}
Logger.Notice.Print(LogClass.GdbStub, $"Currently waiting on {endpoint} for GDB client");
while (!_shuttingDown)
{
try
{
_clientSocket = _listenerSocket.AcceptSocket();
}
catch (SocketException se)
{
Logger.Error?.Print(LogClass.GdbStub,
$"Failed to accept incoming GDB client connection: {Enum.GetName(se.SocketErrorCode)}");
return;
}
// If the user connects before the application is running, wait for the application to start.
int retries = 10;
while ((DebugProcess == null || GetThreads().Length == 0) && retries-- > 0)
{
Thread.Sleep(500);
}
if (DebugProcess == null || GetThreads().Length == 0)
{
Logger.Warning?.Print(LogClass.GdbStub,
"Application is not running, cannot accept GDB client connection");
_clientSocket.Close();
continue;
}
_clientSocket.NoDelay = true;
_readStream = new NetworkStream(_clientSocket, System.IO.FileAccess.Read);
_writeStream = new NetworkStream(_clientSocket, System.IO.FileAccess.Write);
_commands = new GdbCommands(_listenerSocket, _clientSocket, _readStream, _writeStream, this);
Logger.Notice.Print(LogClass.GdbStub, "GDB client connected");
while (true)
{
try
{
switch (_readStream.ReadByte())
{
case -1:
goto EndOfLoop;
case '+':
continue;
case '-':
Logger.Notice.Print(LogClass.GdbStub, "NACK received!");
continue;
case '\x03':
_messages.Add(Message.BreakIn);
break;
case '$':
string cmd = string.Empty;
while (true)
{
int x = _readStream.ReadByte();
if (x == -1)
goto EndOfLoop;
if (x == '#')
break;
cmd += (char)x;
}
string checksum = $"{(char)_readStream.ReadByte()}{(char)_readStream.ReadByte()}";
if (checksum == $"{Helpers.CalculateChecksum(cmd):x2}")
{
_messages.Add(new CommandMessage(cmd));
}
else
{
_messages.Add(Message.SendNack);
}
break;
}
}
catch (IOException)
{
goto EndOfLoop;
}
}
EndOfLoop:
Logger.Notice.Print(LogClass.GdbStub, "GDB client lost connection");
_readStream.Close();
_readStream = null;
_writeStream.Close();
_writeStream = null;
_clientSocket.Close();
_clientSocket = null;
_commands = null;
BreakpointManager.ClearAll();
}
}
}
}

View File

@@ -0,0 +1,58 @@
using Ryujinx.Common.Logging;
using System;
using System.IO;
namespace Ryujinx.HLE.Debugger
{
public partial class Debugger
{
private void MessageHandlerMain()
{
while (!_shuttingDown)
{
try
{
switch (_messages.Take())
{
case Message { Type: MessageType.BreakIn }:
Logger.Notice.Print(LogClass.GdbStub, "Break-in requested");
_commands.Interrupt();
break;
case Message { Type: MessageType.SendNack }:
_writeStream.WriteByte((byte)'-');
break;
case Message { Type: MessageType.Kill }:
return;
case CommandMessage { Command: { } cmd }:
Logger.Debug?.Print(LogClass.GdbStub, $"Received Command: {cmd}");
_writeStream.WriteByte((byte)'+');
_commands.Processor.Process(cmd);
break;
case ThreadBreakMessage { Context: { } ctx }:
DebugProcess.DebugStop();
GThread = CThread = ctx.ThreadUid;
_breakHandlerEvent.Set();
_commands.Processor.Reply($"T05thread:{ctx.ThreadUid:x};");
break;
}
}
catch (IOException e)
{
Logger.Error?.Print(LogClass.GdbStub, "Error while processing GDB messages", e);
}
catch (NullReferenceException e)
{
Logger.Error?.Print(LogClass.GdbStub, "Error while processing GDB messages", e);
}
catch (ObjectDisposedException e)
{
Logger.Error?.Print(LogClass.GdbStub, "Error while processing GDB messages", e);
}
}
}
}
}

View File

@@ -0,0 +1,96 @@
using Gommon;
using JetBrains.Annotations;
using Ryujinx.Common.Logging;
using Ryujinx.HLE.HOS.Kernel.Process;
using Ryujinx.HLE.HOS.Kernel.Threading;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ryujinx.HLE.Debugger
{
public partial class Debugger
{
static Debugger()
{
_rcmdDelegates.Add(["help"],
_ => _rcmdDelegates.Keys
.Where(x => !x[0].Equals("help"))
.Select(x => x.JoinToString('\n'))
.JoinToString('\n') + '\n'
);
_rcmdDelegates.Add(["get info"], dbgr => dbgr.GetProcessInfo());
_rcmdDelegates.Add(["backtrace", "bt"], dbgr => dbgr.GetStackTrace());
_rcmdDelegates.Add(["registers", "reg"], dbgr => dbgr.GetRegisters());
_rcmdDelegates.Add(["minidump"], dbgr => dbgr.GetMinidump());
}
private static readonly Dictionary<string[], Func<Debugger, string>> _rcmdDelegates = new();
public static Func<Debugger, string> FindRcmdDelegate(string command)
{
Func<Debugger, string> searchResult = _ => $"Unknown command: {command}\n";
foreach ((string[] names, Func<Debugger, string> dlg) in _rcmdDelegates)
{
if (names.ContainsIgnoreCase(command.Trim()))
{
searchResult = dlg;
break;
}
}
return searchResult;
}
public string GetStackTrace()
{
if (GThread == null)
return "No thread selected\n";
return Process?.Debugger?.GetGuestStackTrace(DebugProcess.GetThread(GThread.Value)) ?? "No application process found\n";
}
public string GetRegisters()
{
if (GThread == null)
return "No thread selected\n";
return Process?.Debugger?.GetCpuRegisterPrintout(DebugProcess.GetThread(GThread.Value)) ?? "No application process found\n";
}
public string GetMinidump()
{
if (Process is not { } kProcess)
return "No application process found\n";
if (kProcess.Debugger is not { } debugger)
return $"Error getting minidump: debugger is null\n";
var response = debugger.GetMinidump();
Logger.Info?.Print(LogClass.GdbStub, response);
return response;
}
public string GetProcessInfo()
{
try
{
if (Process is not { } kProcess)
return "No application process found\n";
if (kProcess.Debugger is not { } debugger)
return $"Error getting process info: debugger is null\n";
return debugger.GetProcessInfoPrintout();
}
catch (Exception e)
{
Logger.Error?.Print(LogClass.GdbStub, $"Error getting process info: {e.Message}");
return $"Error getting process info: {e.Message}\n";
}
}
}
}

View File

@@ -4,39 +4,38 @@ using Ryujinx.HLE.HOS.Kernel.Process;
using Ryujinx.HLE.HOS.Kernel.Threading;
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using IExecutionContext = Ryujinx.Cpu.IExecutionContext;
using static Ryujinx.HLE.Debugger.Helpers;
namespace Ryujinx.HLE.Debugger
{
public class Debugger : IDisposable
public partial class Debugger : IDisposable
{
internal Switch Device { get; private set; }
public ushort GdbStubPort { get; private set; }
private TcpListener ListenerSocket;
private Socket ClientSocket = null;
private NetworkStream ReadStream = null;
private NetworkStream WriteStream = null;
private BlockingCollection<IMessage> Messages = new(1);
private Thread DebuggerThread;
private Thread MessageHandlerThread;
private bool _shuttingDown = false;
private ManualResetEventSlim _breakHandlerEvent = new(false);
private readonly BlockingCollection<Message.IMarker> _messages = new(1);
private readonly Thread _debuggerThread;
private readonly Thread _messageHandlerThread;
private GdbCommandProcessor CommandProcessor = null;
private TcpListener _listenerSocket;
private Socket _clientSocket;
private NetworkStream _readStream;
private NetworkStream _writeStream;
private GdbCommands _commands;
private bool _shuttingDown;
private readonly ManualResetEventSlim _breakHandlerEvent = new(false);
internal ulong? CThread;
internal ulong? GThread;
internal BreakpointManager BreakpointManager;
public readonly BreakpointManager BreakpointManager;
public Debugger(Switch device, ushort port)
{
@@ -45,273 +44,34 @@ namespace Ryujinx.HLE.Debugger
ARMeilleure.Optimizations.EnableDebugging = true;
DebuggerThread = new Thread(DebuggerThreadMain);
DebuggerThread.Start();
MessageHandlerThread = new Thread(MessageHandlerMain);
MessageHandlerThread.Start();
_debuggerThread = new Thread(MainLoop);
_debuggerThread.Start();
_messageHandlerThread = new Thread(MessageHandlerMain);
_messageHandlerThread.Start();
BreakpointManager = new BreakpointManager(this);
}
internal KProcess Process => Device.System?.DebugGetApplicationProcess();
internal IDebuggableProcess DebugProcess => Device.System?.DebugGetApplicationProcessDebugInterface();
internal KThread[] GetThreads() =>
DebugProcess.GetThreadUids().Select(x => DebugProcess.GetThread(x)).ToArray();
internal KThread[] GetThreads() => DebugProcess.ThreadUids.Select(DebugProcess.GetThread).ToArray();
internal bool IsProcessAarch32 => DebugProcess.GetThread(GThread.Value).Context.IsAarch32;
internal bool IsProcess32Bit => DebugProcess.GetThread(GThread ?? DebugProcess.ThreadUids.First()).Context.IsAarch32;
private void MessageHandlerMain()
{
while (!_shuttingDown)
{
IMessage msg = Messages.Take();
try
{
switch (msg)
{
case BreakInMessage:
Logger.Notice.Print(LogClass.GdbStub, "Break-in requested");
CommandProcessor.Commands.CommandInterrupt();
break;
internal bool WriteRegister(IExecutionContext ctx, int registerId, StringStream ss) =>
IsProcess32Bit
? ctx.WriteRegister32(registerId, ss)
: ctx.WriteRegister64(registerId, ss);
case SendNackMessage:
WriteStream.WriteByte((byte)'-');
break;
case CommandMessage { Command: var cmd }:
Logger.Debug?.Print(LogClass.GdbStub, $"Received Command: {cmd}");
WriteStream.WriteByte((byte)'+');
CommandProcessor.Process(cmd);
break;
case ThreadBreakMessage { Context: var ctx }:
DebugProcess.DebugStop();
GThread = CThread = ctx.ThreadUid;
_breakHandlerEvent.Set();
CommandProcessor.Commands.Reply($"T05thread:{ctx.ThreadUid:x};");
break;
case KillMessage:
return;
}
}
catch (IOException e)
{
Logger.Error?.Print(LogClass.GdbStub, "Error while processing GDB messages", e);
}
catch (NullReferenceException e)
{
Logger.Error?.Print(LogClass.GdbStub, "Error while processing GDB messages", e);
}
}
}
public string GetStackTrace()
{
if (GThread == null)
return "No thread selected\n";
if (Process == null)
return "No application process found\n";
return Process.Debugger.GetGuestStackTrace(DebugProcess.GetThread(GThread.Value));
}
public string GetRegisters()
{
if (GThread == null)
return "No thread selected\n";
if (Process == null)
return "No application process found\n";
return Process.Debugger.GetCpuRegisterPrintout(DebugProcess.GetThread(GThread.Value));
}
public string GetMinidump()
{
var response = new StringBuilder();
response.AppendLine("=== Begin Minidump ===\n");
response.AppendLine(GetProcessInfo());
foreach (var thread in GetThreads())
{
response.AppendLine($"=== Thread {thread.ThreadUid} ===");
try
{
string stackTrace = Process.Debugger.GetGuestStackTrace(thread);
response.AppendLine(stackTrace);
}
catch (Exception e)
{
response.AppendLine($"[Error getting stack trace: {e.Message}]");
}
try
{
string registers = Process.Debugger.GetCpuRegisterPrintout(thread);
response.AppendLine(registers);
}
catch (Exception e)
{
response.AppendLine($"[Error getting registers: {e.Message}]");
}
}
response.AppendLine("=== End Minidump ===");
Logger.Info?.Print(LogClass.GdbStub, response.ToString());
return response.ToString();
}
public string GetProcessInfo()
{
try
{
if (Process == null)
return "No application process found\n";
KProcess kProcess = Process;
var sb = new StringBuilder();
sb.AppendLine($"Program Id: 0x{kProcess.TitleId:x16}");
sb.AppendLine($"Application: {(kProcess.IsApplication ? 1 : 0)}");
sb.AppendLine("Layout:");
sb.AppendLine(
$" Alias: 0x{kProcess.MemoryManager.AliasRegionStart:x10} - 0x{kProcess.MemoryManager.AliasRegionEnd - 1:x10}");
sb.AppendLine(
$" Heap: 0x{kProcess.MemoryManager.HeapRegionStart:x10} - 0x{kProcess.MemoryManager.HeapRegionEnd - 1:x10}");
sb.AppendLine(
$" Aslr: 0x{kProcess.MemoryManager.AslrRegionStart:x10} - 0x{kProcess.MemoryManager.AslrRegionEnd - 1:x10}");
sb.AppendLine(
$" Stack: 0x{kProcess.MemoryManager.StackRegionStart:x10} - 0x{kProcess.MemoryManager.StackRegionEnd - 1:x10}");
sb.AppendLine("Modules:");
var debugger = kProcess.Debugger;
if (debugger != null)
{
var images = debugger.GetLoadedImages();
for (int i = 0; i < images.Count; i++)
{
var image = images[i];
ulong endAddress = image.BaseAddress + image.Size - 1;
string name = image.Name;
sb.AppendLine($" 0x{image.BaseAddress:x10} - 0x{endAddress:x10} {name}");
}
}
return sb.ToString();
}
catch (Exception e)
{
Logger.Error?.Print(LogClass.GdbStub, $"Error getting process info: {e.Message}");
return $"Error getting process info: {e.Message}\n";
}
}
private void DebuggerThreadMain()
{
var endpoint = new IPEndPoint(IPAddress.Any, GdbStubPort);
ListenerSocket = new TcpListener(endpoint);
ListenerSocket.Start();
Logger.Notice.Print(LogClass.GdbStub, $"Currently waiting on {endpoint} for GDB client");
while (!_shuttingDown)
{
try
{
ClientSocket = ListenerSocket.AcceptSocket();
}
catch (SocketException)
{
return;
}
// If the user connects before the application is running, wait for the application to start.
int retries = 10;
while ((DebugProcess == null || GetThreads().Length == 0) && retries-- > 0)
{
Thread.Sleep(200);
}
if (DebugProcess == null || GetThreads().Length == 0)
{
Logger.Warning?.Print(LogClass.GdbStub,
"Application is not running, cannot accept GDB client connection");
ClientSocket.Close();
continue;
}
ClientSocket.NoDelay = true;
ReadStream = new NetworkStream(ClientSocket, System.IO.FileAccess.Read);
WriteStream = new NetworkStream(ClientSocket, System.IO.FileAccess.Write);
CommandProcessor = new GdbCommandProcessor(ListenerSocket, ClientSocket, ReadStream, WriteStream, this);
Logger.Notice.Print(LogClass.GdbStub, "GDB client connected");
while (true)
{
try
{
switch (ReadStream.ReadByte())
{
case -1:
goto EndOfLoop;
case '+':
continue;
case '-':
Logger.Notice.Print(LogClass.GdbStub, "NACK received!");
continue;
case '\x03':
Messages.Add(new BreakInMessage());
break;
case '$':
string cmd = "";
while (true)
{
int x = ReadStream.ReadByte();
if (x == -1)
goto EndOfLoop;
if (x == '#')
break;
cmd += (char)x;
}
string checksum = $"{(char)ReadStream.ReadByte()}{(char)ReadStream.ReadByte()}";
if (checksum == $"{CalculateChecksum(cmd):x2}")
{
Messages.Add(new CommandMessage(cmd));
}
else
{
Messages.Add(new SendNackMessage());
}
break;
}
}
catch (IOException)
{
goto EndOfLoop;
}
}
EndOfLoop:
Logger.Notice.Print(LogClass.GdbStub, "GDB client lost connection");
ReadStream.Close();
ReadStream = null;
WriteStream.Close();
WriteStream = null;
ClientSocket.Close();
ClientSocket = null;
BreakpointManager.ClearAll();
}
}
internal string ReadRegister(IExecutionContext ctx, int registerId) =>
IsProcess32Bit
? ctx.ReadRegister32(registerId)
: ctx.ReadRegister64(registerId);
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
@@ -320,15 +80,15 @@ namespace Ryujinx.HLE.Debugger
{
_shuttingDown = true;
ListenerSocket.Stop();
ClientSocket?.Shutdown(SocketShutdown.Both);
ClientSocket?.Close();
ReadStream?.Close();
WriteStream?.Close();
DebuggerThread.Join();
Messages.Add(new KillMessage());
MessageHandlerThread.Join();
Messages.Dispose();
_listenerSocket.Stop();
_clientSocket?.Shutdown(SocketShutdown.Both);
_clientSocket?.Close();
_readStream?.Close();
_writeStream?.Close();
_debuggerThread.Join();
_messages.Add(Message.Kill);
_messageHandlerThread.Join();
_messages.Dispose();
_breakHandlerEvent.Dispose();
}
}
@@ -338,7 +98,7 @@ namespace Ryujinx.HLE.Debugger
DebugProcess.DebugInterruptHandler(ctx);
_breakHandlerEvent.Reset();
Messages.Add(new ThreadBreakMessage(ctx, address, imm));
_messages.Add(new ThreadBreakMessage(ctx, address, imm));
// Messages.Add can block, so we log it after adding the message to make sure user can see the log at the same time GDB receives the break message
Logger.Notice.Print(LogClass.GdbStub, $"Break hit on thread {ctx.ThreadUid} at pc {address:x016}");
// Wait for the process to stop before returning to avoid BreakHandler being called multiple times from the same breakpoint

View File

@@ -1,7 +1,8 @@
using Gommon;
using Ryujinx.Common;
using Ryujinx.Common.Logging;
using Ryujinx.HLE.HOS.Kernel.Threading;
using System.Linq;
using System.Net.Sockets;
using System.Text;
namespace Ryujinx.HLE.Debugger.Gdb
@@ -10,13 +11,44 @@ namespace Ryujinx.HLE.Debugger.Gdb
{
public readonly GdbCommands Commands;
public GdbCommandProcessor(TcpListener listenerSocket, Socket clientSocket, NetworkStream readStream, NetworkStream writeStream, Debugger debugger)
private Debugger Debugger => Commands.Debugger;
private BreakpointManager BreakpointManager => Commands.Debugger.BreakpointManager;
private IDebuggableProcess DebugProcess => Commands.Debugger.DebugProcess;
public GdbCommandProcessor(GdbCommands commands)
{
Commands = new GdbCommands(listenerSocket, clientSocket, readStream, writeStream, debugger);
Commands = commands;
}
private string previousThreadListXml = "";
public void ReplyHex(string data) => Reply(Helpers.ToHex(data));
public void ReplyHex(byte[] data) => Reply(Helpers.ToHex(data));
public void Reply(string cmd)
{
Logger.Debug?.Print(LogClass.GdbStub, $"Reply: {cmd}");
Commands.WriteStream.Write(Encoding.ASCII.GetBytes($"${cmd}#{Helpers.CalculateChecksum(cmd):x2}"));
}
public void ReplyOK() => Reply("OK");
public void ReplyError() => Reply("E01");
public void Reply(bool success)
{
if (success)
ReplyOK();
else ReplyError();
}
public void Reply(bool success, string cmd)
{
if (success)
Reply(cmd);
else ReplyError();
}
private string _previousThreadListXml = string.Empty;
public void Process(string cmd)
{
StringStream ss = new(cmd);
@@ -24,143 +56,138 @@ namespace Ryujinx.HLE.Debugger.Gdb
switch (ss.ReadChar())
{
case '!':
if (!ss.IsEmpty())
if (!ss.IsEmpty)
{
goto unknownCommand;
}
// Enable extended mode
Commands.ReplyOK();
ReplyOK();
break;
case '?':
if (!ss.IsEmpty())
if (!ss.IsEmpty)
{
goto unknownCommand;
}
Commands.CommandQuery();
Commands.Query();
break;
case 'c':
Commands.CommandContinue(ss.IsEmpty() ? null : ss.ReadRemainingAsHex());
Commands.Continue(ss.IsEmpty ? null : ss.ReadRemainingAsHex());
break;
case 'D':
if (!ss.IsEmpty())
if (!ss.IsEmpty)
{
goto unknownCommand;
}
Commands.CommandDetach();
Commands.Detach();
break;
case 'g':
if (!ss.IsEmpty())
if (!ss.IsEmpty)
{
goto unknownCommand;
}
Commands.CommandReadRegisters();
Commands.ReadRegisters();
break;
case 'G':
Commands.CommandWriteRegisters(ss);
Commands.WriteRegisters(ss);
break;
case 'H':
{
char op = ss.ReadChar();
ulong? threadId = ss.ReadRemainingAsThreadUid();
Commands.CommandSetThread(op, threadId);
Commands.SetThread(op, threadId);
break;
}
case 'k':
Logger.Notice.Print(LogClass.GdbStub, "Kill request received, detach instead");
Commands.Reply("");
Commands.CommandDetach();
Reply(string.Empty);
Commands.Detach();
break;
case 'm':
{
ulong addr = ss.ReadUntilAsHex(',');
ulong len = ss.ReadRemainingAsHex();
Commands.CommandReadMemory(addr, len);
Commands.ReadMemory(addr, len);
break;
}
case 'M':
{
ulong addr = ss.ReadUntilAsHex(',');
ulong len = ss.ReadUntilAsHex(':');
Commands.CommandWriteMemory(addr, len, ss);
Commands.WriteMemory(addr, len, ss);
break;
}
case 'p':
{
ulong gdbRegId = ss.ReadRemainingAsHex();
Commands.CommandReadRegister((int)gdbRegId);
Commands.ReadRegister((int)gdbRegId);
break;
}
case 'P':
{
ulong gdbRegId = ss.ReadUntilAsHex('=');
Commands.CommandWriteRegister((int)gdbRegId, ss);
Commands.WriteRegister((int)gdbRegId, ss);
break;
}
case 'q':
if (ss.ConsumeRemaining("GDBServerVersion"))
{
Commands.Reply($"name:Ryujinx;version:{ReleaseInformation.Version};");
Reply($"name:Ryujinx;version:{ReleaseInformation.Version};");
break;
}
if (ss.ConsumeRemaining("HostInfo"))
{
if (Commands.Debugger.IsProcessAarch32)
{
Commands.Reply(
$"triple:{Helpers.ToHex("arm-unknown-linux-android")};endian:little;ptrsize:4;hostname:{Helpers.ToHex("Ryujinx")};");
}
else
{
Commands.Reply(
$"triple:{Helpers.ToHex("aarch64-unknown-linux-android")};endian:little;ptrsize:8;hostname:{Helpers.ToHex("Ryujinx")};");
}
Reply(
Debugger.IsProcess32Bit
? $"triple:{Helpers.ToHex("arm-unknown-linux-android")};endian:little;ptrsize:4;hostname:{Helpers.ToHex("Ryujinx")};"
: $"triple:{Helpers.ToHex("aarch64-unknown-linux-android")};endian:little;ptrsize:8;hostname:{Helpers.ToHex("Ryujinx")};");
break;
}
if (ss.ConsumeRemaining("Attached"))
{
Reply("1");
break;
}
if (ss.ConsumeRemaining("ProcessInfo"))
{
if (Commands.Debugger.IsProcessAarch32)
{
Commands.Reply(
$"pid:1;cputype:12;cpusubtype:0;triple:{Helpers.ToHex("arm-unknown-linux-android")};ostype:unknown;vendor:none;endian:little;ptrsize:4;");
}
else
{
Commands.Reply(
$"pid:1;cputype:100000c;cpusubtype:0;triple:{Helpers.ToHex("aarch64-unknown-linux-android")};ostype:unknown;vendor:none;endian:little;ptrsize:8;");
}
Reply(
Debugger.IsProcess32Bit
? $"pid:1;cputype:12;cpusubtype:0;triple:{Helpers.ToHex("arm-unknown-linux-android")};ostype:unknown;vendor:none;endian:little;ptrsize:4;"
: $"pid:1;cputype:100000c;cpusubtype:0;triple:{Helpers.ToHex("aarch64-unknown-linux-android")};ostype:unknown;vendor:none;endian:little;ptrsize:8;");
break;
}
if (ss.ConsumePrefix("Supported:") || ss.ConsumeRemaining("Supported"))
{
Commands.Reply("PacketSize=10000;qXfer:features:read+;qXfer:threads:read+;vContSupported+");
Reply("PacketSize=10000;qXfer:features:read+;qXfer:threads:read+;vContSupported+");
break;
}
if (ss.ConsumePrefix("Rcmd,"))
{
string hexCommand = ss.ReadRemaining();
Commands.HandleQRcmdCommand(hexCommand);
Commands.Q_Rcmd(hexCommand);
break;
}
if (ss.ConsumeRemaining("fThreadInfo"))
{
Commands. Reply($"m{string.Join(",", Commands.Debugger.DebugProcess.GetThreadUids().Select(x => $"{x:x}"))}");
Reply(
$"m{Debugger.DebugProcess.ThreadUids.Select(x => $"{x:x}").JoinToString(",")}");
break;
}
if (ss.ConsumeRemaining("sThreadInfo"))
{
Commands.Reply("l");
Reply("l");
break;
}
@@ -169,16 +196,14 @@ namespace Ryujinx.HLE.Debugger.Gdb
ulong? threadId = ss.ReadRemainingAsThreadUid();
if (threadId == null)
{
Commands.ReplyError();
ReplyError();
break;
}
Commands.Reply(Helpers.ToHex(
Commands.Debugger.DebugProcess.IsThreadPaused(
Commands.Debugger.DebugProcess.GetThread(threadId.Value))
ReplyHex(
DebugProcess.IsThreadPaused(DebugProcess.GetThread(threadId.Value))
? "Paused"
: "Running"
)
);
break;
@@ -190,32 +215,32 @@ namespace Ryujinx.HLE.Debugger.Gdb
ulong offset = ss.ReadUntilAsHex(',');
ulong len = ss.ReadRemainingAsHex();
var data = "";
string data;
if (offset > 0)
{
data = previousThreadListXml;
data = _previousThreadListXml;
}
else
{
previousThreadListXml = data = GetThreadListXml();
_previousThreadListXml = data = GetThreadListXml();
}
if (offset >= (ulong)data.Length)
{
Commands.Reply("l");
Reply("l");
break;
}
if (len >= (ulong)data.Length - offset)
{
Commands.Reply("l" + Helpers.ToBinaryFormat(data.Substring((int)offset)));
break;
Reply("l" + Helpers.ToBinaryFormat(data[(int)offset..]));
}
else
{
Commands.Reply("m" + Helpers.ToBinaryFormat(data.Substring((int)offset, (int)len)));
break;
Reply("m" + Helpers.ToBinaryFormat(data.Substring((int)offset, (int)len)));
}
break;
}
if (ss.ConsumePrefix("Xfer:features:read:"))
@@ -226,46 +251,43 @@ namespace Ryujinx.HLE.Debugger.Gdb
if (feature == "target.xml")
{
feature = Commands.Debugger.IsProcessAarch32 ? "target32.xml" : "target64.xml";
feature = Debugger.IsProcess32Bit ? "target32.xml" : "target64.xml";
}
string data;
if (RegisterInformation.Features.TryGetValue(feature, out data))
if (!RegisterInformation.Features.TryGetValue(feature, out string data))
{
if (offset >= (ulong)data.Length)
{
Commands.Reply("l");
break;
}
Reply("E00"); // Invalid annex
break;
}
if (len >= (ulong)data.Length - offset)
{
Commands.Reply("l" + Helpers.ToBinaryFormat(data.Substring((int)offset)));
break;
}
else
{
Commands.Reply("m" + Helpers.ToBinaryFormat(data.Substring((int)offset, (int)len)));
break;
}
if (offset >= (ulong)data.Length)
{
Reply("l");
break;
}
if (len >= (ulong)data.Length - offset)
{
Reply("l" + Helpers.ToBinaryFormat(data[(int)offset..]));
}
else
{
Commands.Reply("E00"); // Invalid annex
break;
Reply("m" + Helpers.ToBinaryFormat(data.Substring((int)offset, (int)len)));
}
break;
}
goto unknownCommand;
case 'Q':
goto unknownCommand;
case 's':
Commands.CommandStep(ss.IsEmpty() ? null : ss.ReadRemainingAsHex());
Commands.Step(ss.IsEmpty ? null : ss.ReadRemainingAsHex());
break;
case 'T':
{
ulong? threadId = ss.ReadRemainingAsThreadUid();
Commands.CommandIsAlive(threadId);
Commands.IsAlive(threadId);
break;
}
case 'v':
@@ -273,13 +295,13 @@ namespace Ryujinx.HLE.Debugger.Gdb
{
if (ss.ConsumeRemaining("?"))
{
Commands.Reply("vCont;c;C;s;S");
Reply("vCont;c;C;s;S");
break;
}
if (ss.ConsumePrefix(";"))
{
Commands.HandleVContCommand(ss);
Commands.VCont(ss);
break;
}
@@ -288,7 +310,7 @@ namespace Ryujinx.HLE.Debugger.Gdb
if (ss.ConsumeRemaining("MustReplyEmpty"))
{
Commands.Reply("");
Reply(string.Empty);
break;
}
@@ -303,29 +325,29 @@ namespace Ryujinx.HLE.Debugger.Gdb
if (extra.Length > 0)
{
Logger.Notice.Print(LogClass.GdbStub, $"Unsupported Z command extra data: {extra}");
Commands.ReplyError();
ReplyError();
return;
}
switch (type)
{
case "0": // Software breakpoint
if (!Commands.Debugger.BreakpointManager.SetBreakPoint(addr, len, false))
if (!BreakpointManager.SetBreakPoint(addr, len))
{
Commands.ReplyError();
ReplyError();
return;
}
Commands.ReplyOK();
ReplyOK();
return;
// ReSharper disable RedundantCaseLabel
case "1": // Hardware breakpoint
case "2": // Write watchpoint
case "3": // Read watchpoint
case "4": // Access watchpoint
Commands.ReplyError();
return;
// ReSharper restore RedundantCaseLabel
default:
Commands. ReplyError();
ReplyError();
return;
}
}
@@ -340,50 +362,50 @@ namespace Ryujinx.HLE.Debugger.Gdb
if (extra.Length > 0)
{
Logger.Notice.Print(LogClass.GdbStub, $"Unsupported z command extra data: {extra}");
Commands.ReplyError();
ReplyError();
return;
}
switch (type)
{
case "0": // Software breakpoint
if (!Commands.Debugger.BreakpointManager.ClearBreakPoint(addr, len))
if (!BreakpointManager.ClearBreakPoint(addr, len))
{
Commands.ReplyError();
ReplyError();
return;
}
Commands.ReplyOK();
ReplyOK();
return;
// ReSharper disable RedundantCaseLabel
case "1": // Hardware breakpoint
case "2": // Write watchpoint
case "3": // Read watchpoint
case "4": // Access watchpoint
Commands.ReplyError();
return;
// ReSharper restore RedundantCaseLabel
default:
Commands.ReplyError();
ReplyError();
return;
}
}
default:
unknownCommand:
Logger.Notice.Print(LogClass.GdbStub, $"Unknown command: {cmd}");
Commands.Reply("");
Reply(string.Empty);
break;
}
}
private string GetThreadListXml()
{
var sb = new StringBuilder();
StringBuilder sb = new();
sb.Append("<?xml version=\"1.0\"?><threads>\n");
foreach (var thread in Commands.Debugger.GetThreads())
foreach (KThread thread in Debugger.GetThreads())
{
string threadName = System.Security.SecurityElement.Escape(thread.GetThreadName());
sb.Append(
$"<thread id=\"{thread.ThreadUid:x}\" name=\"{threadName}\">{(Commands.Debugger.DebugProcess.IsThreadPaused(thread) ? "Paused" : "Running")}</thread>\n");
$"<thread id=\"{thread.ThreadUid:x}\" name=\"{threadName}\">{(DebugProcess.IsThreadPaused(thread) ? "Paused" : "Running")}</thread>\n");
}
sb.Append("</threads>");

View File

@@ -1,73 +1,65 @@
using Ryujinx.Common.Logging;
using Ryujinx.Cpu;
using Ryujinx.HLE.HOS.Kernel.Threading;
using Ryujinx.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
namespace Ryujinx.HLE.Debugger.Gdb
{
class GdbCommands
{
const int GdbRegisterCount64 = 68;
const int GdbRegisterCount32 = 66;
public readonly Debugger Debugger;
private readonly TcpListener _listenerSocket;
private readonly Socket _clientSocket;
private readonly NetworkStream _readStream;
private readonly NetworkStream _writeStream;
private GdbCommandProcessor _processor;
public GdbCommandProcessor Processor
=> _processor ??= new GdbCommandProcessor(this);
internal readonly TcpListener ListenerSocket;
internal readonly Socket ClientSocket;
internal readonly NetworkStream ReadStream;
internal readonly NetworkStream WriteStream;
public GdbCommands(TcpListener listenerSocket, Socket clientSocket, NetworkStream readStream,
NetworkStream writeStream, Debugger debugger)
{
_listenerSocket = listenerSocket;
_clientSocket = clientSocket;
_readStream = readStream;
_writeStream = writeStream;
ListenerSocket = listenerSocket;
ClientSocket = clientSocket;
ReadStream = readStream;
WriteStream = writeStream;
Debugger = debugger;
}
public void Reply(string cmd)
{
Logger.Debug?.Print(LogClass.GdbStub, $"Reply: {cmd}");
_writeStream.Write(Encoding.ASCII.GetBytes($"${cmd}#{Helpers.CalculateChecksum(cmd):x2}"));
}
public void ReplyOK() => Reply("OK");
public void ReplyError() => Reply("E01");
internal void CommandQuery()
internal void Query()
{
// GDB is performing initial contact. Stop everything.
Debugger.DebugProcess.DebugStop();
Debugger.GThread = Debugger.CThread = Debugger.DebugProcess.GetThreadUids().First();
Reply($"T05thread:{Debugger.CThread:x};");
Debugger.GThread = Debugger.CThread = Debugger.DebugProcess.ThreadUids.First();
Processor.Reply($"T05thread:{Debugger.CThread:x};");
}
internal void CommandInterrupt()
internal void Interrupt()
{
// GDB is requesting an interrupt. Stop everything.
Debugger.DebugProcess.DebugStop();
if (Debugger.GThread == null || Debugger.GetThreads().All(x => x.ThreadUid != Debugger.GThread.Value))
{
Debugger.GThread = Debugger.CThread = Debugger.DebugProcess.GetThreadUids().First();
Debugger.GThread = Debugger.CThread = Debugger.DebugProcess.ThreadUids.First();
}
Reply($"T02thread:{Debugger.GThread:x};");
Processor.Reply($"T02thread:{Debugger.GThread:x};");
}
internal void CommandContinue(ulong? newPc)
internal void Continue(ulong? newPc)
{
if (newPc.HasValue)
{
if (Debugger.CThread == null)
{
ReplyError();
Processor.ReplyError();
return;
}
@@ -75,92 +67,86 @@ namespace Ryujinx.HLE.Debugger.Gdb
}
Debugger.DebugProcess.DebugContinue();
Processor.ReplyOK();
}
internal void CommandDetach()
internal void Detach()
{
Debugger.BreakpointManager.ClearAll();
CommandContinue(null);
Continue(null); // Continue() will call ReplyError/ReplyOK for us.
}
internal void CommandReadRegisters()
internal void ReadRegisters()
{
if (Debugger.GThread == null)
{
ReplyError();
Processor.ReplyError();
return;
}
var ctx = Debugger.DebugProcess.GetThread(Debugger.GThread.Value).Context;
string registers = "";
if (Debugger.IsProcessAarch32)
IExecutionContext ctx = Debugger.DebugProcess.GetThread(Debugger.GThread.Value).Context;
string registers = string.Empty;
if (Debugger.IsProcess32Bit)
{
for (int i = 0; i < GdbRegisterCount32; i++)
for (int i = 0; i < GdbRegisters.Count32; i++)
{
registers += GdbRegisters.Read32(ctx, i);
registers += ctx.ReadRegister32(i);
}
}
else
{
for (int i = 0; i < GdbRegisterCount64; i++)
for (int i = 0; i < GdbRegisters.Count64; i++)
{
registers += GdbRegisters.Read64(ctx, i);
registers += ctx.ReadRegister64(i);
}
}
Reply(registers);
Processor.Reply(registers);
}
internal void CommandWriteRegisters(StringStream ss)
internal void WriteRegisters(StringStream ss)
{
if (Debugger.GThread == null)
{
ReplyError();
Processor.ReplyError();
return;
}
var ctx = Debugger.DebugProcess.GetThread(Debugger.GThread.Value).Context;
if (Debugger.IsProcessAarch32)
IExecutionContext ctx = Debugger.DebugProcess.GetThread(Debugger.GThread.Value).Context;
if (Debugger.IsProcess32Bit)
{
for (int i = 0; i < GdbRegisterCount32; i++)
for (int i = 0; i < GdbRegisters.Count32; i++)
{
if (!GdbRegisters.Write32(ctx, i, ss))
if (!ctx.WriteRegister32(i, ss))
{
ReplyError();
Processor.ReplyError();
return;
}
}
}
else
{
for (int i = 0; i < GdbRegisterCount64; i++)
for (int i = 0; i < GdbRegisters.Count64; i++)
{
if (!GdbRegisters.Write64(ctx, i, ss))
if (!ctx.WriteRegister64(i, ss))
{
ReplyError();
Processor.ReplyError();
return;
}
}
}
if (ss.IsEmpty())
{
ReplyOK();
}
else
{
ReplyError();
}
Processor.Reply(ss.IsEmpty);
}
internal void CommandSetThread(char op, ulong? threadId)
internal void SetThread(char op, ulong? threadId)
{
if (threadId is 0 or null)
{
var threads = Debugger.GetThreads();
KThread[] threads = Debugger.GetThreads();
if (threads.Length == 0)
{
ReplyError();
Processor.ReplyError();
return;
}
@@ -169,7 +155,7 @@ namespace Ryujinx.HLE.Debugger.Gdb
if (Debugger.DebugProcess.GetThread(threadId.Value) == null)
{
ReplyError();
Processor.ReplyError();
return;
}
@@ -177,40 +163,40 @@ namespace Ryujinx.HLE.Debugger.Gdb
{
case 'c':
Debugger.CThread = threadId;
ReplyOK();
Processor.ReplyOK();
return;
case 'g':
Debugger.GThread = threadId;
ReplyOK();
Processor.ReplyOK();
return;
default:
ReplyError();
Processor.ReplyError();
return;
}
}
internal void CommandReadMemory(ulong addr, ulong len)
internal void ReadMemory(ulong addr, ulong len)
{
try
{
var data = new byte[len];
byte[] data = new byte[len];
Debugger.DebugProcess.CpuMemory.Read(addr, data);
Reply(Helpers.ToHex(data));
Processor.ReplyHex(data);
}
catch (InvalidMemoryRegionException)
{
// InvalidAccessHandler will show an error message, we log it again to tell user the error is from GDB (which can be ignored)
// TODO: Do not let InvalidAccessHandler show the error message
Logger.Notice.Print(LogClass.GdbStub, $"GDB failed to read memory at 0x{addr:X16}");
ReplyError();
Processor.ReplyError();
}
}
internal void CommandWriteMemory(ulong addr, ulong len, StringStream ss)
internal void WriteMemory(ulong addr, ulong len, StringStream ss)
{
try
{
var data = new byte[len];
byte[] data = new byte[len];
for (ulong i = 0; i < len; i++)
{
data[i] = (byte)ss.ReadLengthAsHex(2);
@@ -218,92 +204,50 @@ namespace Ryujinx.HLE.Debugger.Gdb
Debugger.DebugProcess.CpuMemory.Write(addr, data);
Debugger.DebugProcess.InvalidateCacheRegion(addr, len);
ReplyOK();
Processor.ReplyOK();
}
catch (InvalidMemoryRegionException)
{
ReplyError();
Processor.ReplyError();
}
}
internal void CommandReadRegister(int gdbRegId)
internal void ReadRegister(int gdbRegId)
{
if (Debugger.GThread == null)
{
ReplyError();
Processor.ReplyError();
return;
}
var ctx = Debugger.DebugProcess.GetThread(Debugger.GThread.Value).Context;
string result;
if (Debugger.IsProcessAarch32)
{
result = GdbRegisters.Read32(ctx, gdbRegId);
if (result != null)
{
Reply(result);
}
else
{
ReplyError();
}
}
else
{
result = GdbRegisters.Read64(ctx, gdbRegId);
if (result != null)
{
Reply(result);
}
else
{
ReplyError();
}
}
IExecutionContext ctx = Debugger.DebugProcess.GetThread(Debugger.GThread.Value).Context;
string result = Debugger.ReadRegister(ctx, gdbRegId);
Processor.Reply(result != null, result);
}
internal void CommandWriteRegister(int gdbRegId, StringStream ss)
internal void WriteRegister(int gdbRegId, StringStream ss)
{
if (Debugger.GThread == null)
{
ReplyError();
Processor.ReplyError();
return;
}
var ctx = Debugger.DebugProcess.GetThread(Debugger.GThread.Value).Context;
if (Debugger.IsProcessAarch32)
{
if (GdbRegisters.Write32(ctx, gdbRegId, ss) && ss.IsEmpty())
{
ReplyOK();
}
else
{
ReplyError();
}
}
else
{
if (GdbRegisters.Write64(ctx, gdbRegId, ss) && ss.IsEmpty())
{
ReplyOK();
}
else
{
ReplyError();
}
}
IExecutionContext ctx = Debugger.DebugProcess.GetThread(Debugger.GThread.Value).Context;
Processor.Reply(Debugger.WriteRegister(ctx, gdbRegId, ss) && ss.IsEmpty);
}
internal void CommandStep(ulong? newPc)
internal void Step(ulong? newPc)
{
if (Debugger.CThread == null)
{
ReplyError();
Processor.ReplyError();
return;
}
var thread = Debugger.DebugProcess.GetThread(Debugger.CThread.Value);
KThread thread = Debugger.DebugProcess.GetThread(Debugger.CThread.Value);
if (newPc.HasValue)
{
@@ -312,24 +256,24 @@ namespace Ryujinx.HLE.Debugger.Gdb
if (!Debugger.DebugProcess.DebugStep(thread))
{
ReplyError();
Processor.ReplyError();
}
else
{
Debugger.GThread = Debugger.CThread = thread.ThreadUid;
Reply($"T05thread:{thread.ThreadUid:x};");
Processor.Reply($"T05thread:{thread.ThreadUid:x};");
}
}
internal void CommandIsAlive(ulong? threadId)
internal void IsAlive(ulong? threadId)
{
if (Debugger.GetThreads().Any(x => x.ThreadUid == threadId))
{
ReplyOK();
Processor.ReplyOK();
}
else
{
Reply("E00");
Processor.Reply("E00");
}
}
@@ -341,14 +285,14 @@ namespace Ryujinx.HLE.Debugger.Gdb
Step
}
record VContPendingAction(VContAction Action, ushort? Signal = null);
record VContPendingAction(VContAction Action/*, ushort? Signal = null*/);
internal void HandleVContCommand(StringStream ss)
internal void VCont(StringStream ss)
{
string[] rawActions = ss.ReadRemaining().Split(';', StringSplitOptions.RemoveEmptyEntries);
var threadActionMap = new Dictionary<ulong, VContPendingAction>();
foreach (var thread in Debugger.GetThreads())
Dictionary<ulong, VContPendingAction> threadActionMap = new();
foreach (KThread thread in Debugger.GetThreads())
{
threadActionMap[thread.ThreadUid] = new VContPendingAction(VContAction.None);
}
@@ -358,8 +302,8 @@ namespace Ryujinx.HLE.Debugger.Gdb
// For each inferior thread, the *leftmost* action with a matching thread-id is applied.
for (int i = rawActions.Length - 1; i >= 0; i--)
{
var rawAction = rawActions[i];
var stream = new StringStream(rawAction);
string rawAction = rawActions[i];
StringStream stream = new(rawAction);
char cmd = stream.ReadChar();
VContAction action = cmd switch
@@ -371,10 +315,12 @@ namespace Ryujinx.HLE.Debugger.Gdb
};
// Note: We don't support signals yet.
ushort? signal = null;
//ushort? signal = null;
if (cmd is 'C' or 'S')
{
signal = (ushort)stream.ReadLengthAsHex(2);
/*signal = (ushort)*/stream.ReadLengthAsHex(2);
// we still call the read length method even if we have signals commented
// since that method advances the underlying string position
}
ulong? threadId = null;
@@ -387,14 +333,14 @@ namespace Ryujinx.HLE.Debugger.Gdb
{
if (threadActionMap.ContainsKey(threadId.Value))
{
threadActionMap[threadId.Value] = new VContPendingAction(action, signal);
threadActionMap[threadId.Value] = new VContPendingAction(action/*, signal*/);
}
}
else
{
foreach (var row in threadActionMap.ToList())
foreach (ulong thread in threadActionMap.Keys)
{
threadActionMap[row.Key] = new VContPendingAction(action, signal);
threadActionMap[thread] = new VContPendingAction(action/*, signal*/);
}
if (action == VContAction.Continue)
@@ -411,11 +357,11 @@ namespace Ryujinx.HLE.Debugger.Gdb
bool hasError = false;
foreach (var (threadUid, action) in threadActionMap)
foreach ((ulong threadUid, VContPendingAction action) in threadActionMap)
{
if (action.Action == VContAction.Step)
{
var thread = Debugger.DebugProcess.GetThread(threadUid);
KThread thread = Debugger.DebugProcess.GetThread(threadUid);
if (!Debugger.DebugProcess.DebugStep(thread))
{
hasError = true;
@@ -432,7 +378,7 @@ namespace Ryujinx.HLE.Debugger.Gdb
}
else if (defaultAction == VContAction.None)
{
foreach (var (threadUid, action) in threadActionMap)
foreach ((ulong threadUid, VContPendingAction action) in threadActionMap)
{
if (action.Action == VContAction.Continue)
{
@@ -441,48 +387,33 @@ namespace Ryujinx.HLE.Debugger.Gdb
}
}
if (hasError)
{
ReplyError();
}
else
{
ReplyOK();
}
Processor.Reply(!hasError);
foreach (var (threadUid, action) in threadActionMap)
foreach ((ulong threadUid, VContPendingAction action) in threadActionMap)
{
if (action.Action == VContAction.Step)
{
Debugger.GThread = Debugger.CThread = threadUid;
Reply($"T05thread:{threadUid:x};");
Processor.Reply($"T05thread:{threadUid:x};");
}
}
}
internal void HandleQRcmdCommand(string hexCommand)
internal void Q_Rcmd(string hexCommand)
{
try
{
string command = Helpers.FromHex(hexCommand);
Logger.Debug?.Print(LogClass.GdbStub, $"Received Rcmd: {command}");
string response = command.Trim().ToLowerInvariant() switch
{
"help" => "backtrace\nbt\nregisters\nreg\nget info\nminidump\n",
"get info" => Debugger.GetProcessInfo(),
"backtrace" or "bt" => Debugger.GetStackTrace(),
"registers" or "reg" => Debugger.GetRegisters(),
"minidump" => Debugger.GetMinidump(),
_ => $"Unknown command: {command}\n"
};
Func<Debugger, string> rcmd = Debugger.FindRcmdDelegate(command);
Reply(Helpers.ToHex(response));
Processor.ReplyHex(rcmd(Debugger));
}
catch (Exception e)
{
Logger.Error?.Print(LogClass.GdbStub, $"Error processing Rcmd: {e.Message}");
ReplyError();
Processor.ReplyError();
}
}
}

View File

@@ -6,72 +6,66 @@ namespace Ryujinx.HLE.Debugger.Gdb
{
static class GdbRegisters
{
public const int Count64 = 68;
public const int Count32 = 66;
/*
FPCR = FPSR & ~FpcrMask
All of FPCR's bits are reserved in FPCR and vice versa,
see ARM's documentation.
see ARM's documentation.
*/
private const uint FpcrMask = 0xfc1fffff;
public static string Read64(IExecutionContext state, int gdbRegId)
{
switch (gdbRegId)
{
case >= 0 and <= 31:
return Helpers.ToHex(BitConverter.GetBytes(state.GetX(gdbRegId)));
case 32:
return Helpers.ToHex(BitConverter.GetBytes(state.DebugPc));
case 33:
return Helpers.ToHex(BitConverter.GetBytes(state.Pstate));
case >= 34 and <= 65:
return Helpers.ToHex(state.GetV(gdbRegId - 34).ToArray());
case 66:
return Helpers.ToHex(BitConverter.GetBytes((uint)state.Fpsr));
case 67:
return Helpers.ToHex(BitConverter.GetBytes((uint)state.Fpcr));
default:
return null;
}
}
public static bool Write64(IExecutionContext state, int gdbRegId, StringStream ss)
public static string ReadRegister64(this IExecutionContext state, int registerId) =>
registerId switch
{
>= 0 and <= 31 => Helpers.ToHex(BitConverter.GetBytes(state.GetX(registerId))),
32 => Helpers.ToHex(BitConverter.GetBytes(state.DebugPc)),
33 => Helpers.ToHex(BitConverter.GetBytes(state.Pstate)),
>= 34 and <= 65 => Helpers.ToHex(state.GetV(registerId - 34).ToArray()),
66 => Helpers.ToHex(BitConverter.GetBytes(state.Fpsr)),
67 => Helpers.ToHex(BitConverter.GetBytes(state.Fpcr)),
_ => null
};
public static bool WriteRegister64(this IExecutionContext state, int registerId, StringStream ss)
{
switch (gdbRegId)
switch (registerId)
{
case >= 0 and <= 31:
{
ulong value = ss.ReadLengthAsLEHex(16);
state.SetX(gdbRegId, value);
ulong value = ss.ReadLengthAsLittleEndianHex(16);
state.SetX(registerId, value);
return true;
}
case 32:
{
ulong value = ss.ReadLengthAsLEHex(16);
ulong value = ss.ReadLengthAsLittleEndianHex(16);
state.DebugPc = value;
return true;
}
case 33:
{
ulong value = ss.ReadLengthAsLEHex(8);
ulong value = ss.ReadLengthAsLittleEndianHex(8);
state.Pstate = (uint)value;
return true;
}
case >= 34 and <= 65:
{
ulong value0 = ss.ReadLengthAsLEHex(16);
ulong value1 = ss.ReadLengthAsLEHex(16);
state.SetV(gdbRegId - 34, new V128(value0, value1));
ulong value0 = ss.ReadLengthAsLittleEndianHex(16);
ulong value1 = ss.ReadLengthAsLittleEndianHex(16);
state.SetV(registerId - 34, new V128(value0, value1));
return true;
}
case 66:
{
ulong value = ss.ReadLengthAsLEHex(8);
ulong value = ss.ReadLengthAsLittleEndianHex(8);
state.Fpsr = (uint)value;
return true;
}
case 67:
{
ulong value = ss.ReadLengthAsLEHex(8);
ulong value = ss.ReadLengthAsLittleEndianHex(8);
state.Fpcr = (uint)value;
return true;
}
@@ -80,65 +74,64 @@ namespace Ryujinx.HLE.Debugger.Gdb
}
}
public static string Read32(IExecutionContext state, int gdbRegId)
public static string ReadRegister32(this IExecutionContext state, int registerId)
{
switch (gdbRegId)
switch (registerId)
{
case >= 0 and <= 14:
return Helpers.ToHex(BitConverter.GetBytes((uint)state.GetX(gdbRegId)));
return Helpers.ToHex(BitConverter.GetBytes((uint)state.GetX(registerId)));
case 15:
return Helpers.ToHex(BitConverter.GetBytes((uint)state.DebugPc));
case 16:
return Helpers.ToHex(BitConverter.GetBytes((uint)state.Pstate));
return Helpers.ToHex(BitConverter.GetBytes(state.Pstate));
case >= 17 and <= 32:
return Helpers.ToHex(state.GetV(gdbRegId - 17).ToArray());
return Helpers.ToHex(state.GetV(registerId - 17).ToArray());
case >= 33 and <= 64:
int reg = (gdbRegId - 33);
int reg = (registerId - 33);
int n = reg / 2;
int shift = reg % 2;
ulong value = state.GetV(n).Extract<ulong>(shift);
return Helpers.ToHex(BitConverter.GetBytes(value));
case 65:
uint fpscr = (uint)state.Fpsr | (uint)state.Fpcr;
return Helpers.ToHex(BitConverter.GetBytes(fpscr));
return Helpers.ToHex(BitConverter.GetBytes(state.Fpscr));
default:
return null;
}
}
public static bool Write32(IExecutionContext state, int gdbRegId, StringStream ss)
public static bool WriteRegister32(this IExecutionContext state, int registerId, StringStream ss)
{
switch (gdbRegId)
switch (registerId)
{
case >= 0 and <= 14:
{
ulong value = ss.ReadLengthAsLEHex(8);
state.SetX(gdbRegId, value);
ulong value = ss.ReadLengthAsLittleEndianHex(8);
state.SetX(registerId, value);
return true;
}
case 15:
{
ulong value = ss.ReadLengthAsLEHex(8);
ulong value = ss.ReadLengthAsLittleEndianHex(8);
state.DebugPc = value;
return true;
}
case 16:
{
ulong value = ss.ReadLengthAsLEHex(8);
ulong value = ss.ReadLengthAsLittleEndianHex(8);
state.Pstate = (uint)value;
return true;
}
case >= 17 and <= 32:
{
ulong value0 = ss.ReadLengthAsLEHex(16);
ulong value1 = ss.ReadLengthAsLEHex(16);
state.SetV(gdbRegId - 17, new V128(value0, value1));
ulong value0 = ss.ReadLengthAsLittleEndianHex(16);
ulong value1 = ss.ReadLengthAsLittleEndianHex(16);
state.SetV(registerId - 17, new V128(value0, value1));
return true;
}
case >= 33 and <= 64:
{
ulong value = ss.ReadLengthAsLEHex(16);
int regId = (gdbRegId - 33);
ulong value = ss.ReadLengthAsLittleEndianHex(16);
int regId = (registerId - 33);
int regNum = regId / 2;
int shift = regId % 2;
V128 reg = state.GetV(regNum);
@@ -147,7 +140,7 @@ namespace Ryujinx.HLE.Debugger.Gdb
}
case 65:
{
ulong value = ss.ReadLengthAsLEHex(8);
ulong value = ss.ReadLengthAsLittleEndianHex(8);
state.Fpsr = (uint)value & FpcrMask;
state.Fpcr = (uint)value & ~FpcrMask;
return true;

View File

@@ -43,7 +43,7 @@ namespace Ryujinx.HLE.Debugger
(byte)'$' => "}\x04",
(byte)'*' => "}\x0a",
(byte)'}' => "}\x5d",
_ => Convert.ToChar(x).ToString(),
_ => Convert.ToChar(x).ToString()
}
).JoinToString(string.Empty);
}

View File

@@ -6,16 +6,17 @@ namespace Ryujinx.HLE.Debugger
{
internal interface IDebuggableProcess
{
IVirtualMemoryManager CpuMemory { get; }
ulong[] ThreadUids { get; }
DebugState DebugState { get; }
void DebugStop();
void DebugContinue();
void DebugContinue(KThread thread);
bool DebugStep(KThread thread);
KThread GetThread(ulong threadUid);
DebugState GetDebugState();
bool IsThreadPaused(KThread thread);
ulong[] GetThreadUids();
public void DebugInterruptHandler(IExecutionContext ctx);
IVirtualMemoryManager CpuMemory { get; }
void InvalidateCacheRegion(ulong address, ulong size);
}
}

View File

@@ -0,0 +1,47 @@
using Ryujinx.Cpu;
namespace Ryujinx.HLE.Debugger
{
public enum MessageType
{
Kill,
BreakIn,
SendNack
}
record struct Message(MessageType Type) : Message.IMarker
{
/// <summary>
/// Marker interface for debugger messages.
/// </summary>
internal interface IMarker;
public static Message Kill => new(MessageType.Kill);
public static Message BreakIn => new(MessageType.BreakIn);
public static Message SendNack => new(MessageType.SendNack);
}
struct CommandMessage : Message.IMarker
{
public readonly string Command;
public CommandMessage(string cmd)
{
Command = cmd;
}
}
public class ThreadBreakMessage : Message.IMarker
{
public IExecutionContext Context { get; }
public ulong Address { get; }
public int Opcode { get; }
public ThreadBreakMessage(IExecutionContext context, ulong address, int opcode)
{
Context = context;
Address = address;
Opcode = opcode;
}
}
}

View File

@@ -1,6 +0,0 @@
namespace Ryujinx.HLE.Debugger
{
struct BreakInMessage : IMessage
{
}
}

View File

@@ -1,12 +0,0 @@
namespace Ryujinx.HLE.Debugger
{
struct CommandMessage : IMessage
{
public string Command;
public CommandMessage(string cmd)
{
Command = cmd;
}
}
}

View File

@@ -1,6 +0,0 @@
namespace Ryujinx.HLE.Debugger
{
interface IMessage
{
}
}

View File

@@ -1,6 +0,0 @@
namespace Ryujinx.HLE.Debugger
{
struct KillMessage : IMessage
{
}
}

View File

@@ -1,6 +0,0 @@
namespace Ryujinx.HLE.Debugger
{
struct SendNackMessage : IMessage
{
}
}

View File

@@ -1,18 +0,0 @@
using IExecutionContext = Ryujinx.Cpu.IExecutionContext;
namespace Ryujinx.HLE.Debugger
{
public class ThreadBreakMessage : IMessage
{
public IExecutionContext Context { get; }
public ulong Address { get; }
public int Opcode { get; }
public ThreadBreakMessage(IExecutionContext context, ulong address, int opcode)
{
Context = context;
Address = address;
Opcode = opcode;
}
}
}

View File

@@ -17,12 +17,9 @@ namespace Ryujinx.HLE.Debugger
private static string GetEmbeddedResourceContent(string resourceName)
{
Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Ryujinx.HLE.Debugger.GdbXml." + resourceName);
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
reader.Dispose();
stream.Dispose();
return result;
using Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Ryujinx.HLE.Debugger.Gdb.Xml." + resourceName);
using StreamReader reader = new(stream);
return reader.ReadToEnd();
}
}
}

View File

@@ -5,63 +5,56 @@ namespace Ryujinx.HLE.Debugger
{
internal class StringStream
{
private readonly string Data;
private int Position;
private readonly string _data;
private int _position;
public StringStream(string s)
{
Data = s;
_data = s;
}
public bool IsEmpty => _position >= _data.Length;
public char ReadChar()
{
return Data[Position++];
}
public char ReadChar() => _data[_position++];
public string ReadUntil(char needle)
{
int needlePos = Data.IndexOf(needle, Position);
int needlePos = _data.IndexOf(needle, _position);
if (needlePos == -1)
{
needlePos = Data.Length;
needlePos = _data.Length;
}
string result = Data.Substring(Position, needlePos - Position);
Position = needlePos + 1;
string result = _data.Substring(_position, needlePos - _position);
_position = needlePos + 1;
return result;
}
public string ReadLength(int len)
{
string result = Data.Substring(Position, len);
Position += len;
string result = _data.Substring(_position, len);
_position += len;
return result;
}
public string ReadRemaining()
{
string result = Data.Substring(Position);
Position = Data.Length;
string result = _data[_position..];
_position = _data.Length;
return result;
}
public ulong ReadRemainingAsHex()
{
return ulong.Parse(ReadRemaining(), NumberStyles.HexNumber);
}
public ulong ReadRemainingAsHex()
=> ulong.Parse(ReadRemaining(), NumberStyles.HexNumber);
public ulong ReadUntilAsHex(char needle)
{
return ulong.Parse(ReadUntil(needle), NumberStyles.HexNumber);
}
public ulong ReadUntilAsHex(char needle)
=> ulong.Parse(ReadUntil(needle), NumberStyles.HexNumber);
public ulong ReadLengthAsHex(int len)
{
return ulong.Parse(ReadLength(len), NumberStyles.HexNumber);
}
public ulong ReadLengthAsHex(int len)
=> ulong.Parse(ReadLength(len), NumberStyles.HexNumber);
public ulong ReadLengthAsLEHex(int len)
public ulong ReadLengthAsLittleEndianHex(int len)
{
Debug.Assert(len % 2 == 0);
@@ -83,9 +76,9 @@ namespace Ryujinx.HLE.Debugger
public bool ConsumePrefix(string prefix)
{
if (Data.Substring(Position).StartsWith(prefix))
if (_data[_position..].StartsWith(prefix))
{
Position += prefix.Length;
_position += prefix.Length;
return true;
}
return false;
@@ -93,17 +86,12 @@ namespace Ryujinx.HLE.Debugger
public bool ConsumeRemaining(string match)
{
if (Data.Substring(Position) == match)
if (_data[_position..] == match)
{
Position += match.Length;
_position += match.Length;
return true;
}
return false;
}
public bool IsEmpty()
{
return Position >= Data.Length;
}
}
}

View File

@@ -161,6 +161,116 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
return sb.ToString();
}
public string GetProcessInfoPrintout()
{
StringBuilder sb = new();
sb.AppendLine($"Process: {_owner.Name}, PID: {_owner.Pid}");
sb.AppendLine($"Program Id: 0x{_owner.TitleId:x16}");
sb.AppendLine($"Application: {(_owner.IsApplication ? 1 : 0)}");
sb.AppendLine("Layout:");
sb.AppendLine(
$" Alias: 0x{_owner.MemoryManager.AliasRegionStart:x10} - 0x{_owner.MemoryManager.AliasRegionEnd - 1:x10}");
sb.AppendLine(
$" Heap: 0x{_owner.MemoryManager.HeapRegionStart:x10} - 0x{_owner.MemoryManager.HeapRegionEnd - 1:x10}");
sb.AppendLine(
$" Aslr: 0x{_owner.MemoryManager.AslrRegionStart:x10} - 0x{_owner.MemoryManager.AslrRegionEnd - 1:x10}");
sb.AppendLine(
$" Stack: 0x{_owner.MemoryManager.StackRegionStart:x10} - 0x{_owner.MemoryManager.StackRegionEnd - 1:x10}");
sb.AppendLine("Modules:");
foreach (Image image in GetLoadedImages())
{
ulong endAddress = image.BaseAddress + image.Size - 1;
sb.AppendLine($" 0x{image.BaseAddress:x10} - 0x{endAddress:x10} {image.Name}");
}
return sb.ToString();
}
public string GetMinidump()
{
var result = new StringBuilder();
result.AppendLine("=== Begin Minidump ===\n");
try
{
result.AppendLine(GetProcessInfoPrintout());
}
catch (Exception e)
{
result.AppendLine($"[Error getting process info: {e.Message}]");
}
var debugInterface = _owner?.DebugInterface;
if (debugInterface != null)
{
ulong[] threadUids;
try
{
threadUids = debugInterface.ThreadUids ?? [];
}
catch (Exception e)
{
result.AppendLine($"[Error getting thread uids: {e.Message}]");
threadUids = [];
}
foreach (ulong threadUid in threadUids)
{
result.AppendLine($"=== Thread {threadUid} ===");
KThread thread;
try
{
thread = debugInterface.GetThread(threadUid);
}
catch (Exception e)
{
result.AppendLine($"[Error getting thread: {e.Message}]");
continue;
}
if (thread == null)
{
result.AppendLine("[Thread not found]");
continue;
}
try
{
result.AppendLine(GetGuestStackTrace(thread));
}
catch (Exception e)
{
result.AppendLine($"[Error getting stack trace: {e.Message}]");
}
try
{
result.AppendLine(GetCpuRegisterPrintout(thread));
}
catch (Exception e)
{
result.AppendLine($"[Error getting registers: {e.Message}]");
}
}
}
else
{
result.AppendLine("[Error generating minidump: debugInterface is null]");
}
result.AppendLine("=== End Minidump ===");
return result.ToString();
}
private static bool TryGetSubName(Image image, ulong address, out ElfSymbol symbol)
{
address -= image.BaseAddress;
@@ -267,7 +377,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
{
moduleName = string.Empty;
var rodataStart = image.BaseAddress + image.Size;
ulong rodataStart = image.BaseAddress + image.Size;
KMemoryInfo roInfo = _owner.MemoryManager.QueryMemory(rodataStart);
if (roInfo.Permission != KMemoryPermission.Read)
@@ -275,7 +385,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
return false;
}
var rwdataStart = roInfo.Address + roInfo.Size;
ulong rwdataStart = roInfo.Address + roInfo.Size;
try
{
@@ -305,7 +415,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
}
pathLength = Math.Min(pathLength, rodataBuf.Length - 8);
var pathBuf = rodataBuf.Slice(8, pathLength);
Span<byte> pathBuf = rodataBuf.Slice(8, pathLength);
int lastSlash = pathBuf.LastIndexOfAny(new byte[] { (byte)'\\', (byte)'/' });
moduleName = Encoding.ASCII.GetString(pathBuf.Slice(lastSlash + 1).TrimEnd((byte)0));
@@ -483,12 +593,11 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
lock (_images)
{
var image = new Image(textOffset, textSize, symbols.OrderBy(x => x.Value).ToArray());
Image image = new(textOffset, textSize, symbols.OrderBy(x => x.Value).ToArray());
string moduleName;
if (!GetModuleName(out moduleName, image))
if (!GetModuleName(out string moduleName, image))
{
var newIndex = _images.Count;
int newIndex = _images.Count;
moduleName = $"(unknown{newIndex})";
}
image.Name = moduleName;

View File

@@ -1092,7 +1092,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
MemoryManager = new KPageTable(KernelContext, CpuMemory, Context.AddressSpaceSize);
}
private bool InvalidAccessHandler(ulong va)
private static bool InvalidAccessHandler(ulong va)
{
KernelStatic.GetCurrentThread()?.PrintGuestStackTrace();
KernelStatic.GetCurrentThread()?.PrintGuestRegisterPrintout();
@@ -1104,7 +1104,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
return false;
}
private void UndefinedInstructionHandler(IExecutionContext context, ulong address, int opCode)
private static void UndefinedInstructionHandler(IExecutionContext context, ulong address, int opCode)
{
KernelStatic.GetCurrentThread().PrintGuestStackTrace();
KernelStatic.GetCurrentThread()?.PrintGuestRegisterPrintout();
@@ -1208,16 +1208,16 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
private class DebuggerInterface : IDebuggableProcess
{
private Barrier StepBarrier;
private readonly Barrier _stepBarrier;
private readonly KProcess _parent;
private readonly KernelContext _kernelContext;
private KThread steppingThread;
private KThread _steppingThread;
public DebuggerInterface(KProcess p)
{
_parent = p;
_kernelContext = p.KernelContext;
StepBarrier = new(2);
_stepBarrier = new(2);
}
public void DebugStop()
@@ -1285,7 +1285,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
}
_kernelContext.CriticalSection.Enter();
steppingThread = target;
_steppingThread = target;
bool waiting = target.MutexOwner != null || target.WaitingSync || target.WaitingInArbitration;
target.Context.RequestDebugStep();
if (waiting)
@@ -1305,14 +1305,14 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
_kernelContext.CriticalSection.Leave();
bool stepTimedOut = false;
if (!StepBarrier.SignalAndWait(TimeSpan.FromMilliseconds(2000)))
if (!_stepBarrier.SignalAndWait(TimeSpan.FromMilliseconds(2000)))
{
Logger.Warning?.Print(LogClass.Kernel, $"Failed to step thread {target.ThreadUid} in time.");
stepTimedOut = true;
}
_kernelContext.CriticalSection.Enter();
steppingThread = null;
_steppingThread = null;
if (waiting)
{
lock (_parent._threadingLock)
@@ -1334,26 +1334,28 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
return false;
}
StepBarrier.SignalAndWait();
_stepBarrier.SignalAndWait();
return true;
}
public DebugState GetDebugState()
{
return (DebugState)_parent.debugState;
}
public DebugState DebugState => (DebugState)_parent.debugState;
public bool IsThreadPaused(KThread target)
{
return (target.SchedFlags & ThreadSchedState.ThreadPauseFlag) != 0;
}
public ulong[] GetThreadUids()
public ulong[] ThreadUids
{
lock (_parent._threadingLock)
get
{
var threads = _parent._threads.Where(x => !x.TerminationRequested).ToArray();
return threads.Select(x => x.ThreadUid).ToArray();
lock (_parent._threadingLock)
{
return _parent._threads
.Where(x => !x.TerminationRequested)
.Select(x => x.ThreadUid)
.ToArray();
}
}
}
@@ -1361,25 +1363,25 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
{
lock (_parent._threadingLock)
{
var threads = _parent._threads.Where(x => !x.TerminationRequested).ToArray();
return threads.FirstOrDefault(x => x.ThreadUid == threadUid);
return _parent._threads.Where(x => !x.TerminationRequested)
.FirstOrDefault(x => x.ThreadUid == threadUid);
}
}
public void DebugInterruptHandler(IExecutionContext ctx)
{
_kernelContext.CriticalSection.Enter();
bool stepping = steppingThread != null;
bool stepping = _steppingThread != null;
_kernelContext.CriticalSection.Leave();
if (stepping)
{
StepBarrier.SignalAndWait();
StepBarrier.SignalAndWait();
_stepBarrier.SignalAndWait();
_stepBarrier.SignalAndWait();
}
_parent.InterruptHandler(ctx);
}
public IVirtualMemoryManager CpuMemory { get { return _parent.CpuMemory; } }
public IVirtualMemoryManager CpuMemory => _parent.CpuMemory;
public void InvalidateCacheRegion(ulong address, ulong size)
{

View File

@@ -1,5 +1,4 @@
using System;
using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Kernel.Process
{

View File

@@ -1,6 +1,5 @@
using ARMeilleure.State;
using Ryujinx.Cpu;
using System.Threading;
namespace Ryujinx.HLE.HOS.Kernel.Process
{

View File

@@ -293,7 +293,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading
KThread currentThread = KernelStatic.GetCurrentThread();
KThread selectedThread = _state.SelectedThread;
if (!currentThread.IsThreadNamed && currentThread.GetThreadName() != "")
if (!currentThread.IsThreadNamed && string.IsNullOrEmpty(currentThread.GetThreadName()))
{
currentThread.HostThread.Name = $"<{currentThread.GetThreadName()}>";
currentThread.IsThreadNamed = true;

View File

@@ -1,7 +1,6 @@
using ARMeilleure.State;
using Ryujinx.Common.Logging;
using Ryujinx.Cpu;
using Ryujinx.HLE.Debugger;
using Ryujinx.HLE.HOS.Kernel.Common;
using Ryujinx.HLE.HOS.Kernel.Process;
using Ryujinx.HLE.HOS.Kernel.SupervisorCall;

View File

@@ -38,6 +38,13 @@ namespace Ryujinx.HLE.HOS.Services.Account.Acc.AccountService
}
[CommandCmif(3)]
// LoadIdTokenCacheDeprecated() -> (u32 id_token_cache_size, buffer<bytes, 6>)
public ResultCode LoadIdTokenCacheDeprecated(ServiceCtx context)
{
return _managerServer.LoadIdTokenCache(context);
}
[CommandCmif(4)] // 19.0.0+
// LoadIdTokenCache() -> (u32 id_token_cache_size, buffer<bytes, 6>)
public ResultCode LoadIdTokenCache(ServiceCtx context)
{

View File

@@ -38,6 +38,13 @@ namespace Ryujinx.HLE.HOS.Services.Account.Acc.AccountService
}
[CommandCmif(3)]
// LoadIdTokenCacheDeprecated() -> (u32 id_token_cache_size, buffer<bytes, 6>)
public ResultCode LoadIdTokenCacheDeprecated(ServiceCtx context)
{
return _managerServer.LoadIdTokenCache(context);
}
[CommandCmif(4)] // 19.0.0+
// LoadIdTokenCache() -> (u32 id_token_cache_size, buffer<bytes, 6>)
public ResultCode LoadIdTokenCache(ServiceCtx context)
{

View File

@@ -7,7 +7,6 @@ using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

View File

@@ -83,23 +83,23 @@ namespace Ryujinx.HLE.HOS.Services.Hid.Types.SharedMemory.Common
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<AtomicStorage<T>> ReadEntries(uint maxCount)
{
ulong countAvailaible = Math.Min(Math.Max(0, ReadCurrentCount()), maxCount);
ulong countAvailable = Math.Min(Math.Max(0, ReadCurrentCount()), maxCount);
if (countAvailaible == 0)
if (countAvailable == 0)
{
return ReadOnlySpan<AtomicStorage<T>>.Empty;
}
ulong index = ReadCurrentIndex();
AtomicStorage<T>[] result = new AtomicStorage<T>[countAvailaible];
AtomicStorage<T>[] result = new AtomicStorage<T>[countAvailable];
Span<AtomicStorage<T>> storageSpan = _storage.AsSpan();
for (ulong i = 0; i < countAvailaible; i++)
for (ulong i = 0; i < countAvailable; i++)
{
int inputEntryIndex = (int)((index + MaxEntries + 1 - countAvailaible + i) % MaxEntries);
int outputEntryIndex = (int)(countAvailaible - i - 1);
int inputEntryIndex = (int)((index + MaxEntries + 1 - countAvailable + i) % MaxEntries);
int outputEntryIndex = (int)(countAvailable - i - 1);
ulong samplingNumber0 = storageSpan[inputEntryIndex].ReadSamplingNumberAtomic();
result[outputEntryIndex] = storageSpan[inputEntryIndex];
@@ -107,9 +107,9 @@ namespace Ryujinx.HLE.HOS.Services.Hid.Types.SharedMemory.Common
if (samplingNumber0 != samplingNumber1 && (i > 0 && (result[outputEntryIndex].SamplingNumber - result[outputEntryIndex].SamplingNumber) != 1))
{
ulong tempCount = Math.Min(ReadCurrentCount(), countAvailaible);
ulong tempCount = Math.Min(ReadCurrentCount(), countAvailable);
countAvailaible = Math.Min(tempCount, maxCount);
countAvailable = Math.Min(tempCount, maxCount);
index = ReadCurrentIndex();
i -= 1;

View File

@@ -15,5 +15,14 @@ namespace Ryujinx.HLE.HOS.Services.Ldn
return ResultCode.Success;
}
[CommandCmif(1)] // 18.0.0+
// CreateClientProcessMonitor() -> object<nn::ldn::detail::IClientProcessMonitor>
public ResultCode CreateClientProcessMonitor(ServiceCtx context)
{
MakeObject(context, new IClientProcessMonitor(context));
return ResultCode.Success;
}
}
}

View File

@@ -0,0 +1,20 @@
using Ryujinx.Common.Logging;
namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator
{
class IClientProcessMonitor : DisposableIpcService
{
public IClientProcessMonitor(ServiceCtx context) { }
[CommandCmif(0)] // 18.0.0+
// RegisterClient(u64 pid_placeholder, pid)
public ResultCode RegisterClient(ServiceCtx context)
{
Logger.Stub?.PrintStub(LogClass.ServiceLdn);
return ResultCode.Success;
}
protected override void Dispose(bool isDisposing) { }
}
}

View File

@@ -1,5 +1,3 @@
using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Services.Loader
{
enum ResultCode

View File

@@ -2,7 +2,6 @@ using Ryujinx.Common.Logging;
using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Proxy;
using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;

View File

@@ -1,5 +1,3 @@
using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{
enum WsaError

View File

@@ -1,5 +1,3 @@
using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{
enum BsdSocketOption

View File

@@ -1,5 +1,3 @@
using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{
enum LinuxError

View File

@@ -1,5 +1,3 @@
using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Services.SurfaceFlinger
{
enum Status

View File

@@ -2,7 +2,6 @@ using Ryujinx.Common;
using Ryujinx.Common.Configuration;
using Ryujinx.Common.Logging;
using Ryujinx.Common.PreciseSleep;
using Ryujinx.Cpu;
using Ryujinx.Graphics.GAL;
using Ryujinx.Graphics.Gpu;
using Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvMap;

View File

@@ -1,5 +1,3 @@
using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Services.SurfaceFlinger
{
enum ColorFormat : ulong

View File

@@ -1,5 +1,3 @@
using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Services.Time
{
public enum ResultCode

View File

@@ -1,5 +1,3 @@
using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.Loaders.Elf
{
enum ElfDynamicTag

View File

@@ -9,7 +9,6 @@ using Ryujinx.Common.Logging;
using Ryujinx.Graphics.Gpu;
using Ryujinx.HLE.Loaders.Executables;
using Ryujinx.Memory;
using System;
using System.Linq;
using static Ryujinx.HLE.HOS.ModLoader;

View File

@@ -6,7 +6,6 @@ using Ryujinx.Cpu;
using Ryujinx.HLE.HOS.SystemState;
using Ryujinx.HLE.Loaders.Processes.Extensions;
using Ryujinx.Horizon.Common;
using System;
namespace Ryujinx.HLE.Loaders.Processes
{

View File

@@ -14,7 +14,6 @@ using Ryujinx.HLE.Loaders.Processes;
using Ryujinx.HLE.UI;
using Ryujinx.Memory;
using System;
using System.Threading;
namespace Ryujinx.HLE
{

View File

@@ -1,4 +1,3 @@
using Ryujinx.Common.Memory;
using Ryujinx.HLE.HOS.Services.Hid.Types.SharedMemory.Common;
using Ryujinx.HLE.HOS.Services.Hid.Types.SharedMemory.Npad;
using System;
@@ -60,18 +59,18 @@ namespace Ryujinx.HLE.UI.Input
}
}
public void Update(bool supressEvents = false)
public void Update(bool suppressEvents = false)
{
int npadsCount = _device.Hid.SharedMemory.Npads.Length;
// Process each input individually.
for (int npadIndex = 0; npadIndex < npadsCount; npadIndex++)
{
UpdateNpad(npadIndex, supressEvents);
UpdateNpad(npadIndex, suppressEvents);
}
}
private void UpdateNpad(int npadIndex, bool supressEvents)
private void UpdateNpad(int npadIndex, bool suppressEvents)
{
const int MaxEntries = 1024;
@@ -104,7 +103,7 @@ namespace Ryujinx.HLE.UI.Input
break;
}
if (!supressEvents)
if (!suppressEvents)
{
ProcessNpadButtons(npadIndex, entry.Object.Buttons);
}

View File

@@ -1,72 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<RuntimeIdentifiers>win-x64;osx-x64;linux-x64</RuntimeIdentifiers>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Version>1.0.0-dirty</Version>
<DefineConstants Condition=" '$(ExtraDefineConstants)' != '' ">$(DefineConstants);$(ExtraDefineConstants)</DefineConstants>
<SigningCertificate Condition=" '$(SigningCertificate)' == '' ">-</SigningCertificate>
<TieredPGO>true</TieredPGO>
<DefaultItemExcludes>$(DefaultItemExcludes);._*</DefaultItemExcludes>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="OpenTK.Core" />
<PackageReference Include="Ryujinx.Graphics.Nvdec.Dependencies" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="$([MSBuild]::IsOSPlatform('OSX'))">
<Exec Command="codesign --entitlements '$(ProjectDir)..\..\distribution\macos\entitlements.xml' -f -s $(SigningCertificate) '$(TargetDir)$(TargetName)'" />
</Target>
<ItemGroup>
<ProjectReference Include="..\Ryujinx.Graphics.Vulkan\Ryujinx.Graphics.Vulkan.csproj" />
<ProjectReference Include="..\Ryujinx.Input\Ryujinx.Input.csproj" />
<ProjectReference Include="..\Ryujinx.Input.SDL2\Ryujinx.Input.SDL2.csproj" />
<ProjectReference Include="..\Ryujinx.Audio.Backends.SDL2\Ryujinx.Audio.Backends.SDL2.csproj" />
<ProjectReference Include="..\Ryujinx.Common\Ryujinx.Common.csproj" />
<ProjectReference Include="..\Ryujinx.HLE\Ryujinx.HLE.csproj" />
<ProjectReference Include="..\ARMeilleure\ARMeilleure.csproj" />
<ProjectReference Include="..\Ryujinx.Graphics.OpenGL\Ryujinx.Graphics.OpenGL.csproj" />
<ProjectReference Include="..\Ryujinx.Graphics.Gpu\Ryujinx.Graphics.Gpu.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="CommandLineParser" />
<PackageReference Include="Ryujinx.Graphics.Vulkan.Dependencies.MoltenVK" Condition="'$(RuntimeIdentifier)' != 'linux-x64' AND '$(RuntimeIdentifier)' != 'linux-arm64' AND '$(RuntimeIdentifier)' != 'win-x64'" />
</ItemGroup>
<ItemGroup>
<Content Include="..\..\distribution\legal\THIRDPARTY.md">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<TargetPath>THIRDPARTY.md</TargetPath>
</Content>
<Content Include="..\..\LICENSE.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<TargetPath>LICENSE.txt</TargetPath>
</Content>
</ItemGroup>
<ItemGroup Condition="'$(RuntimeIdentifier)' == 'linux-x64' OR '$(RuntimeIdentifier)' == 'linux-arm64' OR ('$(RuntimeIdentifier)' == '' AND $([MSBuild]::IsOSPlatform('Linux')))">
<Content Include="..\..\distribution\linux\Ryujinx.sh">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Ryujinx.bmp" />
</ItemGroup>
<!-- Due to .net core 3.1 embedded resource loading -->
<PropertyGroup>
<EmbeddedResourceUseDependentUponConvention>false</EmbeddedResourceUseDependentUponConvention>
<ApplicationIcon>..\Ryujinx\Ryujinx.ico</ApplicationIcon>
</PropertyGroup>
<PropertyGroup Condition="'$(RuntimeIdentifier)' != ''">
<PublishSingleFile>true</PublishSingleFile>
<PublishTrimmed>true</PublishTrimmed>
<TrimMode>partial</TrimMode>
</PropertyGroup>
</Project>

View File

@@ -6,7 +6,7 @@ namespace Ryujinx.Horizon.Audio
{
class HwopusIpcServer
{
private const int MaxSessionsCount = 24;
private const int MaxSessionsCount = 25;
private const int PointerBufferSize = 0x1000;
private const int MaxDomains = 8;

View File

@@ -362,7 +362,7 @@ namespace Ryujinx.Input.SDL2
if (HasConfiguration)
{
var joyconStickConfig = GetLogicalJoyStickConfig(inputId);
JoyconConfigControllerStick<GamepadInputId, Common.Configuration.Hid.Controller.StickInputId> joyconStickConfig = GetLogicalJoyStickConfig(inputId);
if (joyconStickConfig != null)
{
@@ -398,7 +398,7 @@ namespace Ryujinx.Input.SDL2
public bool IsPressed(GamepadButtonInputId inputId)
{
if (!_buttonsDriverMapping.TryGetValue(inputId, out var button))
if (!_buttonsDriverMapping.TryGetValue(inputId, out SDL_GameControllerButton button))
{
return false;
}

View File

@@ -105,7 +105,7 @@ namespace Ryujinx.Input.SDL2
private static (int leftIndex, int rightIndex) DetectJoyConPair(List<string> gamepadsIds)
{
var gamepadNames = gamepadsIds.Where(gamepadId => gamepadId != Id)
List<string> gamepadNames = gamepadsIds.Where(gamepadId => gamepadId != Id)
.Select((_, index) => SDL_GameControllerNameForIndex(index)).ToList();
int leftIndex = gamepadNames.IndexOf(SDL2JoyCon.LeftName);
int rightIndex = gamepadNames.IndexOf(SDL2JoyCon.RightName);

View File

@@ -71,8 +71,8 @@ namespace Ryujinx.Ava.Input
{
_size = new Size((int)rect.Width, (int)rect.Height);
}
private void HandleScrollStopped()
private void HandleScrollStopped()
{
Scroll = new Vector2(0, 0);
}
@@ -104,12 +104,18 @@ namespace Ryujinx.Ava.Input
}
private void Parent_PointerPressedEvent(object o, PointerPressedEventArgs args)
{
uint button = (uint)args.GetCurrentPoint(_widget).Properties.PointerUpdateKind;
PointerPoint currentPoint = args.GetCurrentPoint(_widget);
uint button = (uint)currentPoint.Properties.PointerUpdateKind;
if ((uint)PressedButtons.Length > button)
{
PressedButtons[button] = true;
}
if (args.Pointer.Type == PointerType.Touch) // mouse position is unchanged for touch events, set touch position
{
CurrentPosition = new Vector2((float)currentPoint.Position.X, (float)currentPoint.Position.Y);
}
}
private void Parent_PointerMovedEvent(object o, PointerEventArgs args)

View File

@@ -201,8 +201,6 @@ namespace Ryujinx.Ava.Systems
ConfigurationState.Instance.Graphics.AspectRatio.Event += UpdateAspectRatioState;
ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState;
ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState;
ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState;
ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState;
ConfigurationState.Instance.Graphics.AntiAliasing.Event += UpdateAntiAliasing;
ConfigurationState.Instance.Graphics.ScalingFilter.Event += UpdateScalingFilter;
ConfigurationState.Instance.Graphics.ScalingFilterLevel.Event += UpdateScalingFilterLevel;

View File

@@ -848,7 +848,7 @@ namespace Ryujinx.Ava.Systems.AppLibrary
TimeSpan temporary = TimeSpan.Zero;
foreach (var installedApplication in Applications.Items)
foreach (ApplicationData installedApplication in Applications.Items)
{
temporary += LoadAndSaveMetaData(installedApplication.IdString).TimePlayed;
}

View File

@@ -54,7 +54,7 @@ namespace Ryujinx.Ava.Systems
WorkingDirectory = executableDirectory,
};
foreach (var arg in args)
foreach (string arg in args)
{
processStart.ArgumentList.Add(arg);
}

View File

@@ -50,7 +50,7 @@ namespace Ryujinx.Ava.UI.Applet
private string GetWindowsFontByLanguage()
{
var culture = CultureInfo.CurrentUICulture;
CultureInfo culture = CultureInfo.CurrentUICulture;
string langCode = culture.Name;
return culture.TwoLetterISOLanguageName switch

View File

@@ -107,7 +107,7 @@ namespace Ryujinx.Ava.UI.Models
private static async Task<string> GetAllAsyncRequestImpl(HttpClient client = null)
{
var ldnWebHost = ConfigurationState.Instance.Multiplayer.GetLdnWebServer();
string ldnWebHost = ConfigurationState.Instance.Multiplayer.GetLdnWebServer();
LocaleManager.Associate(LocaleKeys.LdnGameListRefreshToolTip, ldnWebHost);

View File

@@ -35,7 +35,7 @@ namespace Ryujinx.Ava.UI.ViewModels
SortApply();
}
var filtered = _visibleEntries;
IEnumerable<LdnGameModel> filtered = _visibleEntries;
if (OnlyShowForOwnedGames)
filtered = filtered.Where(x => _ownedGameTitleIds.ContainsIgnoreCase(x.Title.Id));

View File

@@ -348,7 +348,7 @@ namespace Ryujinx.Ava.UI.ViewModels
{
if (ts.HasValue)
{
var formattedPlayTime = ValueFormatUtils.FormatTimeSpan(ts.Value);
string formattedPlayTime = ValueFormatUtils.FormatTimeSpan(ts.Value);
LocaleManager.Associate(LocaleKeys.GameListLabelTotalTimePlayed, formattedPlayTime);
ShowTotalTimePlayed = formattedPlayTime != string.Empty;
return;
@@ -827,10 +827,10 @@ namespace Ryujinx.Ava.UI.ViewModels
private void RefreshGrid()
{
var appsList = Applications.ToObservableChangeSet()
IObservableList<ApplicationData> appsList = Applications.ToObservableChangeSet()
.Filter(Filter)
.Sort(GetComparer())
.Bind(out var apps)
.Bind(out ReadOnlyObservableCollection<ApplicationData> apps)
.AsObservableList();
AppsObservableList = apps;

View File

@@ -447,9 +447,9 @@ namespace Ryujinx.Ava.UI.ViewModels
_virtualFileSystem = virtualFileSystem;
_contentManager = contentManager;
if (gameIconData != null && gameIconData.Length > 0)
if (gameIconData is { Length: > 0 })
{
using var ms = new MemoryStream(gameIconData);
using MemoryStream ms = new(gameIconData);
_gameIcon = new Bitmap(ms);
}