Compare commits

..

5 Commits

Author SHA1 Message Date
597556cc59 add B and fix add 2026-02-01 12:07:22 +08:00
c1f7a5eabe EnterBlock 2026-01-24 11:30:55 +08:00
100a9d3546 CodeGenerator实现 2026-01-22 21:23:08 +08:00
caf0f58fb0 add指令 2026-01-21 07:51:35 +08:00
ba99106348 寄存器映射 2026-01-10 11:07:27 +08:00
50 changed files with 3660 additions and 1636 deletions

View File

@ -0,0 +1,10 @@
{
"permissions": {
"allow": [
"Bash(dir:*)",
"Bash(wc:*)",
"Bash(for f in src/ARMeilleure/CodeGen/X86/*.cs)",
"Bash(done)"
]
}
}

182
CLAUDE.md Normal file
View File

@ -0,0 +1,182 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
Ryujinx is an open-source Nintendo Switch emulator written in C#. This is a community fork (Ryubing/Ryujinx) focused on Quality of Life improvements for existing users. The emulator provides high-accuracy emulation of the Nintendo Switch's ARMv8 CPU and Maxwell GPU.
## Build Commands
### Building the Project
```bash
dotnet build -c Release -o build
```
### Code Style Enforcement
Run `dotnet format` before committing to ensure code style compliance:
```bash
dotnet format
```
### Running Tests
```bash
# Run all tests
dotnet test
# Run specific test project
dotnet test src/Ryujinx.Tests/Ryujinx.Tests.csproj
dotnet test src/Ryujinx.Tests.Memory/Ryujinx.Tests.Memory.csproj
dotnet test src/Ryujinx.Tests.Unicorn/Ryujinx.Tests.Unicorn.csproj
```
## Requirements
- .NET 9.0 SDK or higher (version 9.0.100 specified in `global.json`)
- Minimum 8GB RAM for optimal performance
## Architecture Overview
### Three-Layer Architecture
```
┌─────────────────────────────────────┐
│ UI Layer (Avalonia MVVM) │ src/Ryujinx (GUI)
│ Headless Mode (SDL2) │ src/Ryujinx.Headless.SDL2
└────────────────────┬────────────────┘
┌────────────────────┴────────────────┐
│ High-Level Emulation (HLE) │
│ - Ryujinx.HLE │ Horizon OS services emulation
│ - Ryujinx.Horizon │ System services implementation
└────────────────────┬────────────────┘
┌────────────────────┴────────────────┐
│ Core Emulation │
│ - ARMeilleure (CPU) │ ARM instruction translation
│ - Ryujinx.Graphics.Gpu │ Maxwell GPU emulation
│ - Ryujinx.Audio │ Audio engine
└────────────────────┬────────────────┘
┌────────────────────┴────────────────┐
│ Backend Implementations │
│ - OpenGL/Vulkan/Metal (Graphics) │
│ - OpenAL/SDL2/SoundIO (Audio) │
│ - SDL2 (Input) │
└─────────────────────────────────────┘
```
### Key Components
**ARMeilleure (src/ARMeilleure/)**
- CPU emulator that translates ARMv8 instructions to x86/ARM64/Loong64 machine code
- Translation pipeline: ARM decode → Custom IR → Optimizations → Code generation
- Supports Profiled Persistent Translation Cache (PPTC) for faster load times
- Code generation backends in `CodeGen/` for different architectures
**Ryujinx.HLE (src/Ryujinx.HLE/)**
- High-Level Emulation of Nintendo Switch OS (Horizon OS)
- `HOS/Services/` contains system service implementations (am, audio, fs, hid, etc.)
- `HOS/Kernel/` handles thread/process management
- `Loaders/` support ELF, NSO, NRO executable formats
- `Debugger/` provides GDB protocol support
**Graphics Stack**
- `Ryujinx.Graphics.Gpu/` - Main GPU emulation engine (Maxwell architecture)
- `Engine/` subdirectory contains graphics command processors (Compute, DMA, GPFifo, Threed, etc.)
- `Shader/` handles shader compilation and disk caching
- `Ryujinx.Graphics.GAL/` - Graphics Abstraction Layer (backend-agnostic interface)
- Backend implementations: OpenGL, Vulkan, Metal (via MoltenVK on macOS)
- `Ryujinx.Graphics.Shader/` - Shader translation to GLSL/SPIR-V
**Memory Management (src/Ryujinx.Memory/)**
- Three memory manager modes: checked (slowest), untuned, host (default/fastest)
- Balances emulation accuracy vs. performance
**UI (src/Ryujinx/)**
- Built with Avalonia (cross-platform XAML framework)
- MVVM pattern using CommunityToolkit.Mvvm
- UI structure: `UI/Views/`, `UI/ViewModels/`, `UI/Windows/`, `UI/Controls/`
- Locale management with auto-generated code (`Ryujinx.UI.LocaleGenerator`)
### Code Generation
Several components use source generators:
- `Ryujinx.HLE.Generators` - Generates HLE service stubs
- `Ryujinx.Horizon.Generators` - Generates Horizon OS bindings
- `Ryujinx.Horizon.Kernel.Generators` - Generates kernel syscalls
- `Ryujinx.UI.LocaleGenerator` - Generates locale string bindings
- `Spv.Generator` - Generates SPIR-V shader code for Vulkan
## Coding Guidelines
Follow the C# coding style defined in `.editorconfig` and `docs/coding-guidelines/coding-style.md`:
- **Braces**: Allman style (braces on new lines)
- **Indentation**: 4 spaces, no tabs
- **Fields**: `_camelCase` for private instance, `s_` prefix for static, `t_` for thread-static
- **Visibility**: Always specify explicitly (e.g., `private`, `public`)
- **var**: Only use when type is explicitly named on right-hand side
- **Imports**: At top of file, outside namespace declarations
- **Types**: Make internal/private types static or sealed unless derivation needed
- **Magic Numbers**: Define as named constants
Always run `dotnet format` before committing.
## Development Workflow
1. Create a branch off `master` (the main branch, not `main`)
2. Make changes and ensure `dotnet format` is run
3. Build with `dotnet build -c Release` and verify clean build
4. Run relevant tests
5. Submit PR against `master` branch
6. Two team members must review and approve before merge
7. CI runs automatically via GitHub Actions (`.github/workflows/`)
## Important Project Patterns
**Abstraction Layers**: The project uses abstraction layers extensively to support multiple backends:
- Graphics backends (OpenGL/Vulkan/Metal)
- Audio backends (OpenAL/SDL2/SoundIO)
- Input systems (SDL2)
- Memory management modes
**Translation Caching**: ARMeilleure uses a persistent translation cache that significantly improves load times after the third launch of a game.
**Disk Shader Caching**: Compiled shaders are cached to disk to avoid recompilation (`Ryujinx.Graphics.Gpu/Shader/DiskCache/`).
**Platform-Specific Code**: The codebase handles Windows, macOS, and Linux with platform-specific implementations where needed.
## Common File Locations
- **System Files**: User folder (accessible via GUI: File → Open Ryujinx Folder)
- **Logs**: `[Executable Folder]/Logs` - chronologically named
- **Configuration**: `Config.json` in Ryujinx data folder
- **Build Output**: `build/` directory after running build command
## Branches and Releases
- **master**: Main branch for stable releases (released monthly)
- **canary**: Automated builds for every commit on master (may be unstable)
- Current working branch is **Loong64** (architecture support feature branch)
## When Working With Specific Systems
**Adding/Modifying HLE Services**: Follow the service implementation guidelines at https://gist.github.com/gdkchan/84ba88cd50efbe58d1babfaa7cd7c455
**Graphics Work**: Understand the GPU command engine structure in `Ryujinx.Graphics.Gpu/Engine/` - each engine (Compute, DMA, Threed, Twod) handles specific GPU operations.
**CPU Instruction Support**: ARM instruction decoding happens in `ARMeilleure/Decoders/`, implementation in `Instructions/`, and code generation in `CodeGen/`.
**UI Changes**: Follow MVVM pattern - Views in `UI/Views/`, logic in `UI/ViewModels/`. Use FluentAvaloniaUI controls for consistency.
## Third-Party Dependencies
The project uses several key libraries:
- **LibHac**: Nintendo Switch filesystem support
- **Avalonia**: Cross-platform UI framework
- **Silk.NET**: Graphics API bindings
- **SDL2**: Audio/Input/Windowing
- **SharpZipLib**: Archive handling
Contributions using code from other projects must follow permissive licenses and be properly attributed in `distribution/legal/THIRDPARTY.md`.

View File

@ -40,7 +40,7 @@
<PackageVersion Include="Ryujinx.Audio.OpenAL.Dependencies" Version="1.21.0.1" />
<PackageVersion Include="Ryujinx.Graphics.Nvdec.Dependencies.AllArch" Version="6.1.2-build3" />
<PackageVersion Include="Ryujinx.Graphics.Vulkan.Dependencies.MoltenVK" Version="1.2.0" />
<PackageVersion Include="Ryujinx.LibHac" Version="0.21.0-alpha.117" />
<PackageVersion Include="Ryujinx.LibHac" Version="0.21.0-alpha.116" />
<PackageVersion Include="Ryujinx.SDL2-CS" Version="2.30.0-build32" />
<PackageVersion Include="Ryujinx.UpdateClient" Version="1.0.44" />
<PackageVersion Include="Ryujinx.Systems.Update.Common" Version="1.0.44" />

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)",
@ -6445,27 +6445,26 @@
{
"ID": "SettingsButtonResetConfirm",
"Translations": {
"ar_SA": "",
"de_DE": "",
"el_GR": "",
"en_US": "I want to reset my settings.",
"es_ES": "Quiero restablecer mi Configuración.",
"fr_FR": "Je veux réinitialiser mes paramètres.",
"he_IL": "",
"it_IT": "Voglio ripristinare le mie impostazioni.",
"ja_JP": "",
"ko_KR": "설정을 초기화하고 싶습니다.",
"no_NO": "Jeg vil tilbakestille innstillingene mine.",
"pl_PL": "",
"pt_BR": "Quero redefinir minhas configurações.",
"ru_RU": "Я хочу сбросить свои настройки.",
"sv_SE": "Jag vill nollställa mina inställningar.",
"th_TH": "",
"tr_TR": "",
"uk_UA": "Я хочу скинути налаштування.",
"zh_CN": "我要重置我的设置",
"zh_TW": "我想重設我的設定"
"ar_SA": "أريد إعادة تعيين إعداداتي",
"de_DE": "Ich möchte meine Einstellungen zurücksetzen",
"el_GR": "Θέλω να επαναφέρω τις ρυθμίσεις μου",
"en_US": "I Want To Reset My Settings",
"es_ES": "Quiero Restablecer Mi Configuración",
"fr_FR": "Je Veux Réinitialiser Mes Paramètres",
"he_IL": "אני רוצה לאפס את ההגדרות שלי",
"it_IT": "Voglio reimpostare le mie impostazioni",
"ja_JP": "設定をリセットしたいです",
"ko_KR": "설정을 초기화하고 싶습니다",
"no_NO": "Jeg vil tilbakestille innstillingene mine",
"pl_PL": "Chcę zresetować moje ustawienia",
"pt_BR": "Quero redefinir minhas configurações",
"ru_RU": "Я хочу сбросить свои настройки",
"sv_SE": "Jag vill nollställa mina inställningar",
"th_TH": "ฉันต้องการรีเซ็ตการตั้งค่าของฉัน",
"tr_TR": "Ayarlarımı sıfırlamak istiyorum",
"uk_UA": "Я хочу скинути налаштування",
"zh_CN": "我要重置我的设置",
"zh_TW": "我想重設我的設定"
}
},
{

View File

@ -2280,7 +2280,6 @@
01008F6008C5E000,"Pokémon™ Violet",gpu;nvdec;ldn-works;amd-vendor-bug;mac-bug,ingame,2024-07-30 02:51:48
0100187003A36000,"Pokémon™: Lets Go, Eevee!",crash;nvdec;online-broken;ldn-broken,ingame,2024-06-01 15:03:04
010003F003A34000,"Pokémon™: Lets Go, Pikachu!",crash;nvdec;online-broken;ldn-broken,ingame,2024-03-15 07:55:41
0100F43008C44000,"Pokémon Legends: Z-A",gpu;crash;ldn-broken,ingame,2025-10-16 19:13:00
0100B3F000BE2000,"Pokkén Tournament™ DX",nvdec;ldn-works;opengl-backend-bug;LAN;amd-vendor-bug;intel-vendor-bug,playable,2024-07-18 23:11:08
010030D005AE6000,"Pokkén Tournament™ DX Demo",demo;opengl-backend-bug,playable,2022-08-10 12:03:19
0100A3500B4EC000,"Polandball: Can Into Space",,playable,2020-06-25 15:13:26

1 title_id game_name labels status last_updated
2280 01008F6008C5E000 Pokémon™ Violet gpu;nvdec;ldn-works;amd-vendor-bug;mac-bug ingame 2024-07-30 02:51:48
2281 0100187003A36000 Pokémon™: Let’s Go, Eevee! crash;nvdec;online-broken;ldn-broken ingame 2024-06-01 15:03:04
2282 010003F003A34000 Pokémon™: Let’s Go, Pikachu! crash;nvdec;online-broken;ldn-broken ingame 2024-03-15 07:55:41
0100F43008C44000 Pokémon Legends: Z-A gpu;crash;ldn-broken ingame 2025-10-16 19:13:00
2283 0100B3F000BE2000 Pokkén Tournament™ DX nvdec;ldn-works;opengl-backend-bug;LAN;amd-vendor-bug;intel-vendor-bug playable 2024-07-18 23:11:08
2284 010030D005AE6000 Pokkén Tournament™ DX Demo demo;opengl-backend-bug playable 2022-08-10 12:03:19
2285 0100A3500B4EC000 Polandball: Can Into Space playable 2020-06-25 15:13:26

View File

@ -0,0 +1,132 @@
using ARMeilleure.IntermediateRepresentation;
using System;
using System.Diagnostics;
using System.IO;
using static ARMeilleure.IntermediateRepresentation.Operand;
namespace ARMeilleure.CodeGen.Loong64
{
class Assembler
{
private readonly Stream _stream;
public Assembler(Stream stream)
{
_stream = stream;
}
public void Add(Operand rd, Operand rj, Operand rk)
{
if (rk.Kind == OperandKind.Constant)
{
Addi(rd, rj, rk.AsInt32());
}
else
{
AddReg(rd, rj, rk);
}
}
public void B(int imm)
{
WriteUInt32(0x50000000 | EncodeSImm26_2(imm));
}
public void Addi(Operand rd, Operand rj, int imm)
{
if (rd.Type == OperandType.I64)
{
WriteUInt32(0x02c00000u | EncodeReg(rd) | EncodeReg(rj) << 5 | EncodeSImm12(imm) << 10);
}
else
{
WriteUInt32(0x02800000u | EncodeReg(rd) | EncodeReg(rj) << 5 | EncodeSImm12(imm) << 10);
}
}
public void AddReg(Operand rd, Operand rj, Operand rk)
{
if (rd.Type == OperandType.I64)
{
WriteUInt32(0x00108000u | EncodeReg(rd) | EncodeReg(rj) << 5 | EncodeReg(rk) << 10);
}
else
{
WriteUInt32(0x00100000u | EncodeReg(rd) | EncodeReg(rj) << 5 | EncodeReg(rk) << 10);
}
}
private static uint EncodeSImm12(int value)
{
uint imm = (uint)value & 0xfff;
Debug.Assert(((int)imm << 20) >> 20 == value, $"Failed to encode constant 0x{value:X}.");
return imm;
}
private static uint EncodeSImm26_2(int value)
{
int shifted = value >> 2;
uint immLo = (uint)shifted & 0xFFFF; // imm[15:0]
uint immHi = ((uint)shifted >> 16) & 0x3FF; // imm[25:16]
uint encoded =
(immLo << 10) | // inst[25:10]
(immHi << 0); // inst[9:0]
uint recon =
((encoded & 0x3FF) << 16) | // inst[9:0] -> imm[25:16]
((encoded >> 10) & 0xFFFF); // inst[25:10] -> imm[15:0]
int decoded = (int)(recon << 6) >> 4;
Debug.Assert(decoded == value, $"Failed to encode constant 0x{value:X}.");
return encoded;
}
private static uint EncodeReg(Operand reg)
{
if (reg.Kind == OperandKind.Constant && reg.Value == 0)
{
return (uint)Loong64Register.zero;
}
uint regIndex = (uint)reg.GetRegister().Index;
Debug.Assert(reg.Kind == OperandKind.Register);
Debug.Assert(regIndex < 32);
return regIndex;
}
#pragma warning disable IDE0051 // Remove unused private member
private void WriteInt16(short value)
{
WriteUInt16((ushort)value);
}
private void WriteInt32(int value)
{
WriteUInt32((uint)value);
}
private void WriteByte(byte value)
{
_stream.WriteByte(value);
}
#pragma warning restore IDE0051
private void WriteUInt16(ushort value)
{
_stream.WriteByte((byte)(value >> 0));
_stream.WriteByte((byte)(value >> 8));
}
private void WriteUInt32(uint value)
{
_stream.WriteByte((byte)(value >> 0));
_stream.WriteByte((byte)(value >> 8));
_stream.WriteByte((byte)(value >> 16));
_stream.WriteByte((byte)(value >> 24));
}
}
}

View File

@ -0,0 +1,100 @@
using System;
namespace ARMeilleure.CodeGen.Loong64
{
static class CallingConvention
{
// 寄存器掩码 (32位整数每位代表一个寄存器)
private const int RegistersMask = unchecked((int)0xffffffff);
private const int ReservedRegsMask = (1 << (int)Loong64Register.zero) | (1 << (int)Loong64Register.ra) | (1 << (int)Loong64Register.tp) | (1 << (int)Loong64Register.sp) | (1 << (int)Loong64Register.r21) | (1 << (int)Loong64Register.fp);
public static int GetIntAvailableRegisters()
{
// 返回可用的通用寄存器掩码
return RegistersMask & ~ReservedRegsMask;
}
public static int GetVecAvailableRegisters()
{
// 返回可用的浮点/向量寄存器掩码
return RegistersMask;
}
public static int GetIntCallerSavedRegisters()
{
// 调用者保存的寄存器 (临时寄存器)
return (GetIntCalleeSavedRegisters() ^ RegistersMask) & ~ReservedRegsMask;
}
public static int GetFpCallerSavedRegisters()
{
return GetFpCalleeSavedRegisters() ^ RegistersMask;
}
public static int GetVecCallerSavedRegisters()
{
return GetVecCalleeSavedRegisters() ^ RegistersMask;
}
public static int GetIntCalleeSavedRegisters()
{
// 被调用者保存的寄存器 (需要保存/恢复)
return unchecked((int)0xff000000);
}
public static int GetFpCalleeSavedRegisters()
{
return unchecked((int)0xff000000); // f24 to f31
}
public static int GetVecCalleeSavedRegisters()
{
return 0;
}
public static int GetArgumentsOnRegsCount()
{
return 8;
}
// 参数寄存器 (Loong64: A0-A7 用于参数)
public static int GetIntArgumentRegister(int index)
{
// index 0-7 → A0-A7 寄存器
if ((uint)index < (uint)GetArgumentsOnRegsCount())
{
return index;
}
throw new ArgumentOutOfRangeException(nameof(index));
}
public static int GetVecArgumentRegister(int index)
{
// index 0-7 → FA0-FA7 寄存器
if ((uint)index < (uint)GetArgumentsOnRegsCount())
{
return index;
}
throw new ArgumentOutOfRangeException(nameof(index));
}
// 返回值寄存器
public static int GetIntReturnRegister()
{
return (int)Loong64Register.a0; // 返回值放在 A0
}
public static int GetIntReturnRegisterHigh()
{
return (int)Loong64Register.a1; // 64位返回值高位
}
public static int GetVecReturnRegister()
{
return 0;
}
}
}

View File

@ -0,0 +1,9 @@
using ARMeilleure.IntermediateRepresentation;
namespace ARMeilleure.CodeGen.Loong64
{
static class CodeGenCommon
{
}
}

View File

@ -0,0 +1,196 @@
using ARMeilleure.CodeGen.Linking;
using ARMeilleure.CodeGen.RegisterAllocators;
using ARMeilleure.IntermediateRepresentation;
using Microsoft.IO;
using Ryujinx.Common.Memory;
using System;
using System.Collections.Generic;
using System.IO;
namespace ARMeilleure.CodeGen.Loong64
{
class CodeGenContext
{
private const int BranchInstLength = 4;
private readonly RecyclableMemoryStream _stream;
public int StreamOffset => (int)_stream.Length;
public AllocationResult AllocResult { get; }
public Assembler Assembler { get; }
public BasicBlock CurrBlock { get; private set; }
public bool HasCall { get; }
public int CallArgsRegionSize { get; }
private readonly Dictionary<BasicBlock, long> _visitedBlocks;
private readonly Dictionary<BasicBlock, List<PendingBranch>> _pendingBranches;
private readonly bool _relocatable;
private readonly struct PendingBranch
{
public readonly Comparison ComparisonType;
public readonly Operand? Operand1;
public readonly Operand? Operand2;
public readonly long BranchPosition;
public PendingBranch(Comparison compType, Operand? op1, Operand? op2, long pos)
{
ComparisonType = compType;
Operand1 = op1;
Operand2 = op2;
BranchPosition = pos;
}
}
public CodeGenContext(AllocationResult allocResult, int maxCallArgs, bool relocatable)
{
_stream = MemoryStreamManager.Shared.GetStream();
AllocResult = allocResult;
Assembler = new Assembler(_stream);
bool hasCall = maxCallArgs >= 0;
HasCall = hasCall;
if (maxCallArgs < 0)
{
maxCallArgs = 0;
}
CallArgsRegionSize = maxCallArgs * 16;
_visitedBlocks = new Dictionary<BasicBlock, long>();
_pendingBranches = new Dictionary<BasicBlock, List<PendingBranch>>();
_relocatable = relocatable;
}
public void EnterBlock(BasicBlock block)
{
CurrBlock = block;
long target = _stream.Position;
// 修补所有跳转到此块的待处理分支
if (_pendingBranches.TryGetValue(block, out List<PendingBranch> list))
{
foreach (PendingBranch pending in list)
{
_stream.Seek(pending.BranchPosition, SeekOrigin.Begin);
WriteBranch(pending.ComparisonType, pending.Operand1, pending.Operand2, target);
}
_stream.Seek(target, SeekOrigin.Begin);
_pendingBranches.Remove(block);
}
_visitedBlocks.Add(block, target);
}
public void JumpTo(BasicBlock target)
{
if (_visitedBlocks.TryGetValue(target, out long offset))
{
// 目标块已生成,直接写入无条件跳转
WriteUnconditionalBranch(offset);
}
else
{
// 目标块未生成,记录待修补(使用特殊的无条件标记)
if (!_pendingBranches.TryGetValue(target, out List<PendingBranch> list))
{
list = new List<PendingBranch>();
_pendingBranches.Add(target, list);
}
// 使用 Comparison.Equal 和 null 操作数表示无条件跳转
list.Add(new PendingBranch(Comparison.Equal, null, null, _stream.Position));
_stream.Seek(BranchInstLength, SeekOrigin.Current);
}
}
public void JumpToIf(Comparison compType, Operand op1, Operand op2, BasicBlock target)
{
if (_visitedBlocks.TryGetValue(target, out long offset))
{
// 目标块已生成,直接写入条件分支
WriteBranch(compType, op1, op2, offset);
}
else
{
// 目标块未生成,记录待修补
if (!_pendingBranches.TryGetValue(target, out List<PendingBranch> list))
{
list = new List<PendingBranch>();
_pendingBranches.Add(target, list);
}
list.Add(new PendingBranch(compType, op1, op2, _stream.Position));
_stream.Seek(BranchInstLength, SeekOrigin.Current);
}
}
private void WriteBranch(Comparison compType, Operand? op1, Operand? op2, long targetPos)
{
// 如果操作数为 null表示无条件跳转
if (op1 == null && op2 == null)
{
WriteUnconditionalBranch(targetPos);
return;
}
int offset = checked((int)(targetPos - _stream.Position));
// TODO: 根据 Comparison 类型调用相应的 Assembler 方法
// 这里需要实现 Loong64 的条件分支指令
switch (compType)
{
case Comparison.Equal:
// Assembler.Beq(op1, op2, offset);
throw new NotImplementedException("Beq not implemented yet");
case Comparison.NotEqual:
// Assembler.Bne(op1, op2, offset);
throw new NotImplementedException("Bne not implemented yet");
case Comparison.Less:
// Assembler.Blt(op1, op2, offset);
throw new NotImplementedException("Blt not implemented yet");
case Comparison.LessOrEqual:
// Assembler.Ble(op1, op2, offset);
throw new NotImplementedException("Ble not implemented yet");
case Comparison.Greater:
// Assembler.Bgt(op1, op2, offset);
throw new NotImplementedException("Bgt not implemented yet");
case Comparison.GreaterOrEqual:
// Assembler.Bge(op1, op2, offset);
throw new NotImplementedException("Bge not implemented yet");
default:
throw new ArgumentException($"Unsupported comparison type: {compType}");
}
}
private void WriteUnconditionalBranch(long targetPos)
{
int offset = checked((int)(targetPos - _stream.Position));
// TODO: 实现 Loong64 的无条件跳转指令
Assembler.B(offset);
throw new NotImplementedException("Unconditional branch not implemented yet");
}
}
}

View File

@ -0,0 +1,153 @@
using ARMeilleure.CodeGen.Linking;
using ARMeilleure.CodeGen.Optimizations;
using ARMeilleure.CodeGen.RegisterAllocators;
using ARMeilleure.CodeGen.Unwinding;
using ARMeilleure.Common;
using ARMeilleure.Diagnostics;
using ARMeilleure.IntermediateRepresentation;
using ARMeilleure.Translation;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using static ARMeilleure.IntermediateRepresentation.Operand;
using static ARMeilleure.IntermediateRepresentation.Operand.Factory;
namespace ARMeilleure.CodeGen.Loong64
{
static class CodeGenerator
{
private const int RegistersCount = 32;
private static readonly Action<CodeGenContext, Operation>[] _instTable;
static CodeGenerator()
{
_instTable = new Action<CodeGenContext, Operation>[EnumUtils.GetCount(typeof(Instruction))];
#pragma warning disable IDE0055 // Disable formatting
Add(Instruction.Add, GenerateAdd);
#pragma warning restore IDE0055
static void Add(Instruction inst, Action<CodeGenContext, Operation> func)
{
_instTable[(int)inst] = func;
}
}
public static CompiledFunction Generate(CompilerContext cctx)
{
ControlFlowGraph cfg = cctx.Cfg;
Logger.StartPass(PassName.Optimization);
if (cctx.Options.HasFlag(CompilerOptions.Optimize))
{
if (cctx.Options.HasFlag(CompilerOptions.SsaForm))
{
Optimizer.RunPass(cfg); // SSA 优化
}
BlockPlacement.RunPass(cfg); // 基本块重排序
}
Logger.EndPass(PassName.Optimization, cfg);
Logger.StartPass(PassName.PreAllocation);
PreAllocator.RunPass(cctx, out int maxCallArgs);
Logger.EndPass(PassName.PreAllocation, cfg);
Logger.StartPass(PassName.RegisterAllocation);
StackAllocator stackAlloc = new();
if (cctx.Options.HasFlag(CompilerOptions.SsaForm))
{
Ssa.Deconstruct(cfg);
}
IRegisterAllocator regAlloc;
if (cctx.Options.HasFlag(CompilerOptions.Lsra))
{
regAlloc = new LinearScanAllocator(); // 快速分配
}
else
{
regAlloc = new HybridAllocator(); // 高质量分配
}
RegisterMasks regMasks = new(
CallingConvention.GetIntAvailableRegisters(),
CallingConvention.GetVecAvailableRegisters(),
CallingConvention.GetIntCallerSavedRegisters(),
CallingConvention.GetVecCallerSavedRegisters(),
CallingConvention.GetIntCalleeSavedRegisters(),
CallingConvention.GetVecCalleeSavedRegisters(),
RegistersCount);
AllocationResult allocResult = regAlloc.RunPass(cfg, stackAlloc, regMasks);
Logger.EndPass(PassName.RegisterAllocation, cfg);
Logger.StartPass(PassName.CodeGeneration);
bool relocatable = (cctx.Options & CompilerOptions.Relocatable) != 0;
CodeGenContext context = new(allocResult, maxCallArgs, relocatable);
UnwindInfo unwindInfo = WritePrologue(context);
for (BasicBlock block = cfg.Blocks.First; block != null; block = block.ListNext)
{
context.EnterBlock(block);
for (Operation node = block.Operations.First; node != default; node = node.ListNext)
{
GenerateOperation(context, node);
}
if (block.SuccessorsCount == 0)
{
// The only blocks which can have 0 successors are exit blocks.
Operation last = block.Operations.Last;
Debug.Assert(last.Instruction is Instruction.Tailcall or
Instruction.Return);
}
else
{
BasicBlock succ = block.GetSuccessor(0);
if (succ != block.ListNext)
{
context.JumpTo(succ);
}
}
}
(byte[] code, RelocInfo relocInfo) = context.Assembler.GetCode();
Logger.EndPass(PassName.CodeGeneration);
return new CompiledFunction(code, unwindInfo, relocInfo);
}
private static void GenerateAdd(CodeGenContext context, Operation operation)
{
Operand dest = operation.Destination;
Operand src1 = operation.GetSource(0);
Operand src2 = operation.GetSource(1);
if (dest.Type.IsInteger())
{
context.Assembler.Add(dest, src1, src2);
}
else
{
// todo
}
}
}
}

View File

@ -0,0 +1,73 @@
using System.Diagnostics.CodeAnalysis;
namespace ARMeilleure.CodeGen.Loong64
{
enum Loong64Register
{
zero = 0,
ra = 1,
tp = 2,
sp = 3,
a0 = 4,
a1 = 5,
a2 = 6,
a3 = 7,
a4 = 8,
a5 = 9,
a6 = 10,
a7 = 11,
t0 = 12,
t1 = 13,
t2 = 14,
t3 = 15,
t4 = 16,
t5 = 17,
t6 = 18,
t7 = 19,
t8 = 20,
r21 = 21,
fp = 22,
s0 = 23,
s1 = 24,
s2 = 25,
s3 = 26,
s4 = 27,
s5 = 28,
s6 = 29,
s7 = 30,
s8 = 31,
fa0 = 0,
fa1 = 1,
fa2 = 2,
fa3 = 3,
fa4 = 4,
fa5 = 5,
fa6 = 6,
fa7 = 7,
ft0 = 8,
ft1 = 9,
ft2 = 10,
ft3 = 11,
ft4 = 12,
ft5 = 13,
ft6 = 14,
ft7 = 15,
ft8 = 16,
ft9 = 17,
ft10 = 18,
ft11 = 19,
ft12 = 20,
ft13 = 21,
ft14 = 22,
ft15 = 23,
fs0 = 24,
fs1 = 25,
fs2 = 26,
fs3 = 27,
fs4 = 28,
fs5 = 29,
fs6 = 30,
fs7 = 31,
}
}

View File

@ -0,0 +1,18 @@
using ARMeilleure.IntermediateRepresentation;
using ARMeilleure.Translation;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using static ARMeilleure.IntermediateRepresentation.Operand.Factory;
using static ARMeilleure.IntermediateRepresentation.Operation.Factory;
namespace ARMeilleure.CodeGen.Loong64
{
static class PreAllocator
{
public static void RunPass(CompilerContext cctx, out int maxCallArgs)
{
maxCallArgs = -1;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -201,7 +201,11 @@ namespace ARMeilleure.Instructions
ExecutionContext context = GetContext();
context.CheckInterrupt();
// If debugging, we'll handle interrupts outside
if (!Optimizations.EnableDebugging)
{
context.CheckInterrupt();
}
Statistics.ResumeTimer();

View File

@ -1,226 +0,0 @@
namespace Ryujinx.Common.Collections
{
/// <summary>
/// Represents a collection that can store 1 bit values.
/// </summary>
public struct BitMap
{
/// <summary>
/// Size in bits of the integer used internally for the groups of bits.
/// </summary>
public const int IntSize = 64;
private const int IntShift = 6;
private const int IntMask = IntSize - 1;
private readonly long[] _masks;
/// <summary>
/// Gets or sets the value of a bit.
/// </summary>
/// <param name="bit">Bit to access</param>
/// <returns>Bit value</returns>
public bool this[int bit]
{
get => IsSet(bit);
set
{
if (value)
{
Set(bit);
}
else
{
Clear(bit);
}
}
}
/// <summary>
/// Creates a new bitmap.
/// </summary>
/// <param name="count">Total number of bits</param>
public BitMap(int count)
{
_masks = new long[(count + IntMask) / IntSize];
}
/// <summary>
/// Checks if any bit is set.
/// </summary>
/// <returns>True if any bit is set, false otherwise</returns>
public bool AnySet()
{
for (int i = 0; i < _masks.Length; i++)
{
if (_masks[i] != 0)
{
return true;
}
}
return false;
}
/// <summary>
/// Checks if a specific bit is set.
/// </summary>
/// <param name="bit">Bit to be checked</param>
/// <returns>True if set, false otherwise</returns>
public bool IsSet(int bit)
{
int wordIndex = bit >> IntShift;
int wordBit = bit & IntMask;
long wordMask = 1L << wordBit;
return (_masks[wordIndex] & wordMask) != 0;
}
/// <summary>
/// Checks if any bit inside a given range of bits is set.
/// </summary>
/// <param name="start">Start bit of the range</param>
/// <param name="end">End bit of the range (inclusive)</param>
/// <returns>True if any bit is set, false otherwise</returns>
public bool IsSet(int start, int end)
{
if (start == end)
{
return IsSet(start);
}
int startIndex = start >> IntShift;
int startBit = start & IntMask;
long startMask = -1L << startBit;
int endIndex = end >> IntShift;
int endBit = end & IntMask;
long endMask = (long)(ulong.MaxValue >> (IntMask - endBit));
if (startIndex == endIndex)
{
return (_masks[startIndex] & startMask & endMask) != 0;
}
if ((_masks[startIndex] & startMask) != 0)
{
return true;
}
for (int i = startIndex + 1; i < endIndex; i++)
{
if (_masks[i] != 0)
{
return true;
}
}
if ((_masks[endIndex] & endMask) != 0)
{
return true;
}
return false;
}
/// <summary>
/// Sets the value of a bit to 1.
/// </summary>
/// <param name="bit">Bit to be set</param>
/// <returns>True if the bit was 0 and then changed to 1, false if it was already 1</returns>
public bool Set(int bit)
{
int wordIndex = bit >> IntShift;
int wordBit = bit & IntMask;
long wordMask = 1L << wordBit;
if ((_masks[wordIndex] & wordMask) != 0)
{
return false;
}
_masks[wordIndex] |= wordMask;
return true;
}
/// <summary>
/// Sets a given range of bits to 1.
/// </summary>
/// <param name="start">Start bit of the range</param>
/// <param name="end">End bit of the range (inclusive)</param>
public void SetRange(int start, int end)
{
if (start == end)
{
Set(start);
return;
}
int startIndex = start >> IntShift;
int startBit = start & IntMask;
long startMask = -1L << startBit;
int endIndex = end >> IntShift;
int endBit = end & IntMask;
long endMask = (long)(ulong.MaxValue >> (IntMask - endBit));
if (startIndex == endIndex)
{
_masks[startIndex] |= startMask & endMask;
}
else
{
_masks[startIndex] |= startMask;
for (int i = startIndex + 1; i < endIndex; i++)
{
_masks[i] |= -1;
}
_masks[endIndex] |= endMask;
}
}
/// <summary>
/// Sets a given bit to 0.
/// </summary>
/// <param name="bit">Bit to be cleared</param>
public void Clear(int bit)
{
int wordIndex = bit >> IntShift;
int wordBit = bit & IntMask;
long wordMask = 1L << wordBit;
_masks[wordIndex] &= ~wordMask;
}
/// <summary>
/// Sets all bits to 0.
/// </summary>
public void Clear()
{
for (int i = 0; i < _masks.Length; i++)
{
_masks[i] = 0;
}
}
/// <summary>
/// Sets one or more groups of bits to 0.
/// See <see cref="IntSize"/> for how many bits are inside each group.
/// </summary>
/// <param name="start">Start index of the group</param>
/// <param name="end">End index of the group (inclusive)</param>
public void ClearInt(int start, int end)
{
for (int i = start; i <= end; i++)
{
_masks[i] = 0;
}
}
}
}

View File

@ -187,17 +187,6 @@ namespace Ryujinx.Common.Logging
}
}
public static void Flush()
{
foreach (ILogTarget target in _logTargets)
{
if (target is AsyncLogTargetWrapper asyncTarget)
{
asyncTarget.Flush();
}
}
}
public static void Shutdown()
{
Updated = null;

View File

@ -27,17 +27,6 @@ namespace Ryujinx.Common.Logging.Targets
private readonly int _overflowTimeout;
private sealed class FlushEventArgs : LogEventArgs
{
public readonly ManualResetEventSlim SignalEvent;
public FlushEventArgs(ManualResetEventSlim signalEvent)
: base(LogLevel.Notice, TimeSpan.Zero, string.Empty, string.Empty)
{
SignalEvent = signalEvent;
}
}
string ILogTarget.Name => _target.Name;
public AsyncLogTargetWrapper(ILogTarget target, int queueLimit = -1, AsyncLogTargetOverflowAction overflowAction = AsyncLogTargetOverflowAction.Block)
@ -52,15 +41,7 @@ namespace Ryujinx.Common.Logging.Targets
{
try
{
LogEventArgs item = _messageQueue.Take();
if (item is FlushEventArgs flush)
{
flush.SignalEvent.Set();
continue;
}
_target.Log(this, item);
_target.Log(this, _messageQueue.Take());
}
catch (InvalidOperationException)
{
@ -87,26 +68,6 @@ namespace Ryujinx.Common.Logging.Targets
}
}
public void Flush()
{
if (_messageQueue.Count == 0 || _messageQueue.IsAddingCompleted)
{
return;
}
using var signal = new ManualResetEventSlim(false);
try
{
_messageQueue.Add(new FlushEventArgs(signal));
}
catch (InvalidOperationException)
{
return;
}
signal.Wait();
}
public void Dispose()
{
GC.SuppressFinalize(this);

View File

@ -106,7 +106,6 @@ namespace Ryujinx.Common
"0100b3f000be2000", // Pokkén Tournament DX
"0100187003a36000", // Pokémon: Let's Go Eevee!
"010003f003a34000", // Pokémon: Let's Go Pikachu!
"0100f43008c44000", // Pokémon Legends: Z-A
//Splatoon Franchise
"0100f8f0000a2000", // Splatoon 2 (EU)

View File

@ -1,4 +1,3 @@
using Ryujinx.Common.Collections;
using Ryujinx.Common.Logging;
using Ryujinx.Graphics.GAL;
using Ryujinx.Graphics.Gpu.Memory;
@ -73,7 +72,6 @@ namespace Ryujinx.Graphics.Gpu.Image
}
private readonly GpuChannel _channel;
private readonly BitMap _invalidMap;
private readonly ConcurrentQueue<DereferenceRequest> _dereferenceQueue = new();
private TextureDescriptor _defaultDescriptor;
@ -168,7 +166,6 @@ namespace Ryujinx.Graphics.Gpu.Image
{
_channel = channel;
_aliasLists = new Dictionary<Texture, TextureAliasList>();
_invalidMap = new BitMap(maximumId + 1);
}
/// <summary>
@ -185,11 +182,6 @@ namespace Ryujinx.Graphics.Gpu.Image
if (texture == null)
{
if (_invalidMap.IsSet(id))
{
return ref descriptor;
}
texture = PhysicalMemory.TextureCache.FindShortCache(descriptor);
if (texture == null)
@ -206,7 +198,6 @@ namespace Ryujinx.Graphics.Gpu.Image
// If this happens, then the texture address is invalid, we can't add it to the cache.
if (texture == null)
{
_invalidMap.Set(id);
return ref descriptor;
}
}
@ -524,8 +515,6 @@ namespace Ryujinx.Graphics.Gpu.Image
RemoveAliasList(texture);
}
}
_invalidMap.Clear(id);
}
}

View File

@ -11,9 +11,12 @@ namespace Ryujinx.HLE.Debugger
{
public byte[] OriginalData { get; }
public Breakpoint(byte[] originalData)
public bool IsStep { get; }
public Breakpoint(byte[] originalData, bool isStep)
{
OriginalData = originalData;
IsStep = isStep;
}
}
@ -41,7 +44,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)
public bool SetBreakPoint(ulong address, ulong length, bool isStep = false)
{
if (_breakpoints.ContainsKey(address))
{
@ -68,7 +71,7 @@ namespace Ryujinx.HLE.Debugger
return false;
}
var breakpoint = new Breakpoint(originalInstruction);
var breakpoint = new Breakpoint(originalInstruction, isStep);
if (_breakpoints.TryAdd(address, breakpoint))
{
Logger.Debug?.Print(LogClass.GdbStub, $"Breakpoint set at 0x{address:X16}");
@ -121,6 +124,30 @@ 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)

File diff suppressed because it is too large Load Diff

View File

@ -1,393 +0,0 @@
using Ryujinx.Common;
using Ryujinx.Common.Logging;
using System.Linq;
using System.Net.Sockets;
using System.Text;
namespace Ryujinx.HLE.Debugger.Gdb
{
class GdbCommandProcessor
{
public readonly GdbCommands Commands;
public GdbCommandProcessor(TcpListener listenerSocket, Socket clientSocket, NetworkStream readStream, NetworkStream writeStream, Debugger debugger)
{
Commands = new GdbCommands(listenerSocket, clientSocket, readStream, writeStream, debugger);
}
private string previousThreadListXml = "";
public void Process(string cmd)
{
StringStream ss = new(cmd);
switch (ss.ReadChar())
{
case '!':
if (!ss.IsEmpty())
{
goto unknownCommand;
}
// Enable extended mode
Commands.ReplyOK();
break;
case '?':
if (!ss.IsEmpty())
{
goto unknownCommand;
}
Commands.CommandQuery();
break;
case 'c':
Commands.CommandContinue(ss.IsEmpty() ? null : ss.ReadRemainingAsHex());
break;
case 'D':
if (!ss.IsEmpty())
{
goto unknownCommand;
}
Commands.CommandDetach();
break;
case 'g':
if (!ss.IsEmpty())
{
goto unknownCommand;
}
Commands.CommandReadRegisters();
break;
case 'G':
Commands.CommandWriteRegisters(ss);
break;
case 'H':
{
char op = ss.ReadChar();
ulong? threadId = ss.ReadRemainingAsThreadUid();
Commands.CommandSetThread(op, threadId);
break;
}
case 'k':
Logger.Notice.Print(LogClass.GdbStub, "Kill request received, detach instead");
Commands.Reply("");
Commands.CommandDetach();
break;
case 'm':
{
ulong addr = ss.ReadUntilAsHex(',');
ulong len = ss.ReadRemainingAsHex();
Commands.CommandReadMemory(addr, len);
break;
}
case 'M':
{
ulong addr = ss.ReadUntilAsHex(',');
ulong len = ss.ReadUntilAsHex(':');
Commands.CommandWriteMemory(addr, len, ss);
break;
}
case 'p':
{
ulong gdbRegId = ss.ReadRemainingAsHex();
Commands.CommandReadRegister((int)gdbRegId);
break;
}
case 'P':
{
ulong gdbRegId = ss.ReadUntilAsHex('=');
Commands.CommandWriteRegister((int)gdbRegId, ss);
break;
}
case 'q':
if (ss.ConsumeRemaining("GDBServerVersion"))
{
Commands.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")};");
}
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;");
}
break;
}
if (ss.ConsumePrefix("Supported:") || ss.ConsumeRemaining("Supported"))
{
Commands.Reply("PacketSize=10000;qXfer:features:read+;qXfer:threads:read+;vContSupported+");
break;
}
if (ss.ConsumePrefix("Rcmd,"))
{
string hexCommand = ss.ReadRemaining();
Commands.HandleQRcmdCommand(hexCommand);
break;
}
if (ss.ConsumeRemaining("fThreadInfo"))
{
Commands. Reply($"m{string.Join(",", Commands.Debugger.DebugProcess.GetThreadUids().Select(x => $"{x:x}"))}");
break;
}
if (ss.ConsumeRemaining("sThreadInfo"))
{
Commands.Reply("l");
break;
}
if (ss.ConsumePrefix("ThreadExtraInfo,"))
{
ulong? threadId = ss.ReadRemainingAsThreadUid();
if (threadId == null)
{
Commands.ReplyError();
break;
}
Commands.Reply(Helpers.ToHex(
Commands.Debugger.DebugProcess.IsThreadPaused(
Commands.Debugger.DebugProcess.GetThread(threadId.Value))
? "Paused"
: "Running"
)
);
break;
}
if (ss.ConsumePrefix("Xfer:threads:read:"))
{
ss.ReadUntil(':');
ulong offset = ss.ReadUntilAsHex(',');
ulong len = ss.ReadRemainingAsHex();
var data = "";
if (offset > 0)
{
data = previousThreadListXml;
}
else
{
previousThreadListXml = data = GetThreadListXml();
}
if (offset >= (ulong)data.Length)
{
Commands.Reply("l");
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 (ss.ConsumePrefix("Xfer:features:read:"))
{
string feature = ss.ReadUntil(':');
ulong offset = ss.ReadUntilAsHex(',');
ulong len = ss.ReadRemainingAsHex();
if (feature == "target.xml")
{
feature = Commands.Debugger.IsProcessAarch32 ? "target32.xml" : "target64.xml";
}
string data;
if (RegisterInformation.Features.TryGetValue(feature, out data))
{
if (offset >= (ulong)data.Length)
{
Commands.Reply("l");
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;
}
}
else
{
Commands.Reply("E00"); // Invalid annex
break;
}
}
goto unknownCommand;
case 'Q':
goto unknownCommand;
case 's':
Commands.CommandStep(ss.IsEmpty() ? null : ss.ReadRemainingAsHex());
break;
case 'T':
{
ulong? threadId = ss.ReadRemainingAsThreadUid();
Commands.CommandIsAlive(threadId);
break;
}
case 'v':
if (ss.ConsumePrefix("Cont"))
{
if (ss.ConsumeRemaining("?"))
{
Commands.Reply("vCont;c;C;s;S");
break;
}
if (ss.ConsumePrefix(";"))
{
Commands.HandleVContCommand(ss);
break;
}
goto unknownCommand;
}
if (ss.ConsumeRemaining("MustReplyEmpty"))
{
Commands.Reply("");
break;
}
goto unknownCommand;
case 'Z':
{
string type = ss.ReadUntil(',');
ulong addr = ss.ReadUntilAsHex(',');
ulong len = ss.ReadLengthAsHex(1);
string extra = ss.ReadRemaining();
if (extra.Length > 0)
{
Logger.Notice.Print(LogClass.GdbStub, $"Unsupported Z command extra data: {extra}");
Commands.ReplyError();
return;
}
switch (type)
{
case "0": // Software breakpoint
if (!Commands.Debugger.BreakpointManager.SetBreakPoint(addr, len))
{
Commands.ReplyError();
return;
}
Commands.ReplyOK();
return;
case "1": // Hardware breakpoint
case "2": // Write watchpoint
case "3": // Read watchpoint
case "4": // Access watchpoint
Commands.ReplyError();
return;
default:
Commands.ReplyError();
return;
}
}
case 'z':
{
string type = ss.ReadUntil(',');
ss.ConsumePrefix(",");
ulong addr = ss.ReadUntilAsHex(',');
ulong len = ss.ReadLengthAsHex(1);
string extra = ss.ReadRemaining();
if (extra.Length > 0)
{
Logger.Notice.Print(LogClass.GdbStub, $"Unsupported z command extra data: {extra}");
Commands.ReplyError();
return;
}
switch (type)
{
case "0": // Software breakpoint
if (!Commands.Debugger.BreakpointManager.ClearBreakPoint(addr, len))
{
Commands.ReplyError();
return;
}
Commands.ReplyOK();
return;
case "1": // Hardware breakpoint
case "2": // Write watchpoint
case "3": // Read watchpoint
case "4": // Access watchpoint
Commands.ReplyError();
return;
default:
Commands.ReplyError();
return;
}
}
default:
unknownCommand:
Logger.Notice.Print(LogClass.GdbStub, $"Unknown command: {cmd}");
Commands.Reply("");
break;
}
}
private string GetThreadListXml()
{
var sb = new StringBuilder();
sb.Append("<?xml version=\"1.0\"?><threads>\n");
foreach (var thread in Commands.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");
}
sb.Append("</threads>");
return sb.ToString();
}
}
}

View File

@ -1,489 +0,0 @@
using Ryujinx.Common.Logging;
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;
public GdbCommands(TcpListener listenerSocket, Socket clientSocket, NetworkStream readStream,
NetworkStream writeStream, Debugger debugger)
{
_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()
{
// GDB is performing initial contact. Stop everything.
Debugger.DebugProcess.DebugStop();
Debugger.GThread = Debugger.CThread = Debugger.DebugProcess.GetThreadUids().First();
Reply($"T05thread:{Debugger.CThread:x};");
}
internal void CommandInterrupt()
{
// 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();
}
Reply($"T02thread:{Debugger.GThread:x};");
}
internal void CommandContinue(ulong? newPc)
{
if (newPc.HasValue)
{
if (Debugger.CThread == null)
{
ReplyError();
return;
}
Debugger.DebugProcess.GetThread(Debugger.CThread.Value).Context.DebugPc = newPc.Value;
}
Debugger.DebugProcess.DebugContinue();
}
internal void CommandDetach()
{
Debugger.BreakpointManager.ClearAll();
CommandContinue(null);
}
internal void CommandReadRegisters()
{
if (Debugger.GThread == null)
{
ReplyError();
return;
}
var ctx = Debugger.DebugProcess.GetThread(Debugger.GThread.Value).Context;
string registers = "";
if (Debugger.IsProcessAarch32)
{
for (int i = 0; i < GdbRegisterCount32; i++)
{
registers += GdbRegisters.Read32(ctx, i);
}
}
else
{
for (int i = 0; i < GdbRegisterCount64; i++)
{
registers += GdbRegisters.Read64(ctx, i);
}
}
Reply(registers);
}
internal void CommandWriteRegisters(StringStream ss)
{
if (Debugger.GThread == null)
{
ReplyError();
return;
}
var ctx = Debugger.DebugProcess.GetThread(Debugger.GThread.Value).Context;
if (Debugger.IsProcessAarch32)
{
for (int i = 0; i < GdbRegisterCount32; i++)
{
if (!GdbRegisters.Write32(ctx, i, ss))
{
ReplyError();
return;
}
}
}
else
{
for (int i = 0; i < GdbRegisterCount64; i++)
{
if (!GdbRegisters.Write64(ctx, i, ss))
{
ReplyError();
return;
}
}
}
if (ss.IsEmpty())
{
ReplyOK();
}
else
{
ReplyError();
}
}
internal void CommandSetThread(char op, ulong? threadId)
{
if (threadId is 0 or null)
{
var threads = Debugger.GetThreads();
if (threads.Length == 0)
{
ReplyError();
return;
}
threadId = threads.First().ThreadUid;
}
if (Debugger.DebugProcess.GetThread(threadId.Value) == null)
{
ReplyError();
return;
}
switch (op)
{
case 'c':
Debugger.CThread = threadId;
ReplyOK();
return;
case 'g':
Debugger.GThread = threadId;
ReplyOK();
return;
default:
ReplyError();
return;
}
}
internal void CommandReadMemory(ulong addr, ulong len)
{
try
{
var data = new byte[len];
Debugger.DebugProcess.CpuMemory.Read(addr, data);
Reply(Helpers.ToHex(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();
}
}
internal void CommandWriteMemory(ulong addr, ulong len, StringStream ss)
{
try
{
var data = new byte[len];
for (ulong i = 0; i < len; i++)
{
data[i] = (byte)ss.ReadLengthAsHex(2);
}
Debugger.DebugProcess.CpuMemory.Write(addr, data);
Debugger.DebugProcess.InvalidateCacheRegion(addr, len);
ReplyOK();
}
catch (InvalidMemoryRegionException)
{
ReplyError();
}
}
internal void CommandReadRegister(int gdbRegId)
{
if (Debugger.GThread == null)
{
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();
}
}
}
internal void CommandWriteRegister(int gdbRegId, StringStream ss)
{
if (Debugger.GThread == null)
{
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();
}
}
}
internal void CommandStep(ulong? newPc)
{
if (Debugger.CThread == null)
{
ReplyError();
return;
}
var thread = Debugger.DebugProcess.GetThread(Debugger.CThread.Value);
if (newPc.HasValue)
{
thread.Context.DebugPc = newPc.Value;
}
if (!Debugger.DebugProcess.DebugStep(thread))
{
ReplyError();
}
else
{
Debugger.GThread = Debugger.CThread = thread.ThreadUid;
Reply($"T05thread:{thread.ThreadUid:x};");
}
}
internal void CommandIsAlive(ulong? threadId)
{
if (Debugger.GetThreads().Any(x => x.ThreadUid == threadId))
{
ReplyOK();
}
else
{
Reply("E00");
}
}
enum VContAction
{
None,
Continue,
Stop,
Step
}
record VContPendingAction(VContAction Action, ushort? Signal = null);
internal void HandleVContCommand(StringStream ss)
{
string[] rawActions = ss.ReadRemaining().Split(';', StringSplitOptions.RemoveEmptyEntries);
var threadActionMap = new Dictionary<ulong, VContPendingAction>();
foreach (var thread in Debugger.GetThreads())
{
threadActionMap[thread.ThreadUid] = new VContPendingAction(VContAction.None);
}
VContAction defaultAction = VContAction.None;
// 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);
char cmd = stream.ReadChar();
VContAction action = cmd switch
{
'c' or 'C' => VContAction.Continue,
's' or 'S' => VContAction.Step,
't' => VContAction.Stop,
_ => VContAction.None
};
// Note: We don't support signals yet.
ushort? signal = null;
if (cmd is 'C' or 'S')
{
signal = (ushort)stream.ReadLengthAsHex(2);
}
ulong? threadId = null;
if (stream.ConsumePrefix(":"))
{
threadId = stream.ReadRemainingAsThreadUid();
}
if (threadId.HasValue)
{
if (threadActionMap.ContainsKey(threadId.Value))
{
threadActionMap[threadId.Value] = new VContPendingAction(action, signal);
}
}
else
{
foreach (var row in threadActionMap.ToList())
{
threadActionMap[row.Key] = new VContPendingAction(action, signal);
}
if (action == VContAction.Continue)
{
defaultAction = action;
}
else
{
Logger.Warning?.Print(LogClass.GdbStub,
$"Received vCont command with unsupported default action: {rawAction}");
}
}
}
bool hasError = false;
foreach (var (threadUid, action) in threadActionMap)
{
if (action.Action == VContAction.Step)
{
var thread = Debugger.DebugProcess.GetThread(threadUid);
if (!Debugger.DebugProcess.DebugStep(thread))
{
hasError = true;
}
}
}
// If we receive "vCont;c", just continue the process.
// If we receive something like "vCont;c:2e;c:2f" (IDA Pro will send commands like this), continue these threads.
// For "vCont;s:2f;c", `DebugProcess.DebugStep()` will continue and suspend other threads if needed, so we don't do anything here.
if (threadActionMap.Values.All(a => a.Action == VContAction.Continue))
{
Debugger.DebugProcess.DebugContinue();
}
else if (defaultAction == VContAction.None)
{
foreach (var (threadUid, action) in threadActionMap)
{
if (action.Action == VContAction.Continue)
{
Debugger.DebugProcess.DebugContinue(Debugger.DebugProcess.GetThread(threadUid));
}
}
}
if (hasError)
{
ReplyError();
}
else
{
ReplyOK();
}
foreach (var (threadUid, action) in threadActionMap)
{
if (action.Action == VContAction.Step)
{
Debugger.GThread = Debugger.CThread = threadUid;
Reply($"T05thread:{threadUid:x};");
}
}
}
internal void HandleQRcmdCommand(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"
};
Reply(Helpers.ToHex(response));
}
catch (Exception e)
{
Logger.Error?.Print(LogClass.GdbStub, $"Error processing Rcmd: {e.Message}");
ReplyError();
}
}
}
}

View File

@ -1,160 +0,0 @@
using ARMeilleure.State;
using Ryujinx.Cpu;
using System;
namespace Ryujinx.HLE.Debugger.Gdb
{
static class GdbRegisters
{
/*
FPCR = FPSR & ~FpcrMask
All of FPCR's bits are reserved in FPCR and vice versa,
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)
{
switch (gdbRegId)
{
case >= 0 and <= 31:
{
ulong value = ss.ReadLengthAsLEHex(16);
state.SetX(gdbRegId, value);
return true;
}
case 32:
{
ulong value = ss.ReadLengthAsLEHex(16);
state.DebugPc = value;
return true;
}
case 33:
{
ulong value = ss.ReadLengthAsLEHex(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));
return true;
}
case 66:
{
ulong value = ss.ReadLengthAsLEHex(8);
state.Fpsr = (uint)value;
return true;
}
case 67:
{
ulong value = ss.ReadLengthAsLEHex(8);
state.Fpcr = (uint)value;
return true;
}
default:
return false;
}
}
public static string Read32(IExecutionContext state, int gdbRegId)
{
switch (gdbRegId)
{
case >= 0 and <= 14:
return Helpers.ToHex(BitConverter.GetBytes((uint)state.GetX(gdbRegId)));
case 15:
return Helpers.ToHex(BitConverter.GetBytes((uint)state.DebugPc));
case 16:
return Helpers.ToHex(BitConverter.GetBytes((uint)state.Pstate));
case >= 17 and <= 32:
return Helpers.ToHex(state.GetV(gdbRegId - 17).ToArray());
case >= 33 and <= 64:
int reg = (gdbRegId - 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));
default:
return null;
}
}
public static bool Write32(IExecutionContext state, int gdbRegId, StringStream ss)
{
switch (gdbRegId)
{
case >= 0 and <= 14:
{
ulong value = ss.ReadLengthAsLEHex(8);
state.SetX(gdbRegId, value);
return true;
}
case 15:
{
ulong value = ss.ReadLengthAsLEHex(8);
state.DebugPc = value;
return true;
}
case 16:
{
ulong value = ss.ReadLengthAsLEHex(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));
return true;
}
case >= 33 and <= 64:
{
ulong value = ss.ReadLengthAsLEHex(16);
int regId = (gdbRegId - 33);
int regNum = regId / 2;
int shift = regId % 2;
V128 reg = state.GetV(regNum);
reg.Insert(shift, value);
return true;
}
case 65:
{
ulong value = ss.ReadLengthAsLEHex(8);
state.Fpsr = (uint)value & FpcrMask;
state.Fpcr = (uint)value & ~FpcrMask;
return true;
}
default:
return false;
}
}
}
}

View File

@ -1,50 +0,0 @@
using Gommon;
using System;
using System.Linq;
using System.Text;
namespace Ryujinx.HLE.Debugger
{
public static class Helpers
{
public static byte CalculateChecksum(string cmd)
{
byte checksum = 0;
foreach (char x in cmd)
{
unchecked
{
checksum += (byte)x;
}
}
return checksum;
}
public static string FromHex(string hexString)
{
if (string.IsNullOrEmpty(hexString))
return string.Empty;
byte[] bytes = Convert.FromHexString(hexString);
return Encoding.ASCII.GetString(bytes);
}
public static string ToHex(byte[] bytes) => string.Join("", bytes.Select(x => $"{x:x2}"));
public static string ToHex(string str) => ToHex(Encoding.ASCII.GetBytes(str));
public static string ToBinaryFormat(string str) => ToBinaryFormat(Encoding.ASCII.GetBytes(str));
public static string ToBinaryFormat(byte[] bytes) =>
bytes.Select(x =>
x switch
{
(byte)'#' => "}\x03",
(byte)'$' => "}\x04",
(byte)'*' => "}\x0a",
(byte)'}' => "}\x5d",
_ => Convert.ToChar(x).ToString(),
}
).JoinToString(string.Empty);
}
}

View File

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

View File

@ -3,7 +3,7 @@ using System.Globalization;
namespace Ryujinx.HLE.Debugger
{
internal class StringStream
class StringStream
{
private readonly string Data;
private int Position;

View File

@ -29,7 +29,6 @@ namespace Ryujinx.HLE.HOS.Kernel
capabilities,
context.ResourceLimit,
MemoryRegion.Service,
context.Device.Configuration.MemoryConfiguration,
null,
customThreadStart);

View File

@ -102,7 +102,6 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
ProcessCreationFlags flags,
bool fromBack,
MemoryRegion memRegion,
MemoryConfiguration memConfig,
ulong address,
ulong size,
KMemoryBlockSlabManager slabManager)
@ -118,7 +117,6 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
addrSpaceBase,
addrSpaceSize,
memRegion,
memConfig,
address,
size,
slabManager);
@ -161,7 +159,6 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
ulong addrSpaceStart,
ulong addrSpaceEnd,
MemoryRegion memRegion,
MemoryConfiguration memConfig,
ulong address,
ulong size,
KMemoryBlockSlabManager slabManager)
@ -196,7 +193,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
case ProcessCreationFlags.AddressSpace64BitDeprecated:
aliasRegion.Size = 0x180000000;
heapRegion.Size = memConfig == MemoryConfiguration.MemoryConfiguration12GiB ? 0x300000000u : 0x180000000u;
heapRegion.Size = 0x180000000;
stackRegion.Size = 0;
tlsIoRegion.Size = 0;
CodeRegionStart = 0x8000000;
@ -226,7 +223,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
int addressSpaceWidth = (int)ulong.Log2(_reservedAddressSpaceSize);
aliasRegion.Size = 1UL << (addressSpaceWidth - 3);
heapRegion.Size = memConfig == MemoryConfiguration.MemoryConfiguration12GiB ? 0x300000000u : 0x180000000u;
heapRegion.Size = 0x180000000;
stackRegion.Size = 1UL << (addressSpaceWidth - 8);
tlsIoRegion.Size = 1UL << (addressSpaceWidth - 3);
CodeRegionStart = BitUtils.AlignDown(address, RegionAlignment);
@ -240,7 +237,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
else
{
aliasRegion.Size = 0x1000000000;
heapRegion.Size = memConfig == MemoryConfiguration.MemoryConfiguration12GiB ? 0x300000000u : 0x180000000u;
heapRegion.Size = 0x180000000;
stackRegion.Size = 0x80000000;
tlsIoRegion.Size = 0x1000000000;
CodeRegionStart = BitUtils.AlignDown(address, RegionAlignment);

View File

@ -124,7 +124,6 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
KPageList pageList,
KResourceLimit resourceLimit,
MemoryRegion memRegion,
MemoryConfiguration memConfig,
IProcessContextFactory contextFactory,
ThreadStart customThreadStart = null)
{
@ -154,7 +153,6 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
creationInfo.Flags,
!creationInfo.Flags.HasFlag(ProcessCreationFlags.EnableAslr),
memRegion,
memConfig,
codeAddress,
codeSize,
slabManager);
@ -191,7 +189,6 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
ReadOnlySpan<uint> capabilities,
KResourceLimit resourceLimit,
MemoryRegion memRegion,
MemoryConfiguration memConfig,
IProcessContextFactory contextFactory,
ThreadStart customThreadStart = null)
{
@ -255,7 +252,6 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
creationInfo.Flags,
!creationInfo.Flags.HasFlag(ProcessCreationFlags.EnableAslr),
memRegion,
memConfig,
codeAddress,
codeSize,
slabManager);
@ -1099,8 +1095,6 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
Logger.Error?.Print(LogClass.Cpu, $"Invalid memory access at virtual address 0x{va:X16}.");
Logger.Flush();
return false;
}
@ -1109,8 +1103,6 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
KernelStatic.GetCurrentThread().PrintGuestStackTrace();
KernelStatic.GetCurrentThread()?.PrintGuestRegisterPrintout();
Logger.Flush();
throw new UndefinedInstructionException(address, opCode);
}

View File

@ -137,7 +137,6 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
capabilities,
resourceLimit,
memRegion,
_context.Device.Configuration.MemoryConfiguration,
contextFactory,
customThreadStart);
@ -889,7 +888,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
[Svc(1)]
public Result SetHeapSize([PointerSized] out ulong address, [PointerSized] ulong size)
{
if ((size & 0xfffffffd001fffff) != 0)
if ((size & 0xfffffffe001fffff) != 0)
{
address = 0;
@ -1894,9 +1893,6 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
return;
}
Logger.Error?.Print(LogClass.KernelSvc, "The guest program broke execution!");
Logger.Flush();
// TODO: Debug events.
currentThread.Owner.TerminateCurrentProcess();

View File

@ -293,12 +293,6 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading
KThread currentThread = KernelStatic.GetCurrentThread();
KThread selectedThread = _state.SelectedThread;
if (!currentThread.IsThreadNamed && currentThread.GetThreadName() != "")
{
currentThread.HostThread.Name = $"<{currentThread.GetThreadName()}>";
currentThread.IsThreadNamed = true;
}
// If the thread is already scheduled and running on the core, we have nothing to do.
if (currentThread == selectedThread)
{

View File

@ -53,8 +53,6 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading
public ulong AffinityMask { get; set; }
public ulong ThreadUid { get; private set; }
public bool IsThreadNamed { get; set; }
private long _totalTimeRunning;

View File

@ -189,7 +189,7 @@ namespace Ryujinx.HLE.Loaders.Processes
codeAddress,
codeSize);
result = process.InitializeKip(creationInfo, kip.Capabilities, pageList, context.ResourceLimit, memoryRegion, context.Device.Configuration.MemoryConfiguration, processContextFactory);
result = process.InitializeKip(creationInfo, kip.Capabilities, pageList, context.ResourceLimit, memoryRegion, processContextFactory);
if (result != Result.Success)
{
Logger.Error?.Print(LogClass.Loader, $"Process initialization returned error \"{result}\".");
@ -389,7 +389,6 @@ namespace Ryujinx.HLE.Loaders.Processes
MemoryMarshal.Cast<byte, uint>(npdm.KernelCapabilityData),
resourceLimit,
memoryRegion,
context.Device.Configuration.MemoryConfiguration,
processContextFactory);
if (result != Result.Success)

View File

@ -33,12 +33,12 @@
</ItemGroup>
<ItemGroup>
<None Remove="Debugger\Gdb\Xml\aarch64-core.xml" />
<None Remove="Debugger\Gdb\Xml\aarch64-fpu.xml" />
<None Remove="Debugger\Gdb\Xml\arm-core.xml" />
<None Remove="Debugger\Gdb\Xml\arm-neon.xml" />
<None Remove="Debugger\Gdb\Xml\target64.xml" />
<None Remove="Debugger\Gdb\Xml\target32.xml" />
<None Remove="Debugger\GdbXml\aarch64-core.xml" />
<None Remove="Debugger\GdbXml\aarch64-fpu.xml" />
<None Remove="Debugger\GdbXml\arm-core.xml" />
<None Remove="Debugger\GdbXml\arm-neon.xml" />
<None Remove="Debugger\GdbXml\target64.xml" />
<None Remove="Debugger\GdbXml\target32.xml" />
<None Remove="Homebrew.npdm" />
<None Remove="HOS\Applets\SoftwareKeyboard\Resources\Logo_Ryujinx.png" />
<None Remove="HOS\Applets\SoftwareKeyboard\Resources\Icon_BtnA.png" />
@ -48,12 +48,12 @@
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Debugger\Gdb\Xml\aarch64-core.xml" />
<EmbeddedResource Include="Debugger\Gdb\Xml\aarch64-fpu.xml" />
<EmbeddedResource Include="Debugger\Gdb\Xml\arm-core.xml" />
<EmbeddedResource Include="Debugger\Gdb\Xml\arm-neon.xml" />
<EmbeddedResource Include="Debugger\Gdb\Xml\target32.xml" />
<EmbeddedResource Include="Debugger\Gdb\Xml\target64.xml" />
<EmbeddedResource Include="Debugger\GdbXml\aarch64-core.xml" />
<EmbeddedResource Include="Debugger\GdbXml\aarch64-fpu.xml" />
<EmbeddedResource Include="Debugger\GdbXml\arm-core.xml" />
<EmbeddedResource Include="Debugger\GdbXml\arm-neon.xml" />
<EmbeddedResource Include="Debugger\GdbXml\target64.xml" />
<EmbeddedResource Include="Debugger\GdbXml\target32.xml" />
<EmbeddedResource Include="Homebrew.npdm" />
<EmbeddedResource Include="HOS\Applets\SoftwareKeyboard\Resources\Logo_Ryujinx.png" />
<EmbeddedResource Include="HOS\Applets\SoftwareKeyboard\Resources\Icon_BtnA.png" />

View File

@ -351,10 +351,7 @@ namespace Ryujinx.Ava
if (isTerminating)
{
Logger.Flush();
Exit();
}
}
internal static void Exit()

View File

@ -11,13 +11,11 @@ using LibHac.Tools.FsSystem.NcaUtils;
using Ryujinx.Ava.Common.Locale;
using Ryujinx.Ava.Systems.PlayReport;
using Ryujinx.Ava.Utilities;
using Ryujinx.Common.Configuration;
using Ryujinx.Common.Logging;
using Ryujinx.HLE.FileSystem;
using Ryujinx.HLE.Loaders.Processes.Extensions;
using System;
using System.IO;
using System.Linq;
using System.Text.Json.Serialization;
namespace Ryujinx.Ava.Systems.AppLibrary
@ -86,32 +84,6 @@ namespace Ryujinx.Ava.Systems.AppLibrary
public LocaleKeys? PlayabilityStatus => Compatibility.Convert(x => x.Status).OrElse(null);
public bool HasPtcCacheFiles
{
get
{
DirectoryInfo mainDir = new(System.IO.Path.Combine(AppDataManager.GamesDirPath, IdString, "cache", "cpu", "0"));
DirectoryInfo backupDir = new(System.IO.Path.Combine(AppDataManager.GamesDirPath, IdString, "cache", "cpu", "1"));
return (mainDir.Exists && (mainDir.EnumerateFiles("*.cache").Any() || mainDir.EnumerateFiles("*.info").Any())) ||
(backupDir.Exists && (backupDir.EnumerateFiles("*.cache").Any() || backupDir.EnumerateFiles("*.info").Any()));
}
}
public bool HasShaderCacheFiles
{
get
{
DirectoryInfo shaderCacheDir = new(System.IO.Path.Combine(AppDataManager.GamesDirPath, IdString, "cache", "shader"));
if (!shaderCacheDir.Exists) return false;
return shaderCacheDir.EnumerateDirectories("*").Any() ||
shaderCacheDir.GetFiles("*.toc").Length != 0 ||
shaderCacheDir.GetFiles("*.data").Length != 0;
}
}
public string LocalizedStatusTooltip =>
Compatibility.Convert(x =>
#pragma warning disable CS8509 // It is exhaustive for all possible values this can contain.

View File

@ -120,13 +120,13 @@
CommandParameter="{Binding}"
Header="{ext:Locale GameListContextMenuCacheManagementNukePptc}"
Icon="{ext:Icon fa-solid fa-trash-can}"
IsEnabled="{Binding SelectedApplication.HasPtcCacheFiles, FallbackValue=False}" />
IsEnabled="{Binding HasPtcCacheFiles}" />
<MenuItem
Command="{Binding PurgeShaderCache}"
CommandParameter="{Binding}"
Header="{ext:Locale GameListContextMenuCacheManagementPurgeShaderCache}"
Icon="{ext:Icon fa-solid fa-trash-can}"
IsEnabled="{Binding SelectedApplication.HasShaderCacheFiles, FallbackValue=False}" />
IsEnabled="{Binding HasShaderCacheFiles}" />
<Separator/>
<MenuItem
Command="{Binding OpenPtcDirectory}"

View File

@ -354,8 +354,8 @@ namespace Ryujinx.Ava.UI.Helpers
primary,
secondaryText,
LocaleManager.Instance[LocaleKeys.InputDialogYes],
LocaleManager.Instance[LocaleKeys.DialogUpdaterShowChangelogMessage],
LocaleManager.Instance[LocaleKeys.InputDialogNo],
LocaleManager.Instance[LocaleKeys.DialogUpdaterShowChangelogMessage],
(int)Symbol.Help,
UserResult.Yes);

View File

@ -6,7 +6,6 @@ using Ryujinx.Ava.Common.Locale;
using Ryujinx.Ava.Common.Models.Amiibo;
using Ryujinx.Ava.UI.Helpers;
using Ryujinx.Ava.UI.Windows;
using Ryujinx.Ava.Utilities;
using Ryujinx.Common;
using Ryujinx.Common.Configuration;
using Ryujinx.Common.Logging;
@ -251,7 +250,6 @@ namespace Ryujinx.Ava.UI.ViewModels
catch (Exception exception)
{
Logger.Warning?.Print(LogClass.Application, $"Unable to read data from '{_amiiboJsonPath}': {exception}");
localIsValid = false;
}
if (!localIsValid || await NeedsUpdate(amiiboJson.LastUpdated))
@ -282,59 +280,11 @@ namespace Ryujinx.Ava.UI.ViewModels
return amiiboJson;
}
private async Task<AmiiboJson?> ReadLocalJsonFileAsync()
{
bool isValid = false;
AmiiboJson amiiboJson = new();
try
{
try
{
if (File.Exists(_amiiboJsonPath))
{
isValid = TryGetAmiiboJson(await File.ReadAllTextAsync(_amiiboJsonPath), out amiiboJson);
}
}
catch (Exception exception)
{
Logger.Warning?.Print(LogClass.Application, $"Unable to read data from '{_amiiboJsonPath}': {exception}");
isValid = false;
}
if (!isValid)
{
return null;
}
}
catch (Exception exception)
{
if (!isValid)
{
Logger.Error?.Print(LogClass.Application, $"Couldn't get valid amiibo data: {exception}");
// Neither local file is not valid JSON, close window.
await ShowInfoDialog();
Close();
}
}
return amiiboJson;
}
private async Task LoadContentAsync()
{
AmiiboJson? amiiboJson;
AmiiboJson amiiboJson = await GetMostRecentAmiiboListOrDefaultJson();
if (CommandLineState.OnlyLocalAmiibo)
amiiboJson = await ReadLocalJsonFileAsync();
else
amiiboJson = await GetMostRecentAmiiboListOrDefaultJson();
if (!amiiboJson.HasValue)
return;
_amiiboList = amiiboJson.Value.Amiibo.OrderBy(amiibo => amiibo.AmiiboSeries).ToList();
_amiiboList = amiiboJson.Amiibo.OrderBy(amiibo => amiibo.AmiiboSeries).ToList();
ParseAmiiboData();
}

View File

@ -2121,7 +2121,8 @@ namespace Ryujinx.Ava.UI.ViewModels
});
public static AsyncRelayCommand<MainWindowViewModel> NukePtcCache { get; } =
Commands.CreateConditional<MainWindowViewModel>(vm => vm?.SelectedApplication?.HasPtcCacheFiles ?? false,
Commands.CreateConditional<MainWindowViewModel>(vm => vm?.SelectedApplication != null &&
vm.HasPtcCacheFiles(),
async viewModel =>
{
UserResult result = await ContentDialogHelper.CreateLocalizedConfirmationDialog(
@ -2170,9 +2171,22 @@ namespace Ryujinx.Ava.UI.ViewModels
}
});
private bool HasPtcCacheFiles()
{
if (this.SelectedApplication == null) return false;
DirectoryInfo mainDir = new DirectoryInfo(Path.Combine(AppDataManager.GamesDirPath,
this.SelectedApplication.IdString, "cache", "cpu", "0"));
DirectoryInfo backupDir = new DirectoryInfo(Path.Combine(AppDataManager.GamesDirPath,
this.SelectedApplication.IdString, "cache", "cpu", "1"));
return (mainDir.Exists && (mainDir.EnumerateFiles("*.cache").Any() || mainDir.EnumerateFiles("*.info").Any())) ||
(backupDir.Exists && (backupDir.EnumerateFiles("*.cache").Any() || backupDir.EnumerateFiles("*.info").Any()));
}
public static AsyncRelayCommand<MainWindowViewModel> PurgeShaderCache { get; } =
Commands.CreateConditional<MainWindowViewModel>(
vm => vm?.SelectedApplication?.HasShaderCacheFiles ?? false,
vm => vm?.SelectedApplication != null && vm.HasShaderCacheFiles(),
async viewModel =>
{
UserResult result = await ContentDialogHelper.CreateLocalizedConfirmationDialog(
@ -2229,6 +2243,20 @@ namespace Ryujinx.Ava.UI.ViewModels
}
});
private bool HasShaderCacheFiles()
{
if (this.SelectedApplication == null) return false;
DirectoryInfo shaderCacheDir = new(Path.Combine(AppDataManager.GamesDirPath,
this.SelectedApplication.IdString, "cache", "shader"));
if (!shaderCacheDir.Exists) return false;
return shaderCacheDir.EnumerateDirectories("*").Any() ||
shaderCacheDir.GetFiles("*.toc").Any() ||
shaderCacheDir.GetFiles("*.data").Any();
}
public static RelayCommand<MainWindowViewModel> OpenPtcDirectory { get; } =
Commands.CreateConditional<MainWindowViewModel>(vm => vm?.SelectedApplication != null,
viewModel =>

View File

@ -35,7 +35,7 @@
<ListBox.Styles>
<Style Selector="ListBoxItem">
<Setter Property="Margin" Value="5" />
<Setter Property="CornerRadius" Value="4" />
<Setter Property="CornerRadius" Value="15" />
</Style>
<Style Selector="ListBoxItem:selected /template/ Rectangle#SelectionIndicator">
<Setter Property="MinHeight" Value="{Binding $parent[UserControl].((viewModels:MainWindowViewModel)DataContext).GridItemSelectorSize}" />
@ -53,7 +53,7 @@
Classes.normal="{Binding $parent[UserControl].((viewModels:MainWindowViewModel)DataContext).IsGridMedium}"
Classes.small="{Binding $parent[UserControl].((viewModels:MainWindowViewModel)DataContext).IsGridSmall}"
ClipToBounds="True"
CornerRadius="4">
CornerRadius="12.5">
<Grid RowDefinitions="Auto,Auto">
<Image
Grid.Row="0"

View File

@ -34,6 +34,9 @@
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.Styles>
<Style Selector="ListBoxItem">
<Setter Property="CornerRadius" Value="15" />
</Style>
<Style Selector="ListBoxItem:selected /template/ Rectangle#SelectionIndicator">
<Setter Property="MinHeight" Value="{Binding $parent[UserControl].((viewModels:MainWindowViewModel)DataContext).ListItemSelectorSize}" />
</Style>
@ -46,9 +49,11 @@
Padding="10"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
ClipToBounds="True"
CornerRadius="5">
ClipToBounds="True">
<Grid ColumnDefinitions="Auto,10,*,150,100">
<Border
ClipToBounds="True"
CornerRadius="7">
<Image
Grid.RowSpan="3"
Grid.Column="0"
@ -58,6 +63,7 @@
Classes.normal="{Binding $parent[UserControl].((viewModels:MainWindowViewModel)DataContext).IsGridMedium}"
Classes.small="{Binding $parent[UserControl].((viewModels:MainWindowViewModel)DataContext).IsGridSmall}"
Source="{Binding Icon, Converter={x:Static helpers:BitmapArrayValueConverter.Instance}}" />
</Border>
<Border
Grid.Column="2"

View File

@ -25,7 +25,6 @@ namespace Ryujinx.Ava.Utilities
public static string LaunchApplicationId { get; private set; }
public static bool StartFullscreenArg { get; private set; }
public static bool HideAvailableUpdates { get; private set; }
public static bool OnlyLocalAmiibo { get; private set; }
public static void ParseArguments(string[] args)
{
@ -131,10 +130,6 @@ namespace Ryujinx.Ava.Utilities
OverridePPTC = args[++i];
break;
case "-la":
case "--local-only-amiibo":
OnlyLocalAmiibo = true;
break;
case "-m":
case "--memory-manager-mode":
if (i + 1 >= args.Length)