mirror of
https://github.com/par274/sharpemu.git
synced 2026-07-25 20:28:48 +08:00
Compare commits
70 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9eb021c7d1 | |||
| 4ac29f340a | |||
| fa2616d224 | |||
| 7b86a91dfa | |||
| 72645cb373 | |||
| 2ad9836d13 | |||
| 62e1775c5c | |||
| 6dacd59a08 | |||
| 9d88542efd | |||
| 373100a6b0 | |||
| f23161be9a | |||
| 081760be3f | |||
| e604fb606d | |||
| df53ff59d9 | |||
| 4c35831cb8 | |||
| 90fdd20f9a | |||
| ae5ef0abe7 | |||
| 5e2c21edf1 | |||
| 3fb9d4db1c | |||
| de13735972 | |||
| fc0efca297 | |||
| 2a9a261913 | |||
| 290f5fd3d7 | |||
| c06c70cad7 | |||
| 5e54250752 | |||
| be6a6a5935 | |||
| caf859cc52 | |||
| d2f3511002 | |||
| 90a5d5176f | |||
| 28a43e09c7 | |||
| 093cfa1f3e | |||
| d8397b022e | |||
| 85cc2b9892 | |||
| 293194c40b | |||
| 1f09de8896 | |||
| ddc452b4fc | |||
| 61a97baf85 | |||
| e80f96ecf5 | |||
| d49c0f1f10 | |||
| 1d33ef90fc | |||
| 26a570633c | |||
| e4f89445b9 | |||
| 1254cc1564 | |||
| 503b3f4d6b | |||
| 6b37ab54f2 | |||
| a84d2344fb | |||
| 787d3a1efb | |||
| 884584da67 | |||
| d43edc865a | |||
| cf6964710a | |||
| 4f028d0483 | |||
| 4db98bd8fe | |||
| 4600a2ed1f | |||
| c5c5ee1f36 | |||
| b48b1a5e09 | |||
| 511a01e03a | |||
| aaebfe017b | |||
| 9cdc8550ec | |||
| d6fccedab8 | |||
| fed7a6d062 | |||
| 50f78f3713 | |||
| 63b440efcd | |||
| 0565d01744 | |||
| 56bf00e9a5 | |||
| 46b729c5b4 | |||
| 4b7df8623a | |||
| 3c2134474d | |||
| 298ef01809 | |||
| 2060dacaf1 | |||
| f73c9e8c3f |
@@ -34,29 +34,31 @@ jobs:
|
||||
name: Init
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
archive-name: ${{ steps.vars.outputs.archive-name }}
|
||||
artifact-name: ${{ steps.vars.outputs.artifact-name }}
|
||||
release-name: ${{ steps.vars.outputs.release-name }}
|
||||
release-tag: ${{ steps.vars.outputs.release-tag }}
|
||||
safe-ref: ${{ steps.vars.outputs.safe-ref }}
|
||||
short-sha: ${{ steps.vars.outputs.short-sha }}
|
||||
version: ${{ steps.vars.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Compute workflow variables
|
||||
id: vars
|
||||
shell: bash
|
||||
run: |
|
||||
short_sha="${GITHUB_SHA::7}"
|
||||
safe_ref="$(echo "${GITHUB_REF_NAME}" | tr '[:upper:]' '[:lower:]' | sed 's#[^a-z0-9._-]#-#g')"
|
||||
archive_name="sharpemu-win64-${short_sha}.zip"
|
||||
artifact_name="sharpemu-win64-${short_sha}"
|
||||
release_tag="win64-${safe_ref}-${short_sha}"
|
||||
release_name="SharpEmu win64 ${short_sha}"
|
||||
version="$(python3 -c 'import sys, xml.etree.ElementTree as ET; version = ET.parse("Directory.Build.props").getroot().findtext(".//SharpEmuVersion"); sys.exit("Directory.Build.props is missing SharpEmuVersion") if not version or not version.strip() else print(version.strip())')"
|
||||
release_tag="v${version}"
|
||||
release_name="SharpEmu v${version}"
|
||||
|
||||
{
|
||||
echo "short-sha=${short_sha}"
|
||||
echo "archive-name=${archive_name}"
|
||||
echo "artifact-name=${artifact_name}"
|
||||
echo "safe-ref=${safe_ref}"
|
||||
echo "release-tag=${release_tag}"
|
||||
echo "release-name=${release_name}"
|
||||
echo "version=${version}"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
reuse:
|
||||
@@ -100,6 +102,9 @@ jobs:
|
||||
- name: Build solution
|
||||
run: dotnet build SharpEmu.slnx -c Release --no-restore
|
||||
|
||||
- name: Validate synthetic shaders
|
||||
run: dotnet run --project tools/SharpEmu.Tools.ShaderDump/SharpEmu.Tools.ShaderDump.csproj -c Release -- artifacts/shader-dump
|
||||
|
||||
- name: Publish win-x64 CLI
|
||||
run: dotnet publish src/SharpEmu.CLI/SharpEmu.CLI.csproj -c Release -r win-x64 --self-contained true --no-restore -p:PublishDir="${env:PUBLISH_DIR}"
|
||||
|
||||
@@ -107,7 +112,8 @@ jobs:
|
||||
run: |
|
||||
New-Item -ItemType Directory -Path $env:RELEASE_DIR -Force | Out-Null
|
||||
|
||||
$archivePath = Join-Path $env:RELEASE_DIR "${{ needs.init.outputs.archive-name }}"
|
||||
$archiveName = "sharpemu-${{ needs.init.outputs.version }}-win-x64-${{ needs.init.outputs.short-sha }}.zip"
|
||||
$archivePath = Join-Path $env:RELEASE_DIR $archiveName
|
||||
if (Test-Path $archivePath) {
|
||||
Remove-Item $archivePath -Force
|
||||
}
|
||||
@@ -117,8 +123,67 @@ jobs:
|
||||
- name: Upload build artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ${{ needs.init.outputs.artifact-name }}
|
||||
path: ${{ env.RELEASE_DIR }}\${{ needs.init.outputs.archive-name }}
|
||||
name: sharpemu-win-x64-${{ needs.init.outputs.short-sha }}
|
||||
path: ${{ env.RELEASE_DIR }}\sharpemu-${{ needs.init.outputs.version }}-win-x64-${{ needs.init.outputs.short-sha }}.zip
|
||||
if-no-files-found: error
|
||||
|
||||
build-posix:
|
||||
name: Build ${{ matrix.rid }}
|
||||
needs:
|
||||
- init
|
||||
- reuse
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
rid: linux-x64
|
||||
- os: macos-latest
|
||||
rid: osx-x64
|
||||
env:
|
||||
DOTNET_NOLOGO: true
|
||||
NUGET_PACKAGES: ${{ github.workspace }}/.nuget/packages
|
||||
PUBLISH_DIR: ${{ github.workspace }}/artifacts/publish/${{ matrix.rid }}
|
||||
RELEASE_DIR: ${{ github.workspace }}/artifacts/release
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup .NET SDK
|
||||
uses: actions/setup-dotnet@v5
|
||||
with:
|
||||
dotnet-version: 10.0.103
|
||||
cache: true
|
||||
cache-dependency-path: |
|
||||
Directory.Packages.props
|
||||
src/**/packages.lock.json
|
||||
|
||||
- name: Restore solution
|
||||
run: dotnet restore SharpEmu.slnx --locked-mode
|
||||
|
||||
- name: Build solution
|
||||
run: dotnet build SharpEmu.slnx -c Release --no-restore
|
||||
|
||||
- name: Publish ${{ matrix.rid }} CLI
|
||||
run: dotnet publish src/SharpEmu.CLI/SharpEmu.CLI.csproj -c Release -r ${{ matrix.rid }} --self-contained true --no-restore -p:PublishDir="$PUBLISH_DIR"
|
||||
|
||||
- name: Stage MoltenVK next to the build
|
||||
if: matrix.rid == 'osx-x64'
|
||||
run: scripts/fetch-macos-moltenvk.sh "$PUBLISH_DIR"
|
||||
|
||||
- name: Create release archive
|
||||
run: |
|
||||
mkdir -p "$RELEASE_DIR"
|
||||
# tar keeps the executable bit, which zip would drop.
|
||||
tar -czf "$RELEASE_DIR/sharpemu-${{ needs.init.outputs.version }}-${{ matrix.rid }}-${{ needs.init.outputs.short-sha }}.tar.gz" \
|
||||
-C "$PUBLISH_DIR" .
|
||||
|
||||
- name: Upload build artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: sharpemu-${{ matrix.rid }}-${{ needs.init.outputs.short-sha }}
|
||||
path: ${{ env.RELEASE_DIR }}/sharpemu-${{ needs.init.outputs.version }}-${{ matrix.rid }}-${{ needs.init.outputs.short-sha }}.tar.gz
|
||||
if-no-files-found: error
|
||||
|
||||
release:
|
||||
@@ -126,34 +191,39 @@ jobs:
|
||||
needs:
|
||||
- init
|
||||
- build
|
||||
- build-posix
|
||||
if: github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Download build artifact
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: ${{ needs.init.outputs.artifact-name }}
|
||||
path: release
|
||||
|
||||
- name: Create or update release
|
||||
shell: bash
|
||||
env:
|
||||
ARCHIVE_NAME: ${{ needs.init.outputs.archive-name }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
RELEASE_NAME: ${{ needs.init.outputs.release-name }}
|
||||
RELEASE_TAG: ${{ needs.init.outputs.release-tag }}
|
||||
VERSION: ${{ needs.init.outputs.version }}
|
||||
run: |
|
||||
asset_path="release/${ARCHIVE_NAME}"
|
||||
notes="Automated Windows build for commit ${GITHUB_SHA}."
|
||||
mapfile -t assets < <(find release -type f \( -name '*.zip' -o -name '*.tar.gz' \) | sort)
|
||||
if [ "${#assets[@]}" -eq 0 ]; then
|
||||
echo "No release assets found." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
notes="Automated SharpEmu v${VERSION} build for commit ${GITHUB_SHA}."
|
||||
|
||||
if gh release view "${RELEASE_TAG}" >/dev/null 2>&1; then
|
||||
gh release upload "${RELEASE_TAG}" "${asset_path}" --clobber
|
||||
gh release upload "${RELEASE_TAG}" "${assets[@]}" --clobber
|
||||
gh release edit "${RELEASE_TAG}" --title "${RELEASE_NAME}" --notes "${notes}"
|
||||
else
|
||||
gh release create "${RELEASE_TAG}" "${asset_path}" \
|
||||
gh release create "${RELEASE_TAG}" "${assets[@]}" \
|
||||
--title "${RELEASE_NAME}" \
|
||||
--notes "${notes}" \
|
||||
--target "${GITHUB_SHA}"
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
<!--
|
||||
Copyright (C) 2026 SharpEmu Emulator Project
|
||||
SPDX-License-Identifier: GPL-2.0-or-later
|
||||
-->
|
||||
|
||||
# Contributing
|
||||
|
||||
Contributions are always welcome!
|
||||
|
||||
Before opening a pull request, please keep the following in mind:
|
||||
|
||||
- Keep PRs small and focused on a single topic.
|
||||
- Discuss large architectural changes before implementing them.
|
||||
- Follow the project's existing coding style.
|
||||
- Do not submit generated code unless you fully understand and can maintain it.
|
||||
- Do not introduce Sony proprietary code, firmware, keys, decrypted assets, or other copyrighted PlayStation materials.
|
||||
- All reverse engineering should be based on publicly available information, clean-room techniques, or your own original research.
|
||||
- Game-specific hacks should be avoided whenever possible. Prefer generic implementations that improve overall compatibility.
|
||||
- New features should not break existing behavior.
|
||||
- Ensure the project builds successfully before submitting a PR.
|
||||
|
||||
If you're unsure about a design decision, feel free to open a discussion or draft PR first.
|
||||
|
||||
## AI-Assisted Contributions
|
||||
|
||||
AI-assisted development is welcome and may be used for research, reverse engineering, code generation, or documentation.
|
||||
|
||||
However, contributors are expected to fully understand every line of code they submit. By opening a pull request, you confirm that you are able to explain, modify, debug, and maintain the submitted code without relying on the AI that generated it.
|
||||
|
||||
When submitting an AI-assisted PR:
|
||||
|
||||
- Clearly explain **what the change does**, **why it is needed**, and **what problem it solves**, using your own words.
|
||||
- Describe **how you verified the change**, including the games, applications, or test cases used.
|
||||
- Avoid excessive product-level logging. Use logging only when it provides meaningful diagnostic value.
|
||||
- Comments should document design decisions or implementation details in your own words. Avoid generic AI-generated comments that merely restate what the code already does.
|
||||
- Be prepared to answer review questions about the implementation. "The AI generated it" is not considered a sufficient explanation.
|
||||
- Large AI-generated changes without a clear understanding of the implementation are unlikely to be accepted.
|
||||
- If the implementation cannot be reasonably explained during code review, the pull request may be rejected regardless of whether it works.
|
||||
|
||||
The quality, correctness, maintainability, and long-term ownership of the submitted code remain the responsibility of the contributor.
|
||||
|
||||
## Coding Style
|
||||
|
||||
SharpEmu follows a consistent coding style across the project. Please ensure your contributions match the existing style.
|
||||
|
||||
- Use **4 spaces** for indentation (no tabs).
|
||||
- Use **2 spaces** for XML-based files (e.g. `.csproj`, `.props`, `.targets`, `.xml`, `yml`, GitHub workflow files where applicable).
|
||||
- Respect the project's `.editorconfig`.
|
||||
- Ensure every text file ends with a **single trailing newline**
|
||||
- Avoid formatting-only commits unless they are the purpose of the PR.
|
||||
- Keep naming, formatting, and file organization consistent with the surrounding code.
|
||||
- Prefer small, focused changes over large refactors.
|
||||
|
||||
### REUSE Compliance
|
||||
|
||||
This repository follows the REUSE Specification.
|
||||
|
||||
Every new file must contain the appropriate SPDX license header. Pull requests that do not comply with the project's REUSE requirements will fail CI and will not be merged.
|
||||
|
||||
### Recommended Development Environment
|
||||
|
||||
The repository includes an `.editorconfig` and Visual Studio solution files.
|
||||
|
||||
For the best experience, we recommend using:
|
||||
|
||||
- Visual Studio Code with;
|
||||
- C#
|
||||
- C# Dev Kit
|
||||
|
||||
Most editors that support `.editorconfig` will automatically apply the project's formatting rules.
|
||||
@@ -10,6 +10,8 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
<Nullable>enable</Nullable>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
|
||||
<SharpEmuVersion>0.0.1</SharpEmuVersion>
|
||||
<Version>$(SharpEmuVersion)</Version>
|
||||
|
||||
<RepoRoot>$([MSBuild]::NormalizeDirectory('$(MSBuildThisFileDirectory)'))</RepoRoot>
|
||||
|
||||
|
||||
@@ -12,11 +12,15 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
<PackageVersion Include="Avalonia.Fonts.Inter" Version="11.3.18" />
|
||||
<PackageVersion Include="Avalonia.Themes.Fluent" Version="11.3.18" />
|
||||
<PackageVersion Include="Iced" Version="1.21.0" />
|
||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageVersion Include="Silk.NET.Input" Version="2.23.0" />
|
||||
<PackageVersion Include="Silk.NET.Vulkan" Version="2.23.0" />
|
||||
<PackageVersion Include="Silk.NET.Vulkan.Extensions.EXT" Version="2.23.0" />
|
||||
<PackageVersion Include="Silk.NET.Vulkan.Extensions.KHR" Version="2.23.0" />
|
||||
<PackageVersion Include="Silk.NET.Windowing" Version="2.23.0" />
|
||||
<!-- Transitive of Avalonia.Desktop; pinned to fix GHSA-xrw6-gwf8-vvr9 -->
|
||||
<PackageVersion Include="Tmds.DBus.Protocol" Version="0.21.3" />
|
||||
<PackageVersion Include="xunit" Version="2.9.3" />
|
||||
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.1" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
</Project>
|
||||
|
||||
@@ -23,10 +23,11 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
<strong>Join our Discord for development updates, compatibility discussions, support, and community chat.</strong>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
> [!WARNING]
|
||||
> Currently the primary development target is Windows.
|
||||
---
|
||||
|
||||
> [!NOTE]
|
||||
> SharpEmu supports Windows x64, Linux x64, and macOS x64. Apple Silicon Macs
|
||||
> can run the macOS x64 build through Rosetta 2.
|
||||
|
||||
> [!WARNING]
|
||||
> SharpEmu is an experimental PS5 emulator developed from scratch in C#. The current focus is on accuracy and infrastructure setup rather than game-specific compatibility.
|
||||
@@ -59,14 +60,33 @@ Current capabilities include:
|
||||
|
||||
Some games have reached like `sceVideoOut` and AGC stages.
|
||||
|
||||
Currently the project primarily targets Windows. Cross-platform support (Linux and macOS) is planned, but development is currently focused on Windows to simplify early-stage debugging and iteration.
|
||||
|
||||
## Using
|
||||
|
||||
* Build or Publish project or download in release tab.
|
||||
* Open Powershell.
|
||||
* Run Emulator GUI.
|
||||
* Or command: `.\SharpEmu "eboot.bin" 2>&1 | Tee-Object -FilePath "log.txt"`
|
||||
SharpEmu supports Windows, Linux, and macOS hosts. Video output uses Vulkan on
|
||||
Windows and Linux, and MoltenVK on macOS. Platform support is still experimental,
|
||||
so compatibility and performance vary by game, operating system, and GPU driver.
|
||||
|
||||
## Using
|
||||
|
||||
Download the release archive for your operating system, extract it, and launch
|
||||
SharpEmu with the path to a legally obtained game's `eboot.bin`.
|
||||
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
.\SharpEmu.exe "C:\path\to\game\eboot.bin" 2>&1 |
|
||||
Tee-Object -FilePath "SharpEmu.log"
|
||||
```
|
||||
|
||||
Linux and macOS:
|
||||
|
||||
```bash
|
||||
chmod +x ./SharpEmu
|
||||
|
||||
./SharpEmu "/path/to/game/eboot.bin" 2>&1 |
|
||||
tee SharpEmu.log
|
||||
```
|
||||
|
||||
A Vulkan-capable GPU and current graphics driver are required. The macOS
|
||||
release includes the MoltenVK Vulkan implementation.
|
||||
|
||||
## Games Tested
|
||||
|
||||
@@ -94,7 +114,7 @@ Currently the project primarily targets Windows. Cross-platform support (Linux a
|
||||
|
||||
## Build
|
||||
|
||||
1. Install the **.NET SDK**.
|
||||
1. Install the .NET SDK version specified in [`global.json`](./global.json).
|
||||
2. Clone the repository: `git clone https://github.com/par274/sharpemu.git`
|
||||
3. Open the solution file (`SharpEmu.slnx`) in **VSCode**.
|
||||
4. Build the project: `dotnet build` or `dotnet publish`
|
||||
@@ -122,3 +142,16 @@ Provided valuable references for filesystem handling and low-level C# implementa
|
||||
# License
|
||||
|
||||
- [**GPL-2.0 license**](https://github.com/par274/sharpemu/blob/main/LICENSE)
|
||||
|
||||
## Contributing
|
||||
|
||||
Before opening an issue or pull request, please read our contribution guidelines:
|
||||
|
||||
**[CONTRIBUTING.md](./CONTRIBUTING.md)**
|
||||
|
||||
The guide covers:
|
||||
- Coding style and formatting
|
||||
- AI-assisted contributions
|
||||
- Pull request expectations
|
||||
- Testing guidelines
|
||||
- Legal and reverse engineering policy
|
||||
|
||||
@@ -8,6 +8,7 @@ path = [
|
||||
"**/packages.lock.json",
|
||||
"scripts/ps5_names.txt",
|
||||
"src/SharpEmu.HLE/Aerolib/aerolib.bin",
|
||||
"src/SharpEmu.GUI/Languages/**",
|
||||
"_logs/**",
|
||||
".github/images/**",
|
||||
"assets/images/**"
|
||||
|
||||
@@ -12,4 +12,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
<Project Path="src/SharpEmu.Libs/SharpEmu.Libs.csproj" />
|
||||
<Project Path="src/SharpEmu.Logging/SharpEmu.Logging.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/tests/">
|
||||
<Project Path="tests/SharpEmu.Libs.Tests/SharpEmu.Libs.Tests.csproj" />
|
||||
</Folder>
|
||||
</Solution>
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 698 B |
Binary file not shown.
|
After Width: | Height: | Size: 802 B |
@@ -0,0 +1,172 @@
|
||||
# Copyright (C) 2026 SharpEmu Emulator Project
|
||||
# SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""Offline check: SysAbiExport ExportName must hash to its Nid (name2nid).
|
||||
|
||||
NIDs absent from aerolib.bin are skipped (unknown/unresolved symbols).
|
||||
Known historic mislabels may be allowlisted with a one-line reason.
|
||||
|
||||
Run from the repository root:
|
||||
python scripts/check_sysabi_aerolib.py
|
||||
python scripts/check_sysabi_aerolib.py --strict
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
from base64 import b64encode as base64enc
|
||||
from binascii import unhexlify as uhx
|
||||
from pathlib import Path
|
||||
|
||||
SRC_ROOT = Path("src")
|
||||
AEROLIB_BIN = Path("src/SharpEmu.HLE/Aerolib/aerolib.bin")
|
||||
SYSABI_EXPORT_RE = re.compile(r"\[SysAbiExport\((.*?)\)\]", re.DOTALL)
|
||||
NID_RE = re.compile(r'Nid\s*=\s*"([^"]+)"')
|
||||
EXPORT_NAME_RE = re.compile(r'ExportName\s*=\s*"([^"]+)"')
|
||||
|
||||
# NID -> reason. Keep minimal; fix ExportName when safe instead of growing this list.
|
||||
ALLOWLISTED_NIDS: dict[str, str] = {
|
||||
"KMcEa+rHsIo": "Historic kernel MapMemory stub bound to sceAvPlayerAddSource NID; API rewrite deferred.",
|
||||
"WV1GwM32NgY": "Historic WebApi2 init alias for PushEventCreateHandle NID; ABI rewrite deferred.",
|
||||
}
|
||||
|
||||
|
||||
def name2nid(name: str) -> str:
|
||||
symbol = hashlib.sha1(name.encode() + uhx("518D64A635DED8C1E6B039B1C3E55230")).digest()
|
||||
id_val = struct.unpack("<Q", symbol[:8])[0]
|
||||
nid = base64enc(uhx("%016x" % id_val), b"+-").rstrip(b"=")
|
||||
return nid.decode("utf-8")
|
||||
|
||||
|
||||
def find_repo_root() -> Path:
|
||||
cwd = Path.cwd()
|
||||
if (cwd / SRC_ROOT).is_dir() and (cwd / "scripts").is_dir():
|
||||
return cwd
|
||||
script_root = Path(__file__).resolve().parent.parent
|
||||
if (script_root / SRC_ROOT).is_dir():
|
||||
return script_root
|
||||
raise SystemExit("Run from the repository root (src/ and scripts/ expected).")
|
||||
|
||||
|
||||
def load_aerolib_nids(aerolib_path: Path) -> set[str]:
|
||||
data = aerolib_path.read_bytes()
|
||||
if len(data) < 4:
|
||||
raise SystemExit(f"Aerolib binary too small: {aerolib_path}")
|
||||
|
||||
count = struct.unpack_from("<I", data, 0)[0]
|
||||
offset = 4
|
||||
nids: set[str] = set()
|
||||
for _ in range(count):
|
||||
if offset >= len(data):
|
||||
raise SystemExit(f"Truncated aerolib.bin while reading NIDs: {aerolib_path}")
|
||||
nid_len = data[offset]
|
||||
offset += 1
|
||||
nid = data[offset : offset + nid_len].decode("utf-8")
|
||||
offset += nid_len
|
||||
if offset + 2 > len(data):
|
||||
raise SystemExit(f"Truncated aerolib.bin name length: {aerolib_path}")
|
||||
name_len = struct.unpack_from("<H", data, offset)[0]
|
||||
offset += 2 + name_len
|
||||
nids.add(nid)
|
||||
return nids
|
||||
|
||||
|
||||
def iter_sysabi_exports(cs_path: Path, text: str):
|
||||
for match in SYSABI_EXPORT_RE.finditer(text):
|
||||
block = match.group(1)
|
||||
nid_match = NID_RE.search(block)
|
||||
export_match = EXPORT_NAME_RE.search(block)
|
||||
if nid_match is None or export_match is None:
|
||||
continue
|
||||
|
||||
nid = nid_match.group(1)
|
||||
export_name = export_match.group(1)
|
||||
nid_attr = f'Nid = "{nid}"'
|
||||
abs_pos = text.find(nid_attr, match.start(), match.end())
|
||||
if abs_pos < 0:
|
||||
abs_pos = match.start()
|
||||
line = text.count("\n", 0, abs_pos) + 1
|
||||
yield cs_path, line, nid, export_name
|
||||
|
||||
|
||||
def scan(src_root: Path, catalog_nids: set[str]):
|
||||
checked = 0
|
||||
mismatches = []
|
||||
skipped_no_catalog = 0
|
||||
allowlisted = 0
|
||||
|
||||
for cs_path in sorted(src_root.rglob("*.cs")):
|
||||
text = cs_path.read_text(encoding="utf-8")
|
||||
for path, line, nid, export_name in iter_sysabi_exports(cs_path, text):
|
||||
checked += 1
|
||||
computed = name2nid(export_name)
|
||||
if computed == nid:
|
||||
continue
|
||||
|
||||
if nid not in catalog_nids:
|
||||
skipped_no_catalog += 1
|
||||
continue
|
||||
|
||||
if nid in ALLOWLISTED_NIDS:
|
||||
allowlisted += 1
|
||||
continue
|
||||
|
||||
mismatches.append((path, line, nid, export_name, computed))
|
||||
|
||||
return checked, mismatches, skipped_no_catalog, allowlisted
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Check that SysAbiExport ExportName values hash to their Nid via name2nid."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--strict",
|
||||
action="store_true",
|
||||
help="Exit 1 when any non-skipped/non-allowlisted ExportName does not hash to its Nid.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--quiet",
|
||||
action="store_true",
|
||||
help="Print only the summary line.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
repo_root = find_repo_root()
|
||||
aerolib_path = repo_root / AEROLIB_BIN
|
||||
if not aerolib_path.is_file():
|
||||
raise SystemExit(f"Missing Aerolib catalog: {aerolib_path.as_posix()}")
|
||||
|
||||
catalog_nids = load_aerolib_nids(aerolib_path)
|
||||
checked, mismatches, skipped_no_catalog, allowlisted = scan(
|
||||
repo_root / SRC_ROOT, catalog_nids
|
||||
)
|
||||
ok = checked - len(mismatches) - skipped_no_catalog - allowlisted
|
||||
|
||||
if not args.quiet:
|
||||
for path, line, nid, export_name, computed in mismatches:
|
||||
rel = path.relative_to(repo_root).as_posix()
|
||||
print(
|
||||
f"{rel}:{line}: NID={nid} ExportName={export_name!r} "
|
||||
f"computed={computed}"
|
||||
)
|
||||
|
||||
print(
|
||||
f"checked={checked} ok={ok} fail={len(mismatches)} "
|
||||
f"skipped_no_catalog={skipped_no_catalog} allowlisted={allowlisted} "
|
||||
f"allowlist_size={len(ALLOWLISTED_NIDS)}"
|
||||
)
|
||||
|
||||
if args.strict and mismatches:
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+37
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
# Copyright (C) 2026 SharpEmu Emulator Project
|
||||
# SPDX-License-Identifier: GPL-2.0-or-later
|
||||
#
|
||||
# Downloads the official (universal x86_64+arm64) MoltenVK dylib and stages
|
||||
# it next to a SharpEmu build as libvulkan.1.dylib. The macOS build runs as
|
||||
# an x86-64 process under Rosetta 2, so Homebrew's arm64-only Vulkan
|
||||
# libraries cannot be used; the presenter looks for this app-local copy.
|
||||
#
|
||||
# Usage: scripts/fetch-macos-moltenvk.sh [output-dir]
|
||||
# (default output: artifacts/bin/Debug/net10.0/osx-x64)
|
||||
set -euo pipefail
|
||||
|
||||
MVK_VERSION="${MVK_VERSION:-v1.4.0}"
|
||||
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
OUT_DIR="${1:-$REPO_ROOT/artifacts/bin/Debug/net10.0/osx-x64}"
|
||||
|
||||
if [[ ! -d "$OUT_DIR" ]]; then
|
||||
echo "output directory does not exist: $OUT_DIR (build first?)" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
WORK_DIR="$(mktemp -d)"
|
||||
trap 'rm -rf "$WORK_DIR"' EXIT
|
||||
|
||||
echo ">> Downloading MoltenVK $MVK_VERSION..."
|
||||
curl -sL -o "$WORK_DIR/mvk.tar" \
|
||||
"https://github.com/KhronosGroup/MoltenVK/releases/download/$MVK_VERSION/MoltenVK-macos.tar"
|
||||
tar -xf "$WORK_DIR/mvk.tar" -C "$WORK_DIR" \
|
||||
MoltenVK/MoltenVK/dynamic/dylib/macOS/libMoltenVK.dylib
|
||||
|
||||
DYLIB="$WORK_DIR/MoltenVK/MoltenVK/dynamic/dylib/macOS/libMoltenVK.dylib"
|
||||
file "$DYLIB" | grep -q x86_64 || { echo "downloaded dylib lacks x86_64 slice" >&2; exit 3; }
|
||||
|
||||
cp "$DYLIB" "$OUT_DIR/libMoltenVK.dylib"
|
||||
cp "$DYLIB" "$OUT_DIR/libvulkan.1.dylib"
|
||||
echo ">> Staged libMoltenVK.dylib + libvulkan.1.dylib in $OUT_DIR"
|
||||
@@ -3,8 +3,8 @@
|
||||
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import struct
|
||||
import hashlib
|
||||
import struct
|
||||
from base64 import b64encode as base64enc
|
||||
from binascii import unhexlify as uhx
|
||||
from pathlib import Path
|
||||
@@ -21,7 +21,7 @@ def name2nid(name):
|
||||
def generate():
|
||||
names_path = Path(NAMES)
|
||||
output_path = Path(OUTPUT)
|
||||
|
||||
|
||||
entries = []
|
||||
with open(names_path, 'r', encoding='utf-8') as f:
|
||||
for line in f:
|
||||
@@ -29,12 +29,12 @@ def generate():
|
||||
if name:
|
||||
nid = name2nid(name)
|
||||
entries.append((nid, name))
|
||||
|
||||
|
||||
print(f"Found {len(entries)} entries")
|
||||
|
||||
data = bytearray()
|
||||
data.extend(struct.pack('<I', len(entries)))
|
||||
|
||||
|
||||
for nid, name in entries:
|
||||
nid_bytes = nid.encode('utf-8')
|
||||
name_bytes = name.encode('utf-8')
|
||||
@@ -42,10 +42,11 @@ def generate():
|
||||
data.extend(nid_bytes)
|
||||
data.extend(struct.pack('<H', len(name_bytes)))
|
||||
data.extend(name_bytes)
|
||||
|
||||
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(output_path, 'wb') as f:
|
||||
f.write(data)
|
||||
|
||||
|
||||
print(f"Generated: {output_path} ({len(data):,} bytes)")
|
||||
print(f"Total entries: {len(entries)}")
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bash
|
||||
# Copyright (C) 2026 SharpEmu Emulator Project
|
||||
# SPDX-License-Identifier: GPL-2.0-or-later
|
||||
#
|
||||
# Smoke-tests the linux-x64 build inside an amd64 container. Useful from any
|
||||
# host (including Apple Silicon, where Docker runs the amd64 image under
|
||||
# emulation) to confirm the cross-platform layer keeps working on Linux.
|
||||
#
|
||||
# Usage: scripts/test-linux-docker.sh /path/to/eboot.bin
|
||||
set -euo pipefail
|
||||
|
||||
GAME_PATH="${1:-}"
|
||||
if [[ -z "$GAME_PATH" || ! -f "$GAME_PATH" ]]; then
|
||||
echo "usage: $0 <path-to-eboot.bin>" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
GAME_DIR="$(cd "$(dirname "$GAME_PATH")" && pwd)"
|
||||
GAME_FILE="$(basename "$GAME_PATH")"
|
||||
PUBLISH_DIR="$REPO_ROOT/artifacts/publish/SharpEmu.CLI/Debug/net10.0/linux-x64"
|
||||
|
||||
echo ">> Publishing linux-x64 self-contained build..."
|
||||
dotnet publish "$REPO_ROOT/src/SharpEmu.CLI" \
|
||||
-c Debug -r linux-x64 --self-contained -p:PublishSingleFile=false
|
||||
|
||||
echo ">> Running inside linux/amd64 container..."
|
||||
docker run --rm --platform linux/amd64 \
|
||||
-v "$PUBLISH_DIR":/app:ro \
|
||||
-v "$GAME_DIR":/game:ro \
|
||||
mcr.microsoft.com/dotnet/runtime-deps:10.0 \
|
||||
/app/SharpEmu --log-level=info "/game/$GAME_FILE"
|
||||
+504
-13
@@ -5,15 +5,19 @@ using SharpEmu.Core.Runtime;
|
||||
using SharpEmu.Core.Cpu;
|
||||
using SharpEmu.GUI;
|
||||
using SharpEmu.HLE;
|
||||
using SharpEmu.Libs.VideoOut;
|
||||
using SharpEmu.Logging;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace SharpEmu.CLI;
|
||||
|
||||
internal static partial class Program
|
||||
{
|
||||
private static readonly SharpEmuLogger Log = SharpEmuLog.For("SharpEmu.CLI");
|
||||
private static readonly object ConsoleMirrorSync = new();
|
||||
private static StreamWriter? _consoleMirrorFile;
|
||||
private const int DefaultImportTraceLimit = 32;
|
||||
private const string MitigatedChildFlag = "--sharpemu-mitigated-child";
|
||||
private const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000;
|
||||
@@ -21,11 +25,15 @@ internal static partial class Program
|
||||
private const int PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY = 0x00020007;
|
||||
private const uint JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000;
|
||||
private const int JobObjectExtendedLimitInformation = 9;
|
||||
private const int STARTF_USESTDHANDLES = 0x00000100;
|
||||
private const uint HANDLE_FLAG_INHERIT = 0x00000001;
|
||||
private const string MitigatedChildEnvironment = "SHARPEMU_MITIGATED_CHILD";
|
||||
private const ulong PROCESS_CREATION_MITIGATION_POLICY_CONTROL_FLOW_GUARD_ALWAYS_OFF = 0x00000002UL << 40;
|
||||
private const ulong PROCESS_CREATION_MITIGATION_POLICY2_CET_USER_SHADOW_STACKS_ALWAYS_OFF = 0x00000002UL << 28;
|
||||
private const ulong PROCESS_CREATION_MITIGATION_POLICY2_USER_CET_SET_CONTEXT_IP_VALIDATION_ALWAYS_OFF = 0x00000002UL << 32;
|
||||
private const ulong PROCESS_CREATION_MITIGATION_POLICY2_XTENDED_CONTROL_FLOW_GUARD_ALWAYS_OFF = 0x00000002UL << 40;
|
||||
private const int ATTACH_PARENT_PROCESS = -1;
|
||||
private const int STD_INPUT_HANDLE = -10;
|
||||
private const int STD_OUTPUT_HANDLE = -11;
|
||||
private const int STD_ERROR_HANDLE = -12;
|
||||
private const uint GENERIC_READ = 0x80000000;
|
||||
@@ -43,6 +51,7 @@ internal static partial class Program
|
||||
}
|
||||
finally
|
||||
{
|
||||
DropConsoleFileMirror();
|
||||
SharpEmuLog.Shutdown();
|
||||
}
|
||||
}
|
||||
@@ -61,7 +70,126 @@ internal static partial class Program
|
||||
// itself to a console before the first write.
|
||||
EnsureCliConsole();
|
||||
UseUtf8ConsoleOutput();
|
||||
if (isMitigatedChild && TryGetLogFileArgument(args, out var earlyLogFilePath))
|
||||
{
|
||||
TryEnableConsoleFileMirror(earlyLogFilePath);
|
||||
}
|
||||
|
||||
if (!CheckHostArchitecture())
|
||||
{
|
||||
return 5;
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsMacOS() || OperatingSystem.IsLinux())
|
||||
{
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
PreloadMacVulkanLoader();
|
||||
}
|
||||
|
||||
// GLFW requires window creation and event processing on the
|
||||
// process main thread: AppKit demands it on macOS, and X11 has a
|
||||
// single event queue that must be serviced from the main thread
|
||||
// (a window created and polled off it may never map, which showed
|
||||
// as a running game with no visible window on Linux). Emulation
|
||||
// moves to a worker thread and the main thread services the window
|
||||
// work the video presenter posts. Windows keeps a per-thread event
|
||||
// queue, so its window stays on the presenter's own thread.
|
||||
var exitCode = 0;
|
||||
HostMainThread.Enable();
|
||||
var emulation = new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
exitCode = RunEmulator(args, isMitigatedChild);
|
||||
}
|
||||
finally
|
||||
{
|
||||
HostMainThread.Shutdown();
|
||||
}
|
||||
}, 32 * 1024 * 1024)
|
||||
{
|
||||
Name = "SharpEmu Emulation",
|
||||
};
|
||||
emulation.Start();
|
||||
HostMainThread.Pump();
|
||||
emulation.Join();
|
||||
return exitCode;
|
||||
}
|
||||
|
||||
return RunEmulator(args, isMitigatedChild);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The supported host execution model, checked before any emulation
|
||||
/// starts: the CPU backend executes guest x86-64 code natively, so the
|
||||
/// host process must be x86-64 — win-x64/linux-x64 on x64 hardware, or
|
||||
/// osx-x64 under Rosetta 2 on Apple Silicon (Rosetta translates the
|
||||
/// whole process, so it still reports as X64 here). An arm64 process
|
||||
/// (e.g. the osx-arm64 build) can browse the GUI but cannot run games;
|
||||
/// failing up front distinguishes that from MoltenVK, signal-handler,
|
||||
/// or guest-memory startup problems.
|
||||
/// </summary>
|
||||
private static bool CheckHostArchitecture()
|
||||
{
|
||||
if (RuntimeInformation.ProcessArchitecture == Architecture.X64)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
Console.Error.WriteLine(
|
||||
$"[LOADER][ERROR] Unsupported process architecture " +
|
||||
$"{RuntimeInformation.ProcessArchitecture}: guest code executes " +
|
||||
"natively, so SharpEmu must run as an x86-64 process.");
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
Console.Error.WriteLine(
|
||||
"[LOADER][ERROR] On Apple Silicon, use the osx-x64 build under " +
|
||||
"Rosetta 2 (install with: softwareupdate --install-rosetta).");
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes a Vulkan loader visible to GLFW's dlopen("libvulkan.1.dylib").
|
||||
/// Homebrew's Vulkan libraries are arm64-only and cannot load into this
|
||||
/// x86-64 (Rosetta 2) process, so a universal libMoltenVK.dylib placed
|
||||
/// next to the executable (named libvulkan.1.dylib) is preloaded here;
|
||||
/// dyld then resolves GLFW's bare-name dlopen to the loaded image.
|
||||
/// </summary>
|
||||
private static void PreloadMacVulkanLoader()
|
||||
{
|
||||
var candidates = new[]
|
||||
{
|
||||
Path.Combine(AppContext.BaseDirectory, "libvulkan.1.dylib"),
|
||||
Path.Combine(AppContext.BaseDirectory, "libMoltenVK.dylib"),
|
||||
Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
|
||||
".sharpemu", "x64lib", "libvulkan.1.dylib"),
|
||||
};
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
if (File.Exists(candidate) && NativeLibrary.TryLoad(candidate, out _))
|
||||
{
|
||||
Console.Error.WriteLine($"[LOADER][INFO] Vulkan loader preloaded: {candidate}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (NativeLibrary.TryLoad("libvulkan.1.dylib", out _))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Console.Error.WriteLine(
|
||||
"[LOADER][WARN] No x86-64 Vulkan loader found; video output will be unavailable. " +
|
||||
"Place a universal libMoltenVK.dylib (from the MoltenVK releases) next to SharpEmu " +
|
||||
"as libvulkan.1.dylib.");
|
||||
}
|
||||
|
||||
private static int RunEmulator(string[] args, bool isMitigatedChild)
|
||||
{
|
||||
Console.Error.WriteLine($"[DEBUG] SharpEmu starting with {args.Length} args");
|
||||
|
||||
if (!isMitigatedChild && TryRunMitigatedChild(args, out var childExitCode))
|
||||
@@ -69,15 +197,21 @@ internal static partial class Program
|
||||
return childExitCode;
|
||||
}
|
||||
|
||||
if (!TryParseArguments(args, out var ebootPath, out var runtimeOptions, out var logLevel))
|
||||
if (!TryParseArguments(args, out var ebootPath, out var runtimeOptions, out var logLevel, out var logFilePath))
|
||||
{
|
||||
PrintUsage();
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!isMitigatedChild && !string.IsNullOrWhiteSpace(logFilePath))
|
||||
{
|
||||
TryEnableConsoleFileMirror(logFilePath);
|
||||
}
|
||||
|
||||
SharpEmuLog.MinimumLevel = logLevel;
|
||||
|
||||
Log.Info(BuildInfo.Banner);
|
||||
Log.Info(HostSystemInfo.Summary);
|
||||
|
||||
ebootPath = Path.GetFullPath(ebootPath);
|
||||
Console.Error.WriteLine($"[DEBUG] Full path: {ebootPath}");
|
||||
@@ -93,8 +227,16 @@ internal static partial class Program
|
||||
using var runtime = SharpEmuRuntime.CreateDefault(runtimeOptions);
|
||||
|
||||
OrbisGen2Result result;
|
||||
ConsoleCancelEventHandler? cancelHandler = null;
|
||||
try
|
||||
{
|
||||
cancelHandler = (_, eventArgs) =>
|
||||
{
|
||||
eventArgs.Cancel = true;
|
||||
VideoOutExports.NotifyHostInterrupt();
|
||||
};
|
||||
Console.CancelKeyPress += cancelHandler;
|
||||
|
||||
Console.Error.WriteLine($"[DEBUG] Running: {ebootPath}");
|
||||
result = runtime.Run(ebootPath);
|
||||
Console.Error.WriteLine($"[DEBUG] Result: {result}");
|
||||
@@ -105,6 +247,13 @@ internal static partial class Program
|
||||
Log.Error("SharpEmu failed to run.", ex);
|
||||
return 3;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (cancelHandler is not null)
|
||||
{
|
||||
Console.CancelKeyPress -= cancelHandler;
|
||||
}
|
||||
}
|
||||
|
||||
Log.Info($"SharpEmu execution completed. Result={result} (0x{(int)result:X8})");
|
||||
if (!string.IsNullOrWhiteSpace(runtime.LastSessionSummary))
|
||||
@@ -234,6 +383,10 @@ internal static partial class Program
|
||||
private static string[] NormalizeInternalArguments(string[] args, out bool isMitigatedChild)
|
||||
{
|
||||
isMitigatedChild = false;
|
||||
var trustedMitigatedChild = string.Equals(
|
||||
Environment.GetEnvironmentVariable(MitigatedChildEnvironment),
|
||||
"1",
|
||||
StringComparison.Ordinal);
|
||||
if (args.Length == 0)
|
||||
{
|
||||
return args;
|
||||
@@ -244,7 +397,7 @@ internal static partial class Program
|
||||
{
|
||||
if (string.Equals(arg, MitigatedChildFlag, StringComparison.Ordinal))
|
||||
{
|
||||
isMitigatedChild = true;
|
||||
isMitigatedChild = trustedMitigatedChild;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -283,9 +436,11 @@ internal static partial class Program
|
||||
var commandLine = BuildCommandLine(processPath, childArgs);
|
||||
var startupInfoEx = new STARTUPINFOEX();
|
||||
startupInfoEx.StartupInfo.cb = Marshal.SizeOf<STARTUPINFOEX>();
|
||||
ConfigureInheritedStdHandles(ref startupInfoEx.StartupInfo);
|
||||
|
||||
nint attributeList = 0;
|
||||
nint mitigationPolicies = 0;
|
||||
var previousChildEnvironment = Environment.GetEnvironmentVariable(MitigatedChildEnvironment);
|
||||
try
|
||||
{
|
||||
nuint attributeListSize = 0;
|
||||
@@ -293,7 +448,9 @@ internal static partial class Program
|
||||
attributeList = Marshal.AllocHGlobal((nint)attributeListSize);
|
||||
if (!InitializeProcThreadAttributeList(attributeList, 1, 0, ref attributeListSize))
|
||||
{
|
||||
return false;
|
||||
childExitCode = 5;
|
||||
Console.Error.WriteLine($"[ERROR] Failed to initialize mitigation attributes: {Marshal.GetLastWin32Error()}");
|
||||
return true;
|
||||
}
|
||||
|
||||
startupInfoEx.lpAttributeList = attributeList;
|
||||
@@ -301,8 +458,7 @@ internal static partial class Program
|
||||
var policy1 = PROCESS_CREATION_MITIGATION_POLICY_CONTROL_FLOW_GUARD_ALWAYS_OFF;
|
||||
var policy2 =
|
||||
PROCESS_CREATION_MITIGATION_POLICY2_CET_USER_SHADOW_STACKS_ALWAYS_OFF |
|
||||
PROCESS_CREATION_MITIGATION_POLICY2_USER_CET_SET_CONTEXT_IP_VALIDATION_ALWAYS_OFF |
|
||||
PROCESS_CREATION_MITIGATION_POLICY2_XTENDED_CONTROL_FLOW_GUARD_ALWAYS_OFF;
|
||||
PROCESS_CREATION_MITIGATION_POLICY2_USER_CET_SET_CONTEXT_IP_VALIDATION_ALWAYS_OFF;
|
||||
|
||||
mitigationPolicies = Marshal.AllocHGlobal(sizeof(ulong) * 2);
|
||||
Marshal.WriteInt64(mitigationPolicies, unchecked((long)policy1));
|
||||
@@ -317,24 +473,31 @@ internal static partial class Program
|
||||
0,
|
||||
0))
|
||||
{
|
||||
return false;
|
||||
childExitCode = 5;
|
||||
Console.Error.WriteLine($"[ERROR] Failed to apply mitigation attributes: {Marshal.GetLastWin32Error()}");
|
||||
return true;
|
||||
}
|
||||
|
||||
var cmdLineBuilder = new StringBuilder(commandLine);
|
||||
nint jobHandle = 0;
|
||||
if (!CreateProcessW(
|
||||
Environment.SetEnvironmentVariable(MitigatedChildEnvironment, "1");
|
||||
var created = CreateProcessW(
|
||||
processPath,
|
||||
cmdLineBuilder,
|
||||
0,
|
||||
0,
|
||||
false,
|
||||
true,
|
||||
EXTENDED_STARTUPINFO_PRESENT,
|
||||
0,
|
||||
Environment.CurrentDirectory,
|
||||
ref startupInfoEx,
|
||||
out var processInfo))
|
||||
out var processInfo);
|
||||
Environment.SetEnvironmentVariable(MitigatedChildEnvironment, previousChildEnvironment);
|
||||
if (!created)
|
||||
{
|
||||
return false;
|
||||
childExitCode = 5;
|
||||
Console.Error.WriteLine($"[ERROR] Failed to launch mitigated child process: {Marshal.GetLastWin32Error()}");
|
||||
return true;
|
||||
}
|
||||
|
||||
try
|
||||
@@ -388,6 +551,8 @@ internal static partial class Program
|
||||
}
|
||||
finally
|
||||
{
|
||||
Environment.SetEnvironmentVariable(MitigatedChildEnvironment, previousChildEnvironment);
|
||||
|
||||
if (attributeList != 0)
|
||||
{
|
||||
DeleteProcThreadAttributeList(attributeList);
|
||||
@@ -401,6 +566,238 @@ internal static partial class Program
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryGetLogFileArgument(IReadOnlyList<string> args, out string path)
|
||||
{
|
||||
for (var i = 0; i < args.Count; i++)
|
||||
{
|
||||
var argument = args[i];
|
||||
if (string.Equals(argument, "--log-file", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (i + 1 < args.Count &&
|
||||
!string.IsNullOrWhiteSpace(args[i + 1]) &&
|
||||
!args[i + 1].StartsWith("--", StringComparison.Ordinal) &&
|
||||
ShouldConsumeLogFilePath(args, i + 1))
|
||||
{
|
||||
path = args[i + 1];
|
||||
return true;
|
||||
}
|
||||
|
||||
path = BuildDefaultLogFilePath(TryFindEbootPathToken(args));
|
||||
return true;
|
||||
}
|
||||
|
||||
const string logFilePrefix = "--log-file=";
|
||||
if (argument.StartsWith(logFilePrefix, StringComparison.OrdinalIgnoreCase) &&
|
||||
!string.IsNullOrWhiteSpace(argument[logFilePrefix.Length..]))
|
||||
{
|
||||
path = argument[logFilePrefix.Length..];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
path = string.Empty;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static string BuildDefaultLogFilePath(string? ebootPath)
|
||||
{
|
||||
var baseDirectory = AppContext.BaseDirectory;
|
||||
var logsDirectory = Path.Combine(baseDirectory, "user", "logs");
|
||||
var name = TryReadTitleId(ebootPath) ?? "UNKNOWN";
|
||||
|
||||
foreach (var invalid in Path.GetInvalidFileNameChars())
|
||||
{
|
||||
name = name.Replace(invalid, '_');
|
||||
}
|
||||
|
||||
return Path.Combine(logsDirectory, $"{name}-{DateTime.Now:yyyyMMdd-HHmmss}.log");
|
||||
}
|
||||
|
||||
private static string? TryReadTitleId(string? ebootPath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(ebootPath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var directory = Path.GetDirectoryName(Path.GetFullPath(ebootPath));
|
||||
if (string.IsNullOrEmpty(directory))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (var paramPath in new[]
|
||||
{
|
||||
Path.Combine(directory, "sce_sys", "param.json"),
|
||||
Path.Combine(directory, "param.json"),
|
||||
})
|
||||
{
|
||||
if (!File.Exists(paramPath))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
using var stream = File.OpenRead(paramPath);
|
||||
using var document = JsonDocument.Parse(stream);
|
||||
if (document.RootElement.TryGetProperty("titleId", out var titleIdElement) &&
|
||||
titleIdElement.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
var titleId = titleIdElement.GetString();
|
||||
if (!string.IsNullOrWhiteSpace(titleId))
|
||||
{
|
||||
return titleId.Trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Logging should never block launch; unknown title ids use a stable fallback.
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? TryFindEbootPathToken(IReadOnlyList<string> args)
|
||||
{
|
||||
for (var i = args.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var argument = args[i];
|
||||
if (string.IsNullOrWhiteSpace(argument) ||
|
||||
argument.StartsWith("--", StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
return argument;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool ShouldConsumeLogFilePath(IReadOnlyList<string> args, int candidateIndex)
|
||||
{
|
||||
var candidate = args[candidateIndex];
|
||||
if (LooksLikeLogFilePath(candidate))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
for (var i = candidateIndex + 1; i < args.Count; i++)
|
||||
{
|
||||
var argument = args[i];
|
||||
if (!string.IsNullOrWhiteSpace(argument) &&
|
||||
!argument.StartsWith("--", StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool LooksLikeLogFilePath(string path)
|
||||
{
|
||||
var extension = Path.GetExtension(path);
|
||||
return string.Equals(extension, ".log", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(extension, ".txt", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static void TryEnableConsoleFileMirror(string path)
|
||||
{
|
||||
lock (ConsoleMirrorSync)
|
||||
{
|
||||
if (_consoleMirrorFile is not null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var directory = Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrEmpty(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
var stream = new FileStream(
|
||||
path,
|
||||
FileMode.Create,
|
||||
FileAccess.Write,
|
||||
FileShare.ReadWrite,
|
||||
bufferSize: 4096,
|
||||
FileOptions.SequentialScan);
|
||||
_consoleMirrorFile = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false))
|
||||
{
|
||||
AutoFlush = true,
|
||||
};
|
||||
|
||||
Console.SetOut(new TeeTextWriter(Console.Out, _consoleMirrorFile));
|
||||
Console.SetError(new TeeTextWriter(Console.Error, _consoleMirrorFile));
|
||||
Console.Error.WriteLine($"[DEBUG] Log file: {Path.GetFullPath(path)}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[WARN] Could not open log file '{path}': {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void DropConsoleFileMirror()
|
||||
{
|
||||
lock (ConsoleMirrorSync)
|
||||
{
|
||||
try
|
||||
{
|
||||
_consoleMirrorFile?.Flush();
|
||||
_consoleMirrorFile?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
_consoleMirrorFile = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void ConfigureInheritedStdHandles(ref STARTUPINFO startupInfo)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var input = GetStdHandle(STD_INPUT_HANDLE);
|
||||
var output = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
var error = GetStdHandle(STD_ERROR_HANDLE);
|
||||
if (!IsHandleValid(output) && !IsHandleValid(error))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsHandleValid(input))
|
||||
{
|
||||
_ = SetHandleInformation(input, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
|
||||
startupInfo.hStdInput = input;
|
||||
}
|
||||
|
||||
if (IsHandleValid(output))
|
||||
{
|
||||
_ = SetHandleInformation(output, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
|
||||
startupInfo.hStdOutput = output;
|
||||
}
|
||||
|
||||
if (IsHandleValid(error))
|
||||
{
|
||||
_ = SetHandleInformation(error, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
|
||||
startupInfo.hStdError = error;
|
||||
}
|
||||
|
||||
startupInfo.dwFlags |= STARTF_USESTDHANDLES;
|
||||
}
|
||||
|
||||
private static string BuildCommandLine(string processPath, IReadOnlyList<string> args)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
@@ -503,27 +900,30 @@ internal static partial class Program
|
||||
|
||||
private static void PrintUsage()
|
||||
{
|
||||
Log.Info("Usage: SharpEmu.CLI [--strict] [--trace-imports[=N]] [--cpu-engine=<native>] [--log-level=<level>] <path-to-eboot.bin>");
|
||||
Log.Info(@"Example: SharpEmu.CLI --cpu-engine=native --trace-imports=64 --log-level=debug ""E:\Games\...\eboot.bin""");
|
||||
Log.Info("Usage: SharpEmu.CLI [--strict] [--trace-imports[=N]] [--cpu-engine=<native>] [--log-level=<level>] [--log-file[=<path>]] <path-to-eboot.bin>");
|
||||
Log.Info(@"Example: SharpEmu.CLI --cpu-engine=native --trace-imports=64 --log-level=debug --log-file ""E:\Games\...\eboot.bin""");
|
||||
}
|
||||
|
||||
private static bool TryParseArguments(
|
||||
string[] args,
|
||||
out string ebootPath,
|
||||
out SharpEmuRuntimeOptions runtimeOptions,
|
||||
out LogLevel logLevel)
|
||||
out LogLevel logLevel,
|
||||
out string? logFilePath)
|
||||
{
|
||||
if (args.Length == 0)
|
||||
{
|
||||
ebootPath = string.Empty;
|
||||
runtimeOptions = default;
|
||||
logLevel = SharpEmuLog.MinimumLevel;
|
||||
logFilePath = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
var strictDynlibResolution = false;
|
||||
var importTraceLimit = 0;
|
||||
var cpuEngine = CpuExecutionEngine.NativeOnly;
|
||||
logFilePath = null;
|
||||
logLevel = SharpEmuLog.MinimumLevel;
|
||||
var pathTokens = new List<string>(args.Length);
|
||||
for (var i = 0; i < args.Length; i++)
|
||||
@@ -553,6 +953,7 @@ internal static partial class Program
|
||||
{
|
||||
ebootPath = string.Empty;
|
||||
runtimeOptions = default;
|
||||
logFilePath = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -566,6 +967,7 @@ internal static partial class Program
|
||||
{
|
||||
ebootPath = string.Empty;
|
||||
runtimeOptions = default;
|
||||
logFilePath = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -573,6 +975,23 @@ internal static partial class Program
|
||||
continue;
|
||||
}
|
||||
|
||||
if (string.Equals(argument, "--log-file", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (i + 1 < args.Length &&
|
||||
!string.IsNullOrWhiteSpace(args[i + 1]) &&
|
||||
!args[i + 1].StartsWith("--", StringComparison.Ordinal) &&
|
||||
ShouldConsumeLogFilePath(args, i + 1))
|
||||
{
|
||||
logFilePath = args[++i];
|
||||
}
|
||||
else
|
||||
{
|
||||
logFilePath = BuildDefaultLogFilePath(TryFindEbootPathToken(args));
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
const string logLevelPrefix = "--log-level=";
|
||||
if (argument.StartsWith(logLevelPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
@@ -596,6 +1015,7 @@ internal static partial class Program
|
||||
ebootPath = string.Empty;
|
||||
runtimeOptions = default;
|
||||
logLevel = SharpEmuLog.MinimumLevel;
|
||||
logFilePath = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -618,11 +1038,27 @@ internal static partial class Program
|
||||
continue;
|
||||
}
|
||||
|
||||
const string logFilePrefix = "--log-file=";
|
||||
if (argument.StartsWith(logFilePrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
logFilePath = argument[logFilePrefix.Length..];
|
||||
if (string.IsNullOrWhiteSpace(logFilePath))
|
||||
{
|
||||
ebootPath = string.Empty;
|
||||
runtimeOptions = default;
|
||||
logLevel = SharpEmuLog.MinimumLevel;
|
||||
return false;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (argument.StartsWith("--", StringComparison.Ordinal))
|
||||
{
|
||||
ebootPath = string.Empty;
|
||||
runtimeOptions = default;
|
||||
logLevel = SharpEmuLog.MinimumLevel;
|
||||
logFilePath = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -634,6 +1070,7 @@ internal static partial class Program
|
||||
ebootPath = string.Empty;
|
||||
runtimeOptions = default;
|
||||
logLevel = SharpEmuLog.MinimumLevel;
|
||||
logFilePath = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -735,6 +1172,56 @@ internal static partial class Program
|
||||
public nuint PeakJobMemoryUsed;
|
||||
}
|
||||
|
||||
private sealed class TeeTextWriter : TextWriter
|
||||
{
|
||||
private readonly TextWriter _primary;
|
||||
private readonly TextWriter _mirror;
|
||||
|
||||
public TeeTextWriter(TextWriter primary, TextWriter mirror)
|
||||
{
|
||||
_primary = primary;
|
||||
_mirror = mirror;
|
||||
}
|
||||
|
||||
public override Encoding Encoding => _primary.Encoding;
|
||||
|
||||
public override void Write(char value)
|
||||
{
|
||||
lock (ConsoleMirrorSync)
|
||||
{
|
||||
_primary.Write(value);
|
||||
_mirror.Write(value);
|
||||
}
|
||||
}
|
||||
|
||||
public override void Write(string? value)
|
||||
{
|
||||
lock (ConsoleMirrorSync)
|
||||
{
|
||||
_primary.Write(value);
|
||||
_mirror.Write(value);
|
||||
}
|
||||
}
|
||||
|
||||
public override void WriteLine(string? value)
|
||||
{
|
||||
lock (ConsoleMirrorSync)
|
||||
{
|
||||
_primary.WriteLine(value);
|
||||
_mirror.WriteLine(value);
|
||||
}
|
||||
}
|
||||
|
||||
public override void Flush()
|
||||
{
|
||||
lock (ConsoleMirrorSync)
|
||||
{
|
||||
_primary.Flush();
|
||||
_mirror.Flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool InitializeProcThreadAttributeList(
|
||||
@@ -819,6 +1306,10 @@ internal static partial class Program
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool SetStdHandle(int stdHandle, nint handle);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool SetHandleInformation(nint handle, uint mask, uint flags);
|
||||
|
||||
[DllImport("kernel32.dll", EntryPoint = "CreateFileW", SetLastError = true, CharSet = CharSet.Unicode)]
|
||||
private static extern nint CreateFileW(
|
||||
string fileName,
|
||||
|
||||
@@ -16,14 +16,28 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
console window; CLI mode re-attaches to the parent terminal's console. -->
|
||||
<OutputType>WinExe</OutputType>
|
||||
<AssemblyName>SharpEmu</AssemblyName>
|
||||
<RuntimeIdentifiers>win-x64;linux-x64;osx-arm64</RuntimeIdentifiers>
|
||||
<!-- osx-x64 is the macOS target: the CPU backend executes guest x86-64
|
||||
natively, so on Apple Silicon it runs under Rosetta 2. -->
|
||||
<RuntimeIdentifiers>win-x64;linux-x64;osx-x64;osx-arm64</RuntimeIdentifiers>
|
||||
<SelfContained>true</SelfContained>
|
||||
<PublishSingleFile>true</PublishSingleFile>
|
||||
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
|
||||
<EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<Version>0.0.1</Version>
|
||||
<ServerGarbageCollection>true</ServerGarbageCollection>
|
||||
<ConcurrentGarbageCollection>true</ConcurrentGarbageCollection>
|
||||
<TieredPGO>true</TieredPGO>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Background GC's write-watch revisit calls FlushProcessWriteBuffers,
|
||||
which on macOS uses thread_get_register_pointer_values; under Rosetta 2
|
||||
that Mach call can stall indefinitely on threads executing translated
|
||||
guest code, wedging the whole runtime (every allocating thread then
|
||||
blocks behind the never-finishing GC). Non-concurrent GC never takes
|
||||
that path. Windows and Linux keep concurrent GC. -->
|
||||
<PropertyGroup Condition="$([System.String]::Copy('$(RuntimeIdentifier)').StartsWith('osx'))">
|
||||
<ConcurrentGarbageCollection>false</ConcurrentGarbageCollection>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
|
||||
@@ -48,6 +62,11 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
<TargetPath>LICENSE.txt</TargetPath>
|
||||
<Visible>False</Visible>
|
||||
</Content>
|
||||
<Content Include="..\SharpEmu.GUI\Languages\*.json" Condition="'$(Configuration)' != 'Release'">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<TargetPath>Languages\%(Filename)%(Extension)</TargetPath>
|
||||
<Visible>False</Visible>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Keep glfw as a loose file next to the executable; every other native
|
||||
@@ -55,7 +74,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
<Target Name="KeepGlfwOutsideSingleFile" AfterTargets="ComputeResolvedFilesToPublishList">
|
||||
<ItemGroup>
|
||||
<_GlfwPublishFiles Include="@(ResolvedFileToPublish)"
|
||||
Condition="$([System.String]::Copy('%(ResolvedFileToPublish.Filename)').StartsWith('glfw'))" />
|
||||
Condition="$([System.String]::Copy('%(ResolvedFileToPublish.Filename)').StartsWith('glfw')) Or $([System.String]::Copy('%(ResolvedFileToPublish.Filename)').StartsWith('libglfw'))" />
|
||||
<ResolvedFileToPublish Remove="@(_GlfwPublishFiles)" />
|
||||
<ResolvedFileToPublish Include="@(_GlfwPublishFiles)">
|
||||
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
|
||||
|
||||
@@ -135,6 +135,23 @@
|
||||
"Ultz.Native.GLFW": "3.4.0"
|
||||
}
|
||||
},
|
||||
"Silk.NET.Input.Common": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.23.0",
|
||||
"contentHash": "QbJVV7kFBHEByayXCYdJtXXI9Sp4a+QAf0IdGV6uCWkFYcEmqBYW3aaNGvFOdSwTBDbHL5T/OtOCrGh4qYhk7A==",
|
||||
"dependencies": {
|
||||
"Silk.NET.Windowing.Common": "2.23.0"
|
||||
}
|
||||
},
|
||||
"Silk.NET.Input.Glfw": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.23.0",
|
||||
"contentHash": "KGHYqsv/IQRJtD6dloYh2tN4CkaM40vxM2kj0cGKBoCQiBDYHHhJiyDTyMPx0W7Fz5IgnhnG42ELmIAa0DH69A==",
|
||||
"dependencies": {
|
||||
"Silk.NET.Input.Common": "2.23.0",
|
||||
"Silk.NET.Windowing.Glfw": "2.23.0"
|
||||
}
|
||||
},
|
||||
"Silk.NET.Maths": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.23.0",
|
||||
@@ -225,6 +242,7 @@
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"SharpEmu.HLE": "[1.0.0, )",
|
||||
"Silk.NET.Input": "[2.23.0, )",
|
||||
"Silk.NET.Vulkan": "[2.23.0, )",
|
||||
"Silk.NET.Vulkan.Extensions.EXT": "[2.23.0, )",
|
||||
"Silk.NET.Vulkan.Extensions.KHR": "[2.23.0, )",
|
||||
@@ -282,6 +300,16 @@
|
||||
"resolved": "1.21.0",
|
||||
"contentHash": "dv5+81Q1TBQvVMSOOOmRcjJmvWcX3BZPZsIq31+RLc5cNft0IHAyNlkdb7ZarOWG913PyBoFDsDXoCIlKmLclg=="
|
||||
},
|
||||
"Silk.NET.Input": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[2.23.0, )",
|
||||
"resolved": "2.23.0",
|
||||
"contentHash": "Xzl+tVwAp2eEd8blmGQjmJrsZPnp3PWG0KJjiAQHaY2Zr/ELVWeAROKXmZdCAvexzmte2JVGEy/dxnMycbxlpg==",
|
||||
"dependencies": {
|
||||
"Silk.NET.Input.Common": "2.23.0",
|
||||
"Silk.NET.Input.Glfw": "2.23.0"
|
||||
}
|
||||
},
|
||||
"Silk.NET.Vulkan": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[2.23.0, )",
|
||||
@@ -434,6 +462,59 @@
|
||||
"contentHash": "Iy22JopynbOJ32vA0lBhFEzGi65GQJBuJHYBYRBpydrDpNoTiHnjIXfA65Gu+8qsOr/ZEoIF8r9aHCgAXuO6DA=="
|
||||
}
|
||||
},
|
||||
"net10.0/osx-x64": {
|
||||
"Avalonia.Angle.Windows.Natives": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.25547.20250602",
|
||||
"contentHash": "ZL0VLc4s9rvNNFt19Pxm5UNAkmKNylugAwJPX9ulXZ6JWs/l6XZihPWWTyezaoNOVyEPU8YbURtW7XMAtqXH5A=="
|
||||
},
|
||||
"Avalonia.Native": {
|
||||
"type": "Transitive",
|
||||
"resolved": "11.3.18",
|
||||
"contentHash": "8g53DROFW6wVJAnTsE1Iu5bdZO5r0oqxbdbMQODs1QDYCK2IU/y/x/vQVKCYOvqxl4tXkzU9tExv8XqSGPWthQ==",
|
||||
"dependencies": {
|
||||
"Avalonia": "11.3.18"
|
||||
}
|
||||
},
|
||||
"HarfBuzzSharp.NativeAssets.Linux": {
|
||||
"type": "Transitive",
|
||||
"resolved": "8.3.1.1",
|
||||
"contentHash": "3EZ1mpIiKWRLL5hUYA82ZHteeDIVaEA/Z0rA/wU6tjx6crcAkJnBPwDXZugBSfo8+J3EznvRJf49uMsqYfKrHg=="
|
||||
},
|
||||
"HarfBuzzSharp.NativeAssets.macOS": {
|
||||
"type": "Transitive",
|
||||
"resolved": "8.3.1.1",
|
||||
"contentHash": "jbtCsgftcaFLCA13tVKo5iWdElJScrulLTKJre36O4YQTIlwDtPPqhRZNk+Y0vv4D1gxbscasGRucUDfS44ofQ=="
|
||||
},
|
||||
"HarfBuzzSharp.NativeAssets.Win32": {
|
||||
"type": "Transitive",
|
||||
"resolved": "8.3.1.1",
|
||||
"contentHash": "UsJtQsfAJoFDZrXc4hCUfRPMqccfKZ0iumJ/upcUjz/cmsTgVFGNEL5yaJWmkqsuFYdMWbj/En5/kS4PFl9hBA=="
|
||||
},
|
||||
"SkiaSharp.NativeAssets.Linux": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.88.9",
|
||||
"contentHash": "cWSaJKVPWAaT/WIn9c8T5uT/l4ETwHxNJTkEOtNKjphNo8AW6TF9O32aRkxqw3l8GUdUo66Bu7EiqtFh/XG0Zg==",
|
||||
"dependencies": {
|
||||
"SkiaSharp": "2.88.9"
|
||||
}
|
||||
},
|
||||
"SkiaSharp.NativeAssets.macOS": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.88.9",
|
||||
"contentHash": "Nv5spmKc4505Ep7oUoJ5vp3KweFpeNqxpyGDWyeEPTX2uR6S6syXIm3gj75dM0YJz7NPvcix48mR5laqs8dPuA=="
|
||||
},
|
||||
"SkiaSharp.NativeAssets.Win32": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.88.9",
|
||||
"contentHash": "wb2kYgU7iy84nQLYZwMeJXixvK++GoIuECjU4ECaUKNuflyRlJKyiRhN1MAHswvlvzuvkrjRWlK0Za6+kYQK7w=="
|
||||
},
|
||||
"Ultz.Native.GLFW": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.4.0",
|
||||
"contentHash": "Iy22JopynbOJ32vA0lBhFEzGi65GQJBuJHYBYRBpydrDpNoTiHnjIXfA65Gu+8qsOr/ZEoIF8r9aHCgAXuO6DA=="
|
||||
}
|
||||
},
|
||||
"net10.0/win-x64": {
|
||||
"Avalonia.Angle.Windows.Natives": {
|
||||
"type": "Transitive",
|
||||
|
||||
@@ -7,6 +7,7 @@ using SharpEmu.Core.Cpu.Native;
|
||||
using SharpEmu.Core.Loader;
|
||||
using SharpEmu.Core.Memory;
|
||||
using SharpEmu.HLE;
|
||||
using SharpEmu.HLE.Host;
|
||||
using SharpEmu.Logging;
|
||||
|
||||
namespace SharpEmu.Core.Cpu;
|
||||
@@ -21,15 +22,22 @@ public sealed class CpuDispatcher : ICpuDispatcher, IDisposable
|
||||
ModuleInitializer,
|
||||
}
|
||||
|
||||
private const ulong StackBaseAddress = 0x7FFF_F000_0000UL;
|
||||
// The top of the x86-64 user address space (0x7FFD..0x7FFF) is only
|
||||
// freely mappable on Windows; on macOS/Linux it hosts the dyld shared
|
||||
// cache / vdso and (under Rosetta 2) the translator runtime, so POSIX
|
||||
// hosts use the equivalent layout one slot lower at 0x6FFx.
|
||||
private static readonly ulong StackBaseAddress = OperatingSystem.IsWindows() ? 0x7FFF_F000_0000UL : 0x6FFF_F000_0000UL;
|
||||
private const ulong StackSize = 0x0020_0000UL;
|
||||
private const ulong TlsBaseAddress = 0x7FFE_0000_0000UL;
|
||||
private static readonly ulong TlsBaseAddress = OperatingSystem.IsWindows() ? 0x7FFE_0000_0000UL : 0x6FFE_0000_0000UL;
|
||||
private const ulong TlsSize = 0x0001_0000UL;
|
||||
private const ulong TlsPrefixSize = 0x0000_1000UL;
|
||||
private const ulong BootstrapStubBaseAddress = 0x7FFD_F000_0000UL;
|
||||
private const ulong BootstrapPayloadBaseAddress = 0x7FFD_E000_0000UL;
|
||||
private const ulong DynlibFallbackStubBaseAddress = 0x7FFD_D000_0000UL;
|
||||
private const ulong ReturnToHostStubBaseAddress = 0x7FFD_C000_0000UL;
|
||||
// The static TLS blocks live at negative offsets from the TCB (FreeBSD
|
||||
// amd64 variant II); libc.prx alone reaches beyond -0x1700, so give the
|
||||
// prefix a full 64KB on POSIX. Windows keeps its historical 4KB prefix.
|
||||
private static readonly ulong TlsPrefixSize = OperatingSystem.IsWindows() ? 0x0000_1000UL : 0x0001_0000UL;
|
||||
private static readonly ulong BootstrapStubBaseAddress = OperatingSystem.IsWindows() ? 0x7FFD_F000_0000UL : 0x6FFD_F000_0000UL;
|
||||
private static readonly ulong BootstrapPayloadBaseAddress = OperatingSystem.IsWindows() ? 0x7FFD_E000_0000UL : 0x6FFD_E000_0000UL;
|
||||
private static readonly ulong DynlibFallbackStubBaseAddress = OperatingSystem.IsWindows() ? 0x7FFD_D000_0000UL : 0x6FFD_D000_0000UL;
|
||||
private static readonly ulong ReturnToHostStubBaseAddress = OperatingSystem.IsWindows() ? 0x7FFD_C000_0000UL : 0x6FFD_C000_0000UL;
|
||||
private const ulong BootstrapRegionSize = 0x0000_1000UL;
|
||||
private const ulong ReturnToHostStubStride = 0x0100_0000UL;
|
||||
private const ulong BootstrapPayloadResultOffset = 0x28UL;
|
||||
@@ -41,16 +49,19 @@ public sealed class CpuDispatcher : ICpuDispatcher, IDisposable
|
||||
];
|
||||
private readonly IVirtualMemory _virtualMemory;
|
||||
private readonly IModuleManager _moduleManager;
|
||||
private readonly IHostPlatform? _hostPlatform;
|
||||
private INativeCpuBackend? _nativeCpuBackend;
|
||||
|
||||
public CpuDispatcher(
|
||||
IVirtualMemory virtualMemory,
|
||||
IModuleManager moduleManager,
|
||||
INativeCpuBackend? nativeCpuBackend = null)
|
||||
INativeCpuBackend? nativeCpuBackend = null,
|
||||
IHostPlatform? hostPlatform = null)
|
||||
{
|
||||
_virtualMemory = virtualMemory ?? throw new ArgumentNullException(nameof(virtualMemory));
|
||||
_moduleManager = moduleManager ?? throw new ArgumentNullException(nameof(moduleManager));
|
||||
_nativeCpuBackend = nativeCpuBackend;
|
||||
_hostPlatform = hostPlatform;
|
||||
}
|
||||
|
||||
public ulong? LastEntryPoint { get; private set; }
|
||||
@@ -266,7 +277,7 @@ public sealed class CpuDispatcher : ICpuDispatcher, IDisposable
|
||||
entryFrameDiagnostic,
|
||||
Environment.NewLine,
|
||||
"CpuEngine: native-only");
|
||||
_nativeCpuBackend ??= new DirectExecutionBackend(_moduleManager);
|
||||
_nativeCpuBackend ??= new DirectExecutionBackend(_moduleManager, _hostPlatform);
|
||||
if (_nativeCpuBackend.TryExecute(
|
||||
context,
|
||||
entryPoint,
|
||||
|
||||
@@ -8,6 +8,7 @@ using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using SharpEmu.HLE;
|
||||
using SharpEmu.HLE.Host;
|
||||
using SharpEmu.Logging;
|
||||
|
||||
namespace SharpEmu.Core.Cpu.Native;
|
||||
@@ -134,8 +135,9 @@ public sealed partial class DirectExecutionBackend
|
||||
int num2 = 0;
|
||||
List<ulong> list = new List<ulong>(16);
|
||||
ulong num3 = scanStart;
|
||||
MEMORY_BASIC_INFORMATION64 lpBuffer;
|
||||
while (num3 < scanEnd && VirtualQuery((void*)num3, out lpBuffer, (nuint)sizeof(MEMORY_BASIC_INFORMATION64)) != 0)
|
||||
var hostMemory = ResolveDiagnosticsHostMemory();
|
||||
HostRegionInfo lpBuffer;
|
||||
while (num3 < scanEnd && hostMemory.Query(num3, out lpBuffer))
|
||||
{
|
||||
ulong baseAddress = lpBuffer.BaseAddress;
|
||||
ulong num4 = baseAddress + lpBuffer.RegionSize;
|
||||
@@ -145,7 +147,7 @@ public sealed partial class DirectExecutionBackend
|
||||
}
|
||||
ulong value = Math.Max(num3, baseAddress);
|
||||
ulong num5 = Math.Min(num4, scanEnd);
|
||||
if (lpBuffer.State == 4096 && IsReadableProtection(lpBuffer.Protect) && !IsExecutableProtection(lpBuffer.Protect))
|
||||
if (lpBuffer.State == HostRegionState.Committed && IsReadableProtection(lpBuffer.RawProtection) && !IsExecutableProtection(lpBuffer.RawProtection))
|
||||
{
|
||||
ulong num6 = AlignUp(value, 8uL);
|
||||
for (ulong num7 = num6; num7 + 8 <= num5; num7 += 8)
|
||||
@@ -350,7 +352,7 @@ public sealed partial class DirectExecutionBackend
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (VirtualQuery((void*)address, out var lpBuffer, (nuint)sizeof(MEMORY_BASIC_INFORMATION64)) == 0)
|
||||
if (!ResolveDiagnosticsHostMemory().Query(address, out var lpBuffer))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -359,7 +361,7 @@ public sealed partial class DirectExecutionBackend
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (lpBuffer.State != 4096 || !IsReadableProtection(lpBuffer.Protect))
|
||||
if (lpBuffer.State != HostRegionState.Committed || !IsReadableProtection(lpBuffer.RawProtection))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -391,12 +393,12 @@ public sealed partial class DirectExecutionBackend
|
||||
return true;
|
||||
}
|
||||
|
||||
if (VirtualQuery((void*)address, out var lpBuffer, (nuint)sizeof(MEMORY_BASIC_INFORMATION64)) == 0)
|
||||
if (!ResolveDiagnosticsHostMemory().Query(address, out var lpBuffer))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var executable = lpBuffer.State == 4096 && IsExecutableProtection(lpBuffer.Protect);
|
||||
var executable = lpBuffer.State == HostRegionState.Committed && IsExecutableProtection(lpBuffer.RawProtection);
|
||||
if (executable)
|
||||
{
|
||||
_knownExecutablePages.TryAdd(pageAddress, 0);
|
||||
@@ -415,6 +417,14 @@ public sealed partial class DirectExecutionBackend
|
||||
return (value + num) & ~num;
|
||||
}
|
||||
|
||||
// Diagnostics helpers are static (reachable from static handler paths), so
|
||||
// they use the platform injected into the backend active on this thread and
|
||||
// fall back to the process-wide singleton only when no run is bound.
|
||||
private static IHostMemory ResolveDiagnosticsHostMemory()
|
||||
{
|
||||
return _activeExecutionBackend?._hostMemory ?? HostPlatform.Current.Memory;
|
||||
}
|
||||
|
||||
private static bool IsReadableProtection(uint protect)
|
||||
{
|
||||
if ((protect & 0x100) != 0 || (protect & 1) != 0)
|
||||
|
||||
@@ -9,7 +9,9 @@ using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using SharpEmu.Core.Cpu.Disasm;
|
||||
using SharpEmu.Core.Cpu.Native.Windows;
|
||||
using SharpEmu.HLE;
|
||||
using SharpEmu.HLE.Host;
|
||||
|
||||
namespace SharpEmu.Core.Cpu.Native;
|
||||
|
||||
@@ -20,14 +22,20 @@ public sealed partial class DirectExecutionBackend
|
||||
|
||||
private unsafe void SetupExceptionHandler()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
SetupPosixExceptionHandler();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_DISABLE_RAW_HANDLER"), "1", StringComparison.Ordinal))
|
||||
{
|
||||
_rawExceptionHandlerStub = CreateExceptionHandlerTrampoline(RawVectoredHandlerPtrManaged);
|
||||
_rawExceptionHandlerStub = _faultHandling.CreateHandlerThunk(RawVectoredHandlerPtrManaged, _hostRspSlotTlsIndex, _tlsGetValueAddress);
|
||||
if (_rawExceptionHandlerStub == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Failed to create raw exception handler trampoline");
|
||||
}
|
||||
_rawExceptionHandler = (nint)AddVectoredExceptionHandler(1u, _rawExceptionHandlerStub);
|
||||
_rawExceptionHandler = _faultHandling.AddFirstChanceHandler(_rawExceptionHandlerStub);
|
||||
Console.Error.WriteLine($"[LOADER][INFO] Raw exception handler installed: 0x{_rawExceptionHandler:X16}");
|
||||
}
|
||||
else
|
||||
@@ -37,22 +45,22 @@ public sealed partial class DirectExecutionBackend
|
||||
|
||||
_handlerDelegate = VectoredHandler;
|
||||
_handlerHandle = GCHandle.Alloc(_handlerDelegate);
|
||||
_exceptionHandlerStub = CreateExceptionHandlerTrampoline(Marshal.GetFunctionPointerForDelegate(_handlerDelegate));
|
||||
_exceptionHandlerStub = _faultHandling.CreateHandlerThunk(Marshal.GetFunctionPointerForDelegate(_handlerDelegate), _hostRspSlotTlsIndex, _tlsGetValueAddress);
|
||||
if (_exceptionHandlerStub == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Failed to create exception handler trampoline");
|
||||
}
|
||||
_exceptionHandler = (nint)AddVectoredExceptionHandler(1u, _exceptionHandlerStub);
|
||||
_exceptionHandler = _faultHandling.AddFirstChanceHandler(_exceptionHandlerStub);
|
||||
Console.Error.WriteLine($"[LOADER][INFO] Exception handler installed: 0x{_exceptionHandler:X16}");
|
||||
|
||||
_unhandledFilterDelegate = UnhandledExceptionFilter;
|
||||
_unhandledFilterHandle = GCHandle.Alloc(_unhandledFilterDelegate);
|
||||
_unhandledFilterStub = CreateExceptionHandlerTrampoline(Marshal.GetFunctionPointerForDelegate(_unhandledFilterDelegate));
|
||||
_unhandledFilterStub = _faultHandling.CreateHandlerThunk(Marshal.GetFunctionPointerForDelegate(_unhandledFilterDelegate), _hostRspSlotTlsIndex, _tlsGetValueAddress);
|
||||
if (_unhandledFilterStub == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Failed to create unhandled exception filter trampoline");
|
||||
}
|
||||
SetUnhandledExceptionFilter(_unhandledFilterStub);
|
||||
_faultHandling.SetUnhandledFilter(_unhandledFilterStub);
|
||||
}
|
||||
|
||||
private unsafe int UnhandledExceptionFilter(void* exceptionInfo)
|
||||
@@ -60,8 +68,8 @@ public sealed partial class DirectExecutionBackend
|
||||
try
|
||||
{
|
||||
EXCEPTION_RECORD* exceptionRecord = ((EXCEPTION_POINTERS*)exceptionInfo)->ExceptionRecord;
|
||||
ulong rip = ReadCtxU64(((EXCEPTION_POINTERS*)exceptionInfo)->ContextRecord, 248);
|
||||
ulong rsp = ReadCtxU64(((EXCEPTION_POINTERS*)exceptionInfo)->ContextRecord, 152);
|
||||
ulong rip = ReadCtxU64(((EXCEPTION_POINTERS*)exceptionInfo)->ContextRecord, CTX_RIP);
|
||||
ulong rsp = ReadCtxU64(((EXCEPTION_POINTERS*)exceptionInfo)->ContextRecord, CTX_RSP);
|
||||
Console.Error.WriteLine("[LOADER][FATAL] Unhandled exception filter fired.");
|
||||
Console.Error.WriteLine($"[LOADER][FATAL] Code: 0x{exceptionRecord->ExceptionCode:X8}");
|
||||
Console.Error.WriteLine($"[LOADER][FATAL] Exception Address: 0x{(ulong)(nint)exceptionRecord->ExceptionAddress:X16}");
|
||||
@@ -100,8 +108,8 @@ public sealed partial class DirectExecutionBackend
|
||||
return 0;
|
||||
}
|
||||
|
||||
ulong rip = ReadCtxU64(contextRecord, 248);
|
||||
ulong rsp = ReadCtxU64(contextRecord, 152);
|
||||
ulong rip = ReadCtxU64(contextRecord, CTX_RIP);
|
||||
ulong rsp = ReadCtxU64(contextRecord, CTX_RSP);
|
||||
|
||||
// Thread-mode probe: a hardware exception raised while this thread is inside
|
||||
// the managed import gateway means the VEH->managed reentry happened from
|
||||
@@ -112,7 +120,7 @@ public sealed partial class DirectExecutionBackend
|
||||
$"veh_in_gateway code=0x{exceptionCode:X8} rip=0x{rip:X16} gateway_depth={_threadModeGatewayDepth}");
|
||||
}
|
||||
|
||||
if (exceptionCode == 3221225477u && TryHandleLazyCommittedPage(exceptionRecord, rip, rsp))
|
||||
if (exceptionCode == WindowsFaultCodes.AccessViolation && TryHandleLazyCommittedPage(exceptionRecord, rip, rsp))
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
@@ -127,10 +135,10 @@ public sealed partial class DirectExecutionBackend
|
||||
|
||||
switch (exceptionCode)
|
||||
{
|
||||
case 3221225477u:
|
||||
case WindowsFaultCodes.AccessViolation:
|
||||
LogAccessViolationTrace(exceptionAddress, exceptionRecord);
|
||||
break;
|
||||
case 3221226505u:
|
||||
case WindowsFaultCodes.FastFail:
|
||||
{
|
||||
ulong p0 = exceptionRecord->NumberParameters >= 1 ? (*exceptionRecord->ExceptionInformation) : 0;
|
||||
ulong p1 = exceptionRecord->NumberParameters >= 2 ? exceptionRecord->ExceptionInformation[1] : 0;
|
||||
@@ -140,21 +148,21 @@ public sealed partial class DirectExecutionBackend
|
||||
}
|
||||
}
|
||||
|
||||
ulong rax = ReadCtxU64(contextRecord, 120);
|
||||
ulong rbx = ReadCtxU64(contextRecord, 144);
|
||||
ulong rcx = ReadCtxU64(contextRecord, 128);
|
||||
ulong rdx = ReadCtxU64(contextRecord, 136);
|
||||
ulong rsi = ReadCtxU64(contextRecord, 168);
|
||||
ulong rdi = ReadCtxU64(contextRecord, 176);
|
||||
ulong rbp = ReadCtxU64(contextRecord, 160);
|
||||
ulong r8 = ReadCtxU64(contextRecord, 184);
|
||||
ulong r9 = ReadCtxU64(contextRecord, 192);
|
||||
ulong r10 = ReadCtxU64(contextRecord, 200);
|
||||
ulong r11 = ReadCtxU64(contextRecord, 208);
|
||||
ulong r12 = ReadCtxU64(contextRecord, 216);
|
||||
ulong r13 = ReadCtxU64(contextRecord, 224);
|
||||
ulong r14 = ReadCtxU64(contextRecord, 232);
|
||||
ulong r15 = ReadCtxU64(contextRecord, 240);
|
||||
ulong rax = ReadCtxU64(contextRecord, CTX_RAX);
|
||||
ulong rbx = ReadCtxU64(contextRecord, CTX_RBX);
|
||||
ulong rcx = ReadCtxU64(contextRecord, CTX_RCX);
|
||||
ulong rdx = ReadCtxU64(contextRecord, CTX_RDX);
|
||||
ulong rsi = ReadCtxU64(contextRecord, CTX_RSI);
|
||||
ulong rdi = ReadCtxU64(contextRecord, CTX_RDI);
|
||||
ulong rbp = ReadCtxU64(contextRecord, CTX_RBP);
|
||||
ulong r8 = ReadCtxU64(contextRecord, CTX_R8);
|
||||
ulong r9 = ReadCtxU64(contextRecord, CTX_R9);
|
||||
ulong r10 = ReadCtxU64(contextRecord, CTX_R10);
|
||||
ulong r11 = ReadCtxU64(contextRecord, CTX_R11);
|
||||
ulong r12 = ReadCtxU64(contextRecord, CTX_R12);
|
||||
ulong r13 = ReadCtxU64(contextRecord, CTX_R13);
|
||||
ulong r14 = ReadCtxU64(contextRecord, CTX_R14);
|
||||
ulong r15 = ReadCtxU64(contextRecord, CTX_R15);
|
||||
|
||||
Console.Error.WriteLine("[LOADER][INFO] =========================================");
|
||||
Console.Error.WriteLine("[LOADER][INFO] NATIVE EXCEPTION CAUGHT!");
|
||||
@@ -185,7 +193,7 @@ public sealed partial class DirectExecutionBackend
|
||||
|
||||
ulong accessType = 0;
|
||||
ulong target = 0;
|
||||
if (exceptionCode == 3221225477u && exceptionRecord->NumberParameters >= 2)
|
||||
if (exceptionCode == WindowsFaultCodes.AccessViolation && exceptionRecord->NumberParameters >= 2)
|
||||
{
|
||||
accessType = *exceptionRecord->ExceptionInformation;
|
||||
target = exceptionRecord->ExceptionInformation[1];
|
||||
@@ -198,26 +206,23 @@ public sealed partial class DirectExecutionBackend
|
||||
};
|
||||
Console.Error.WriteLine("[LOADER][INFO] AV access: " + accessText);
|
||||
Console.Error.WriteLine($"[LOADER][INFO] AV target: 0x{target:X16}");
|
||||
if (VirtualQuery((void*)target, out var mbi, (nuint)sizeof(MEMORY_BASIC_INFORMATION64)) != 0)
|
||||
if (_hostMemory.Query(target, out var mbi))
|
||||
{
|
||||
Console.Error.WriteLine($"[LOADER][INFO] AV target region: base=0x{mbi.BaseAddress:X16} size=0x{mbi.RegionSize:X16} state=0x{mbi.State:X08} protect=0x{mbi.Protect:X08}");
|
||||
Console.Error.WriteLine($"[LOADER][INFO] AV target region: base=0x{mbi.BaseAddress:X16} size=0x{mbi.RegionSize:X16} state=0x{mbi.RawState:X08} protect=0x{mbi.RawProtection:X08}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
Console.Error.WriteLine("[LOADER][INFO] Stack qwords (RSP..):");
|
||||
for (int i = 0; i < 16; i++)
|
||||
{
|
||||
Console.Error.WriteLine("[LOADER][INFO] Stack qwords (RSP..):");
|
||||
for (int i = 0; i < 16; i++)
|
||||
ulong stackAddr = rsp + (ulong)(i * 8);
|
||||
if (!TryReadHostQword(stackAddr, out ulong value))
|
||||
{
|
||||
ulong stackAddr = rsp + (ulong)(i * 8);
|
||||
ulong value = (ulong)Marshal.ReadInt64((nint)stackAddr);
|
||||
Console.Error.WriteLine($"[LOADER][INFO] [rsp+0x{i * 8:X2}] @0x{stackAddr:X16} = 0x{value:X16}");
|
||||
Console.Error.WriteLine("[LOADER][WARNING] Could not read stack qwords.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
Console.Error.WriteLine("[LOADER][WARNING] Could not read stack qwords.");
|
||||
Console.Error.WriteLine($"[LOADER][INFO] [rsp+0x{i * 8:X2}] @0x{stackAddr:X16} = 0x{value:X16}");
|
||||
}
|
||||
|
||||
try
|
||||
@@ -230,8 +235,11 @@ public sealed partial class DirectExecutionBackend
|
||||
{
|
||||
break;
|
||||
}
|
||||
ulong next = (ulong)Marshal.ReadInt64((nint)frame);
|
||||
ulong ret = (ulong)Marshal.ReadInt64((nint)(frame + 8));
|
||||
if (!TryReadHostQword(frame, out ulong next) || !TryReadHostQword(frame + 8, out ulong ret))
|
||||
{
|
||||
Console.Error.WriteLine("[LOADER][WARNING] Could not walk RBP frame chain.");
|
||||
break;
|
||||
}
|
||||
string extra = TryFormatNearestRuntimeSymbol(ret, out string retSym) ? $" [{retSym}]" : string.Empty;
|
||||
Console.Error.WriteLine($"[LOADER][INFO] frame#{i}: rbp=0x{frame:X16} ret=0x{ret:X16}{extra} next=0x{next:X16}");
|
||||
if (next <= frame)
|
||||
@@ -248,16 +256,15 @@ public sealed partial class DirectExecutionBackend
|
||||
|
||||
switch (exceptionCode)
|
||||
{
|
||||
case 3221225477u:
|
||||
case WindowsFaultCodes.AccessViolation:
|
||||
Console.Error.WriteLine("[LOADER][ERROR] Type: Access Violation");
|
||||
Console.Error.WriteLine("[LOADER][ERROR] This usually means:");
|
||||
Console.Error.WriteLine("[LOADER][ERROR] - Guest code called an unmapped import");
|
||||
Console.Error.WriteLine("[LOADER][ERROR] - Guest code accessed unmapped memory");
|
||||
Console.Error.WriteLine("[LOADER][ERROR] - Need to implement HLE for this NID");
|
||||
try
|
||||
byte[] code = new byte[16];
|
||||
if (TryReadHostBytes(rip, code))
|
||||
{
|
||||
byte[] code = new byte[16];
|
||||
Marshal.Copy((nint)rip, code, 0, code.Length);
|
||||
Console.Error.WriteLine("[LOADER][INFO] Code at RIP: " + BitConverter.ToString(code).Replace("-", " "));
|
||||
if (code[0] == 100)
|
||||
{
|
||||
@@ -273,20 +280,18 @@ public sealed partial class DirectExecutionBackend
|
||||
Console.Error.WriteLine($"[LOADER][INFO] RBP: 0x{rbp:X16} (mod 16 = {rbp % 16})");
|
||||
Console.Error.WriteLine($"[LOADER][INFO] RSP: 0x{rsp:X16} (mod 16 = {rsp % 16})");
|
||||
}
|
||||
if (rip > 16)
|
||||
byte[] before = new byte[16];
|
||||
if (rip > 16 && TryReadHostBytes(rip - 16, before))
|
||||
{
|
||||
byte[] before = new byte[16];
|
||||
Marshal.Copy((nint)(rip - 16), before, 0, before.Length);
|
||||
Console.Error.WriteLine("[LOADER][INFO] Code before RIP: " + BitConverter.ToString(before).Replace("-", " "));
|
||||
}
|
||||
if (rip > 32)
|
||||
byte[] window = new byte[64];
|
||||
if (rip > 32 && TryReadHostBytes(rip - 32, window))
|
||||
{
|
||||
byte[] window = new byte[64];
|
||||
Marshal.Copy((nint)(rip - 32), window, 0, window.Length);
|
||||
Console.Error.WriteLine("[LOADER][INFO] Code window [RIP-0x20..]: " + BitConverter.ToString(window).Replace("-", " "));
|
||||
}
|
||||
}
|
||||
catch
|
||||
else
|
||||
{
|
||||
Console.Error.WriteLine("[LOADER][ERROR] Could not read code at RIP");
|
||||
}
|
||||
@@ -295,11 +300,11 @@ public sealed partial class DirectExecutionBackend
|
||||
DumpGuestReferenceDiagnostics();
|
||||
DumpGuestPointerWindowDiagnostics();
|
||||
break;
|
||||
case 2147483651u:
|
||||
case WindowsFaultCodes.Breakpoint:
|
||||
Console.Error.WriteLine("[LOADER][WARNING] Type: Breakpoint (int3)");
|
||||
Console.Error.WriteLine("[LOADER][WARNING] Unexpected breakpoint in direct-bridge mode");
|
||||
break;
|
||||
case 3221225501u:
|
||||
case WindowsFaultCodes.IllegalInstruction:
|
||||
Console.Error.WriteLine("[LOADER][INFO] Type: Illegal Instruction");
|
||||
break;
|
||||
}
|
||||
@@ -332,8 +337,8 @@ public sealed partial class DirectExecutionBackend
|
||||
EXCEPTION_POINTERS* pointers = (EXCEPTION_POINTERS*)exceptionInfo;
|
||||
EXCEPTION_RECORD* record = pointers->ExceptionRecord;
|
||||
void* contextRecord = pointers->ContextRecord;
|
||||
ulong rip = contextRecord != null ? ReadCtxU64(contextRecord, 248) : 0;
|
||||
ulong rsp = contextRecord != null ? ReadCtxU64(contextRecord, 152) : 0;
|
||||
ulong rip = contextRecord != null ? ReadCtxU64(contextRecord, CTX_RIP) : 0;
|
||||
ulong rsp = contextRecord != null ? ReadCtxU64(contextRecord, CTX_RSP) : 0;
|
||||
ulong accessType = record->NumberParameters >= 1 ? *record->ExceptionInformation : 0;
|
||||
ulong target = record->NumberParameters >= 2 ? record->ExceptionInformation[1] : 0;
|
||||
Console.Error.WriteLine(
|
||||
@@ -479,7 +484,7 @@ public sealed partial class DirectExecutionBackend
|
||||
ulong address = scanBase;
|
||||
while (address < scanEnd)
|
||||
{
|
||||
if (VirtualQuery((void*)address, out var mbi, (nuint)sizeof(MEMORY_BASIC_INFORMATION64)) == 0)
|
||||
if (!_hostMemory.Query(address, out var mbi))
|
||||
{
|
||||
break;
|
||||
}
|
||||
@@ -491,9 +496,9 @@ public sealed partial class DirectExecutionBackend
|
||||
break;
|
||||
}
|
||||
|
||||
if (mbi.State == MEM_COMMIT &&
|
||||
IsReadableProtection(mbi.Protect) &&
|
||||
IsExecutableProtection(mbi.Protect))
|
||||
if (mbi.State == HostRegionState.Committed &&
|
||||
IsReadableProtection(mbi.RawProtection) &&
|
||||
IsExecutableProtection(mbi.RawProtection))
|
||||
{
|
||||
ScanExecutableRegionForTargetReferences(regionBase, regionEnd, targetList, hitCounts, maxHitsPerTarget);
|
||||
}
|
||||
@@ -798,13 +803,13 @@ public sealed partial class DirectExecutionBackend
|
||||
return false;
|
||||
}
|
||||
|
||||
if (VirtualQuery((void*)address, out var mbi, (nuint)sizeof(MEMORY_BASIC_INFORMATION64)) == 0)
|
||||
if (!_hostMemory.Query(address, out var mbi))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
ulong regionEnd = mbi.BaseAddress + mbi.RegionSize;
|
||||
if (mbi.State != MEM_COMMIT || !IsReadableProtection(mbi.Protect) || regionEnd <= address || address > regionEnd - 8)
|
||||
if (mbi.State != HostRegionState.Committed || !IsReadableProtection(mbi.RawProtection) || regionEnd <= address || address > regionEnd - 8)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -821,6 +826,61 @@ public sealed partial class DirectExecutionBackend
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryReadHostQword(ulong address, out ulong value)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
// A stray read inside the signal handler would raise a nested
|
||||
// SIGSEGV and kill the process before diagnostics finish, so
|
||||
// probe the region table instead of relying on try/catch.
|
||||
return TryReadStackU64(address, out value);
|
||||
}
|
||||
|
||||
value = 0;
|
||||
try
|
||||
{
|
||||
value = (ulong)Marshal.ReadInt64((nint)address);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private unsafe bool TryReadHostBytes(ulong address, byte[] buffer)
|
||||
{
|
||||
if (address < 65536)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
// See TryReadHostQword: probe every touched page before reading.
|
||||
ulong end = address + (ulong)buffer.Length;
|
||||
for (ulong page = address & 0xFFFFFFFFFFFFF000uL; page < end; page += 4096)
|
||||
{
|
||||
if (!_hostMemory.Query(page, out var mbi) ||
|
||||
mbi.State != HostRegionState.Committed ||
|
||||
!IsReadableProtection(mbi.RawProtection))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Marshal.Copy((nint)address, buffer, 0, buffer.Length);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private string FormatPointerWithNearestSymbol(ulong value)
|
||||
{
|
||||
string text = $"0x{value:X16}";
|
||||
@@ -916,25 +976,25 @@ public sealed partial class DirectExecutionBackend
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (VirtualQuery((void*)faultAddress, out var mbi, (nuint)sizeof(MEMORY_BASIC_INFORMATION64)) == 0)
|
||||
if (!_hostMemory.Query(faultAddress, out var mbi))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
ulong pageBase = faultAddress & 0xFFFFFFFFFFFFF000uL;
|
||||
uint commitProtect = ResolveLazyCommitProtection(accessType, mbi.AllocationProtect);
|
||||
uint commitProtect = ResolveLazyCommitProtection(accessType, mbi.RawAllocationProtection);
|
||||
int traceIndex = Interlocked.Increment(ref _lazyCommitTraceCount);
|
||||
bool traceLazyCommit = ShouldTraceLazyCommit(traceIndex);
|
||||
if (traceLazyCommit)
|
||||
{
|
||||
Console.Error.WriteLine($"[LOADER][TRACE] lazy-query#{traceIndex}: fault=0x{faultAddress:X16} owner={owner} rip=0x{rip:X16} rsp=0x{rsp:X16} state=0x{mbi.State:X08} base=0x{mbi.BaseAddress:X16} size=0x{mbi.RegionSize:X16} alloc=0x{mbi.AllocationProtect:X08} prot=0x{mbi.Protect:X08}");
|
||||
Console.Error.WriteLine($"[LOADER][TRACE] lazy-query#{traceIndex}: fault=0x{faultAddress:X16} owner={owner} rip=0x{rip:X16} rsp=0x{rsp:X16} state=0x{mbi.RawState:X08} base=0x{mbi.BaseAddress:X16} size=0x{mbi.RegionSize:X16} alloc=0x{mbi.RawAllocationProtection:X08} prot=0x{mbi.RawProtection:X08}");
|
||||
}
|
||||
|
||||
if (mbi.State == 4096 && IsAccessCompatible(accessType, mbi.Protect))
|
||||
if (mbi.State == HostRegionState.Committed && IsAccessCompatible(accessType, mbi.RawProtection))
|
||||
{
|
||||
if (traceLazyCommit)
|
||||
{
|
||||
Console.Error.WriteLine($"[LOADER][TRACE] lazy-commit-race#{traceIndex}: fault=0x{faultAddress:X16} protect=0x{mbi.Protect:X08}");
|
||||
Console.Error.WriteLine($"[LOADER][TRACE] lazy-commit-race#{traceIndex}: fault=0x{faultAddress:X16} protect=0x{mbi.RawProtection:X08}");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -943,10 +1003,10 @@ public sealed partial class DirectExecutionBackend
|
||||
ulong committedBase = 0;
|
||||
ulong committedSize = 0;
|
||||
|
||||
if (mbi.State == 65536)
|
||||
if (mbi.State == HostRegionState.Free)
|
||||
{
|
||||
if (TryGetLazyCommitWindow(faultAddress, mbi.BaseAddress, mbi.RegionSize, out var windowBase, out var windowSize) &&
|
||||
TryReserveThenCommit(windowBase, windowSize, windowBase, windowSize, commitProtect))
|
||||
TryReserveThenCommit(_hostMemory, windowBase, windowSize, windowBase, windowSize, commitProtect))
|
||||
{
|
||||
committed = true;
|
||||
committedBase = windowBase;
|
||||
@@ -955,7 +1015,7 @@ public sealed partial class DirectExecutionBackend
|
||||
else
|
||||
{
|
||||
ulong largeBase = faultAddress & 0xFFFFFFFFFFE00000uL;
|
||||
if (TryReserveThenCommit(largeBase, 2097152uL, largeBase, 2097152uL, commitProtect))
|
||||
if (TryReserveThenCommit(_hostMemory, largeBase, 2097152uL, largeBase, 2097152uL, commitProtect))
|
||||
{
|
||||
committed = true;
|
||||
committedBase = largeBase;
|
||||
@@ -966,13 +1026,13 @@ public sealed partial class DirectExecutionBackend
|
||||
if (!committed)
|
||||
{
|
||||
ulong region64kBase = faultAddress & 0xFFFFFFFFFFFF0000uL;
|
||||
if (TryReserveThenCommit(region64kBase, 65536uL, region64kBase, 65536uL, commitProtect))
|
||||
if (TryReserveThenCommit(_hostMemory, region64kBase, 65536uL, region64kBase, 65536uL, commitProtect))
|
||||
{
|
||||
committed = true;
|
||||
committedBase = region64kBase;
|
||||
committedSize = 65536uL;
|
||||
}
|
||||
else if (TryReserveThenCommit(pageBase, 4096uL, pageBase, 4096uL, commitProtect))
|
||||
else if (TryReserveThenCommit(_hostMemory, pageBase, 4096uL, pageBase, 4096uL, commitProtect))
|
||||
{
|
||||
committed = true;
|
||||
committedBase = pageBase;
|
||||
@@ -985,7 +1045,7 @@ public sealed partial class DirectExecutionBackend
|
||||
return false;
|
||||
}
|
||||
|
||||
TryCommitRange(pageBase + 4096, 4096uL, commitProtect);
|
||||
TryCommitRange(_hostMemory, pageBase + 4096, 4096uL, commitProtect);
|
||||
if (traceLazyCommit)
|
||||
{
|
||||
Console.Error.WriteLine($"[LOADER][TRACE] lazy-reserve-commit#{traceIndex}: addr=0x{committedBase:X16} size=0x{committedSize:X16} access={accessType} protect=0x{commitProtect:X8}");
|
||||
@@ -993,13 +1053,13 @@ public sealed partial class DirectExecutionBackend
|
||||
return true;
|
||||
}
|
||||
|
||||
if (mbi.State != 8192)
|
||||
if (mbi.State != HostRegionState.Reserved)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (TryGetLazyCommitWindow(faultAddress, mbi.BaseAddress, mbi.RegionSize, out var commitWindowBase, out var commitWindowSize) &&
|
||||
TryCommitRange(commitWindowBase, commitWindowSize, commitProtect))
|
||||
TryCommitRange(_hostMemory, commitWindowBase, commitWindowSize, commitProtect))
|
||||
{
|
||||
committed = true;
|
||||
committedBase = commitWindowBase;
|
||||
@@ -1008,7 +1068,7 @@ public sealed partial class DirectExecutionBackend
|
||||
else
|
||||
{
|
||||
ulong largeCommitBase = faultAddress & 0xFFFFFFFFFFE00000uL;
|
||||
if (TryCommitRange(largeCommitBase, 2097152uL, commitProtect))
|
||||
if (TryCommitRange(_hostMemory, largeCommitBase, 2097152uL, commitProtect))
|
||||
{
|
||||
committed = true;
|
||||
committedBase = largeCommitBase;
|
||||
@@ -1019,19 +1079,19 @@ public sealed partial class DirectExecutionBackend
|
||||
if (!committed)
|
||||
{
|
||||
ulong region64kBase = faultAddress & 0xFFFFFFFFFFFF0000uL;
|
||||
if (TryCommitRange(region64kBase, 65536uL, commitProtect))
|
||||
if (TryCommitRange(_hostMemory, region64kBase, 65536uL, commitProtect))
|
||||
{
|
||||
committed = true;
|
||||
committedBase = region64kBase;
|
||||
committedSize = 65536uL;
|
||||
}
|
||||
else if (TryCommitRange(pageBase, 8192uL, commitProtect))
|
||||
else if (TryCommitRange(_hostMemory, pageBase, 8192uL, commitProtect))
|
||||
{
|
||||
committed = true;
|
||||
committedBase = pageBase;
|
||||
committedSize = 8192uL;
|
||||
}
|
||||
else if (TryCommitRange(pageBase, 4096uL, commitProtect))
|
||||
else if (TryCommitRange(_hostMemory, pageBase, 4096uL, commitProtect))
|
||||
{
|
||||
committed = true;
|
||||
committedBase = pageBase;
|
||||
@@ -1044,7 +1104,7 @@ public sealed partial class DirectExecutionBackend
|
||||
return false;
|
||||
}
|
||||
|
||||
TryCommitRange(pageBase + 4096, 4096uL, commitProtect);
|
||||
TryCommitRange(_hostMemory, pageBase + 4096, 4096uL, commitProtect);
|
||||
if (traceLazyCommit)
|
||||
{
|
||||
Console.Error.WriteLine($"[LOADER][TRACE] lazy-commit#{traceIndex}: addr=0x{committedBase:X16} size=0x{committedSize:X16} access={accessType} protect=0x{commitProtect:X8}");
|
||||
@@ -1085,31 +1145,33 @@ public sealed partial class DirectExecutionBackend
|
||||
return true;
|
||||
}
|
||||
|
||||
static unsafe bool TryCommitRange(ulong baseAddress, ulong length, uint protection)
|
||||
// The commit protection is one of the two raw values ResolveLazyCommitProtection
|
||||
// produces (0x40 RWX / 0x04 RW); the enum mapping reproduces those exactly.
|
||||
static bool TryCommitRange(IHostMemory hostMemory, ulong baseAddress, ulong length, uint protection)
|
||||
{
|
||||
if (length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return VirtualAlloc((void*)baseAddress, (nuint)length, 4096u, protection) != null;
|
||||
return hostMemory.Commit(baseAddress, length, protection == 64u ? HostPageProtection.ReadWriteExecute : HostPageProtection.ReadWrite);
|
||||
}
|
||||
|
||||
static unsafe bool TryReserveRange(ulong baseAddress, ulong length)
|
||||
static bool TryReserveRange(IHostMemory hostMemory, ulong baseAddress, ulong length)
|
||||
{
|
||||
if (length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return VirtualAlloc((void*)baseAddress, (nuint)length, 8192u, 4u) != null;
|
||||
return hostMemory.Reserve(baseAddress, length, HostPageProtection.ReadWrite) != 0;
|
||||
}
|
||||
|
||||
static bool TryReserveThenCommit(ulong reserveAddress, ulong reserveSize, ulong commitAddress, ulong commitSize, uint protection)
|
||||
static bool TryReserveThenCommit(IHostMemory hostMemory, ulong reserveAddress, ulong reserveSize, ulong commitAddress, ulong commitSize, uint protection)
|
||||
{
|
||||
if (!TryReserveRange(reserveAddress, reserveSize))
|
||||
if (!TryReserveRange(hostMemory, reserveAddress, reserveSize))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return TryCommitRange(commitAddress, commitSize, protection);
|
||||
return TryCommitRange(hostMemory, commitAddress, commitSize, protection);
|
||||
}
|
||||
|
||||
static bool IsAccessCompatible(ulong accessType, uint protection)
|
||||
|
||||
@@ -8,8 +8,10 @@ using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using SharpEmu.Core.Cpu;
|
||||
using SharpEmu.Core.Cpu.Native.Windows;
|
||||
using SharpEmu.Core.Loader;
|
||||
using SharpEmu.HLE;
|
||||
using SharpEmu.HLE.Host;
|
||||
|
||||
namespace SharpEmu.Core.Cpu.Native;
|
||||
|
||||
@@ -69,23 +71,23 @@ public sealed partial class DirectExecutionBackend
|
||||
private unsafe static int TryRecoverUnresolvedSentinel(void* exceptionInfo)
|
||||
{
|
||||
EXCEPTION_RECORD* exceptionRecord = ((EXCEPTION_POINTERS*)exceptionInfo)->ExceptionRecord;
|
||||
if (exceptionRecord->ExceptionCode != 3221225477u)
|
||||
if (exceptionRecord->ExceptionCode != WindowsFaultCodes.AccessViolation)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
void* contextRecord = ((EXCEPTION_POINTERS*)exceptionInfo)->ContextRecord;
|
||||
ulong value = ReadCtxU64(contextRecord, 248);
|
||||
ulong value = ReadCtxU64(contextRecord, CTX_RIP);
|
||||
ulong value2 = (ulong)exceptionRecord->ExceptionAddress;
|
||||
if (!IsUnresolvedSentinel(value) && !IsUnresolvedSentinel(value2))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
ulong rsp = ReadCtxU64(contextRecord, 152);
|
||||
WriteCtxU64(contextRecord, 120, 0uL);
|
||||
ulong rsp = ReadCtxU64(contextRecord, CTX_RSP);
|
||||
WriteCtxU64(contextRecord, CTX_RAX, 0uL);
|
||||
if (TryGetPlausibleReturnFromStack(rsp, out var returnRip, out var nextRsp))
|
||||
{
|
||||
WriteCtxU64(contextRecord, 152, nextRsp);
|
||||
WriteCtxU64(contextRecord, 248, returnRip);
|
||||
WriteCtxU64(contextRecord, CTX_RSP, nextRsp);
|
||||
WriteCtxU64(contextRecord, CTX_RIP, returnRip);
|
||||
Interlocked.Increment(ref _rawSentinelRecoveries);
|
||||
if (LogThreadMode)
|
||||
{
|
||||
@@ -161,7 +163,7 @@ public sealed partial class DirectExecutionBackend
|
||||
*(ulong*)(xmmSlot + 8));
|
||||
}
|
||||
cpuContext[CpuRegister.Rsp] = (ulong)argPackPtr + 96uL;
|
||||
if (string.Equals(importStubEntry.Nid, RuntimeStubNids.BootstrapBridge, StringComparison.Ordinal))
|
||||
if (importStubEntry.Kind == ImportStubKind.BootstrapBridge)
|
||||
{
|
||||
NormalizeKernelDynlibDlsymArguments(cpuContext, out _, out _);
|
||||
*(ulong*)argPackPtr = cpuContext[CpuRegister.Rdi];
|
||||
@@ -238,6 +240,22 @@ public sealed partial class DirectExecutionBackend
|
||||
cpuContext[CpuRegister.Rax] = 0uL;
|
||||
return 0uL;
|
||||
}
|
||||
if (_hostShutdownRequested)
|
||||
{
|
||||
if (isGuestWorker &&
|
||||
TryYieldGuestThreadToHostStub(argPackPtr, num, num7, importStubEntry.Nid, "host shutdown"))
|
||||
{
|
||||
cpuContext[CpuRegister.Rax] = 0uL;
|
||||
return 0uL;
|
||||
}
|
||||
|
||||
if (!isGuestWorker &&
|
||||
TryAbortGuestForHostShutdown(argPackPtr, num, num7))
|
||||
{
|
||||
cpuContext[CpuRegister.Rax] = 1uL;
|
||||
return 1uL;
|
||||
}
|
||||
}
|
||||
bool flag0 = ShouldSuppressStrlenTrace(importStubEntry.Nid);
|
||||
bool flag = num7 >= 2156221920u && num7 <= 2156225024u;
|
||||
bool flag2 = num7 >= 2156351360u && num7 <= 2156352080u;
|
||||
@@ -245,12 +263,13 @@ public sealed partial class DirectExecutionBackend
|
||||
bool flag4 = !string.IsNullOrWhiteSpace(_importFilter);
|
||||
bool flag5 = false;
|
||||
ExportedFunction? matchedExport = importStubEntry.Export;
|
||||
var traceFlags = importStubEntry.TraceFlags;
|
||||
bool periodicTrace = num <= 128 ||
|
||||
(num >= 240 && num <= 400) ||
|
||||
(num >= 900 && num <= 1300) ||
|
||||
num % 100000 == 0L ||
|
||||
(importStubEntry.Nid == "tsvEmnenz48" && (num <= 256 || num % 1000 == 0L)) ||
|
||||
(importStubEntry.Nid == "rTXw65xmLIA" && (num <= 256 || num % 128 == 0)) ||
|
||||
((traceFlags & ImportStubTraceFlags.PeriodicEvery1000) != 0 && (num <= 256 || num % 1000 == 0L)) ||
|
||||
((traceFlags & ImportStubTraceFlags.PeriodicEvery128) != 0 && (num <= 256 || num % 128 == 0)) ||
|
||||
flag ||
|
||||
flag2 ||
|
||||
flag3;
|
||||
@@ -311,15 +330,15 @@ public sealed partial class DirectExecutionBackend
|
||||
cpuContext[CpuRegister.Rsi],
|
||||
cpuContext[CpuRegister.Rdx]);
|
||||
}
|
||||
if (importStubEntry.Nid == "8zTFvBIAIN8" && num <= 256)
|
||||
if ((traceFlags & ImportStubTraceFlags.Memset) != 0 && num <= 256)
|
||||
{
|
||||
Console.Error.WriteLine($"[LOADER][TRACE] memset#{num}: dst=0x{cpuContext[CpuRegister.Rdi]:X16} val=0x{cpuContext[CpuRegister.Rsi] & 0xFF:X2} len=0x{cpuContext[CpuRegister.Rdx]:X16} ret=0x{num7:X16}");
|
||||
}
|
||||
if (importStubEntry.Nid == "tsvEmnenz48" && num <= 64)
|
||||
if ((traceFlags & ImportStubTraceFlags.CxaAtexit) != 0 && num <= 64)
|
||||
{
|
||||
Console.Error.WriteLine($"[LOADER][TRACE] __cxa_atexit#{num}: func=0x{cpuContext[CpuRegister.Rdi]:X16} arg=0x{cpuContext[CpuRegister.Rsi]:X16} dso=0x{cpuContext[CpuRegister.Rdx]:X16} ret=0x{num7:X16}");
|
||||
}
|
||||
if (importStubEntry.Nid == "bzQExy189ZI" || importStubEntry.Nid == "8G2LB+A3rzg")
|
||||
if ((traceFlags & ImportStubTraceFlags.RawArgs) != 0)
|
||||
{
|
||||
Console.Error.WriteLine($"[LOADER][TRACE] {importStubEntry.Nid}#{num}: rdi=0x{cpuContext[CpuRegister.Rdi]:X16} rsi=0x{cpuContext[CpuRegister.Rsi]:X16} rdx=0x{cpuContext[CpuRegister.Rdx]:X16} ret=0x{num7:X16}");
|
||||
}
|
||||
@@ -349,7 +368,7 @@ public sealed partial class DirectExecutionBackend
|
||||
Console.Error.Flush();
|
||||
}
|
||||
}
|
||||
if (importStubEntry.Nid == "Ou3iL1abvng")
|
||||
if ((traceFlags & ImportStubTraceFlags.StackChkFail) != 0)
|
||||
{
|
||||
if (_logStackCheck)
|
||||
{
|
||||
@@ -381,7 +400,7 @@ public sealed partial class DirectExecutionBackend
|
||||
ActiveGuestReturnSlotAddress);
|
||||
try
|
||||
{
|
||||
if (string.Equals(importStubEntry.Nid, RuntimeStubNids.BootstrapBridge, StringComparison.Ordinal))
|
||||
if (importStubEntry.Kind == ImportStubKind.BootstrapBridge)
|
||||
{
|
||||
if (_logBootstrap)
|
||||
{
|
||||
@@ -390,12 +409,11 @@ public sealed partial class DirectExecutionBackend
|
||||
|
||||
orbisGen2Result = DispatchBootstrapBridge();
|
||||
}
|
||||
else if (string.Equals(importStubEntry.Nid, RuntimeStubNids.KernelDynlibDlsym, StringComparison.Ordinal) ||
|
||||
string.Equals(importStubEntry.Nid, "LwG8g3niqwA", StringComparison.Ordinal))
|
||||
else if (importStubEntry.Kind == ImportStubKind.KernelDynlibDlsym)
|
||||
{
|
||||
orbisGen2Result = DispatchKernelDynlibDlsym();
|
||||
}
|
||||
else if (string.Equals(importStubEntry.Nid, "r8mvOaWdi28", StringComparison.Ordinal))
|
||||
else if (importStubEntry.Kind == ImportStubKind.Il2CppApiLookupSymbol)
|
||||
{
|
||||
orbisGen2Result = DispatchIl2CppApiLookupSymbol();
|
||||
}
|
||||
@@ -517,8 +535,7 @@ public sealed partial class DirectExecutionBackend
|
||||
out var blockContinuation,
|
||||
out var hasBlockContinuation,
|
||||
out var blockWakeKey,
|
||||
out var blockResumeHandler,
|
||||
out var blockWakeHandler,
|
||||
out var blockWaiter,
|
||||
out var blockDeadlineTimestamp) &&
|
||||
TryYieldGuestThreadToHostStub(argPackPtr, num, num7, importStubEntry.Nid, blockReason))
|
||||
{
|
||||
@@ -528,8 +545,7 @@ public sealed partial class DirectExecutionBackend
|
||||
GuestThreadExecution.CurrentGuestThreadHandle,
|
||||
blockContinuation,
|
||||
blockWakeKey,
|
||||
blockResumeHandler,
|
||||
blockWakeHandler,
|
||||
blockWaiter,
|
||||
blockDeadlineTimestamp);
|
||||
}
|
||||
|
||||
@@ -660,8 +676,7 @@ public sealed partial class DirectExecutionBackend
|
||||
out var blockContinuation,
|
||||
out var hasBlockContinuation,
|
||||
out var blockWakeKey,
|
||||
out var blockResumeHandler,
|
||||
out var blockWakeHandler,
|
||||
out var blockWaiter,
|
||||
out var blockDeadlineTimestamp) &&
|
||||
TryYieldGuestThreadToHostStub(argPackPtr, dispatchIndex, returnRip, importStubEntry.Nid, blockReason))
|
||||
{
|
||||
@@ -671,8 +686,7 @@ public sealed partial class DirectExecutionBackend
|
||||
GuestThreadExecution.CurrentGuestThreadHandle,
|
||||
blockContinuation,
|
||||
blockWakeKey,
|
||||
blockResumeHandler,
|
||||
blockWakeHandler,
|
||||
blockWaiter,
|
||||
blockDeadlineTimestamp);
|
||||
}
|
||||
|
||||
@@ -736,6 +750,9 @@ public sealed partial class DirectExecutionBackend
|
||||
var expectedEqueueTimeout =
|
||||
string.Equals(nid, "fzyMKs9kim0", StringComparison.Ordinal) &&
|
||||
result == OrbisGen2Result.ORBIS_GEN2_ERROR_TIMED_OUT;
|
||||
var expectedEventFlagTimeout =
|
||||
string.Equals(nid, "JTvBflhYazQ", StringComparison.Ordinal) &&
|
||||
result == OrbisGen2Result.ORBIS_GEN2_ERROR_TIMED_OUT;
|
||||
var expectedMutexTrylockBusy =
|
||||
string.Equals(nid, "K-jXhbt2gn4", StringComparison.Ordinal) &&
|
||||
result == OrbisGen2Result.ORBIS_GEN2_ERROR_BUSY;
|
||||
@@ -748,6 +765,7 @@ public sealed partial class DirectExecutionBackend
|
||||
if (!expectedFileProbeMiss &&
|
||||
!expectedTimedWaitTimeout &&
|
||||
!expectedEqueueTimeout &&
|
||||
!expectedEventFlagTimeout &&
|
||||
!expectedMutexTrylockBusy &&
|
||||
!expectedUserServiceNoEvent &&
|
||||
!expectedPrivacyInvalidParameter)
|
||||
@@ -810,11 +828,15 @@ public sealed partial class DirectExecutionBackend
|
||||
return !_logUsleep;
|
||||
}
|
||||
|
||||
// Mutex lock uses this block-capable leaf path. Keep it out of the no-block subset.
|
||||
return nid is
|
||||
"9UK1vLZQft4" or // scePthreadMutexLock
|
||||
"tn3VlD0hG60" or // scePthreadMutexUnlock
|
||||
"7H0iTOciTLo" or // pthread_mutex_lock
|
||||
"tn3VlD0hG60" or // scePthreadMutexUnlock
|
||||
"2Z+PpY6CaJg" or // pthread_mutex_unlock
|
||||
"EgmLo6EWgso" or // pthread_rwlock_unlock
|
||||
"+L98PIbGttk" or // scePthreadRwlockUnlock
|
||||
"q1cHNfGycLI" or // scePadRead
|
||||
"8aI7R7WaOlc" or // sceAmprCommandBufferConstructor
|
||||
"zgXifHT9ErY" or // sceVideoOutIsFlipPending
|
||||
"V++UgBtQhn0" or // sceAgcGetDataPacketPayloadAddress
|
||||
@@ -873,7 +895,7 @@ public sealed partial class DirectExecutionBackend
|
||||
"Q2V+iqvjgC0" or // vsnprintf
|
||||
"j4ViWNHEgww" or // strlen
|
||||
"5jNubw4vlAA" or // strnlen
|
||||
"LHMrG7e8G78" or // wcslen
|
||||
"LHMrG7e8G78" or // wcsmisc
|
||||
"WkkeywLJcgU" or // wcslen
|
||||
"Ovb2dSJOAuE" or // strcmp
|
||||
"aesyjrHVWy4" or // strncmp
|
||||
@@ -888,12 +910,7 @@ public sealed partial class DirectExecutionBackend
|
||||
"6ULAa0fq4jA" or // scePthreadRwlockInit
|
||||
"1471ajPzxh0" or // pthread_rwlock_destroy
|
||||
"BB+kb08Tl9A" or // scePthreadRwlockDestroy
|
||||
"iGjsr1WAtI0" or // pthread_rwlock_rdlock
|
||||
"Ox9i0c7L5w0" or // scePthreadRwlockRdlock
|
||||
"sIlRvQqsN2Y" or // pthread_rwlock_wrlock
|
||||
"mqdNorrB+gI" or // scePthreadRwlockWrlock
|
||||
"EgmLo6EWgso" or // pthread_rwlock_unlock
|
||||
"+L98PIbGttk" or // scePthreadRwlockUnlock
|
||||
// rwlock rd/wr lock removed (can block); init/destroy/unlock stay.
|
||||
"aI+OeCz8xrQ" or // scePthreadSelf
|
||||
"EotR8a3ASf4" or // pthread_self
|
||||
"eoht7mQOCmo" or // scePthreadGetspecific
|
||||
@@ -972,6 +989,31 @@ public sealed partial class DirectExecutionBackend
|
||||
return true;
|
||||
}
|
||||
|
||||
private unsafe bool TryAbortGuestForHostShutdown(nint argPackPtr, long dispatchIndex, ulong returnRip)
|
||||
{
|
||||
ulong hostExit = ActiveEntryReturnSentinelRip;
|
||||
if (hostExit < 65536 || !TryPatchActiveGuestReturnSlot(hostExit))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
*(ulong*)(argPackPtr + 96) = hostExit;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
ActiveForcedGuestExit = true;
|
||||
if (string.IsNullOrWhiteSpace(LastError))
|
||||
{
|
||||
LastError = "Host shutdown requested.";
|
||||
}
|
||||
Console.Error.WriteLine(
|
||||
$"[LOADER][INFO] Guest unwind for host shutdown at import#{dispatchIndex} ret=0x{returnRip:X16} -> host_exit=0x{hostExit:X16}");
|
||||
return true;
|
||||
}
|
||||
|
||||
private unsafe bool TryCompleteGuestEntryToHostStub(nint argPackPtr, long dispatchIndex, ulong returnRip, string nid, string reason, ulong value)
|
||||
{
|
||||
ulong hostExit = ActiveEntryReturnSentinelRip;
|
||||
@@ -1078,7 +1120,15 @@ public sealed partial class DirectExecutionBackend
|
||||
}
|
||||
|
||||
private static bool IsImportLoopGuardBoundary(string nid) =>
|
||||
string.Equals(nid, "1jfXLRVzisc", StringComparison.Ordinal);
|
||||
nid switch
|
||||
{
|
||||
"1jfXLRVzisc" => true, // sceKernelUsleep
|
||||
"QcteRwbsnV0" => true, // usleep
|
||||
"n88vx3C5nW8" => true, // gettimeofday
|
||||
"Zxa0VhQVTsk" => true, // sceKernelWaitSema
|
||||
"T72hz6ffq08" => true, // scePthreadYield
|
||||
_ => false
|
||||
};
|
||||
|
||||
private void ResetImportLoopPattern()
|
||||
{
|
||||
@@ -1673,9 +1723,9 @@ public sealed partial class DirectExecutionBackend
|
||||
{
|
||||
var candidateBase = ImportStubRegionCanonicalBase -
|
||||
(ulong)candidateIndex * ImportStubRegionAddressStride;
|
||||
if (VirtualQuery((void*)candidateBase, out var memoryInfo, (nuint)sizeof(MEMORY_BASIC_INFORMATION64)) == 0 ||
|
||||
if (!_hostMemory.Query(candidateBase, out var memoryInfo) ||
|
||||
memoryInfo.RegionSize == 0 ||
|
||||
memoryInfo.State != 4096)
|
||||
memoryInfo.State != HostRegionState.Committed)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -1916,23 +1966,36 @@ public sealed partial class DirectExecutionBackend
|
||||
return false;
|
||||
}
|
||||
|
||||
List<byte> list = new List<byte>(Math.Min(maxLength, 256));
|
||||
Span<byte> destination = stackalloc byte[1];
|
||||
for (int i = 0; i < maxLength; i++)
|
||||
// Reads stay byte-by-byte through TryReadByteCompat (its Marshal.ReadByte
|
||||
// fallback must probe exactly up to the terminator), but the bytes land in a
|
||||
// stack buffer instead of a List<byte> + ToArray per symbol resolution.
|
||||
const int StackBufferLength = 512;
|
||||
byte[]? rented = maxLength > StackBufferLength ? System.Buffers.ArrayPool<byte>.Shared.Rent(maxLength) : null;
|
||||
Span<byte> buffer = rented is null ? stackalloc byte[StackBufferLength] : rented;
|
||||
try
|
||||
{
|
||||
if (!TryReadByteCompat(address + (ulong)i, destination))
|
||||
for (int i = 0; i < maxLength; i++)
|
||||
{
|
||||
return false;
|
||||
if (!TryReadByteCompat(address + (ulong)i, buffer.Slice(i, 1)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (buffer[i] == 0)
|
||||
{
|
||||
value = System.Text.Encoding.ASCII.GetString(buffer[..i]);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
value = System.Text.Encoding.ASCII.GetString(buffer[..maxLength]);
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (rented is not null)
|
||||
{
|
||||
System.Buffers.ArrayPool<byte>.Shared.Return(rented);
|
||||
}
|
||||
if (destination[0] == 0)
|
||||
{
|
||||
value = System.Text.Encoding.ASCII.GetString(list.ToArray());
|
||||
return true;
|
||||
}
|
||||
list.Add(destination[0]);
|
||||
}
|
||||
value = System.Text.Encoding.ASCII.GetString(list.ToArray());
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryReadByteCompat(ulong address, Span<byte> destination)
|
||||
@@ -2014,7 +2077,7 @@ public sealed partial class DirectExecutionBackend
|
||||
uint flNewProtect = default(uint);
|
||||
try
|
||||
{
|
||||
if (Marshal.ReadByte(num2) != 232 || !VirtualProtect((void*)num, 5u, 64u, &flNewProtect))
|
||||
if (Marshal.ReadByte(num2) != 232 || !_hostMemory.Protect((ulong)(void*)num, 5u, HostPageProtection.ReadWriteExecute, out flNewProtect))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -2022,7 +2085,7 @@ public sealed partial class DirectExecutionBackend
|
||||
{
|
||||
Marshal.WriteByte(num2 + i, 144);
|
||||
}
|
||||
FlushInstructionCache(GetCurrentProcess(), (void*)num, 5u);
|
||||
_hostMemory.FlushInstructionCache((ulong)(void*)num, 5u);
|
||||
_patchedEa020eLookupCall = true;
|
||||
Console.Error.WriteLine($"[LOADER][WARNING] Import#{dispatchIndex}: patched hash-lookup call at 0x{num:X16} -> NOP*5");
|
||||
}
|
||||
@@ -2033,7 +2096,7 @@ public sealed partial class DirectExecutionBackend
|
||||
{
|
||||
if (flNewProtect != 0)
|
||||
{
|
||||
VirtualProtect((void*)num, 5u, flNewProtect, &flNewProtect);
|
||||
_hostMemory.ProtectRaw((ulong)(void*)num, 5u, flNewProtect, out flNewProtect);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using SharpEmu.HLE;
|
||||
using SharpEmu.HLE.Host;
|
||||
using SharpEmu.HLE.Host.Posix;
|
||||
|
||||
namespace SharpEmu.Core.Cpu.Native;
|
||||
|
||||
@@ -35,20 +37,6 @@ public sealed partial class DirectExecutionBackend
|
||||
private bool _nativeWorkersDisposed;
|
||||
private int _nativeWorkerCreationFailedLogged;
|
||||
|
||||
private const uint StackSizeParamIsAReservation = 0x00010000u;
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern nint CreateThread(
|
||||
nint lpThreadAttributes,
|
||||
nuint dwStackSize,
|
||||
nint lpStartAddress,
|
||||
nint lpParameter,
|
||||
uint dwCreationFlags,
|
||||
out uint lpThreadId);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern uint WaitForSingleObject(nint hHandle, uint dwMilliseconds);
|
||||
|
||||
// Runs an emitted guest entry stub. Preferred path is a pooled native worker
|
||||
// thread; falls back to the historical inline calli (guest frames above this
|
||||
// thread's managed frames) when workers are disabled or unavailable.
|
||||
@@ -61,7 +49,7 @@ public sealed partial class DirectExecutionBackend
|
||||
var worker = RentNativeGuestExecutor();
|
||||
if (worker is null)
|
||||
{
|
||||
TlsSetValue(_hostRspSlotTlsIndex, (nint)hostRspSlot);
|
||||
_hostThreading.SetTlsValue(_hostRspSlotTlsIndex, (nint)hostRspSlot);
|
||||
return CallNativeEntry(entryStub);
|
||||
}
|
||||
try
|
||||
@@ -185,8 +173,20 @@ public sealed partial class DirectExecutionBackend
|
||||
private static nint _exitThreadAddress;
|
||||
|
||||
private readonly DirectExecutionBackend _backend;
|
||||
private readonly AutoResetEvent _workAvailable = new(false);
|
||||
private readonly AutoResetEvent _workCompleted = new(false);
|
||||
// Windows uses AutoResetEvent (its SafeWaitHandle is a real kernel
|
||||
// event the emitted loop can wait on); POSIX uses worker-event
|
||||
// semaphores shared the same way via PosixHostStubs.
|
||||
private readonly AutoResetEvent? _workAvailable;
|
||||
private readonly AutoResetEvent? _workCompleted;
|
||||
private nint _workSemaphore;
|
||||
private nint _doneSemaphore;
|
||||
|
||||
// RunPrologue/RunEpilogue compile to the host ABI (SysV on POSIX); the
|
||||
// emitted loop calls them with Win64 registers, so POSIX routes the
|
||||
// calls through register-shuffling thunks (shared by all workers).
|
||||
private static nint _posixPrologueThunk;
|
||||
private static nint _posixEpilogueThunk;
|
||||
private static readonly object PosixThunkGate = new();
|
||||
private GCHandle _selfHandle;
|
||||
private void* _controlBlock;
|
||||
private void* _loopStub;
|
||||
@@ -225,11 +225,16 @@ public sealed partial class DirectExecutionBackend
|
||||
private NativeGuestExecutor(DirectExecutionBackend backend)
|
||||
{
|
||||
_backend = backend;
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
_workAvailable = new AutoResetEvent(false);
|
||||
_workCompleted = new AutoResetEvent(false);
|
||||
}
|
||||
}
|
||||
|
||||
public static NativeGuestExecutor? TryCreate(DirectExecutionBackend backend)
|
||||
{
|
||||
if (!EnsureKernel32Exports())
|
||||
if (!EnsureHostRuntimeExports(backend._hostSymbols))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
@@ -242,32 +247,27 @@ public sealed partial class DirectExecutionBackend
|
||||
return executor;
|
||||
}
|
||||
|
||||
private static bool EnsureKernel32Exports()
|
||||
private static bool EnsureHostRuntimeExports(IHostSymbolResolver symbols)
|
||||
{
|
||||
if (_exitThreadAddress != 0)
|
||||
{
|
||||
return _waitForSingleObjectAddress != 0 && _setEventAddress != 0;
|
||||
}
|
||||
nint kernel32 = GetModuleHandle("kernel32.dll");
|
||||
if (kernel32 == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
_waitForSingleObjectAddress = GetProcAddress(kernel32, "WaitForSingleObject");
|
||||
_setEventAddress = GetProcAddress(kernel32, "SetEvent");
|
||||
_exitThreadAddress = GetProcAddress(kernel32, "ExitThread");
|
||||
_waitForSingleObjectAddress = symbols.GetAddress(HostRuntimeFunction.WaitForSingleObject);
|
||||
_setEventAddress = symbols.GetAddress(HostRuntimeFunction.SetEvent);
|
||||
_exitThreadAddress = symbols.GetAddress(HostRuntimeFunction.ExitThread);
|
||||
return _waitForSingleObjectAddress != 0 && _setEventAddress != 0 && _exitThreadAddress != 0;
|
||||
}
|
||||
|
||||
private bool Initialize()
|
||||
{
|
||||
_selfHandle = GCHandle.Alloc(this);
|
||||
_controlBlock = VirtualAlloc(null, 4096u, 12288u, 4u);
|
||||
_controlBlock = (void*)_backend._hostMemory.Allocate(0, 4096u, HostPageProtection.ReadWrite);
|
||||
if (_controlBlock == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
_loopStub = VirtualAlloc(null, LoopStubSize, 12288u, 64u);
|
||||
_loopStub = (void*)_backend._hostMemory.Allocate(0, LoopStubSize, HostPageProtection.ReadWriteExecute);
|
||||
if (_loopStub == null)
|
||||
{
|
||||
return false;
|
||||
@@ -276,8 +276,34 @@ public sealed partial class DirectExecutionBackend
|
||||
var prologuePtr = (nint)(delegate* unmanaged<nint, nint>)&RunPrologue;
|
||||
var epiloguePtr = (nint)(delegate* unmanaged<nint, int, void>)&RunEpilogue;
|
||||
var executorHandle = GCHandle.ToIntPtr(_selfHandle);
|
||||
var workHandle = _workAvailable.SafeWaitHandle.DangerousGetHandle();
|
||||
var doneHandle = _workCompleted.SafeWaitHandle.DangerousGetHandle();
|
||||
nint workHandle;
|
||||
nint doneHandle;
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
workHandle = _workAvailable!.SafeWaitHandle.DangerousGetHandle();
|
||||
doneHandle = _workCompleted!.SafeWaitHandle.DangerousGetHandle();
|
||||
}
|
||||
else
|
||||
{
|
||||
lock (PosixThunkGate)
|
||||
{
|
||||
if (_posixPrologueThunk == 0)
|
||||
{
|
||||
_posixPrologueThunk = PosixHostStubs.CreateWin64ToSysVThunk(prologuePtr);
|
||||
_posixEpilogueThunk = PosixHostStubs.CreateWin64ToSysVThunk(epiloguePtr);
|
||||
}
|
||||
}
|
||||
prologuePtr = _posixPrologueThunk;
|
||||
epiloguePtr = _posixEpilogueThunk;
|
||||
_workSemaphore = PosixHostStubs.CreateWorkerEvent();
|
||||
_doneSemaphore = PosixHostStubs.CreateWorkerEvent();
|
||||
if (_workSemaphore == 0 || _doneSemaphore == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
workHandle = _workSemaphore;
|
||||
doneHandle = _doneSemaphore;
|
||||
}
|
||||
|
||||
byte* code = (byte*)_loopStub;
|
||||
int offset = 0;
|
||||
@@ -349,17 +375,15 @@ public sealed partial class DirectExecutionBackend
|
||||
*(int*)(code + skipJump) = skipEntryOffset - (skipJump + sizeof(int));
|
||||
|
||||
uint oldProtect = 0;
|
||||
if (!VirtualProtect(_loopStub, LoopStubSize, 32u, &oldProtect))
|
||||
if (!_backend._hostMemory.Protect((ulong)_loopStub, LoopStubSize, HostPageProtection.ReadExecute, out oldProtect))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
FlushInstructionCache(GetCurrentProcess(), _loopStub, LoopStubSize);
|
||||
_threadHandle = CreateThread(
|
||||
0,
|
||||
WorkerStackReservation,
|
||||
_backend._hostMemory.FlushInstructionCache((ulong)_loopStub, LoopStubSize);
|
||||
_threadHandle = _backend._hostThreading.CreateNativeThread(
|
||||
(nint)_loopStub,
|
||||
0,
|
||||
StackSizeParamIsAReservation,
|
||||
WorkerStackReservation,
|
||||
out _nativeThreadId);
|
||||
if (_threadHandle == 0)
|
||||
{
|
||||
@@ -397,8 +421,8 @@ public sealed partial class DirectExecutionBackend
|
||||
_runYieldRequested = false;
|
||||
_runYieldReason = null;
|
||||
_runForcedExit = false;
|
||||
_workAvailable.Set();
|
||||
_workCompleted.WaitOne();
|
||||
SignalWorkAvailable();
|
||||
WaitWorkCompleted();
|
||||
_runContext = null;
|
||||
_runState = null;
|
||||
yieldRequested = _runYieldRequested;
|
||||
@@ -411,6 +435,28 @@ public sealed partial class DirectExecutionBackend
|
||||
return _runNativeResult;
|
||||
}
|
||||
|
||||
private void SignalWorkAvailable()
|
||||
{
|
||||
if (_workAvailable is not null)
|
||||
{
|
||||
_workAvailable.Set();
|
||||
return;
|
||||
}
|
||||
|
||||
_ = PosixHostStubs.SignalWorkerEvent(_workSemaphore);
|
||||
}
|
||||
|
||||
private void WaitWorkCompleted()
|
||||
{
|
||||
if (_workCompleted is not null)
|
||||
{
|
||||
_workCompleted.WaitOne();
|
||||
return;
|
||||
}
|
||||
|
||||
_ = PosixHostStubs.WaitWorkerEvent(_doneSemaphore, -1);
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly]
|
||||
private static nint RunPrologue(nint executorHandle)
|
||||
{
|
||||
@@ -465,7 +511,7 @@ public sealed partial class DirectExecutionBackend
|
||||
_prevYieldRequested = _activeGuestThreadYieldRequested;
|
||||
_prevYieldReason = _activeGuestThreadYieldReason;
|
||||
_prevState = _activeGuestThreadState;
|
||||
_prevHostRspSlot = TlsGetValue(backend._hostRspSlotTlsIndex);
|
||||
_prevHostRspSlot = backend._hostThreading.GetTlsValue(backend._hostRspSlotTlsIndex);
|
||||
_prevGuestThreadHandle = GuestThreadExecution.EnterGuestThread(_runGuestThreadHandle);
|
||||
_entered = true;
|
||||
_activeExecutionBackend = backend;
|
||||
@@ -477,11 +523,11 @@ public sealed partial class DirectExecutionBackend
|
||||
_activeGuestThreadYieldReason = null;
|
||||
_activeGuestThreadState = _runState;
|
||||
backend.BindTlsBase(_runContext!);
|
||||
TlsSetValue(backend._hostRspSlotTlsIndex, _runHostRspSlot);
|
||||
backend._hostThreading.SetTlsValue(backend._hostRspSlotTlsIndex, _runHostRspSlot);
|
||||
if (_runState is { } state)
|
||||
{
|
||||
_prevHostThreadId = Volatile.Read(ref state.HostThreadId);
|
||||
Volatile.Write(ref state.HostThreadId, unchecked((int)GetCurrentThreadId()));
|
||||
Volatile.Write(ref state.HostThreadId, unchecked((int)backend._hostThreading.CurrentThreadId));
|
||||
}
|
||||
if (_runAffinityMask != 0)
|
||||
{
|
||||
@@ -511,7 +557,7 @@ public sealed partial class DirectExecutionBackend
|
||||
{
|
||||
Volatile.Write(ref state.HostThreadId, _prevHostThreadId);
|
||||
}
|
||||
TlsSetValue(_backend._hostRspSlotTlsIndex, _prevHostRspSlot);
|
||||
_backend._hostThreading.SetTlsValue(_backend._hostRspSlotTlsIndex, _prevHostRspSlot);
|
||||
GuestThreadExecution.RestoreGuestThread(_prevGuestThreadHandle);
|
||||
_activeExecutionBackend = _prevBackend;
|
||||
_activeCpuContext = _prevContext;
|
||||
@@ -540,7 +586,7 @@ public sealed partial class DirectExecutionBackend
|
||||
}
|
||||
try
|
||||
{
|
||||
_workAvailable.Set();
|
||||
SignalWorkAvailable();
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
@@ -548,8 +594,8 @@ public sealed partial class DirectExecutionBackend
|
||||
var exited = _threadHandle == 0;
|
||||
if (_threadHandle != 0)
|
||||
{
|
||||
exited = WaitForSingleObject(_threadHandle, 1000u) == 0u;
|
||||
CloseHandle(_threadHandle);
|
||||
exited = _backend._hostThreading.WaitForThreadExit(_threadHandle, 1000u);
|
||||
_backend._hostThreading.CloseThreadHandle(_threadHandle);
|
||||
_threadHandle = 0;
|
||||
}
|
||||
if (!exited)
|
||||
@@ -563,20 +609,30 @@ public sealed partial class DirectExecutionBackend
|
||||
}
|
||||
if (_loopStub != null)
|
||||
{
|
||||
VirtualFree(_loopStub, 0u, 32768u);
|
||||
_backend._hostMemory.Free((ulong)_loopStub);
|
||||
_loopStub = null;
|
||||
}
|
||||
if (_controlBlock != null)
|
||||
{
|
||||
VirtualFree(_controlBlock, 0u, 32768u);
|
||||
_backend._hostMemory.Free((ulong)_controlBlock);
|
||||
_controlBlock = null;
|
||||
}
|
||||
if (_selfHandle.IsAllocated)
|
||||
{
|
||||
_selfHandle.Free();
|
||||
}
|
||||
_workAvailable.Dispose();
|
||||
_workCompleted.Dispose();
|
||||
_workAvailable?.Dispose();
|
||||
_workCompleted?.Dispose();
|
||||
if (_workSemaphore != 0)
|
||||
{
|
||||
PosixHostStubs.DestroyWorkerEvent(_workSemaphore);
|
||||
_workSemaphore = 0;
|
||||
}
|
||||
if (_doneSemaphore != 0)
|
||||
{
|
||||
PosixHostStubs.DestroyWorkerEvent(_doneSemaphore);
|
||||
_doneSemaphore = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using SharpEmu.Core.Cpu.Native.Windows;
|
||||
|
||||
namespace SharpEmu.Core.Cpu.Native;
|
||||
|
||||
public sealed unsafe partial class DirectExecutionBackend
|
||||
{
|
||||
// POSIX bridge for the Windows vectored-exception-handler logic. A
|
||||
// sigaction(SIGSEGV/SIGBUS/SIGILL) handler rebuilds the EXCEPTION_POINTERS
|
||||
// view the shared handlers expect (Win64 CONTEXT register offsets) from
|
||||
// the signal's mcontext, runs the same recovery chain the VEH path uses
|
||||
// (unresolved-import trap sentinels, demand-paging of lazily-committed
|
||||
// guest pages, fault diagnostics), and writes register changes back into
|
||||
// the mcontext so sigreturn resumes the repaired guest. Unrecovered
|
||||
// faults are forwarded to the previously installed handler so the .NET
|
||||
// runtime keeps turning its own faults into managed exceptions.
|
||||
|
||||
private const int PosixSigIll = 4;
|
||||
private const int PosixSigSegv = 11;
|
||||
private static readonly int PosixSigBus = OperatingSystem.IsMacOS() ? 10 : 7;
|
||||
|
||||
// struct sigaction: the handler pointer leads on both platforms; Darwin
|
||||
// packs { handler(8), mask(4), flags(4) }, Linux glibc/musl packs
|
||||
// { handler(8), mask(128), flags(4), restorer(8) }.
|
||||
private static readonly int PosixSigactionSize = OperatingSystem.IsMacOS() ? 16 : 152;
|
||||
private static readonly int PosixSigactionFlagsOffset = OperatingSystem.IsMacOS() ? 12 : 136;
|
||||
|
||||
private static readonly int PosixSaSigInfo = OperatingSystem.IsMacOS() ? 0x0040 : 0x0004;
|
||||
private static readonly int PosixSaNoDefer = OperatingSystem.IsMacOS() ? 0x0010 : 0x40000000;
|
||||
|
||||
// siginfo_t.si_addr: Darwin { signo, errno, code, pid, uid, status, addr },
|
||||
// Linux { signo, errno, code, pad32, addr }.
|
||||
private static readonly int PosixSigInfoAddressOffset = OperatingSystem.IsMacOS() ? 24 : 16;
|
||||
|
||||
// Darwin ucontext_t stores a pointer to __darwin_mcontext64 at +48; the
|
||||
// general registers live in its __ss thread state after the 16-byte
|
||||
// exception state. Linux glibc embeds mcontext_t inline at +40 with the
|
||||
// registers in gregs[23]. Rosetta 2 delivers the regular x86-64 layout
|
||||
// to translated processes.
|
||||
private const int DarwinUcontextMcontextOffset = 48;
|
||||
private const int DarwinMcontextErrOffset = 4;
|
||||
private const int DarwinMcontextFaultAddressOffset = 8;
|
||||
private const int LinuxUcontextGregsOffset = 40;
|
||||
private const int LinuxGregsErrOffset = 19 * 8;
|
||||
|
||||
// Byte offsets of the general registers relative to GetPosixRegisterBase,
|
||||
// ordered to match the contiguous Win64 CONTEXT block CTX_RAX..CTX_RIP
|
||||
// (rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi, r8..r15, rip). Verified
|
||||
// against the x86-64 platform headers.
|
||||
private static readonly int[] PosixRegisterOffsets = OperatingSystem.IsMacOS()
|
||||
? new[] { 16, 32, 40, 24, 72, 64, 56, 48, 80, 88, 96, 104, 112, 120, 128, 136, 144 }
|
||||
: new[] { 104, 112, 96, 88, 120, 80, 72, 64, 0, 8, 16, 24, 32, 40, 48, 56, 128 };
|
||||
|
||||
private static DirectExecutionBackend? _posixSignalBackend;
|
||||
private static bool _posixSignalHandlersInstalled;
|
||||
private static bool _posixRawRecoveryEnabled;
|
||||
private static bool _posixSignalWarmup;
|
||||
private static readonly nint[] _posixPreviousActions = new nint[32];
|
||||
private static int _posixSignalTraceCount;
|
||||
|
||||
[ThreadStatic]
|
||||
private static int _posixSignalHandlerDepth;
|
||||
|
||||
private void SetupPosixExceptionHandler()
|
||||
{
|
||||
if (string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_DISABLE_POSIX_SIGNALS"), "1", StringComparison.Ordinal))
|
||||
{
|
||||
Console.Error.WriteLine("[LOADER][WARN] POSIX signal exception bridge disabled by SHARPEMU_DISABLE_POSIX_SIGNALS=1; guest faults will not be recovered.");
|
||||
return;
|
||||
}
|
||||
|
||||
_posixSignalBackend = this;
|
||||
if (_posixSignalHandlersInstalled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_posixRawRecoveryEnabled = !string.Equals(
|
||||
Environment.GetEnvironmentVariable("SHARPEMU_DISABLE_RAW_HANDLER"), "1", StringComparison.Ordinal);
|
||||
if (!_posixRawRecoveryEnabled)
|
||||
{
|
||||
Console.Error.WriteLine("[LOADER][INFO] Raw sentinel recovery disabled by SHARPEMU_DISABLE_RAW_HANDLER=1");
|
||||
}
|
||||
|
||||
WarmUpPosixSignalPath();
|
||||
|
||||
if (!InstallPosixSignalHandler(PosixSigSegv) ||
|
||||
!InstallPosixSignalHandler(PosixSigBus) ||
|
||||
!InstallPosixSignalHandler(PosixSigIll))
|
||||
{
|
||||
throw new InvalidOperationException("Failed to install POSIX fault signal handlers");
|
||||
}
|
||||
|
||||
_posixSignalHandlersInstalled = true;
|
||||
Console.Error.WriteLine("[LOADER][INFO] POSIX signal exception bridge installed (SIGSEGV/SIGBUS/SIGILL)");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the signal-recovery path once with fabricated inputs before the
|
||||
/// handlers are installed. The first entry into the handler must not
|
||||
/// require JIT compilation (a fault can interrupt arbitrary runtime
|
||||
/// states), and under Rosetta 2 the signal trampoline cannot enter x86
|
||||
/// code that has never been executed (and therefore never translated): a
|
||||
/// cold handler is silently never invoked and the faulting instruction
|
||||
/// retries forever.
|
||||
/// </summary>
|
||||
private void WarmUpPosixSignalPath()
|
||||
{
|
||||
byte* fakeUcontext = stackalloc byte[512];
|
||||
new Span<byte>(fakeUcontext, 512).Clear();
|
||||
byte* fakeMcontext = stackalloc byte[512];
|
||||
new Span<byte>(fakeMcontext, 512).Clear();
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
*(byte**)(fakeUcontext + DarwinUcontextMcontextOffset) = fakeMcontext;
|
||||
}
|
||||
|
||||
_posixSignalWarmup = true;
|
||||
try
|
||||
{
|
||||
((delegate* unmanaged<int, nint, nint, void>)&HandlePosixSignal)(PosixSigSegv, 0, (nint)fakeUcontext);
|
||||
|
||||
// Warm the branches the fabricated fault above skips without
|
||||
// spamming diagnostics: the benign-exception path through
|
||||
// VectoredHandler, the lazy-commit probe (fault address 0 bails
|
||||
// out immediately), and the chain helper (signal 0 has no saved
|
||||
// action and sigaction(0, ...) fails with EINVAL).
|
||||
EXCEPTION_RECORD record = default;
|
||||
record.ExceptionCode = DBG_PRINTEXCEPTION_C;
|
||||
byte* contextRecord = stackalloc byte[Win64ContextOffsets.Size];
|
||||
new Span<byte>(contextRecord, Win64ContextOffsets.Size).Clear();
|
||||
EXCEPTION_POINTERS pointers;
|
||||
pointers.ExceptionRecord = &record;
|
||||
pointers.ContextRecord = contextRecord;
|
||||
_ = VectoredHandler(&pointers);
|
||||
|
||||
record.ExceptionCode = 3221225477u;
|
||||
record.NumberParameters = 2;
|
||||
// 0x70000 is never guest-owned, so this walks the vmem region
|
||||
// scan and the PRT range check, then bails out silently.
|
||||
record.ExceptionInformation[1] = 0x70000;
|
||||
_ = TryHandleLazyCommittedPage(&record, 0, 0);
|
||||
ChainPreviousPosixAction(0, 0, 0);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_posixSignalWarmup = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool InstallPosixSignalHandler(int signal)
|
||||
{
|
||||
byte* action = stackalloc byte[PosixSigactionSize];
|
||||
new Span<byte>(action, PosixSigactionSize).Clear();
|
||||
*(nint*)action = (nint)(delegate* unmanaged<int, nint, nint, void>)&HandlePosixSignal;
|
||||
// No SA_ONSTACK: the runtime's alternate stacks are far too small for
|
||||
// the recovery/diagnostic path (JIT compilation of cold handler code
|
||||
// can run inside the signal frame). Guest faults deliver onto the 2MB
|
||||
// guest stack, host faults onto the regular thread stack — the same
|
||||
// stacks Windows dispatches exceptions on.
|
||||
*(int*)(action + PosixSigactionFlagsOffset) = PosixSaSigInfo | PosixSaNoDefer;
|
||||
|
||||
var previous = (byte*)NativeMemory.AllocZeroed((nuint)PosixSigactionSize);
|
||||
if (sigaction(signal, action, previous) != 0)
|
||||
{
|
||||
NativeMemory.Free(previous);
|
||||
Console.Error.WriteLine($"[LOADER][ERROR] sigaction({signal}) failed: errno={Marshal.GetLastPInvokeError()}");
|
||||
return false;
|
||||
}
|
||||
|
||||
_posixPreviousActions[signal] = (nint)previous;
|
||||
return true;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly]
|
||||
private static void HandlePosixSignal(int signal, nint siginfo, nint ucontext)
|
||||
{
|
||||
if (_posixSignalHandlerDepth > 0)
|
||||
{
|
||||
// A fault inside our own fault handler (diagnostics touched an
|
||||
// unmapped address): restore the default action and return so the
|
||||
// re-executed instruction terminates the process.
|
||||
RestoreDefaultPosixAction(signal);
|
||||
return;
|
||||
}
|
||||
|
||||
_posixSignalHandlerDepth++;
|
||||
try
|
||||
{
|
||||
if (TryHandlePosixFault(signal, siginfo, ucontext))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// A managed exception must never unwind out of a signal frame.
|
||||
}
|
||||
finally
|
||||
{
|
||||
_posixSignalHandlerDepth--;
|
||||
}
|
||||
|
||||
ChainPreviousPosixAction(signal, siginfo, ucontext);
|
||||
}
|
||||
|
||||
private static bool TryHandlePosixFault(int signal, nint siginfo, nint ucontext)
|
||||
{
|
||||
byte* registers = GetPosixRegisterBase(ucontext);
|
||||
if (registers == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
byte* contextRecord = stackalloc byte[Win64ContextOffsets.Size];
|
||||
new Span<byte>(contextRecord, Win64ContextOffsets.Size).Clear();
|
||||
int[] offsets = PosixRegisterOffsets;
|
||||
for (int i = 0; i < offsets.Length; i++)
|
||||
{
|
||||
WriteCtxU64(contextRecord, CTX_RAX + i * 8, *(ulong*)(registers + offsets[i]));
|
||||
}
|
||||
|
||||
EXCEPTION_RECORD record = default;
|
||||
record.ExceptionAddress = (void*)ReadCtxU64(contextRecord, CTX_RIP);
|
||||
if (signal == PosixSigIll)
|
||||
{
|
||||
record.ExceptionCode = 3221225501u;
|
||||
}
|
||||
else
|
||||
{
|
||||
ulong faultAddress = GetPosixFaultAddress(siginfo, registers);
|
||||
record.ExceptionCode = 3221225477u;
|
||||
record.NumberParameters = 2;
|
||||
record.ExceptionInformation[0] = GetPosixAccessType(registers, faultAddress, ReadCtxU64(contextRecord, CTX_RIP));
|
||||
record.ExceptionInformation[1] = faultAddress;
|
||||
}
|
||||
|
||||
EXCEPTION_POINTERS pointers;
|
||||
pointers.ExceptionRecord = &record;
|
||||
pointers.ContextRecord = contextRecord;
|
||||
|
||||
int traceIndex = _posixSignalWarmup ? 0 : Interlocked.Increment(ref _posixSignalTraceCount);
|
||||
bool traceSignal = traceIndex > 0 && (traceIndex <= 16 || traceIndex % 1024 == 0 ||
|
||||
string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_POSIX_SIGNALS"), "1", StringComparison.Ordinal));
|
||||
if (traceSignal)
|
||||
{
|
||||
Console.Error.WriteLine(
|
||||
$"[LOADER][TRACE] posix-signal#{traceIndex}: sig={signal} rip=0x{ReadCtxU64(contextRecord, CTX_RIP):X16} " +
|
||||
$"fault=0x{record.ExceptionInformation[1]:X16} access={record.ExceptionInformation[0]} rsp=0x{ReadCtxU64(contextRecord, CTX_RSP):X16}");
|
||||
Console.Error.Flush();
|
||||
}
|
||||
|
||||
// Sentinel recovery runs first: on Windows both vectored handlers see
|
||||
// every fault anyway, and recovering here avoids dumping the full
|
||||
// VectoredHandler diagnostics for each recoverable trap.
|
||||
int disposition = 0;
|
||||
if (_posixRawRecoveryEnabled)
|
||||
{
|
||||
disposition = TryRecoverUnresolvedSentinel(&pointers);
|
||||
}
|
||||
if (disposition != -1 && !_posixSignalWarmup && _posixSignalBackend is { } backend)
|
||||
{
|
||||
disposition = backend.VectoredHandler(&pointers);
|
||||
}
|
||||
if (traceSignal)
|
||||
{
|
||||
Console.Error.WriteLine(
|
||||
$"[LOADER][TRACE] posix-signal#{traceIndex}: recovered={disposition == -1} new_rip=0x{ReadCtxU64(contextRecord, CTX_RIP):X16}");
|
||||
Console.Error.Flush();
|
||||
}
|
||||
if (disposition != -1 && !_posixSignalWarmup)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < offsets.Length; i++)
|
||||
{
|
||||
*(ulong*)(registers + offsets[i]) = ReadCtxU64(contextRecord, CTX_RAX + i * 8);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static byte* GetPosixRegisterBase(nint ucontext)
|
||||
{
|
||||
if (ucontext == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
return *(byte**)((byte*)ucontext + DarwinUcontextMcontextOffset);
|
||||
}
|
||||
|
||||
return (byte*)ucontext + LinuxUcontextGregsOffset;
|
||||
}
|
||||
|
||||
private static ulong GetPosixFaultAddress(nint siginfo, byte* registers)
|
||||
{
|
||||
ulong address = siginfo != 0 ? *(ulong*)((byte*)siginfo + PosixSigInfoAddressOffset) : 0;
|
||||
if (address == 0 && OperatingSystem.IsMacOS())
|
||||
{
|
||||
address = *(ulong*)(registers + DarwinMcontextFaultAddressOffset);
|
||||
}
|
||||
|
||||
return address;
|
||||
}
|
||||
|
||||
private static ulong GetPosixAccessType(byte* registers, ulong faultAddress, ulong rip)
|
||||
{
|
||||
// x86 page-fault error code: bit 1 = write access, bit 4 = instruction
|
||||
// fetch. Fall back to comparing the fault address against RIP when
|
||||
// the error code is not populated (e.g. under Rosetta 2 translation).
|
||||
ulong error = OperatingSystem.IsMacOS()
|
||||
? *(uint*)(registers + DarwinMcontextErrOffset)
|
||||
: *(ulong*)(registers + LinuxGregsErrOffset);
|
||||
if ((error & 0x10) != 0)
|
||||
{
|
||||
return 8;
|
||||
}
|
||||
if ((error & 0x2) != 0)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
return faultAddress != 0 && faultAddress == rip ? 8u : 0u;
|
||||
}
|
||||
|
||||
private static void RestoreDefaultPosixAction(int signal)
|
||||
{
|
||||
byte* action = stackalloc byte[PosixSigactionSize];
|
||||
new Span<byte>(action, PosixSigactionSize).Clear();
|
||||
_ = sigaction(signal, action, null);
|
||||
}
|
||||
|
||||
private static void ChainPreviousPosixAction(int signal, nint siginfo, nint ucontext)
|
||||
{
|
||||
byte* previous = (uint)signal < (uint)_posixPreviousActions.Length
|
||||
? (byte*)_posixPreviousActions[signal]
|
||||
: null;
|
||||
nint handler = previous != null ? *(nint*)previous : 0;
|
||||
if (handler == 0)
|
||||
{
|
||||
// SIG_DFL (or nothing saved): reinstate the default action and
|
||||
// return, so re-executing the faulting instruction terminates the
|
||||
// process with the original fault context intact.
|
||||
RestoreDefaultPosixAction(signal);
|
||||
return;
|
||||
}
|
||||
if (handler == 1)
|
||||
{
|
||||
// SIG_IGN
|
||||
return;
|
||||
}
|
||||
|
||||
int flags = *(int*)(previous + PosixSigactionFlagsOffset);
|
||||
if ((flags & PosixSaSigInfo) != 0)
|
||||
{
|
||||
((delegate* unmanaged<int, nint, nint, void>)handler)(signal, siginfo, ucontext);
|
||||
}
|
||||
else
|
||||
{
|
||||
((delegate* unmanaged<int, void>)handler)(signal);
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport("libc", SetLastError = true)]
|
||||
private static extern int sigaction(int signum, void* act, void* oldact);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,49 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using SharpEmu.HLE.Host;
|
||||
|
||||
namespace SharpEmu.Core.Cpu.Native;
|
||||
|
||||
/// <summary>
|
||||
/// Placeholder for hosts whose fault bridge is installed directly by the
|
||||
/// execution backend. POSIX uses its sigaction bridge and never calls these
|
||||
/// Windows-shaped registration methods.
|
||||
/// </summary>
|
||||
internal sealed class NullHostFaultHandling : IHostFaultHandling
|
||||
{
|
||||
public static NullHostFaultHandling Instance { get; } = new();
|
||||
|
||||
private NullHostFaultHandling()
|
||||
{
|
||||
}
|
||||
|
||||
public nint CreateHandlerThunk(nint managedCallback, uint hostRspSwitchTlsSlot, nint tlsGetValueAddress)
|
||||
{
|
||||
_ = managedCallback;
|
||||
_ = hostRspSwitchTlsSlot;
|
||||
_ = tlsGetValueAddress;
|
||||
return 0;
|
||||
}
|
||||
|
||||
public void FreeThunk(nint thunk)
|
||||
{
|
||||
_ = thunk;
|
||||
}
|
||||
|
||||
public nint AddFirstChanceHandler(nint thunk)
|
||||
{
|
||||
_ = thunk;
|
||||
return 0;
|
||||
}
|
||||
|
||||
public void RemoveHandler(nint handle)
|
||||
{
|
||||
_ = handle;
|
||||
}
|
||||
|
||||
public void SetUnhandledFilter(nint thunk)
|
||||
{
|
||||
_ = thunk;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
using SharpEmu.HLE;
|
||||
using SharpEmu.HLE.Host;
|
||||
|
||||
namespace SharpEmu.Core.Cpu.Native;
|
||||
|
||||
@@ -11,17 +12,15 @@ public sealed unsafe class StubManager : IDisposable
|
||||
private readonly List<nint> _allocatedStubs = new();
|
||||
private readonly Dictionary<string, nint> _importHandlers = new();
|
||||
private readonly Dictionary<ulong, nint> _stubAddresses = new();
|
||||
private readonly IHostMemory _hostMemory;
|
||||
private byte* _pltMemory;
|
||||
private int _pltOffset;
|
||||
private const int PltMemorySize = 1024 * 1024; // 1MB for stubs
|
||||
|
||||
public StubManager()
|
||||
public StubManager(IHostMemory? hostMemory = null)
|
||||
{
|
||||
_pltMemory = (byte*)VirtualAlloc(
|
||||
null,
|
||||
(nuint)PltMemorySize,
|
||||
AllocationType.Reserve | AllocationType.Commit,
|
||||
MemoryProtection.ExecuteReadWrite);
|
||||
_hostMemory = hostMemory ?? HostPlatform.Current.Memory;
|
||||
_pltMemory = (byte*)_hostMemory.Allocate(0, PltMemorySize, HostPageProtection.ReadWriteExecute);
|
||||
|
||||
if (_pltMemory == null)
|
||||
{
|
||||
@@ -185,7 +184,7 @@ public sealed unsafe class StubManager : IDisposable
|
||||
{
|
||||
if (_pltMemory != null)
|
||||
{
|
||||
VirtualFree(_pltMemory, 0, FreeType.Release);
|
||||
_hostMemory.Free((ulong)_pltMemory);
|
||||
_pltMemory = null;
|
||||
}
|
||||
|
||||
@@ -194,29 +193,5 @@ public sealed unsafe class StubManager : IDisposable
|
||||
_stubAddresses.Clear();
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern void* VirtualAlloc(void* lpAddress, nuint dwSize, AllocationType flAllocationType, MemoryProtection flProtect);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool VirtualFree(void* lpAddress, nuint dwSize, FreeType dwFreeType);
|
||||
|
||||
[Flags]
|
||||
private enum AllocationType : uint
|
||||
{
|
||||
Commit = 0x1000,
|
||||
Reserve = 0x2000,
|
||||
}
|
||||
|
||||
[Flags]
|
||||
private enum MemoryProtection : uint
|
||||
{
|
||||
ExecuteReadWrite = 0x40,
|
||||
}
|
||||
|
||||
private enum FreeType : uint
|
||||
{
|
||||
Release = 0x8000,
|
||||
}
|
||||
|
||||
public delegate void ImportHandler(CpuContext context);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.Core.Cpu.Native.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// Byte offsets into the Win64 CONTEXT record delivered to vectored exception
|
||||
/// handlers. The handlers read/write guest registers directly at these offsets
|
||||
/// (no managed CONTEXT struct exists); a future POSIX backend gets a sibling
|
||||
/// class for its mcontext layout.
|
||||
/// </summary>
|
||||
internal static class Win64ContextOffsets
|
||||
{
|
||||
public const int Size = 0x4D0;
|
||||
public const int Mxcsr = 52;
|
||||
public const int Rax = 120;
|
||||
public const int Rcx = 128;
|
||||
public const int Rdx = 136;
|
||||
public const int Rbx = 144;
|
||||
public const int Rsp = 152;
|
||||
public const int Rbp = 160;
|
||||
public const int Rsi = 168;
|
||||
public const int Rdi = 176;
|
||||
public const int R8 = 184;
|
||||
public const int R9 = 192;
|
||||
public const int R10 = 200;
|
||||
public const int R11 = 208;
|
||||
public const int R12 = 216;
|
||||
public const int R13 = 224;
|
||||
public const int R14 = 232;
|
||||
public const int R15 = 240;
|
||||
public const int Rip = 248;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.Core.Cpu.Native.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// Windows NTSTATUS exception codes and EXCEPTION_RECORD access-type values the
|
||||
/// fault handlers filter on. Values are the same numbers the handlers previously
|
||||
/// compared as bare literals; only the spelling changed.
|
||||
/// </summary>
|
||||
internal static class WindowsFaultCodes
|
||||
{
|
||||
public const uint AccessViolation = 0xC0000005u; // 3221225477
|
||||
public const uint Breakpoint = 0x80000003u; // 2147483651
|
||||
public const uint IllegalInstruction = 0xC000001Du; // 3221225501
|
||||
public const uint FastFail = 0xC0000409u; // 3221226505
|
||||
public const uint StackOverflow = 0xC00000FDu;
|
||||
public const uint ClrManagedException = 0xE0434352u;
|
||||
|
||||
// EXCEPTION_RECORD.ExceptionInformation[0] for access violations.
|
||||
public const ulong AccessRead = 0;
|
||||
public const ulong AccessWrite = 1;
|
||||
public const ulong AccessExecute = 8;
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
using SharpEmu.HLE.Host;
|
||||
|
||||
namespace SharpEmu.Core.Cpu.Native.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// Vectored-exception-handler installation and the handler pre-filter thunk.
|
||||
/// The thunk is inherently Windows-shaped (TEB stack-limit reads via gs:,
|
||||
/// NTSTATUS pre-filtering, Win64 calling convention) and moved here whole from
|
||||
/// DirectExecutionBackend; a POSIX backend supplies a sibling built around
|
||||
/// sigaction/sigaltstack instead.
|
||||
/// </summary>
|
||||
internal sealed unsafe partial class WindowsFaultHandling : IHostFaultHandling
|
||||
{
|
||||
private readonly IHostMemory _memory;
|
||||
|
||||
public WindowsFaultHandling(IHostMemory memory)
|
||||
{
|
||||
_memory = memory;
|
||||
}
|
||||
|
||||
public nint CreateHandlerThunk(nint managedCallback, uint hostRspSwitchTlsSlot, nint tlsGetValueAddress)
|
||||
{
|
||||
const uint stubSize = 256u;
|
||||
void* ptr = (void*)_memory.Allocate(0, stubSize, HostPageProtection.ReadWriteExecute);
|
||||
if (ptr == null)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
byte* code = (byte*)ptr;
|
||||
int offset = 0;
|
||||
// Native pre-filter: these exception codes are raised while the thread can be in
|
||||
// cooperative GC mode (a C# throw is RaiseException(0xE0434352) on the throwing
|
||||
// thread; FailFast/stack-overflow arrive mid-runtime-failure). Entering the managed
|
||||
// handler then trips the CLR's reverse-P/Invoke check and kills the process with
|
||||
// "Invalid Program: attempted to call a UnmanagedCallersOnly method from managed
|
||||
// code" — this is why no managed throw (even one with a catch handler) ever
|
||||
// survived inside the emulator. Continue the handler search without touching
|
||||
// managed code; the CLR's own VEH handles its exceptions. MSVC C++ exceptions
|
||||
// (Vulkan drivers, host CRT) are excluded too: the managed handler only ever
|
||||
// returned CONTINUE_SEARCH for them.
|
||||
ReadOnlySpan<uint> nonManagedExceptionCodes =
|
||||
[WindowsFaultCodes.ClrManagedException, 0xE06D7363u, WindowsFaultCodes.FastFail, WindowsFaultCodes.StackOverflow];
|
||||
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0x8B); EmitByte(code, ref offset, 0x01); // mov rax, [rcx] (ExceptionRecord*)
|
||||
EmitByte(code, ref offset, 0x8B); EmitByte(code, ref offset, 0x00); // mov eax, [rax] (ExceptionCode)
|
||||
var passJumpOffsets = stackalloc int[nonManagedExceptionCodes.Length];
|
||||
for (int i = 0; i < nonManagedExceptionCodes.Length; i++)
|
||||
{
|
||||
EmitByte(code, ref offset, 0x3D); // cmp eax, imm32
|
||||
EmitUInt32(code, ref offset, nonManagedExceptionCodes[i]);
|
||||
EmitByte(code, ref offset, 0x74); // je pass
|
||||
passJumpOffsets[i] = offset;
|
||||
EmitByte(code, ref offset, 0x00);
|
||||
}
|
||||
EmitByte(code, ref offset, 0xEB); EmitByte(code, ref offset, 0x03); // jmp over pass block
|
||||
int passOffset = offset;
|
||||
EmitByte(code, ref offset, 0x31); EmitByte(code, ref offset, 0xC0); // pass: xor eax, eax (EXCEPTION_CONTINUE_SEARCH)
|
||||
EmitByte(code, ref offset, 0xC3); // ret
|
||||
for (int i = 0; i < nonManagedExceptionCodes.Length; i++)
|
||||
{
|
||||
code[passJumpOffsets[i]] = checked((byte)(passOffset - (passJumpOffsets[i] + 1)));
|
||||
}
|
||||
EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0x54); // push r12
|
||||
EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0x55); // push r13
|
||||
EmitByte(code, ref offset, 0x49); EmitByte(code, ref offset, 0x89); EmitByte(code, ref offset, 0xE4); // mov r12, rsp
|
||||
EmitByte(code, ref offset, 0x49); EmitByte(code, ref offset, 0x89); EmitByte(code, ref offset, 0xCD); // mov r13, rcx
|
||||
EmitByte(code, ref offset, 0x65); EmitByte(code, ref offset, 0x48); // mov rax, gs:[8]
|
||||
EmitByte(code, ref offset, 0x8B); EmitByte(code, ref offset, 0x04); EmitByte(code, ref offset, 0x25);
|
||||
EmitUInt32(code, ref offset, 8u);
|
||||
EmitByte(code, ref offset, 0x49); EmitByte(code, ref offset, 0x39); EmitByte(code, ref offset, 0xC4); // cmp r12, rax
|
||||
EmitByte(code, ref offset, 0x0F); EmitByte(code, ref offset, 0x83); // jae guestStack
|
||||
int aboveStackJump = offset;
|
||||
EmitUInt32(code, ref offset, 0u);
|
||||
EmitByte(code, ref offset, 0x65); EmitByte(code, ref offset, 0x48); // mov rax, gs:[0x10]
|
||||
EmitByte(code, ref offset, 0x8B); EmitByte(code, ref offset, 0x04); EmitByte(code, ref offset, 0x25);
|
||||
EmitUInt32(code, ref offset, 0x10u);
|
||||
EmitByte(code, ref offset, 0x49); EmitByte(code, ref offset, 0x39); EmitByte(code, ref offset, 0xC4); // cmp r12, rax
|
||||
EmitByte(code, ref offset, 0x0F); EmitByte(code, ref offset, 0x82); // jb guestStack
|
||||
int belowStackJump = offset;
|
||||
EmitUInt32(code, ref offset, 0u);
|
||||
|
||||
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0x83); EmitByte(code, ref offset, 0xEC); EmitByte(code, ref offset, 0x28);
|
||||
EmitByte(code, ref offset, 0x4C); EmitByte(code, ref offset, 0x89); EmitByte(code, ref offset, 0xE9); // mov rcx, r13
|
||||
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0xB8);
|
||||
*(nint*)(code + offset) = managedCallback;
|
||||
offset += sizeof(nint);
|
||||
EmitByte(code, ref offset, 0xFF); EmitByte(code, ref offset, 0xD0);
|
||||
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0x83); EmitByte(code, ref offset, 0xC4); EmitByte(code, ref offset, 0x28);
|
||||
EmitByte(code, ref offset, 0xE9);
|
||||
int hostRestoreJump = offset;
|
||||
EmitUInt32(code, ref offset, 0u);
|
||||
|
||||
int guestStackOffset = offset;
|
||||
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0x83); EmitByte(code, ref offset, 0xEC); EmitByte(code, ref offset, 0x28);
|
||||
EmitByte(code, ref offset, 0xB9);
|
||||
EmitUInt32(code, ref offset, hostRspSwitchTlsSlot);
|
||||
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0xB8);
|
||||
*(nint*)(code + offset) = tlsGetValueAddress;
|
||||
offset += sizeof(nint);
|
||||
EmitByte(code, ref offset, 0xFF); EmitByte(code, ref offset, 0xD0);
|
||||
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0x83); EmitByte(code, ref offset, 0xC4); EmitByte(code, ref offset, 0x28);
|
||||
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0x85); EmitByte(code, ref offset, 0xC0); // test rax, rax
|
||||
EmitByte(code, ref offset, 0x0F); EmitByte(code, ref offset, 0x84);
|
||||
int missingTlsJump = offset;
|
||||
EmitUInt32(code, ref offset, 0u);
|
||||
EmitByte(code, ref offset, 0x4C); EmitByte(code, ref offset, 0x8B); EmitByte(code, ref offset, 0x18); // mov r11, [rax]
|
||||
EmitByte(code, ref offset, 0x4D); EmitByte(code, ref offset, 0x85); EmitByte(code, ref offset, 0xDB); // test r11, r11
|
||||
EmitByte(code, ref offset, 0x0F); EmitByte(code, ref offset, 0x84);
|
||||
int missingHostStackJump = offset;
|
||||
EmitUInt32(code, ref offset, 0u);
|
||||
EmitByte(code, ref offset, 0x4C); EmitByte(code, ref offset, 0x89); EmitByte(code, ref offset, 0xDC); // mov rsp, r11
|
||||
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0x83); EmitByte(code, ref offset, 0xEC); EmitByte(code, ref offset, 0x28);
|
||||
EmitByte(code, ref offset, 0x4C); EmitByte(code, ref offset, 0x89); EmitByte(code, ref offset, 0xE9); // mov rcx, r13
|
||||
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0xB8);
|
||||
*(nint*)(code + offset) = managedCallback;
|
||||
offset += sizeof(nint);
|
||||
EmitByte(code, ref offset, 0xFF); EmitByte(code, ref offset, 0xD0);
|
||||
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0x83); EmitByte(code, ref offset, 0xC4); EmitByte(code, ref offset, 0x28);
|
||||
EmitByte(code, ref offset, 0xE9);
|
||||
int guestRestoreJump = offset;
|
||||
EmitUInt32(code, ref offset, 0u);
|
||||
|
||||
int passThroughOffset = offset;
|
||||
EmitByte(code, ref offset, 0x31); EmitByte(code, ref offset, 0xC0); // xor eax, eax
|
||||
int restoreOffset = offset;
|
||||
EmitByte(code, ref offset, 0x4C); EmitByte(code, ref offset, 0x89); EmitByte(code, ref offset, 0xE4); // mov rsp, r12
|
||||
EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0x5D);
|
||||
EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0x5C);
|
||||
EmitByte(code, ref offset, 0xC3);
|
||||
|
||||
*(int*)(code + aboveStackJump) = guestStackOffset - (aboveStackJump + sizeof(int));
|
||||
*(int*)(code + belowStackJump) = guestStackOffset - (belowStackJump + sizeof(int));
|
||||
*(int*)(code + hostRestoreJump) = restoreOffset - (hostRestoreJump + sizeof(int));
|
||||
*(int*)(code + missingTlsJump) = passThroughOffset - (missingTlsJump + sizeof(int));
|
||||
*(int*)(code + missingHostStackJump) = passThroughOffset - (missingHostStackJump + sizeof(int));
|
||||
*(int*)(code + guestRestoreJump) = restoreOffset - (guestRestoreJump + sizeof(int));
|
||||
|
||||
if (!_memory.Protect((ulong)ptr, stubSize, HostPageProtection.ReadExecute, out _))
|
||||
{
|
||||
Console.Error.WriteLine($"[LOADER][ERROR] VirtualProtect failed for exception handler trampoline at 0x{(nint)ptr:X16}");
|
||||
_ = _memory.Free((ulong)ptr);
|
||||
return 0;
|
||||
}
|
||||
_memory.FlushInstructionCache((ulong)ptr, (ulong)offset);
|
||||
return (nint)ptr;
|
||||
}
|
||||
|
||||
public void FreeThunk(nint thunk)
|
||||
{
|
||||
_ = _memory.Free((ulong)thunk);
|
||||
}
|
||||
|
||||
public nint AddFirstChanceHandler(nint thunk)
|
||||
{
|
||||
return (nint)AddVectoredExceptionHandler(1u, thunk);
|
||||
}
|
||||
|
||||
public void RemoveHandler(nint handle)
|
||||
{
|
||||
_ = RemoveVectoredExceptionHandler((void*)handle);
|
||||
}
|
||||
|
||||
public void SetUnhandledFilter(nint thunk)
|
||||
{
|
||||
_ = SetUnhandledExceptionFilter(thunk);
|
||||
}
|
||||
|
||||
private static void EmitByte(byte* code, ref int offset, byte value)
|
||||
{
|
||||
code[offset++] = value;
|
||||
}
|
||||
|
||||
private static void EmitUInt32(byte* code, ref int offset, uint value)
|
||||
{
|
||||
*(uint*)(code + offset) = value;
|
||||
offset += sizeof(uint);
|
||||
}
|
||||
|
||||
[LibraryImport("kernel32.dll")]
|
||||
private static partial void* AddVectoredExceptionHandler(uint first, IntPtr handler);
|
||||
|
||||
[LibraryImport("kernel32.dll")]
|
||||
private static partial uint RemoveVectoredExceptionHandler(void* handle);
|
||||
|
||||
[LibraryImport("kernel32.dll")]
|
||||
private static partial IntPtr SetUnhandledExceptionFilter(IntPtr lpTopLevelExceptionFilter);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ using SharpEmu.HLE;
|
||||
|
||||
namespace SharpEmu.Core.Cpu;
|
||||
|
||||
public sealed class TrackedCpuMemory : ICpuMemory, ITrackedCpuMemory, IGuestMemoryAllocator
|
||||
public sealed class TrackedCpuMemory : ICpuMemory, ITrackedCpuMemory, IGuestMemoryAllocator, ICpuMemoryWrapper
|
||||
{
|
||||
private readonly ICpuMemory _inner;
|
||||
|
||||
@@ -50,4 +50,9 @@ public sealed class TrackedCpuMemory : ICpuMemory, ITrackedCpuMemory, IGuestMemo
|
||||
address = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool TryFreeGuestMemory(ulong address)
|
||||
{
|
||||
return _inner is IGuestMemoryAllocator allocator && allocator.TryFreeGuestMemory(address);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,13 @@ public static class Ps5ParamJsonReader
|
||||
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(data);
|
||||
ReadOnlyMemory<byte> json = data;
|
||||
if (json.Span.StartsWith("\uFEFF"u8))
|
||||
{
|
||||
json = json[3..];
|
||||
}
|
||||
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
return TryReadPs5Param(doc.RootElement);
|
||||
}
|
||||
catch (JsonException)
|
||||
@@ -56,12 +62,15 @@ public static class Ps5ParamJsonReader
|
||||
|
||||
private static (string? Title, string? TitleId, string? Version) TryReadPs5Param(JsonElement root)
|
||||
{
|
||||
string? titleId = root.TryGetProperty("titleId", out var eTid) ? eTid.GetString() : null;
|
||||
if (root.ValueKind != JsonValueKind.Object)
|
||||
return (null, null, null);
|
||||
|
||||
var titleId = GetString(root, "titleId");
|
||||
|
||||
string? ver =
|
||||
(root.TryGetProperty("contentVersion", out var cv) ? cv.GetString() : null)
|
||||
?? (root.TryGetProperty("masterVersion", out var mv) ? mv.GetString() : null)
|
||||
?? (root.TryGetProperty("targetContentVersion", out var tv) ? tv.GetString() : null);
|
||||
GetString(root, "contentVersion")
|
||||
?? GetString(root, "masterVersion")
|
||||
?? GetString(root, "targetContentVersion");
|
||||
|
||||
string? title = ExtractTitleName(root);
|
||||
|
||||
@@ -70,34 +79,49 @@ public static class Ps5ParamJsonReader
|
||||
|
||||
private static string? ExtractTitleName(JsonElement root)
|
||||
{
|
||||
if (!root.TryGetProperty("localizedParameters", out var lp))
|
||||
if ((!root.TryGetProperty("localizedParameters", out var lp) || lp.ValueKind != JsonValueKind.Object) &&
|
||||
root.TryGetProperty("disc", out var disc) && disc.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
if (root.TryGetProperty("disc", out var disc) && disc.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
disc.TryGetProperty("localizedParameters", out lp);
|
||||
}
|
||||
disc.TryGetProperty("localizedParameters", out lp);
|
||||
}
|
||||
|
||||
if (lp.ValueKind != JsonValueKind.Object)
|
||||
return null;
|
||||
|
||||
string? defLang = lp.TryGetProperty("defaultLanguage", out var dl) ? dl.GetString() : null;
|
||||
var defLang = GetString(lp, "defaultLanguage");
|
||||
|
||||
if (!string.IsNullOrEmpty(defLang))
|
||||
{
|
||||
if (lp.TryGetProperty(defLang, out var langObj) && langObj.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
if (langObj.TryGetProperty("titleName", out var tn))
|
||||
return tn.GetString();
|
||||
var title = GetString(langObj, "titleName");
|
||||
if (!string.IsNullOrWhiteSpace(title))
|
||||
return title;
|
||||
}
|
||||
}
|
||||
|
||||
if (lp.TryGetProperty("en-US", out var en) && en.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
if (en.TryGetProperty("titleName", out var tn2))
|
||||
return tn2.GetString();
|
||||
var title = GetString(en, "titleName");
|
||||
if (!string.IsNullOrWhiteSpace(title))
|
||||
return title;
|
||||
}
|
||||
|
||||
foreach (var property in lp.EnumerateObject())
|
||||
{
|
||||
if (property.Value.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
var title = GetString(property.Value, "titleName");
|
||||
if (!string.IsNullOrWhiteSpace(title))
|
||||
return title;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? GetString(JsonElement parent, string propertyName) =>
|
||||
parent.TryGetProperty(propertyName, out var value) && value.ValueKind == JsonValueKind.String
|
||||
? value.GetString()
|
||||
: null;
|
||||
}
|
||||
|
||||
@@ -17,7 +17,9 @@ namespace SharpEmu.Core.Loader;
|
||||
public sealed class SelfLoader : ISelfLoader
|
||||
{
|
||||
private static readonly SharpEmuLogger Log = SharpEmuLog.For("Loader");
|
||||
private const uint SelfMagic = 0x4F153D1D;
|
||||
private const uint ElfMagic = 0x7F454C46;
|
||||
private const uint Ps4SelfMagic = 0x4F153D1D;
|
||||
private const uint Ps5SelfMagic = 0x5414F5EE;
|
||||
private const ulong SelfSegmentFlag = 0x800;
|
||||
private const int PageSize = 0x1000;
|
||||
private const ulong ImportStubBaseAddress = 0x0000_7000_0000_0000UL;
|
||||
@@ -323,7 +325,8 @@ public sealed class SelfLoader : ISelfLoader
|
||||
throw new InvalidDataException("Input image is too small to contain an ELF header.");
|
||||
}
|
||||
|
||||
if (imageData.Length >= sizeof(uint) && BinaryPrimitives.ReadUInt32BigEndian(imageData[..sizeof(uint)]) == SelfMagic)
|
||||
var magic = BinaryPrimitives.ReadUInt32BigEndian(imageData[..sizeof(uint)]);
|
||||
if (magic is Ps4SelfMagic or Ps5SelfMagic)
|
||||
{
|
||||
var selfHeader = ReadUnmanaged<SelfHeader>(imageData, 0);
|
||||
if (!selfHeader.HasKnownLayout || selfHeader.Unknown != 0x22)
|
||||
@@ -345,6 +348,12 @@ public sealed class SelfLoader : ISelfLoader
|
||||
return new LoadContext(IsSelf: true, elfOffset, selfHeader.FileSize, segments);
|
||||
}
|
||||
|
||||
if (magic != ElfMagic)
|
||||
{
|
||||
throw new InvalidDataException(
|
||||
$"Unsupported executable signature 0x{magic:X8}");
|
||||
}
|
||||
|
||||
return new LoadContext(IsSelf: false, ElfOffset: 0, SelfFileSize: 0, Array.Empty<SelfSegment>());
|
||||
}
|
||||
|
||||
@@ -2380,10 +2389,14 @@ public sealed class SelfLoader : ISelfLoader
|
||||
public ulong FileSize => _fileSize;
|
||||
|
||||
public bool HasKnownLayout =>
|
||||
_ident0 == 0x4F &&
|
||||
_ident1 == 0x15 &&
|
||||
_ident2 == 0x3D &&
|
||||
_ident3 == 0x1D &&
|
||||
((_ident0 == 0x4F &&
|
||||
_ident1 == 0x15 &&
|
||||
_ident2 == 0x3D &&
|
||||
_ident3 == 0x1D) ||
|
||||
(_ident0 == 0x54 &&
|
||||
_ident1 == 0x14 &&
|
||||
_ident2 == 0xF5 &&
|
||||
_ident3 == 0xEE)) &&
|
||||
_ident4 == 0x00 &&
|
||||
_ident5 == 0x01 &&
|
||||
_ident6 == 0x01 &&
|
||||
|
||||
@@ -4,11 +4,12 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using SharpEmu.Core.Loader;
|
||||
using SharpEmu.HLE;
|
||||
using SharpEmu.HLE.Host;
|
||||
using SharpEmu.Logging;
|
||||
|
||||
namespace SharpEmu.Core.Memory;
|
||||
|
||||
public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryAllocator, IDisposable
|
||||
public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryAllocator, IGuestAddressSpace, IDisposable
|
||||
{
|
||||
private static readonly SharpEmuLogger Log = SharpEmuLog.For("VMEM");
|
||||
|
||||
@@ -28,41 +29,27 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
private const ulong DefaultLazyReservePrimeBytes = 0x0400_0000UL; // 64 MiB
|
||||
private const ulong LazyReservePrimeChunkBytes = 0x0200_0000UL; // 32 MiB
|
||||
|
||||
private const uint MEM_COMMIT = 0x1000;
|
||||
private const uint MEM_RESERVE = 0x2000;
|
||||
private const uint MEM_RELEASE = 0x8000;
|
||||
// Raw Windows PAGE_* values retained for the internal region/protection
|
||||
// bookkeeping: regions and saved old-protection values always carry the raw
|
||||
// value of the host platform in use, and these classification helpers only
|
||||
// ever see values this class itself assigned (see IHostMemory.ProtectRaw).
|
||||
private const uint PAGE_EXECUTE_READ = 0x20;
|
||||
private const uint PAGE_EXECUTE_READWRITE = 0x40;
|
||||
private const uint PAGE_EXECUTE = 0x10;
|
||||
private const uint PAGE_EXECUTE_WRITECOPY = 0x80;
|
||||
private const uint PAGE_NOACCESS = 0x01;
|
||||
private const uint PAGE_READWRITE = 0x04;
|
||||
private const uint PAGE_READONLY = 0x02;
|
||||
|
||||
private readonly IHostMemory _hostMemory;
|
||||
private ulong _guestAllocationArenaBase;
|
||||
private ulong _guestAllocationOffset;
|
||||
private readonly SortedDictionary<ulong, ulong> _guestAllocationFreeRanges = new();
|
||||
private readonly Dictionary<ulong, (ulong Offset, ulong Size)> _guestAllocations = new();
|
||||
private static readonly ulong LazyReservePrimeBytes = ResolveLazyReservePrimeBytes();
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern void* VirtualAlloc(void* lpAddress, nuint dwSize, uint flAllocationType, uint flProtect);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool VirtualFree(void* lpAddress, nuint dwSize, uint dwFreeType);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool VirtualProtect(void* lpAddress, nuint dwSize, uint flNewProtect, out uint lpflOldProtect);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern nuint VirtualQuery(void* lpAddress, out MemoryBasicInformation64 lpBuffer, nuint dwLength);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern void* GetCurrentProcess();
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool FlushInstructionCache(void* hProcess, void* lpBaseAddress, nuint dwSize);
|
||||
public PhysicalVirtualMemory(IHostMemory? hostMemory = null)
|
||||
{
|
||||
_hostMemory = hostMemory ?? HostPlatform.Current.Memory;
|
||||
}
|
||||
|
||||
public bool TryAllocateAtExact(ulong desiredAddress, ulong size, bool executable, out ulong actualAddress)
|
||||
{
|
||||
@@ -74,17 +61,17 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
|
||||
var alignedSize = (size + 0xFFF) & ~0xFFFUL;
|
||||
var protection = executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
|
||||
var allocationType = MEM_COMMIT | MEM_RESERVE;
|
||||
var result = VirtualAlloc((void*)desiredAddress, (nuint)alignedSize, allocationType, protection);
|
||||
if (result == null)
|
||||
var hostProtection = executable ? HostPageProtection.ReadWriteExecute : HostPageProtection.ReadWrite;
|
||||
var result = _hostMemory.Allocate(desiredAddress, alignedSize, hostProtection);
|
||||
if (result == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
actualAddress = (ulong)result;
|
||||
actualAddress = result;
|
||||
if (actualAddress != desiredAddress)
|
||||
{
|
||||
VirtualFree(result, 0, MEM_RELEASE);
|
||||
_hostMemory.Free(result);
|
||||
actualAddress = 0;
|
||||
return false;
|
||||
}
|
||||
@@ -119,33 +106,33 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
var alignedSize = (size + 0xFFF) & ~0xFFFUL;
|
||||
|
||||
var protection = executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
|
||||
var allocationType = MEM_COMMIT | MEM_RESERVE;
|
||||
var hostProtection = executable ? HostPageProtection.ReadWriteExecute : HostPageProtection.ReadWrite;
|
||||
var reservedOnly = false;
|
||||
var preferReserveOnly = !executable &&
|
||||
alignedSize >= LargeDataReserveThreshold &&
|
||||
alignedSize > FullCommitRegionLimit;
|
||||
|
||||
void* result = null;
|
||||
ulong result = 0;
|
||||
if (preferReserveOnly)
|
||||
{
|
||||
result = VirtualAlloc((void*)desiredAddress, (nuint)alignedSize, MEM_RESERVE, PAGE_READWRITE);
|
||||
if (result == null && allowAlternative)
|
||||
result = _hostMemory.Reserve(desiredAddress, alignedSize, HostPageProtection.ReadWrite);
|
||||
if (result == 0 && allowAlternative)
|
||||
{
|
||||
result = VirtualAlloc(null, (nuint)alignedSize, MEM_RESERVE, PAGE_READWRITE);
|
||||
result = _hostMemory.Reserve(0, alignedSize, HostPageProtection.ReadWrite);
|
||||
}
|
||||
|
||||
if (result != null)
|
||||
if (result != 0)
|
||||
{
|
||||
reservedOnly = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (result == null)
|
||||
if (result == 0)
|
||||
{
|
||||
result = VirtualAlloc((void*)desiredAddress, (nuint)alignedSize, allocationType, protection);
|
||||
result = _hostMemory.Allocate(desiredAddress, alignedSize, hostProtection);
|
||||
}
|
||||
|
||||
if (result == null)
|
||||
if (result == 0)
|
||||
{
|
||||
if (!allowAlternative)
|
||||
{
|
||||
@@ -153,32 +140,32 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
}
|
||||
|
||||
TraceVmem($"Could not allocate at 0x{desiredAddress:X16}, trying any address...");
|
||||
result = VirtualAlloc(null, (nuint)alignedSize, allocationType, protection);
|
||||
result = _hostMemory.Allocate(0, alignedSize, hostProtection);
|
||||
|
||||
if (result == null)
|
||||
if (result == 0)
|
||||
{
|
||||
if (!executable)
|
||||
{
|
||||
result = VirtualAlloc((void*)desiredAddress, (nuint)alignedSize, MEM_RESERVE, PAGE_READWRITE);
|
||||
if (result == null && allowAlternative)
|
||||
result = _hostMemory.Reserve(desiredAddress, alignedSize, HostPageProtection.ReadWrite);
|
||||
if (result == 0 && allowAlternative)
|
||||
{
|
||||
result = VirtualAlloc(null, (nuint)alignedSize, MEM_RESERVE, PAGE_READWRITE);
|
||||
result = _hostMemory.Reserve(0, alignedSize, HostPageProtection.ReadWrite);
|
||||
}
|
||||
|
||||
if (result != null)
|
||||
if (result != 0)
|
||||
{
|
||||
reservedOnly = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (result == null)
|
||||
if (result == 0)
|
||||
{
|
||||
throw new OutOfMemoryException($"Failed to allocate {alignedSize} bytes of virtual memory");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var actualAddress = (ulong)result;
|
||||
var actualAddress = result;
|
||||
|
||||
var lazyPrimeState = "n/a";
|
||||
if (reservedOnly)
|
||||
@@ -191,9 +178,8 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
{
|
||||
var remaining = primeBytes - committedBytes;
|
||||
var chunkBytes = Math.Min(remaining, LazyReservePrimeChunkBytes);
|
||||
var commitAddress = (void*)(actualAddress + committedBytes);
|
||||
var committed = VirtualAlloc(commitAddress, (nuint)chunkBytes, MEM_COMMIT, PAGE_READWRITE);
|
||||
if (committed == null)
|
||||
var commitAddress = actualAddress + committedBytes;
|
||||
if (!_hostMemory.Commit(commitAddress, chunkBytes, HostPageProtection.ReadWrite))
|
||||
{
|
||||
break;
|
||||
}
|
||||
@@ -263,6 +249,71 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
var requestedCursor = AlignUp(desiredAddress, effectiveAlignment);
|
||||
var cursor = GetAllocationSearchCursor(desiredAddress, requestedCursor, effectiveAlignment, executable);
|
||||
|
||||
// Under Rosetta 2 the kernel can ignore placement hints for whole
|
||||
// windows, so page-stepped exact probes are pathological on macOS.
|
||||
// Linux must keep using the exact-address search below: PS5 resource
|
||||
// descriptors cannot represent ordinary 0x7F... host mappings. Linux
|
||||
// HostMemory uses MAP_FIXED_NOREPLACE, making those low-address probes
|
||||
// safe without clobbering existing host mappings.
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
// Prefer the requested low address. Besides matching the guest
|
||||
// address model, this keeps the allocation representable by every
|
||||
// PS5 GPU descriptor (the strictest ones carry 40 address bits).
|
||||
try
|
||||
{
|
||||
var exactAddress = AllocateAt(
|
||||
cursor,
|
||||
alignedSize,
|
||||
executable,
|
||||
allowAlternative: false);
|
||||
if (exactAddress == cursor)
|
||||
{
|
||||
actualAddress = exactAddress;
|
||||
UpdateAllocationSearchCursor(
|
||||
desiredAddress,
|
||||
effectiveAlignment,
|
||||
executable,
|
||||
exactAddress + alignedSize);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
// Over-allocate by the alignment so a kernel-chosen placement
|
||||
// always contains an aligned start; the unused head/tail stays
|
||||
// part of the tracked region and is simply never handed out.
|
||||
var reserveSize = effectiveAlignment > PageSize
|
||||
? alignedSize + effectiveAlignment
|
||||
: alignedSize;
|
||||
try
|
||||
{
|
||||
var posixAddress = AllocateAt(cursor, reserveSize, executable, allowAlternative: true);
|
||||
if (posixAddress != 0)
|
||||
{
|
||||
var alignedBase = AlignUp(posixAddress, effectiveAlignment);
|
||||
const ulong gpuAddressLimit = 1UL << 40;
|
||||
if (alignedBase < gpuAddressLimit &&
|
||||
alignedSize <= gpuAddressLimit - alignedBase &&
|
||||
alignedBase + alignedSize <= posixAddress + reserveSize)
|
||||
{
|
||||
actualAddress = alignedBase;
|
||||
UpdateAllocationSearchCursor(desiredAddress, effectiveAlignment, executable, alignedBase + alignedSize);
|
||||
return true;
|
||||
}
|
||||
|
||||
ReleaseUntrackedAllocation(posixAddress);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var attempt = 0; attempt < 0x10000; attempt++)
|
||||
{
|
||||
if (cursor == 0 || ulong.MaxValue - cursor < alignedSize)
|
||||
@@ -297,6 +348,28 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
return false;
|
||||
}
|
||||
|
||||
private void ReleaseUntrackedAllocation(ulong address)
|
||||
{
|
||||
_gate.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
for (var i = 0; i < _regions.Count; i++)
|
||||
{
|
||||
if (_regions[i].VirtualAddress == address)
|
||||
{
|
||||
_regions.RemoveAt(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.ExitWriteLock();
|
||||
}
|
||||
|
||||
_hostMemory.Free(address);
|
||||
}
|
||||
|
||||
public bool TryAllocateGuestMemory(ulong size, ulong alignment, out ulong address)
|
||||
{
|
||||
address = 0;
|
||||
@@ -316,7 +389,9 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
GuestAllocationArenaSize,
|
||||
executable: false,
|
||||
allowAlternative: true);
|
||||
_guestAllocationOffset = GuestAllocationArenaStartOffset;
|
||||
_guestAllocationFreeRanges.Add(
|
||||
GuestAllocationArenaStartOffset,
|
||||
GuestAllocationArenaSize - GuestAllocationArenaStartOffset);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
@@ -324,18 +399,128 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
}
|
||||
}
|
||||
|
||||
var alignedOffset = AlignUp(_guestAllocationOffset, alignment);
|
||||
if (alignedOffset > GuestAllocationArenaSize || size > GuestAllocationArenaSize - alignedOffset)
|
||||
ulong rangeOffset = 0;
|
||||
ulong rangeSize = 0;
|
||||
ulong alignedOffset = 0;
|
||||
var found = false;
|
||||
foreach (var range in _guestAllocationFreeRanges)
|
||||
{
|
||||
alignedOffset = AlignUp(range.Key, alignment);
|
||||
if (alignedOffset >= range.Key &&
|
||||
alignedOffset - range.Key <= range.Value &&
|
||||
size <= range.Value - (alignedOffset - range.Key))
|
||||
{
|
||||
rangeOffset = range.Key;
|
||||
rangeSize = range.Value;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_guestAllocationFreeRanges.Remove(rangeOffset);
|
||||
if (alignedOffset > rangeOffset)
|
||||
{
|
||||
_guestAllocationFreeRanges.Add(rangeOffset, alignedOffset - rangeOffset);
|
||||
}
|
||||
|
||||
var allocationEnd = alignedOffset + size;
|
||||
var rangeEnd = rangeOffset + rangeSize;
|
||||
if (allocationEnd < rangeEnd)
|
||||
{
|
||||
_guestAllocationFreeRanges.Add(allocationEnd, rangeEnd - allocationEnd);
|
||||
}
|
||||
|
||||
address = _guestAllocationArenaBase + alignedOffset;
|
||||
_guestAllocationOffset = alignedOffset + size;
|
||||
_guestAllocations.Add(address, (alignedOffset, size));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryFreeGuestMemory(ulong address)
|
||||
{
|
||||
lock (_guestAllocationGate)
|
||||
{
|
||||
if (!_guestAllocations.Remove(address, out var allocation))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var freeOffset = allocation.Offset;
|
||||
var freeSize = allocation.Size;
|
||||
ulong? previousOffset = null;
|
||||
ulong? nextOffset = null;
|
||||
|
||||
foreach (var range in _guestAllocationFreeRanges)
|
||||
{
|
||||
if (range.Key < freeOffset)
|
||||
{
|
||||
previousOffset = range.Key;
|
||||
continue;
|
||||
}
|
||||
|
||||
nextOffset = range.Key;
|
||||
break;
|
||||
}
|
||||
|
||||
if (previousOffset is { } previous &&
|
||||
previous + _guestAllocationFreeRanges[previous] == freeOffset)
|
||||
{
|
||||
freeOffset = previous;
|
||||
freeSize += _guestAllocationFreeRanges[previous];
|
||||
_guestAllocationFreeRanges.Remove(previous);
|
||||
}
|
||||
|
||||
if (nextOffset is { } next && freeOffset + freeSize == next)
|
||||
{
|
||||
freeSize += _guestAllocationFreeRanges[next];
|
||||
_guestAllocationFreeRanges.Remove(next);
|
||||
}
|
||||
|
||||
_guestAllocationFreeRanges.Add(freeOffset, freeSize);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryProtect(ulong address, ulong size, GuestPageProtection protection)
|
||||
{
|
||||
if (size == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return _hostMemory.Protect(address, size, ResolveProtection(protection), out _);
|
||||
}
|
||||
|
||||
// Reproduces the decomposition KernelMemoryCompatExports.ResolveHostProtection
|
||||
// performed before this seam existed; the Windows backend maps each case back
|
||||
// to the identical PAGE_* value.
|
||||
private static HostPageProtection ResolveProtection(GuestPageProtection protection)
|
||||
{
|
||||
var read = (protection & GuestPageProtection.Read) != 0;
|
||||
var write = (protection & GuestPageProtection.Write) != 0;
|
||||
var execute = (protection & GuestPageProtection.Execute) != 0;
|
||||
|
||||
if (execute)
|
||||
{
|
||||
return write
|
||||
? HostPageProtection.ReadWriteExecute
|
||||
: read
|
||||
? HostPageProtection.ReadExecute
|
||||
: HostPageProtection.Execute;
|
||||
}
|
||||
|
||||
return write
|
||||
? HostPageProtection.ReadWrite
|
||||
: read
|
||||
? HostPageProtection.ReadOnly
|
||||
: HostPageProtection.NoAccess;
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
lock (_guestAllocationGate)
|
||||
@@ -345,7 +530,7 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
{
|
||||
foreach (var region in _regions)
|
||||
{
|
||||
VirtualFree((void*)region.VirtualAddress, 0, MEM_RELEASE);
|
||||
_hostMemory.Free(region.VirtualAddress);
|
||||
}
|
||||
_regions.Clear();
|
||||
_pageProtections.Clear();
|
||||
@@ -360,7 +545,8 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
}
|
||||
|
||||
_guestAllocationArenaBase = 0;
|
||||
_guestAllocationOffset = 0;
|
||||
_guestAllocationFreeRanges.Clear();
|
||||
_guestAllocations.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -419,46 +605,67 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
|
||||
private void ApplySegmentProtection(ulong mapStart, ulong mapEnd, ProgramHeaderFlags flags)
|
||||
{
|
||||
var runStart = mapStart;
|
||||
var runFlags = ProgramHeaderFlags.None;
|
||||
var hasRun = false;
|
||||
|
||||
for (var pageAddress = mapStart; pageAddress < mapEnd; pageAddress += PageSize)
|
||||
{
|
||||
_pageProtections.TryGetValue(pageAddress, out var existingFlags);
|
||||
var mergedFlags = existingFlags | flags;
|
||||
_pageProtections[pageAddress] = mergedFlags;
|
||||
SetProtection(pageAddress, PageSize, mergedFlags);
|
||||
|
||||
if (!hasRun)
|
||||
{
|
||||
runStart = pageAddress;
|
||||
runFlags = mergedFlags;
|
||||
hasRun = true;
|
||||
}
|
||||
else if (mergedFlags != runFlags)
|
||||
{
|
||||
SetProtection(runStart, pageAddress - runStart, runFlags);
|
||||
runStart = pageAddress;
|
||||
runFlags = mergedFlags;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasRun)
|
||||
{
|
||||
SetProtection(runStart, mapEnd - runStart, runFlags);
|
||||
}
|
||||
}
|
||||
|
||||
private void SetProtection(ulong address, ulong size, ProgramHeaderFlags flags)
|
||||
{
|
||||
uint protection;
|
||||
HostPageProtection protection;
|
||||
|
||||
if (flags == ProgramHeaderFlags.None)
|
||||
{
|
||||
protection = PAGE_NOACCESS;
|
||||
protection = HostPageProtection.NoAccess;
|
||||
}
|
||||
else if ((flags & ProgramHeaderFlags.Execute) != 0)
|
||||
{
|
||||
protection = (flags & ProgramHeaderFlags.Write) != 0
|
||||
? PAGE_EXECUTE_READWRITE
|
||||
: PAGE_EXECUTE_READ;
|
||||
? HostPageProtection.ReadWriteExecute
|
||||
: HostPageProtection.ReadExecute;
|
||||
}
|
||||
else if ((flags & ProgramHeaderFlags.Write) != 0)
|
||||
{
|
||||
protection = PAGE_READWRITE;
|
||||
protection = HostPageProtection.ReadWrite;
|
||||
}
|
||||
else
|
||||
{
|
||||
protection = PAGE_READONLY;
|
||||
protection = HostPageProtection.ReadOnly;
|
||||
}
|
||||
|
||||
if (!VirtualProtect((void*)address, (nuint)size, protection, out _))
|
||||
if (!_hostMemory.Protect(address, size, protection, out _))
|
||||
{
|
||||
throw new InvalidOperationException($"Failed to set memory protection at 0x{address:X16}");
|
||||
}
|
||||
|
||||
if ((flags & ProgramHeaderFlags.Execute) != 0)
|
||||
{
|
||||
FlushInstructionCache(GetCurrentProcess(), (void*)address, (nuint)size);
|
||||
_hostMemory.FlushInstructionCache(address, size);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -550,6 +757,47 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryCompare(ulong virtualAddress, ReadOnlySpan<byte> expected)
|
||||
{
|
||||
_gate.EnterReadLock();
|
||||
try
|
||||
{
|
||||
var region = FindRegion(virtualAddress, (ulong)expected.Length);
|
||||
if (region is null ||
|
||||
!TryResolveRegionOffset(
|
||||
virtualAddress,
|
||||
(ulong)expected.Length,
|
||||
region,
|
||||
out var offset))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (expected.IsEmpty)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var srcPtr = (void*)(region.VirtualAddress + offset);
|
||||
if (region.IsReservedOnly &&
|
||||
!EnsureRangeCommitted((ulong)srcPtr, (ulong)expected.Length, region))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!CanReadWithoutProtectionChange((ulong)srcPtr, (ulong)expected.Length, region))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return new ReadOnlySpan<byte>(srcPtr, expected.Length).SequenceEqual(expected);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.ExitReadLock();
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryWrite(ulong virtualAddress, ReadOnlySpan<byte> source)
|
||||
{
|
||||
var requiresExclusiveAccess = false;
|
||||
@@ -689,7 +937,7 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!VirtualProtect(destPtr, (nuint)source.Length, PAGE_EXECUTE_READWRITE, out var oldProtect))
|
||||
if (!_hostMemory.Protect((ulong)destPtr, (ulong)source.Length, HostPageProtection.ReadWriteExecute, out var oldProtect))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -703,10 +951,10 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
}
|
||||
finally
|
||||
{
|
||||
VirtualProtect(destPtr, (nuint)source.Length, oldProtect, out _);
|
||||
_hostMemory.ProtectRaw((ulong)destPtr, (ulong)source.Length, oldProtect, out _);
|
||||
if (IsExecutableProtection(oldProtect))
|
||||
{
|
||||
FlushInstructionCache(GetCurrentProcess(), destPtr, (nuint)source.Length);
|
||||
_hostMemory.FlushInstructionCache((ulong)destPtr, (ulong)source.Length);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -728,9 +976,14 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
_gate.EnterReadLock();
|
||||
try
|
||||
{
|
||||
return FindRegion(virtualAddress, 1) is not null
|
||||
? (void*)virtualAddress
|
||||
: null;
|
||||
var region = FindRegion(virtualAddress, 1);
|
||||
if (region is null ||
|
||||
(region.IsReservedOnly && !EnsureRangeCommitted(virtualAddress, 1, region)))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return (void*)virtualAddress;
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -932,12 +1185,12 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
return protection is PAGE_READWRITE or PAGE_EXECUTE_READWRITE;
|
||||
}
|
||||
|
||||
private static uint GetCommitProtection(MemoryRegion region)
|
||||
private static HostPageProtection GetCommitProtection(MemoryRegion region)
|
||||
{
|
||||
return region.IsExecutable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
|
||||
return region.IsExecutable ? HostPageProtection.ReadWriteExecute : HostPageProtection.ReadWrite;
|
||||
}
|
||||
|
||||
private static unsafe bool EnsureRangeCommitted(ulong address, ulong size, MemoryRegion region)
|
||||
private bool EnsureRangeCommitted(ulong address, ulong size, MemoryRegion region)
|
||||
{
|
||||
if (size == 0 || !region.IsReservedOnly)
|
||||
{
|
||||
@@ -951,7 +1204,7 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
var pageAddress = startPage;
|
||||
while (pageAddress < endPage)
|
||||
{
|
||||
if (VirtualQuery((void*)pageAddress, out var info, (nuint)sizeof(MemoryBasicInformation64)) == 0)
|
||||
if (!_hostMemory.Query(pageAddress, out var info))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -965,19 +1218,19 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
return false;
|
||||
}
|
||||
|
||||
if (info.State == MEM_COMMIT)
|
||||
if (info.State == HostRegionState.Committed)
|
||||
{
|
||||
pageAddress = rangeEnd;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (info.State != MEM_RESERVE)
|
||||
if (info.State != HostRegionState.Reserved)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var commitSize = rangeEnd - pageAddress;
|
||||
if (VirtualAlloc((void*)pageAddress, (nuint)commitSize, MEM_COMMIT, commitProtection) == null)
|
||||
if (!_hostMemory.Commit(pageAddress, commitSize, commitProtection))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -998,11 +1251,11 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
|
||||
var startPage = AlignDown(address, PageSize);
|
||||
var endPage = AlignUp(address + size, PageSize);
|
||||
var temporaryProtection = region.IsExecutable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
|
||||
var temporaryProtection = region.IsExecutable ? HostPageProtection.ReadWriteExecute : HostPageProtection.ReadWrite;
|
||||
|
||||
for (var pageAddress = startPage; pageAddress < endPage; pageAddress += PageSize)
|
||||
{
|
||||
if (!VirtualProtect((void*)pageAddress, (nuint)PageSize, temporaryProtection, out var oldProtection))
|
||||
if (!_hostMemory.Protect(pageAddress, PageSize, temporaryProtection, out var oldProtection))
|
||||
{
|
||||
RestorePageProtections(touchedPages);
|
||||
touchedPages.Clear();
|
||||
@@ -1015,11 +1268,11 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void RestorePageProtections(List<(ulong Address, uint Protection)> touchedPages)
|
||||
private void RestorePageProtections(List<(ulong Address, uint Protection)> touchedPages)
|
||||
{
|
||||
foreach (var (pageAddress, protection) in touchedPages)
|
||||
{
|
||||
VirtualProtect((void*)pageAddress, (nuint)PageSize, protection, out _);
|
||||
_hostMemory.ProtectRaw(pageAddress, PageSize, protection, out _);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1076,16 +1329,4 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
public uint Protection { get; set; }
|
||||
}
|
||||
|
||||
private struct MemoryBasicInformation64
|
||||
{
|
||||
public ulong BaseAddress;
|
||||
public ulong AllocationBase;
|
||||
public uint AllocationProtect;
|
||||
public uint Alignment1;
|
||||
public ulong RegionSize;
|
||||
public uint State;
|
||||
public uint Protect;
|
||||
public uint Type;
|
||||
public uint Alignment2;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,15 +41,14 @@ public sealed class VirtualMemory : IVirtualMemory
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
foreach (var existing in _regions)
|
||||
var insertionIndex = FindInsertionIndex(virtualAddress);
|
||||
if ((insertionIndex > 0 && virtualAddress < _regions[insertionIndex - 1].EndAddress) ||
|
||||
(insertionIndex < _regions.Count && endAddress > _regions[insertionIndex].Region.VirtualAddress))
|
||||
{
|
||||
if (virtualAddress < existing.EndAddress && endAddress > existing.Region.VirtualAddress)
|
||||
{
|
||||
throw new InvalidOperationException("Attempted to map an overlapping virtual memory region.");
|
||||
}
|
||||
throw new InvalidOperationException("Attempted to map an overlapping virtual memory region.");
|
||||
}
|
||||
|
||||
_regions.Add(new MappedRegion(
|
||||
_regions.Insert(insertionIndex, new MappedRegion(
|
||||
new VirtualMemoryRegion(virtualAddress, memorySize, fileOffset, (ulong)fileData.Length, protection),
|
||||
endAddress,
|
||||
backingMemory));
|
||||
@@ -74,12 +73,12 @@ public sealed class VirtualMemory : IVirtualMemory
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!TryResolveRegion(virtualAddress, destination.Length, out var region, out var offset))
|
||||
if (!TryValidateRange(virtualAddress, destination.Length, ProgramHeaderFlags.Read, out var regionIndex))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
region.BackingMemory.AsSpan(offset, destination.Length).CopyTo(destination);
|
||||
CopyFromRegions(virtualAddress, destination, regionIndex);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -88,39 +87,127 @@ public sealed class VirtualMemory : IVirtualMemory
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!TryResolveRegion(virtualAddress, source.Length, out var region, out var offset))
|
||||
if (!TryValidateRange(virtualAddress, source.Length, ProgramHeaderFlags.Write, out var regionIndex))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
source.CopyTo(region.BackingMemory.AsSpan(offset, source.Length));
|
||||
CopyToRegions(virtualAddress, source, regionIndex);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryResolveRegion(ulong virtualAddress, int length, out MappedRegion region, out int offset)
|
||||
private bool TryValidateRange(
|
||||
ulong virtualAddress,
|
||||
int length,
|
||||
ProgramHeaderFlags requiredProtection,
|
||||
out int regionIndex)
|
||||
{
|
||||
foreach (var candidate in _regions)
|
||||
regionIndex = FindContainingRegionIndex(virtualAddress);
|
||||
if (regionIndex < 0)
|
||||
{
|
||||
if (virtualAddress < candidate.Region.VirtualAddress || virtualAddress >= candidate.EndAddress)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var candidateOffset = checked((int)(virtualAddress - candidate.Region.VirtualAddress));
|
||||
if (candidateOffset + length > candidate.BackingMemory.Length)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
region = candidate;
|
||||
offset = candidateOffset;
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
region = default;
|
||||
offset = 0;
|
||||
return false;
|
||||
var currentAddress = virtualAddress;
|
||||
var remaining = length;
|
||||
var currentIndex = regionIndex;
|
||||
while (true)
|
||||
{
|
||||
if (currentIndex >= _regions.Count)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var region = _regions[currentIndex];
|
||||
if (currentAddress < region.Region.VirtualAddress ||
|
||||
currentAddress >= region.EndAddress ||
|
||||
(region.Region.Protection & requiredProtection) == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (remaining == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var available = region.EndAddress - currentAddress;
|
||||
var chunkLength = (int)Math.Min((ulong)remaining, available);
|
||||
remaining -= chunkLength;
|
||||
if (remaining == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
currentAddress += (ulong)chunkLength;
|
||||
currentIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
private int FindContainingRegionIndex(ulong virtualAddress)
|
||||
{
|
||||
var insertionIndex = FindInsertionIndex(virtualAddress);
|
||||
if (insertionIndex < _regions.Count &&
|
||||
_regions[insertionIndex].Region.VirtualAddress == virtualAddress)
|
||||
{
|
||||
return insertionIndex;
|
||||
}
|
||||
|
||||
var candidateIndex = insertionIndex - 1;
|
||||
return candidateIndex >= 0 && virtualAddress < _regions[candidateIndex].EndAddress
|
||||
? candidateIndex
|
||||
: -1;
|
||||
}
|
||||
|
||||
private void CopyFromRegions(ulong virtualAddress, Span<byte> destination, int regionIndex)
|
||||
{
|
||||
var copied = 0;
|
||||
var currentAddress = virtualAddress;
|
||||
while (copied < destination.Length)
|
||||
{
|
||||
var region = _regions[regionIndex++];
|
||||
var regionOffset = checked((int)(currentAddress - region.Region.VirtualAddress));
|
||||
var chunkLength = Math.Min(destination.Length - copied, region.BackingMemory.Length - regionOffset);
|
||||
region.BackingMemory.AsSpan(regionOffset, chunkLength).CopyTo(destination[copied..]);
|
||||
copied += chunkLength;
|
||||
currentAddress += (ulong)chunkLength;
|
||||
}
|
||||
}
|
||||
|
||||
private void CopyToRegions(ulong virtualAddress, ReadOnlySpan<byte> source, int regionIndex)
|
||||
{
|
||||
var copied = 0;
|
||||
var currentAddress = virtualAddress;
|
||||
while (copied < source.Length)
|
||||
{
|
||||
var region = _regions[regionIndex++];
|
||||
var regionOffset = checked((int)(currentAddress - region.Region.VirtualAddress));
|
||||
var chunkLength = Math.Min(source.Length - copied, region.BackingMemory.Length - regionOffset);
|
||||
source.Slice(copied, chunkLength).CopyTo(region.BackingMemory.AsSpan(regionOffset, chunkLength));
|
||||
copied += chunkLength;
|
||||
currentAddress += (ulong)chunkLength;
|
||||
}
|
||||
}
|
||||
|
||||
private int FindInsertionIndex(ulong virtualAddress)
|
||||
{
|
||||
var lower = 0;
|
||||
var upper = _regions.Count;
|
||||
while (lower < upper)
|
||||
{
|
||||
var middle = lower + ((upper - lower) / 2);
|
||||
if (_regions[middle].Region.VirtualAddress < virtualAddress)
|
||||
{
|
||||
lower = middle + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
upper = middle;
|
||||
}
|
||||
}
|
||||
|
||||
return lower;
|
||||
}
|
||||
|
||||
private readonly record struct MappedRegion(VirtualMemoryRegion Region, ulong EndAddress, byte[] BackingMemory);
|
||||
|
||||
@@ -7,6 +7,7 @@ using SharpEmu.Core.Cpu.Disasm;
|
||||
using SharpEmu.Core.Loader;
|
||||
using SharpEmu.Core.Memory;
|
||||
using SharpEmu.HLE;
|
||||
using SharpEmu.HLE.Host;
|
||||
using SharpEmu.Libs.VideoOut;
|
||||
using SharpEmu.Libs.Kernel;
|
||||
using SharpEmu.Libs.AppContent;
|
||||
@@ -83,18 +84,22 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
|
||||
ImportTraceLimit = Math.Max(0, options.ImportTraceLimit),
|
||||
};
|
||||
var moduleManager = new ModuleManager();
|
||||
moduleManager.RegisterFromAssembly(typeof(VideoOutExports).Assembly, Generation.Gen4 | Generation.Gen5, Aerolib.Instance);
|
||||
moduleManager.RegisterFromAssembly(typeof(KernelExports).Assembly, Generation.Gen4 | Generation.Gen5, Aerolib.Instance);
|
||||
moduleManager.Freeze();
|
||||
|
||||
var virtualMemory = new PhysicalVirtualMemory();
|
||||
// Resolve the host platform once at the composition root; on unsupported
|
||||
// OSes this throws PlatformNotSupportedException with a clear message
|
||||
// instead of failing on the first native call.
|
||||
var hostPlatform = HostPlatform.Current;
|
||||
|
||||
var virtualMemory = new PhysicalVirtualMemory(hostPlatform.Memory);
|
||||
|
||||
var fileSystem = new PhysicalFileSystem();
|
||||
|
||||
return new SharpEmuRuntime(
|
||||
new SelfLoader(),
|
||||
virtualMemory,
|
||||
new CpuDispatcher(virtualMemory, moduleManager),
|
||||
new CpuDispatcher(virtualMemory, moduleManager, hostPlatform: hostPlatform),
|
||||
moduleManager,
|
||||
Aerolib.Instance,
|
||||
cpuExecutionOptions,
|
||||
|
||||
@@ -36,6 +36,23 @@
|
||||
"Ultz.Native.GLFW": "3.4.0"
|
||||
}
|
||||
},
|
||||
"Silk.NET.Input.Common": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.23.0",
|
||||
"contentHash": "QbJVV7kFBHEByayXCYdJtXXI9Sp4a+QAf0IdGV6uCWkFYcEmqBYW3aaNGvFOdSwTBDbHL5T/OtOCrGh4qYhk7A==",
|
||||
"dependencies": {
|
||||
"Silk.NET.Windowing.Common": "2.23.0"
|
||||
}
|
||||
},
|
||||
"Silk.NET.Input.Glfw": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.23.0",
|
||||
"contentHash": "KGHYqsv/IQRJtD6dloYh2tN4CkaM40vxM2kj0cGKBoCQiBDYHHhJiyDTyMPx0W7Fz5IgnhnG42ELmIAa0DH69A==",
|
||||
"dependencies": {
|
||||
"Silk.NET.Input.Common": "2.23.0",
|
||||
"Silk.NET.Windowing.Glfw": "2.23.0"
|
||||
}
|
||||
},
|
||||
"Silk.NET.Maths": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.23.0",
|
||||
@@ -74,6 +91,7 @@
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"SharpEmu.HLE": "[1.0.0, )",
|
||||
"Silk.NET.Input": "[2.23.0, )",
|
||||
"Silk.NET.Vulkan": "[2.23.0, )",
|
||||
"Silk.NET.Vulkan.Extensions.EXT": "[2.23.0, )",
|
||||
"Silk.NET.Vulkan.Extensions.KHR": "[2.23.0, )",
|
||||
@@ -83,6 +101,16 @@
|
||||
"sharpemu.logging": {
|
||||
"type": "Project"
|
||||
},
|
||||
"Silk.NET.Input": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[2.23.0, )",
|
||||
"resolved": "2.23.0",
|
||||
"contentHash": "Xzl+tVwAp2eEd8blmGQjmJrsZPnp3PWG0KJjiAQHaY2Zr/ELVWeAROKXmZdCAvexzmte2JVGEy/dxnMycbxlpg==",
|
||||
"dependencies": {
|
||||
"Silk.NET.Input.Common": "2.23.0",
|
||||
"Silk.NET.Input.Glfw": "2.23.0"
|
||||
}
|
||||
},
|
||||
"Silk.NET.Vulkan": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[2.23.0, )",
|
||||
|
||||
@@ -127,6 +127,34 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
|
||||
</Style>
|
||||
|
||||
<!-- Top-level page switcher (Library / Options): plain transparent
|
||||
buttons, not TabItem, so there is no Fluent selected-tab underline.
|
||||
The active page is conveyed by brightness alone; LB/RB gamepad
|
||||
hints flank the pair. -->
|
||||
<Style Selector="Button.segment">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
<Setter Property="Foreground" Value="{StaticResource MutedBrush}" />
|
||||
<Setter Property="FontSize" Value="22" />
|
||||
<Setter Property="FontWeight" Value="Bold" />
|
||||
<Setter Property="Padding" Value="6,4" />
|
||||
<Setter Property="CornerRadius" Value="8" />
|
||||
</Style>
|
||||
<Style Selector="Button.segment:pointerover /template/ ContentPresenter#PART_ContentPresenter">
|
||||
<Setter Property="Background" Value="{StaticResource ElevatedBrush}" />
|
||||
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
|
||||
</Style>
|
||||
<Style Selector="Button.segment.active">
|
||||
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
|
||||
</Style>
|
||||
|
||||
<!-- Gamepad shoulder-button hint chip (LB/RB, L1/R1). -->
|
||||
<Style Selector="Border.padHint">
|
||||
<Setter Property="Background" Value="{StaticResource ElevatedBrush}" />
|
||||
<Setter Property="CornerRadius" Value="6" />
|
||||
<Setter Property="Padding" Value="8,3" />
|
||||
</Style>
|
||||
|
||||
<Style Selector="ContextMenu">
|
||||
<Setter Property="Background" Value="{StaticResource CardBrush}" />
|
||||
<Setter Property="BorderBrush" Value="{StaticResource CardBorderBrush}" />
|
||||
|
||||
@@ -27,8 +27,10 @@ public sealed class ConsoleWindow : Window
|
||||
Action clear,
|
||||
bool autoScroll)
|
||||
{
|
||||
var loc = Localization.Instance;
|
||||
|
||||
_sourceLines = lines;
|
||||
Title = "SharpEmu Console";
|
||||
Title = loc.Get("Console.WindowTitle");
|
||||
Width = 980;
|
||||
Height = 620;
|
||||
MinWidth = 520;
|
||||
@@ -36,10 +38,15 @@ public sealed class ConsoleWindow : Window
|
||||
Background = new SolidColorBrush(Color.Parse("#0D1017"));
|
||||
Icon = new WindowIcon(AssetLoader.Open(new Uri("avares://SharpEmu.GUI/Assets/SharpEmu.ico")));
|
||||
|
||||
_searchBox = new TextBox { Watermark = "Search...", Width = 320, Margin = new Thickness(0, 0, 12, 0) };
|
||||
_searchBox = new TextBox
|
||||
{
|
||||
Watermark = loc.Get("Console.SearchWatermark"),
|
||||
Width = 320,
|
||||
Margin = new Thickness(0, 0, 12, 0),
|
||||
};
|
||||
_autoScrollCheck = new CheckBox
|
||||
{
|
||||
Content = "Auto-scroll",
|
||||
Content = loc.Get("Console.AutoScroll"),
|
||||
IsChecked = autoScroll,
|
||||
FontSize = 12,
|
||||
Margin = new Thickness(0, 0, 12, 0),
|
||||
@@ -48,11 +55,16 @@ public sealed class ConsoleWindow : Window
|
||||
var copyButton = new Button
|
||||
{
|
||||
Classes = { "ghost" },
|
||||
Content = "Copy",
|
||||
Content = loc.Get("Console.Copy"),
|
||||
Padding = new Thickness(10, 4),
|
||||
Margin = new Thickness(0, 0, 8, 0),
|
||||
};
|
||||
var clearButton = new Button { Classes = { "ghost" }, Content = "Clear", Padding = new Thickness(10, 4) };
|
||||
var clearButton = new Button
|
||||
{
|
||||
Classes = { "ghost" },
|
||||
Content = loc.Get("Console.Clear"),
|
||||
Padding = new Thickness(10, 4),
|
||||
};
|
||||
copyButton.Click += async (_, _) => await CopyAsync();
|
||||
clearButton.Click += (_, _) => clear();
|
||||
_searchBox.TextChanged += (_, _) => RefreshVisibleLines();
|
||||
@@ -87,7 +99,7 @@ public sealed class ConsoleWindow : Window
|
||||
new TextBlock
|
||||
{
|
||||
Classes = { "sectionTitle" },
|
||||
Text = "CONSOLE",
|
||||
Text = loc.Get("Console.Title"),
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
},
|
||||
_searchBox.WithGridColumn(1),
|
||||
|
||||
@@ -168,8 +168,7 @@ internal sealed class EmulatorProcess : IDisposable
|
||||
var policy1 = PROCESS_CREATION_MITIGATION_POLICY_CONTROL_FLOW_GUARD_ALWAYS_OFF;
|
||||
var policy2 =
|
||||
PROCESS_CREATION_MITIGATION_POLICY2_CET_USER_SHADOW_STACKS_ALWAYS_OFF |
|
||||
PROCESS_CREATION_MITIGATION_POLICY2_USER_CET_SET_CONTEXT_IP_VALIDATION_ALWAYS_OFF |
|
||||
PROCESS_CREATION_MITIGATION_POLICY2_XTENDED_CONTROL_FLOW_GUARD_ALWAYS_OFF;
|
||||
PROCESS_CREATION_MITIGATION_POLICY2_USER_CET_SET_CONTEXT_IP_VALIDATION_ALWAYS_OFF;
|
||||
|
||||
mitigationPolicies = Marshal.AllocHGlobal(sizeof(ulong) * 2);
|
||||
Marshal.WriteInt64(mitigationPolicies, unchecked((long)policy1));
|
||||
@@ -200,29 +199,10 @@ internal sealed class EmulatorProcess : IDisposable
|
||||
ref startupInfoEx,
|
||||
out var processInfo);
|
||||
|
||||
if (!created)
|
||||
{
|
||||
// Some mitigation policy bits (e.g. XFG) are not supported on
|
||||
// older Windows builds. Mirror the CLI's behavior and fall back
|
||||
// to launching without the mitigation attribute list.
|
||||
startupInfoEx.lpAttributeList = 0;
|
||||
created = CreateProcessW(
|
||||
exePath,
|
||||
new StringBuilder(BuildCommandLine(exePath, arguments)),
|
||||
0,
|
||||
0,
|
||||
true,
|
||||
CREATE_NO_WINDOW,
|
||||
0,
|
||||
currentDirectory,
|
||||
ref startupInfoEx,
|
||||
out processInfo);
|
||||
}
|
||||
|
||||
if (!created)
|
||||
{
|
||||
var error = Marshal.GetLastWin32Error();
|
||||
throw new Win32Exception(error, $"Failed to start '{exePath}' (Win32 error {error}: {new Win32Exception(error).Message}).");
|
||||
throw new Win32Exception(error, $"Failed to start '{exePath}' with CET/CFG mitigation disabled (Win32 error {error}: {new Win32Exception(error).Message}).");
|
||||
}
|
||||
|
||||
CloseHandle(processInfo.hThread);
|
||||
|
||||
@@ -29,10 +29,12 @@ public sealed class GameEntry : INotifyPropertyChanged
|
||||
private long _sizeBytes;
|
||||
|
||||
public GameEntry(
|
||||
string name, string? titleId, string path, long sizeBytes, string? coverPath, string? backgroundPath)
|
||||
string name, string? titleId, string? version, string path, long sizeBytes,
|
||||
string? coverPath, string? backgroundPath)
|
||||
{
|
||||
Name = name;
|
||||
TitleId = titleId;
|
||||
Version = version;
|
||||
Path = path;
|
||||
_sizeBytes = sizeBytes;
|
||||
CoverPath = coverPath;
|
||||
@@ -46,6 +48,9 @@ public sealed class GameEntry : INotifyPropertyChanged
|
||||
|
||||
public string? TitleId { get; }
|
||||
|
||||
/// <summary>Content version from sce_sys/param.json, e.g. "01.000.000".</summary>
|
||||
public string? Version { get; }
|
||||
|
||||
public string Path { get; }
|
||||
|
||||
/// <summary>
|
||||
@@ -65,7 +70,7 @@ public sealed class GameEntry : INotifyPropertyChanged
|
||||
|
||||
_sizeBytes = value;
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SizeBytes)));
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Detail)));
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SizeText)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,9 +111,15 @@ public sealed class GameEntry : INotifyPropertyChanged
|
||||
|
||||
public bool HasCover => _cover is not null;
|
||||
|
||||
public string Detail => TitleId is not null
|
||||
? $"{TitleId} • {FormatSize(SizeBytes)}"
|
||||
: FormatSize(SizeBytes);
|
||||
public bool HasTitleId => TitleId is not null;
|
||||
|
||||
/// <summary>Badge text shown in the launch bar, e.g. "v01.000.000".</summary>
|
||||
public string? VersionText => Version is null ? null : $"v{Version}";
|
||||
|
||||
public bool HasVersion => Version is not null;
|
||||
|
||||
/// <summary>Formatted install size badge shown in the launch bar.</summary>
|
||||
public string SizeText => FormatSize(SizeBytes);
|
||||
|
||||
private static string ComputeInitials(string name)
|
||||
{
|
||||
|
||||
@@ -42,9 +42,15 @@ public sealed class GuiSettings
|
||||
|
||||
public string? EmulatorPath { get; set; }
|
||||
|
||||
/// <summary>UI language, matching a file code under Languages/ (e.g. "en", "tr").</summary>
|
||||
public string Language { get; set; } = "en";
|
||||
|
||||
/// <summary>Publish launcher/game status to Discord Rich Presence.</summary>
|
||||
public bool DiscordRichPresence { get; set; } = true;
|
||||
|
||||
/// <summary>Names of SHARPEMU_* switches set to "1" in the emulator's environment at launch.</summary>
|
||||
public List<string> EnvironmentToggles { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Discord application ID used for Rich Presence; the default is the
|
||||
/// SharpEmu application. Override to rebrand what Discord shows as
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
{
|
||||
"_languageName": "العربية",
|
||||
|
||||
"Page.Library": "المكتبة",
|
||||
"Page.Options": "الخيارات",
|
||||
"Page.GameCount.One": "لعبة واحدة",
|
||||
"Page.GameCount.Other": "{0} لعبة",
|
||||
|
||||
"Library.SearchWatermark": "ابحث في المكتبة...",
|
||||
"Library.AddFolder": "+ إضافة مجلد",
|
||||
"Library.Rescan": "⟳ إعادة الفحص",
|
||||
"Library.OpenFile": "فتح ملف...",
|
||||
|
||||
"Library.Context.Launch": "تشغيل",
|
||||
"Library.Context.OpenFolder": "فتح مجلد اللعبة",
|
||||
"Library.Context.CopyPath": "نسخ المسار",
|
||||
"Library.Context.CopyTitleId": "نسخ معرف العنوان",
|
||||
"Library.Context.Remove": "إزالة من المكتبة",
|
||||
|
||||
"Library.Empty.Title": "مكتبتك فارغة",
|
||||
"Library.Empty.Hint": "أضف مجلداً يحتوي على ألعابك للبدء.",
|
||||
"Library.Empty.SearchTitle": "لا توجد ألعاب تطابق بحثك",
|
||||
"Library.Empty.SearchHint": "لا شيء في المكتبة يطابق “{0}”.",
|
||||
"Library.Empty.AddFolder": "+ إضافة مجلد ألعاب",
|
||||
|
||||
"Library.Loading": "جارٍ تحميل المكتبة...",
|
||||
|
||||
"Options.General": "عام",
|
||||
"Options.Section.Emulation": "المحاكاة",
|
||||
"Options.Section.Logging": "التسجيل",
|
||||
"Options.Section.Launcher": "المُشغِّل",
|
||||
|
||||
"Options.CpuEngine.Label": "محرك المعالج",
|
||||
"Options.CpuEngine.Desc": "محرك التنفيذ المستخدم لتشغيل كود اللعبة.",
|
||||
"Options.CpuEngine.Native": "أصلي",
|
||||
|
||||
"Options.Strict.Label": "ربط صارم للمكتبات الديناميكية (dynlib)",
|
||||
"Options.Strict.Desc": "إفشال التشغيل عندما يتعذر التعرف على رمز مستورد.",
|
||||
|
||||
"Options.LogLevel.Label": "مستوى التسجيل",
|
||||
"Options.LogLevel.Desc": "مدى تفصيل مخرجات نافذة سجلات المحاكي.",
|
||||
"Options.LogLevel.Trace": "تتبع",
|
||||
"Options.LogLevel.Debug": "تصحيح الأخطاء",
|
||||
"Options.LogLevel.Info": "معلومات",
|
||||
"Options.LogLevel.Warning": "تحذير",
|
||||
"Options.LogLevel.Error": "خطأ",
|
||||
"Options.LogLevel.Critical": "حرج",
|
||||
|
||||
"Options.TraceImports.Label": "حد تتبع الاستيراد",
|
||||
"Options.TraceImports.Desc": "تتبع أول N استيراد لكل وحدة (0 = إيقاف).",
|
||||
|
||||
"Options.LogToFile.Label": "التسجيل في ملف",
|
||||
"Options.LogToFile.Desc": "نسخ مخرجات المحاكي إلى ملف سجل.",
|
||||
|
||||
"Options.LogFilePath.Label": "مسار ملف السجل",
|
||||
"Options.LogFilePath.Default": "لا يوجد مسار مخصص — تُحفظ السجلات في user/logs بجوار المحاكي.",
|
||||
"Options.LogFilePath.Select": "تحديد...",
|
||||
|
||||
"Options.OverrideLogFile.Label": "الكتابة فوق ملف السجل",
|
||||
"Options.OverrideLogFile.Desc": "استخدام مسار الملف الدقيق بدلاً من إلحاق معرف العنوان والطابع الزمني.",
|
||||
|
||||
"Options.TitleMusic.Label": "موسيقى اللعبة",
|
||||
"Options.TitleMusic.Desc": "تكرار موسيقى المعاينة للعبة المحددة في المكتبة.",
|
||||
|
||||
"Options.Discord.Label": "حالة دسكورد",
|
||||
"Options.Discord.Desc": "إظهار اللعبة قيد التشغيل في ملفك الشخصي على دسكورد.",
|
||||
|
||||
"Options.Language.Label": "لغة المحاكي",
|
||||
"Options.Language.Desc": "اللغة المستخدمة في جميع أنحاء المشغل. تُطبق فوراً.",
|
||||
|
||||
"Common.On": "تشغيل",
|
||||
"Common.Off": "إيقاف",
|
||||
|
||||
"Console.Title": "نافذة السجلات",
|
||||
"Console.SearchWatermark": "بحث...",
|
||||
"Console.AutoScroll": "تمرير تلقائي",
|
||||
"Console.Split": "تقسيم",
|
||||
"Console.Copy": "نسخ",
|
||||
"Console.Clear": "مسح",
|
||||
"Console.WindowTitle": "نافذة سجلات SharpEmu",
|
||||
|
||||
"Launch.NoGameSelected": "لم تُحدد أي لعبة",
|
||||
"Launch.NoGameHint": "اختر لعبة من المكتبة، أو افتح ملف eboot.bin مباشرة.",
|
||||
"Launch.Idle": "خامل",
|
||||
"Launch.Console": "≡ نافذة السجلات",
|
||||
"Launch.Launch": "▶ تشغيل",
|
||||
"Launch.Stop": "■ إيقاف",
|
||||
"Launch.Running": "قيد التشغيل — {0}",
|
||||
"Launch.Stopping": "جارٍ الإيقاف...",
|
||||
"Launch.Exited": "انتهى برمز {0} ({1})",
|
||||
"Launch.ExeNotFound": "لم يُعثر على الملف التنفيذي SharpEmu. ابنِ مشروع SharpEmu.CLI أولاً (dotnet build).",
|
||||
"Launch.LogFile": "ملف السجل: {0}",
|
||||
"Launch.Command": "$ SharpEmu {0}",
|
||||
"Launch.StartFailed": "فشل بدء تشغيل المحاكي: {0}",
|
||||
"Launch.ProcessExited": "انتهت العملية برمز {0} ({1}).",
|
||||
|
||||
"Exit.Ok": "موافق",
|
||||
"Exit.InvalidArguments": "معطيات غير صالحة",
|
||||
"Exit.EbootNotFound": "لم يُعثر على eboot",
|
||||
"Exit.RuntimeException": "استثناء وقت التشغيل",
|
||||
"Exit.EmulationError": "خطأ في المحاكاة",
|
||||
"Exit.Unknown": "غير معروف",
|
||||
|
||||
"Status.EmulatorLocating": "المحاكي: جارٍ تحديد الموقع...",
|
||||
"Status.EmulatorPath": "المحاكي: {0}",
|
||||
"Status.EmulatorNotFound": "المحاكي: لم يُعثر على الملف التنفيذي SharpEmu — ابنِ SharpEmu.CLI أولاً.",
|
||||
"Status.ScanningLibrary": "جارٍ فحص المكتبة...",
|
||||
"Status.AddFolderPrompt": "أضف مجلد ألعاب لملء المكتبة.",
|
||||
"Status.LibraryScanned": "فُحصت المكتبة: {0} لعبة في {1} مجلد.",
|
||||
"Status.CouldNotOpenFolder": "تعذر فتح المجلد: {0}",
|
||||
"Status.CopiedToClipboard": "نُسخ {0} إلى الحافظة.",
|
||||
"Status.RemovedFromLibrary": "أُزيل “{0}” من المكتبة. أعد إضافة مجلده لاستعادته.",
|
||||
"Status.Running": "جارٍ تشغيل {0}",
|
||||
"Status.Stopping": "جارٍ الإيقاف...",
|
||||
"Status.Idle": "خامل",
|
||||
|
||||
"Clipboard.Path": "المسار",
|
||||
"Clipboard.TitleId": "معرف العنوان",
|
||||
|
||||
"Discord.Playing": "يلعب {0}",
|
||||
"Discord.Browsing": "يتصفح المكتبة",
|
||||
|
||||
"Dialog.ChooseGameFolder": "اختر مجلداً يحتوي على ألعاب",
|
||||
"Dialog.OpenExecutable": "افتح ملفاً تنفيذياً لتشغيله",
|
||||
"Dialog.PsExecutables": "ملفات PS التنفيذية",
|
||||
"Dialog.SaveLogFile": "حدد مكان حفظ ملف السجل",
|
||||
"Dialog.PlainTextFiles": "ملفات نصية عادية",
|
||||
"Dialog.LogFiles": "ملفات السجل"
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
{
|
||||
"_languageName": "Português (Brasil)",
|
||||
|
||||
"Page.Library": "Biblioteca",
|
||||
"Page.Options": "Opções",
|
||||
"Page.GameCount.One": "1 Jogo",
|
||||
"Page.GameCount.Other": "{0} jogos",
|
||||
|
||||
"Library.SearchWatermark": "Pesquisar na biblioteca…",
|
||||
"Library.AddFolder": "+ Adicionar pasta",
|
||||
"Library.Rescan": "⟳ Atualizar biblioteca",
|
||||
"Library.OpenFile": "Abrir arquivo…",
|
||||
|
||||
"Library.Context.Launch": "Jogar",
|
||||
"Library.Context.OpenFolder": "Abrir pasta do jogo",
|
||||
"Library.Context.CopyPath": "Copiar o caminho",
|
||||
"Library.Context.CopyTitleId": "Copiar ID do título",
|
||||
"Library.Context.Remove": "Remover da biblioteca",
|
||||
|
||||
"Library.Empty.Title": "Sua biblioteca está vazia",
|
||||
"Library.Empty.Hint": "Adicione uma pasta contendo seus jogos para começar.",
|
||||
"Library.Empty.SearchTitle": "Nenhum jogo corresponde à sua busca",
|
||||
"Library.Empty.SearchHint": "Nada na biblioteca corresponde a “{0}”.",
|
||||
"Library.Empty.AddFolder": "+ Adicionar pasta do jogo",
|
||||
|
||||
"Library.Loading": "Carregando biblioteca…",
|
||||
|
||||
"Options.General": "Opções Gerais",
|
||||
"Options.Env.Tab": "Ambiente",
|
||||
"Options.Section.Environment": "VARIÁVEIS DE AMBIENTE",
|
||||
"Options.Env.Desc": "Switches passados para o emulador como variáveis de ambiente na inicialização.",
|
||||
"Options.Env.Bthid.Desc": "Reporta o Bluetooth HID como indisponível para títulos cujo middleware de volante/FFB fica esperando indefinidamente.\nDeixe desativado normalmente. Alguns títulos travam quando a inicialização falha.",
|
||||
"Options.Env.LoopGuard.Desc": "Não force o encerramento de títulos que repetem a mesma chamada por tempo demais.\nExperimente isso quando um jogo fecha sozinho durante o carregamento.",
|
||||
"Options.Env.VkValidation.Desc": "Ativa as camadas de validação do Vulkan para depuração de GPU.\nLento. Requer que o Vulkan SDK esteja instalado.",
|
||||
"Options.Env.DumpSpirv.Desc": "Extrai os shaders AGC e suas traduções SPIR-V para a pasta shader-dumps.\nUse ao reportar bugs de shader ou renderização.",
|
||||
"Options.Env.LogDirectMemory.Desc": "Registra alocações de memória direta e falhas no console.\nUse quando um jogo aborta ou fecha durante a inicialização (boot).",
|
||||
"Options.Env.LogNp.Desc": "Registra chamadas da biblioteca NP (PlayStation Network) no console.",
|
||||
"Options.Section.Emulation": "EMULAÇÃO",
|
||||
"Options.Section.Logging": "LOGS",
|
||||
"Options.Section.Launcher": "INICIALIZADOR",
|
||||
|
||||
"Options.CpuEngine.Label": "Motor da CPU",
|
||||
"Options.CpuEngine.Desc": "Motor de execução usado para executar o código do jogo.",
|
||||
"Options.CpuEngine.Native": "Nativo",
|
||||
|
||||
"Options.Strict.Label": "Resolução estrita de bibliotecas dinâmicas",
|
||||
"Options.Strict.Desc": "Interrompe a inicialização caso um símbolo importado não possa ser vinculado.",
|
||||
|
||||
"Options.LogLevel.Label": "Nível de log",
|
||||
"Options.LogLevel.Desc": "Nível de detalhamento das mensagens exibidas no console do emulador.",
|
||||
"Options.LogLevel.Trace": "Trace",
|
||||
"Options.LogLevel.Debug": "Debug",
|
||||
"Options.LogLevel.Info": "Info",
|
||||
"Options.LogLevel.Warning": "Warning",
|
||||
"Options.LogLevel.Error": "Error",
|
||||
"Options.LogLevel.Critical": "Critical",
|
||||
|
||||
"Options.TraceImports.Label": "Limite de rastreamento de importações",
|
||||
"Options.TraceImports.Desc": "Rastreia as primeiras N importações de cada módulo (0 = desativado).",
|
||||
|
||||
"Options.LogToFile.Label": "Salvar log em arquivo",
|
||||
"Options.LogToFile.Desc": "Copia a saída do emulador para um arquivo de log.",
|
||||
|
||||
"Options.LogFilePath.Label": "Caminho do arquivo de log",
|
||||
"Options.LogFilePath.Default": "Nenhum caminho definido — logs vão para user/logs na pasta do emulador.",
|
||||
"Options.LogFilePath.Select": "Selecionar…",
|
||||
|
||||
"Options.OverrideLogFile.Label": "Sobrescrever arquivo de log",
|
||||
"Options.OverrideLogFile.Desc": "Use o caminho exato do arquivo em vez de adicionar o ID do título e o log de data e hora.",
|
||||
|
||||
"Options.TitleMusic.Label": "Música de prévia",
|
||||
"Options.TitleMusic.Desc": "Reproduz em loop a música de prévia do jogo selecionado na biblioteca.",
|
||||
|
||||
"Options.Discord.Label": "Status do Discord",
|
||||
"Options.Discord.Desc": "Exibir o jogo em execução no seu perfil do Discord.",
|
||||
|
||||
"Options.Language.Label": "Idioma do emulador",
|
||||
"Options.Language.Desc": "Idioma usado em toda a interface do emulador. A alteração é aplicada imediatamente.",
|
||||
|
||||
"Common.On": "Ativado",
|
||||
"Common.Off": "Desativado",
|
||||
|
||||
"Console.Title": "CONSOLE",
|
||||
"Console.SearchWatermark": "Pesquisar...",
|
||||
"Console.AutoScroll": "Rolagem automática",
|
||||
"Console.Split": "Recortar",
|
||||
"Console.Copy": "Copiar",
|
||||
"Console.Clear": "Limpar",
|
||||
"Console.WindowTitle": "Console do SharpEmu",
|
||||
|
||||
"Launch.NoGameSelected": "Nenhum jogo selecionado",
|
||||
"Launch.NoGameHint": "Selecione um jogo na biblioteca ou abra um arquivo eboot.bin diretamente.",
|
||||
"Launch.Idle": "Ocioso",
|
||||
"Launch.Console": "≡ Console",
|
||||
"Launch.Launch": "▶ Iniciar",
|
||||
"Launch.Stop": "■ Parar",
|
||||
"Launch.Running": "Em execução — {0}",
|
||||
"Launch.Stopping": "Encerrando…",
|
||||
"Launch.Exited": "Encerrado com código {0} ({1})",
|
||||
"Launch.ExeNotFound": "Executável do SharpEmu não encontrado. Compile primeiro o projeto SharpEmu.CLI (dotnet build).",
|
||||
"Launch.LogFile": "Arquivo de log: {0}",
|
||||
"Launch.Command": "$ SharpEmu {0}",
|
||||
"Launch.StartFailed": "Falha ao iniciar o emulador: {0}",
|
||||
"Launch.ProcessExited": "O processo foi encerrado com código {0} ({1}).",
|
||||
|
||||
"Exit.Ok": "OK",
|
||||
"Exit.InvalidArguments": "argumentos inválidos",
|
||||
"Exit.EbootNotFound": "eboot.bin não encontrado",
|
||||
"Exit.RuntimeException": "exceção em tempo de execução",
|
||||
"Exit.EmulationError": "erro de emulação",
|
||||
"Exit.Unknown": "desconhecido",
|
||||
|
||||
"Status.EmulatorLocating": "Emulador: localizando…",
|
||||
"Status.EmulatorPath": "Emulador: {0}",
|
||||
"Status.EmulatorNotFound": "Emulador: executável do SharpEmu não encontrado — compile o SharpEmu.CLI primeiro.",
|
||||
"Status.ScanningLibrary": "Verificando biblioteca…",
|
||||
"Status.AddFolderPrompt": "Adicione uma pasta de jogos para preencher a biblioteca.",
|
||||
"Status.LibraryScanned": "Biblioteca verificada: {0} jogo(s) em {1} pasta(s).",
|
||||
"Status.CouldNotOpenFolder": "Não foi possível abrir a pasta: {0}",
|
||||
"Status.CopiedToClipboard": "{0} copiado para a área de transferência.",
|
||||
"Status.RemovedFromLibrary": "“{0}” removido da biblioteca. Adicione novamente sua pasta para restaurá-lo.",
|
||||
"Status.Running": "Executando {0}",
|
||||
"Status.Stopping": "Encerrando…",
|
||||
"Status.Idle": "Ocioso",
|
||||
|
||||
"Clipboard.Path": "Caminho",
|
||||
"Clipboard.TitleId": "ID do título",
|
||||
|
||||
"Discord.Playing": "Jogando {0}",
|
||||
"Discord.Browsing": "Navegando pela biblioteca",
|
||||
|
||||
"Dialog.ChooseGameFolder": "Escolha uma pasta contendo jogos",
|
||||
"Dialog.OpenExecutable": "Abrir um executável para iniciar",
|
||||
"Dialog.PsExecutables": "Executáveis de PS",
|
||||
"Dialog.SaveLogFile": "Selecione onde salvar o arquivo de log",
|
||||
"Dialog.PlainTextFiles": "Arquivos de texto simples",
|
||||
"Dialog.LogFiles": "Arquivos de log"
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
{
|
||||
"_languageName": "Deutsch",
|
||||
|
||||
"Page.Library": "Bibliothek",
|
||||
"Page.Options": "Optionen",
|
||||
"Page.GameCount.One": "1 Spiel",
|
||||
"Page.GameCount.Other": "{0} Spiele",
|
||||
|
||||
"Library.SearchWatermark": "Bibliothek durchsuchen…",
|
||||
"Library.AddFolder": "+ Spielordner hinzufügen",
|
||||
"Library.Rescan": "⟳ Neu scannen",
|
||||
"Library.OpenFile": "Datei öffnen…",
|
||||
|
||||
"Library.Context.Launch": "Starten",
|
||||
"Library.Context.OpenFolder": "Spielordner öffnen",
|
||||
"Library.Context.CopyPath": "Pfad kopieren",
|
||||
"Library.Context.CopyTitleId": "Title ID kopieren",
|
||||
"Library.Context.Remove": "Aus Bibliothek entfernen",
|
||||
|
||||
"Library.Empty.Title": "Deine Bibliothek ist leer",
|
||||
"Library.Empty.Hint": "Füge einen Ordner mit deinen Spielen hinzu, um zu beginnen.",
|
||||
"Library.Empty.SearchTitle": "Keine Spiele gefunden",
|
||||
"Library.Empty.SearchHint": "Nichts in der Bibliothek entspricht “{0}”.",
|
||||
"Library.Empty.AddFolder": "+ Spielordner hinzufügen",
|
||||
|
||||
"Library.Loading": "Bibliothek wird geladen…",
|
||||
|
||||
"Options.General": "Allgemein",
|
||||
"Options.Section.Emulation": "EMULATION",
|
||||
"Options.Section.Logging": "PROTOKOLLIERUNG",
|
||||
"Options.Section.Launcher": "LAUNCHER",
|
||||
|
||||
"Options.CpuEngine.Label": "CPU-Engine",
|
||||
"Options.CpuEngine.Desc": "Ausführungs-Engine, die zum Ausführen des Spiel-Codes verwendet wird.",
|
||||
"Options.CpuEngine.Native": "Nativ",
|
||||
|
||||
"Options.Strict.Label": "Strikte dynlib-Auflösung",
|
||||
"Options.Strict.Desc": "Starten abbrechen, wenn ein importiertes Symbol nicht aufgelöst werden kann.",
|
||||
|
||||
"Options.LogLevel.Label": "Protokollstufe",
|
||||
"Options.LogLevel.Desc": "Ausführlichkeit der Emulator-Konsolenausgabe.",
|
||||
"Options.LogLevel.Trace": "Trace",
|
||||
"Options.LogLevel.Debug": "Debug",
|
||||
"Options.LogLevel.Info": "Info",
|
||||
"Options.LogLevel.Warning": "Warnung",
|
||||
"Options.LogLevel.Error": "Fehler",
|
||||
"Options.LogLevel.Critical": "Kritisch",
|
||||
|
||||
"Options.TraceImports.Label": "Import-Trace-Limit",
|
||||
"Options.TraceImports.Desc": "Die ersten N Imports pro Modul verfolgen (0 = aus).",
|
||||
|
||||
"Options.LogToFile.Label": "In Datei protokollieren",
|
||||
"Options.LogToFile.Desc": "Emulator-Ausgabe zusätzlich in eine Log-Datei schreiben.",
|
||||
|
||||
"Options.LogFilePath.Label": "Protokolldatei-Pfad",
|
||||
"Options.LogFilePath.Default": "Kein benutzerdefinierter Pfad – Logs werden im Ordner user/logs neben dem Emulator gespeichert.",
|
||||
"Options.LogFilePath.Select": "Auswählen…",
|
||||
|
||||
"Options.OverrideLogFile.Label": "Protokolldatei überschreiben",
|
||||
"Options.OverrideLogFile.Desc": "Genauen Dateipfad verwenden, statt Title-ID und Zeitstempel anzuhängen.",
|
||||
|
||||
"Options.TitleMusic.Label": "Titel-Musik",
|
||||
"Options.TitleMusic.Desc": "Die Vorschau-Musik des ausgewählten Spiels in der Bibliothek loopend abspielen.",
|
||||
|
||||
"Options.Discord.Label": "Discord-Präsenz",
|
||||
"Options.Discord.Desc": "Zeigt das aktuell gespielte Spiel in deinem Discord-Profil an.",
|
||||
|
||||
"Options.Language.Label": "Emulator-Sprache",
|
||||
"Options.Language.Desc": "Sprache der Benutzeroberfläche. Wird sofort angewendet.",
|
||||
|
||||
"Common.On": "An",
|
||||
"Common.Off": "Aus",
|
||||
|
||||
"Console.Title": "KONSOLE",
|
||||
"Console.SearchWatermark": "Suchen...",
|
||||
"Console.AutoScroll": "Auto-Scroll",
|
||||
"Console.Split": "Teilen",
|
||||
"Console.Copy": "Kopieren",
|
||||
"Console.Clear": "Leeren",
|
||||
"Console.WindowTitle": "SharpEmu Konsole",
|
||||
|
||||
"Launch.NoGameSelected": "Kein Spiel ausgewählt",
|
||||
"Launch.NoGameHint": "Wähle ein Spiel aus der Bibliothek aus oder öffne eine eboot.bin direkt.",
|
||||
"Launch.Idle": "Bereit",
|
||||
"Launch.Console": "≡ Konsole",
|
||||
"Launch.Launch": "▶ Starten",
|
||||
"Launch.Stop": "■ Stoppen",
|
||||
"Launch.Running": "Läuft -- {0}",
|
||||
"Launch.Stopping": "Wird beendet…",
|
||||
"Launch.Exited": "Beendet mit Code {0} ({1})",
|
||||
"Launch.ExeNotFound": "SharpEmu-Executable wurde nicht gefunden. Baue zuerst das SharpEmu.CLI-Projekt (dotnet build).",
|
||||
"Launch.LogFile": "Log-Datei: {0}",
|
||||
"Launch.Command": "$ SharpEmu {0}",
|
||||
"Launch.StartFailed": "Emulator konnte nicht gestartet werden: {0}",
|
||||
"Launch.ProcessExited": "Prozess wurde mit Code {0} ({1}) beendet.",
|
||||
|
||||
"Exit.Ok": "OK",
|
||||
"Exit.InvalidArguments": "Ungültige Argumente",
|
||||
"Exit.EbootNotFound": "eboot nicht gefunden",
|
||||
"Exit.RuntimeException": "Laufzeitfehler",
|
||||
"Exit.EmulationError": "Emulationsfehler",
|
||||
"Exit.Unknown": "unbekannt",
|
||||
|
||||
"Status.EmulatorLocating": "Emulator: wird gesucht…",
|
||||
"Status.EmulatorPath": "Emulator: {0}",
|
||||
"Status.EmulatorNotFound": "Emulator: SharpEmu-Executable nicht gefunden -- baue zuerst SharpEmu.CLI.",
|
||||
"Status.ScanningLibrary": "Bibliothek wird gescannt…",
|
||||
"Status.AddFolderPrompt": "Füge einen Spielordner hinzu, um die Bibliothek zu füllen.",
|
||||
"Status.LibraryScanned": "Bibliothek gescannt: {0} Spiel(e) in {1} Ordner(n).",
|
||||
"Status.CouldNotOpenFolder": "Ordner konnte nicht geöffnet werden: {0}",
|
||||
"Status.CopiedToClipboard": "{0} in die Zwischenablage kopiert.",
|
||||
"Status.RemovedFromLibrary": "“{0}” wurde aus der Bibliothek entfernt. Füge den Ordner erneut hinzu, um es wiederherzustellen.",
|
||||
"Status.Running": "Läuft {0}",
|
||||
"Status.Stopping": "Wird gestoppt…",
|
||||
"Status.Idle": "Bereit",
|
||||
|
||||
"Clipboard.Path": "Pfad",
|
||||
"Clipboard.TitleId": "Title ID",
|
||||
|
||||
"Discord.Playing": "Spielt {0}",
|
||||
"Discord.Browsing": "Durchsucht die Bibliothek",
|
||||
|
||||
"Dialog.ChooseGameFolder": "Spielordner auswählen",
|
||||
"Dialog.OpenExecutable": "Ausführbare Datei zum Starten öffnen",
|
||||
"Dialog.PsExecutables": "PS-Ausführbare Dateien",
|
||||
"Dialog.SaveLogFile": "Protokolldatei speichern unter",
|
||||
"Dialog.PlainTextFiles": "Textdateien",
|
||||
"Dialog.LogFiles": "Protokolldateien"
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
{
|
||||
"_languageName": "Dansk",
|
||||
|
||||
"Page.Library": "Bibliotek",
|
||||
"Page.Options": "Indstillinger",
|
||||
"Page.GameCount.One": "1 spil",
|
||||
"Page.GameCount.Other": "{0} spil",
|
||||
|
||||
"Library.SearchWatermark": "Søg i biblioteket…",
|
||||
"Library.AddFolder": "+ Tilføj mappe",
|
||||
"Library.Rescan": "⟳ Genindlæs",
|
||||
"Library.OpenFile": "Åbn fil…",
|
||||
|
||||
"Library.Context.Launch": "Start",
|
||||
"Library.Context.OpenFolder": "Åbn spilmappe",
|
||||
"Library.Context.CopyPath": "Kopiér sti",
|
||||
"Library.Context.CopyTitleId": "Kopiér titel-ID",
|
||||
"Library.Context.Remove": "Fjern fra bibliotek",
|
||||
|
||||
"Library.Empty.Title": "Dit bibliotek er tomt",
|
||||
"Library.Empty.Hint": "Tilføj en mappe med dine spil for at komme i gang.",
|
||||
"Library.Empty.SearchTitle": "Ingen spil matcher din søgning",
|
||||
"Library.Empty.SearchHint": "Intet i biblioteket matcher “{0}”.",
|
||||
"Library.Empty.AddFolder": "+ Tilføj spilmappe",
|
||||
|
||||
"Library.Loading": "Indlæser bibliotek…",
|
||||
|
||||
"Options.General": "Generelt",
|
||||
"Options.Section.Emulation": "EMULERING",
|
||||
"Options.Section.Logging": "LOGGING",
|
||||
"Options.Section.Launcher": "LAUNCHER",
|
||||
|
||||
"Options.CpuEngine.Label": "CPU-engine",
|
||||
"Options.CpuEngine.Desc": "Den eksekveringsengine der bruges til at køre spilkode.",
|
||||
"Options.CpuEngine.Native": "Native",
|
||||
|
||||
"Options.Strict.Label": "Streng dynlib-opløsning",
|
||||
"Options.Strict.Desc": "Afbryd opstarten, når et importeret symbol ikke kan findes.",
|
||||
|
||||
"Options.LogLevel.Label": "Logniveau",
|
||||
"Options.LogLevel.Desc": "Detaljeringsgrad for emulatorens konsoloutput.",
|
||||
"Options.LogLevel.Trace": "Trace",
|
||||
"Options.LogLevel.Debug": "Debug",
|
||||
"Options.LogLevel.Info": "Info",
|
||||
"Options.LogLevel.Warning": "Advarsel",
|
||||
"Options.LogLevel.Error": "Fejl",
|
||||
"Options.LogLevel.Critical": "Kritisk",
|
||||
|
||||
"Options.TraceImports.Label": "Grænse for import-trace",
|
||||
"Options.TraceImports.Desc": "Spor de første N imports pr. modul (0 = fra).",
|
||||
|
||||
"Options.LogToFile.Label": "Log til fil",
|
||||
"Options.LogToFile.Desc": "Spejl emulatorens output til en logfil.",
|
||||
|
||||
"Options.LogFilePath.Label": "Sti til logfil",
|
||||
"Options.LogFilePath.Default": "Ingen brugerdefineret sti — logs gemmes i user/logs ved siden af emulatoren.",
|
||||
"Options.LogFilePath.Select": "Vælg…",
|
||||
|
||||
"Options.OverrideLogFile.Label": "Tilsidesæt logfil",
|
||||
"Options.OverrideLogFile.Desc": "Brug den præcise filsti i stedet for at tilføje titel-ID og tidsstempel.",
|
||||
|
||||
"Options.TitleMusic.Label": "Titelmusik",
|
||||
"Options.TitleMusic.Desc": "Gentag det valgte spils forhåndsvisningsmusik i biblioteket.",
|
||||
|
||||
"Options.Discord.Label": "Discord-tilstedeværelse",
|
||||
"Options.Discord.Desc": "Vis det kørende spil på din Discord-profil.",
|
||||
|
||||
"Options.Language.Label": "Emulatorsprog",
|
||||
"Options.Language.Desc": "Sprog der bruges i hele launcheren. Anvendes med det samme.",
|
||||
|
||||
"Common.On": "Til",
|
||||
"Common.Off": "Fra",
|
||||
|
||||
"Console.Title": "KONSOL",
|
||||
"Console.SearchWatermark": "Søg...",
|
||||
"Console.AutoScroll": "Auto-scroll",
|
||||
"Console.Split": "Opdel",
|
||||
"Console.Copy": "Kopiér",
|
||||
"Console.Clear": "Ryd",
|
||||
"Console.WindowTitle": "SharpEmu-konsol",
|
||||
|
||||
"Launch.NoGameSelected": "Intet spil valgt",
|
||||
"Launch.NoGameHint": "Vælg et spil fra biblioteket, eller åbn en eboot.bin direkte.",
|
||||
"Launch.Idle": "Inaktiv",
|
||||
"Launch.Console": "≡ Konsol",
|
||||
"Launch.Launch": "▶ Start",
|
||||
"Launch.Stop": "■ Stop",
|
||||
"Launch.Running": "Kører — {0}",
|
||||
"Launch.Stopping": "Stopper…",
|
||||
"Launch.Exited": "Afsluttet med kode {0} ({1})",
|
||||
"Launch.ExeNotFound": "SharpEmu-programmet blev ikke fundet. Byg SharpEmu.CLI-projektet først (dotnet build).",
|
||||
"Launch.LogFile": "Logfil: {0}",
|
||||
"Launch.Command": "$ SharpEmu {0}",
|
||||
"Launch.StartFailed": "Kunne ikke starte emulatoren: {0}",
|
||||
"Launch.ProcessExited": "Processen afsluttede med kode {0} ({1}).",
|
||||
|
||||
"Exit.Ok": "OK",
|
||||
"Exit.InvalidArguments": "ugyldige argumenter",
|
||||
"Exit.EbootNotFound": "eboot ikke fundet",
|
||||
"Exit.RuntimeException": "runtime-fejl",
|
||||
"Exit.EmulationError": "emuleringsfejl",
|
||||
"Exit.Unknown": "ukendt",
|
||||
|
||||
"Status.EmulatorLocating": "Emulator: lokaliserer…",
|
||||
"Status.EmulatorPath": "Emulator: {0}",
|
||||
"Status.EmulatorNotFound": "Emulator: SharpEmu-programmet blev ikke fundet — byg SharpEmu.CLI først.",
|
||||
"Status.ScanningLibrary": "Skanner bibliotek…",
|
||||
"Status.AddFolderPrompt": "Tilføj en spilmappe for at udfylde biblioteket.",
|
||||
"Status.LibraryScanned": "Bibliotek skannet: {0} spil i {1} mappe(r).",
|
||||
"Status.CouldNotOpenFolder": "Kunne ikke åbne mappe: {0}",
|
||||
"Status.CopiedToClipboard": "{0} kopieret til udklipsholderen.",
|
||||
"Status.RemovedFromLibrary": "“{0}” fjernet fra biblioteket. Tilføj mappen igen for at gendanne det.",
|
||||
"Status.Running": "Kører {0}",
|
||||
"Status.Stopping": "Stopper…",
|
||||
"Status.Idle": "Inaktiv",
|
||||
|
||||
"Clipboard.Path": "Sti",
|
||||
"Clipboard.TitleId": "Titel-ID",
|
||||
|
||||
"Discord.Playing": "Spiller {0}",
|
||||
"Discord.Browsing": "Gennemser biblioteket",
|
||||
|
||||
"Dialog.ChooseGameFolder": "Vælg en mappe der indeholder spil",
|
||||
"Dialog.OpenExecutable": "Åbn et program der skal startes",
|
||||
"Dialog.PsExecutables": "PS-programmer",
|
||||
"Dialog.SaveLogFile": "Vælg hvor logfilen skal gemmes",
|
||||
"Dialog.PlainTextFiles": "Almindelige tekstfiler",
|
||||
"Dialog.LogFiles": "Logfiler"
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
{
|
||||
"_languageName": "English",
|
||||
|
||||
"Page.Library": "Library",
|
||||
"Page.Options": "Options",
|
||||
"Page.GameCount.One": "1 game",
|
||||
"Page.GameCount.Other": "{0} games",
|
||||
|
||||
"Library.SearchWatermark": "Search library…",
|
||||
"Library.AddFolder": "+ Add folder",
|
||||
"Library.Rescan": "⟳ Rescan",
|
||||
"Library.OpenFile": "Open file…",
|
||||
|
||||
"Library.Context.Launch": "Launch",
|
||||
"Library.Context.OpenFolder": "Open game folder",
|
||||
"Library.Context.CopyPath": "Copy path",
|
||||
"Library.Context.CopyTitleId": "Copy title ID",
|
||||
"Library.Context.Remove": "Remove from library",
|
||||
|
||||
"Library.Empty.Title": "Your library is empty",
|
||||
"Library.Empty.Hint": "Add a folder containing your games to get started.",
|
||||
"Library.Empty.SearchTitle": "No games match your search",
|
||||
"Library.Empty.SearchHint": "Nothing in the library matches “{0}”.",
|
||||
"Library.Empty.AddFolder": "+ Add game folder",
|
||||
|
||||
"Library.Loading": "Loading library…",
|
||||
|
||||
"Options.General": "General",
|
||||
"Options.Env.Tab": "Environment",
|
||||
"Options.Section.Environment": "ENVIRONMENT VARIABLES",
|
||||
"Options.Env.Desc": "Switches passed to the emulator as environment variables at launch.",
|
||||
"Options.Env.Bthid.Desc": "Report Bluetooth HID as unavailable for titles whose wheel/FFB middleware polls forever.\nLeave off normally. Some titles freeze when init fails.",
|
||||
"Options.Env.LoopGuard.Desc": "Do not force quit titles that repeat the same call for too long.\nTry this when a game exits on its own while loading.",
|
||||
"Options.Env.VkValidation.Desc": "Enable Vulkan validation layers for GPU debugging.\nSlow. Requires the Vulkan SDK to be installed.",
|
||||
"Options.Env.DumpSpirv.Desc": "Dump AGC shaders and their SPIR-V translations to the shader-dumps folder.\nUse when reporting shader or rendering bugs.",
|
||||
"Options.Env.LogDirectMemory.Desc": "Log direct memory allocations and failures to the console.\nUse when a game aborts or exits during boot.",
|
||||
"Options.Env.LogNp.Desc": "Log NP (PlayStation Network) library calls to the console.",
|
||||
"Options.Section.Emulation": "EMULATION",
|
||||
"Options.Section.Logging": "LOGGING",
|
||||
"Options.Section.Launcher": "LAUNCHER",
|
||||
|
||||
"Options.CpuEngine.Label": "CPU engine",
|
||||
"Options.CpuEngine.Desc": "Execution engine used to run game code.",
|
||||
"Options.CpuEngine.Native": "Native",
|
||||
|
||||
"Options.Strict.Label": "Strict dynlib resolution",
|
||||
"Options.Strict.Desc": "Fail the launch when an imported symbol cannot be resolved.",
|
||||
|
||||
"Options.LogLevel.Label": "Log level",
|
||||
"Options.LogLevel.Desc": "Verbosity of the emulator console output.",
|
||||
"Options.LogLevel.Trace": "Trace",
|
||||
"Options.LogLevel.Debug": "Debug",
|
||||
"Options.LogLevel.Info": "Info",
|
||||
"Options.LogLevel.Warning": "Warning",
|
||||
"Options.LogLevel.Error": "Error",
|
||||
"Options.LogLevel.Critical": "Critical",
|
||||
|
||||
"Options.TraceImports.Label": "Import trace limit",
|
||||
"Options.TraceImports.Desc": "Trace the first N imports per module (0 = off).",
|
||||
|
||||
"Options.LogToFile.Label": "Log to file",
|
||||
"Options.LogToFile.Desc": "Mirror emulator output to a log file.",
|
||||
|
||||
"Options.LogFilePath.Label": "Log file path",
|
||||
"Options.LogFilePath.Default": "No custom path — logs go to user/logs next to the emulator.",
|
||||
"Options.LogFilePath.Select": "Select…",
|
||||
|
||||
"Options.OverrideLogFile.Label": "Override log file",
|
||||
"Options.OverrideLogFile.Desc": "Use the exact file path instead of appending title ID and timestamp.",
|
||||
|
||||
"Options.TitleMusic.Label": "Title music",
|
||||
"Options.TitleMusic.Desc": "Loop the selected game's preview music in the library.",
|
||||
|
||||
"Options.Discord.Label": "Discord presence",
|
||||
"Options.Discord.Desc": "Show the running game on your Discord profile.",
|
||||
|
||||
"Options.Language.Label": "Emulator language",
|
||||
"Options.Language.Desc": "Language used throughout the launcher. Applies immediately.",
|
||||
|
||||
"Common.On": "On",
|
||||
"Common.Off": "Off",
|
||||
|
||||
"Console.Title": "CONSOLE",
|
||||
"Console.SearchWatermark": "Search...",
|
||||
"Console.AutoScroll": "Auto-scroll",
|
||||
"Console.Split": "Split",
|
||||
"Console.Copy": "Copy",
|
||||
"Console.Clear": "Clear",
|
||||
"Console.WindowTitle": "SharpEmu Console",
|
||||
|
||||
"Launch.NoGameSelected": "No game selected",
|
||||
"Launch.NoGameHint": "Pick a game from the library, or open an eboot.bin directly.",
|
||||
"Launch.Idle": "Idle",
|
||||
"Launch.Console": "≡ Console",
|
||||
"Launch.Launch": "▶ Launch",
|
||||
"Launch.Stop": "■ Stop",
|
||||
"Launch.Running": "Running — {0}",
|
||||
"Launch.Stopping": "Stopping…",
|
||||
"Launch.Exited": "Exited with code {0} ({1})",
|
||||
"Launch.ExeNotFound": "SharpEmu executable not found. Build the SharpEmu.CLI project first (dotnet build).",
|
||||
"Launch.LogFile": "Log file: {0}",
|
||||
"Launch.Command": "$ SharpEmu {0}",
|
||||
"Launch.StartFailed": "Failed to start the emulator: {0}",
|
||||
"Launch.ProcessExited": "Process exited with code {0} ({1}).",
|
||||
|
||||
"Exit.Ok": "OK",
|
||||
"Exit.InvalidArguments": "invalid arguments",
|
||||
"Exit.EbootNotFound": "eboot not found",
|
||||
"Exit.RuntimeException": "runtime exception",
|
||||
"Exit.EmulationError": "emulation error",
|
||||
"Exit.Unknown": "unknown",
|
||||
|
||||
"Status.EmulatorLocating": "Emulator: locating…",
|
||||
"Status.EmulatorPath": "Emulator: {0}",
|
||||
"Status.EmulatorNotFound": "Emulator: SharpEmu executable not found — build SharpEmu.CLI first.",
|
||||
"Status.ScanningLibrary": "Scanning library…",
|
||||
"Status.AddFolderPrompt": "Add a game folder to populate the library.",
|
||||
"Status.LibraryScanned": "Library scanned: {0} game(s) in {1} folder(s).",
|
||||
"Status.CouldNotOpenFolder": "Could not open folder: {0}",
|
||||
"Status.CopiedToClipboard": "{0} copied to clipboard.",
|
||||
"Status.RemovedFromLibrary": "Removed “{0}” from the library. Re-add its folder to restore it.",
|
||||
"Status.Running": "Running {0}",
|
||||
"Status.Stopping": "Stopping…",
|
||||
"Status.Idle": "Idle",
|
||||
|
||||
"Clipboard.Path": "Path",
|
||||
"Clipboard.TitleId": "Title ID",
|
||||
|
||||
"Discord.Playing": "Playing {0}",
|
||||
"Discord.Browsing": "Browsing the library",
|
||||
|
||||
"Dialog.ChooseGameFolder": "Choose a folder containing games",
|
||||
"Dialog.OpenExecutable": "Open an executable to launch",
|
||||
"Dialog.PsExecutables": "PS executables",
|
||||
"Dialog.SaveLogFile": "Select where to save the Log file",
|
||||
"Dialog.PlainTextFiles": "Plain Text Files",
|
||||
"Dialog.LogFiles": "Log Files",
|
||||
|
||||
"Options.About" : "About",
|
||||
"About.Github.Label": "GitHub",
|
||||
"About.Github.Desc": "Source code, issues and project development.",
|
||||
"About.Discord.Label": "Discord",
|
||||
"About.Discord.Desc": "Join the community, get support and follow development.",
|
||||
"About.GithubButton": "Contribute in GitHub!",
|
||||
"About.DiscordButton": "Join our Discord!"
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
{
|
||||
"_languageName": "Español",
|
||||
|
||||
"Page.Library": "Biblioteca",
|
||||
"Page.Options": "Opciones",
|
||||
"Page.GameCount.One": "1 juego",
|
||||
"Page.GameCount.Other": "{0} juegos",
|
||||
|
||||
"Library.SearchWatermark": "Buscar en la biblioteca…",
|
||||
"Library.AddFolder": "+ Añadir carpeta",
|
||||
"Library.Rescan": "⟳ Volver a escanear",
|
||||
"Library.OpenFile": "Abrir archivo…",
|
||||
|
||||
"Library.Context.Launch": "Iniciar",
|
||||
"Library.Context.OpenFolder": "Abrir carpeta de juegos",
|
||||
"Library.Context.CopyPath": "Copiar ruta",
|
||||
"Library.Context.CopyTitleId": "Copiar ID del título",
|
||||
"Library.Context.Remove": "Eliminar de la biblioteca",
|
||||
|
||||
"Library.Empty.Title": "Tu biblioteca está vacía",
|
||||
"Library.Empty.Hint": "Añade una carpeta que contenga tus juegos para empezar.",
|
||||
"Library.Empty.SearchTitle": "Ningún juego coincide con la búsqueda",
|
||||
"Library.Empty.SearchHint": "No se ha encontrado nada en la biblioteca que coincida con “{0}”.",
|
||||
"Library.Empty.AddFolder": "+ Añadir carpeta de juegos",
|
||||
|
||||
"Library.Loading": "Cargando biblioteca…",
|
||||
|
||||
"Options.General": "General",
|
||||
"Options.Section.Emulation": "EMULACIÓN",
|
||||
"Options.Section.Logging": "LOGS",
|
||||
"Options.Section.Launcher": "LAUNCHER",
|
||||
|
||||
"Options.CpuEngine.Label": "Motor de CPU",
|
||||
"Options.CpuEngine.Desc": "Motor utilizado para ejecutar el código del juego.",
|
||||
"Options.CpuEngine.Native": "Nativo",
|
||||
|
||||
"Options.Strict.Label": "Resolución estricta de dynlib (Bibliotecas dinámicas)",
|
||||
"Options.Strict.Desc": "Detener la ejecución cuando un símbolo importado no se pueda resolver.",
|
||||
|
||||
"Options.LogLevel.Label": "Nivel de Log",
|
||||
"Options.LogLevel.Desc": "Verbosidad de la salida en consola del emulador.",
|
||||
"Options.LogLevel.Trace": "Trazas",
|
||||
"Options.LogLevel.Debug": "Depuración",
|
||||
"Options.LogLevel.Info": "Información",
|
||||
"Options.LogLevel.Warning": "Advertencia",
|
||||
"Options.LogLevel.Error": "Error",
|
||||
"Options.LogLevel.Critical": "Crítico",
|
||||
|
||||
"Options.TraceImports.Label": "Límite de trazado de importaciones",
|
||||
"Options.TraceImports.Desc": "Trazar las primeras N importaciones por módulo (0 = off).",
|
||||
|
||||
"Options.LogToFile.Label": "Registrar log en archivo",
|
||||
"Options.LogToFile.Desc": "Duplicar la salida del emulador en un archivo de logs.",
|
||||
|
||||
"Options.LogFilePath.Label": "Ruta del archivo de Log",
|
||||
"Options.LogFilePath.Default": "Sin ruta personalizada — los logs van a user/logs al lado del emulador.",
|
||||
"Options.LogFilePath.Select": "Seleccionar…",
|
||||
|
||||
"Options.OverrideLogFile.Label": "Sobreescribir archivo de logs",
|
||||
"Options.OverrideLogFile.Desc": "Utilizar la misma ruta para el archivo de logs en vez de añadir la ID del título y marca de tiempo.",
|
||||
|
||||
"Options.TitleMusic.Label": "Música del título",
|
||||
"Options.TitleMusic.Desc": "Repetir en bucle la preview de la música del juego seleccionado en la biblioteca.",
|
||||
|
||||
"Options.Discord.Label": "Actividad de Discord",
|
||||
"Options.Discord.Desc": "Mostrar juego en ejecución en tu perfil de Discord.",
|
||||
|
||||
"Options.Language.Label": "Idioma del emulador",
|
||||
"Options.Language.Desc": "Idioma utilizado en todo el launcher. Se aplica inmediatamente.",
|
||||
|
||||
"Common.On": "Encendido",
|
||||
"Common.Off": "Apagado",
|
||||
|
||||
"Console.Title": "CONSOLA",
|
||||
"Console.SearchWatermark": "Buscar...",
|
||||
"Console.AutoScroll": "Desplazamiento automático",
|
||||
"Console.Split": "Desacoplar",
|
||||
"Console.Copy": "Copiar",
|
||||
"Console.Clear": "Limpiar",
|
||||
"Console.WindowTitle": "Consola SharpEmu",
|
||||
|
||||
"Launch.NoGameSelected": "No hay ningún juego seleccionado",
|
||||
"Launch.NoGameHint": "Selecciona un juego de la biblioteca o abre un eboot.bin directamente.",
|
||||
"Launch.Idle": "Inactivo",
|
||||
"Launch.Console": "≡ Consola",
|
||||
"Launch.Launch": "▶ Iniciar",
|
||||
"Launch.Stop": "■ Detener",
|
||||
"Launch.Running": "En ejecución — {0}",
|
||||
"Launch.Stopping": "Deteniendo…",
|
||||
"Launch.Exited": "Finalizó con el código {0} ({1})",
|
||||
"Launch.ExeNotFound": "No se ha encontrado el ejecutable de SharpEmu. Compila previamente el proyecto SharpEmu.CLI (dotnet build).",
|
||||
"Launch.LogFile": "Archivo de Log: {0}",
|
||||
"Launch.Command": "$ SharpEmu {0}",
|
||||
"Launch.StartFailed": "Error al iniciar el emulador: {0}",
|
||||
"Launch.ProcessExited": "El proceso finalizó con el código {0} ({1}).",
|
||||
|
||||
"Exit.Ok": "OK",
|
||||
"Exit.InvalidArguments": "argumentos no válidos",
|
||||
"Exit.EbootNotFound": "no se encontró eboot",
|
||||
"Exit.RuntimeException": "excepción en tiempo de ejecución",
|
||||
"Exit.EmulationError": "error de emulación",
|
||||
"Exit.Unknown": "desconocido",
|
||||
|
||||
"Status.EmulatorLocating": "Emulador: localizando…",
|
||||
"Status.EmulatorPath": "Emulador: {0}",
|
||||
"Status.EmulatorNotFound": "Emulador: No se encontró el ejecutable de SharpEmu — compila previamente SharpEmu.CLI.",
|
||||
"Status.ScanningLibrary": "Escaneando biblioteca…",
|
||||
"Status.AddFolderPrompt": "Añade una carpeta de juegos para poblar la biblioteca.",
|
||||
"Status.LibraryScanned": "Biblioteca escaneada: Se encontraron {0} juego(s) en {1} carpeta(s).",
|
||||
"Status.CouldNotOpenFolder": "No se ha podido abrir la carpeta: {0}",
|
||||
"Status.CopiedToClipboard": "{0} copiado al portapapeles.",
|
||||
"Status.RemovedFromLibrary": "Se eliminó “{0}” de la biblioteca. Vuelve a añadir su carpeta para restaurarlo.",
|
||||
"Status.Running": "Ejecutando {0}",
|
||||
"Status.Stopping": "Deteniendo…",
|
||||
"Status.Idle": "Inactivo",
|
||||
|
||||
"Clipboard.Path": "Ruta",
|
||||
"Clipboard.TitleId": "ID del título",
|
||||
|
||||
"Discord.Playing": "Jugando a {0}",
|
||||
"Discord.Browsing": "Navegando en la biblioteca, buscando un juego para divertirse.",
|
||||
|
||||
"Dialog.ChooseGameFolder": "Selecciona una carpeta que contenga juegos",
|
||||
"Dialog.OpenExecutable": "Abrir un ejecutable para iniciar",
|
||||
"Dialog.PsExecutables": "Ejecutables de PS",
|
||||
"Dialog.SaveLogFile": "Selecciona dónde guardar el archivo de Logs",
|
||||
"Dialog.PlainTextFiles": "Archivos en texto plano",
|
||||
"Dialog.LogFiles": "Archivos de Log",
|
||||
|
||||
"Options.About" : "Informacion",
|
||||
"About.Github.Label": "GitHub",
|
||||
"About.Github.Desc": "Código fuente, issues y desarrollo del proyecto.",
|
||||
"About.Discord.Label": "Discord",
|
||||
"About.Discord.Desc": "Únete a la comunidad, recibe soporte y sigue el desarrollo.",
|
||||
"About.GithubButton": "Contribuye en GitHub!",
|
||||
"About.DiscordButton": "Únete a nuestro Discord!"
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
{
|
||||
"_languageName": "Français",
|
||||
|
||||
"Page.Library": "Bibliothèque",
|
||||
"Page.Options": "Options",
|
||||
"Page.GameCount.One": "1 jeu",
|
||||
"Page.GameCount.Other": "{0} jeux",
|
||||
|
||||
"Library.SearchWatermark": "Rechercher dans la bibliothèque…",
|
||||
"Library.AddFolder": "+ Ajouter un dossier",
|
||||
"Library.Rescan": "⟳ Analyser à nouveau",
|
||||
"Library.OpenFile": "Ouvrir un fichier…",
|
||||
|
||||
"Library.Context.Launch": "Lancer",
|
||||
"Library.Context.OpenFolder": "Ouvrir le dossier du jeu",
|
||||
"Library.Context.CopyPath": "Copier le chemin",
|
||||
"Library.Context.CopyTitleId": "Copier l’identifiant du jeu",
|
||||
"Library.Context.Remove": "Retirer de la bibliothèque",
|
||||
|
||||
"Library.Empty.Title": "Votre bibliothèque est vide",
|
||||
"Library.Empty.Hint": "Ajoutez un dossier contenant vos jeux pour commencer.",
|
||||
"Library.Empty.SearchTitle": "Aucun jeu ne correspond à votre recherche",
|
||||
"Library.Empty.SearchHint": "Aucun élément de la bibliothèque ne correspond à « {0} ».",
|
||||
"Library.Empty.AddFolder": "+ Ajouter un dossier de jeux",
|
||||
|
||||
"Library.Loading": "Chargement de la bibliothèque…",
|
||||
|
||||
"Options.General": "Général",
|
||||
"Options.Section.Emulation": "ÉMULATION",
|
||||
"Options.Section.Logging": "JOURNALISATION",
|
||||
"Options.Section.Launcher": "LANCEUR",
|
||||
|
||||
"Options.CpuEngine.Label": "Moteur CPU",
|
||||
"Options.CpuEngine.Desc": "Moteur d’exécution utilisé pour exécuter le code du jeu.",
|
||||
"Options.CpuEngine.Native": "Natif",
|
||||
|
||||
"Options.Strict.Label": "Résolution stricte des bibliothèques dynamiques",
|
||||
"Options.Strict.Desc": "Interrompre le lancement lorsqu’un symbole importé ne peut pas être résolu.",
|
||||
|
||||
"Options.LogLevel.Label": "Niveau de journalisation",
|
||||
"Options.LogLevel.Desc": "Niveau de détail des messages affichés dans la console de l’émulateur.",
|
||||
"Options.LogLevel.Trace": "Traçage",
|
||||
"Options.LogLevel.Debug": "Débogage",
|
||||
"Options.LogLevel.Info": "Informations",
|
||||
"Options.LogLevel.Warning": "Avertissements",
|
||||
"Options.LogLevel.Error": "Erreurs",
|
||||
"Options.LogLevel.Critical": "Erreurs critiques",
|
||||
|
||||
"Options.TraceImports.Label": "Limite de traçage des imports",
|
||||
"Options.TraceImports.Desc": "Tracer les N premiers imports de chaque module (0 = désactivé).",
|
||||
|
||||
"Options.LogToFile.Label": "Enregistrer dans un fichier",
|
||||
"Options.LogToFile.Desc": "Copier la sortie de l’émulateur dans un fichier journal.",
|
||||
|
||||
"Options.LogFilePath.Label": "Chemin du fichier journal",
|
||||
"Options.LogFilePath.Default": "Aucun chemin personnalisé — les journaux sont enregistrés dans user/logs à côté de l’émulateur.",
|
||||
"Options.LogFilePath.Select": "Sélectionner…",
|
||||
|
||||
"Options.OverrideLogFile.Label": "Remplacer le fichier journal",
|
||||
"Options.OverrideLogFile.Desc": "Utiliser exactement ce chemin au lieu d’ajouter l’identifiant du jeu et l’horodatage.",
|
||||
|
||||
"Options.TitleMusic.Label": "Musique du jeu",
|
||||
"Options.TitleMusic.Desc": "Lire en boucle la musique d’aperçu du jeu sélectionné dans la bibliothèque.",
|
||||
|
||||
"Options.Discord.Label": "Présence Discord",
|
||||
"Options.Discord.Desc": "Afficher le jeu en cours d’exécution sur votre profil Discord.",
|
||||
|
||||
"Options.Language.Label": "Langue de l’émulateur",
|
||||
"Options.Language.Desc": "Langue utilisée dans l’ensemble du lanceur. Le changement est immédiat.",
|
||||
|
||||
"Common.On": "Activé",
|
||||
"Common.Off": "Désactivé",
|
||||
|
||||
"Console.Title": "CONSOLE",
|
||||
"Console.SearchWatermark": "Rechercher…",
|
||||
"Console.AutoScroll": "Défilement automatique",
|
||||
"Console.Split": "Détacher",
|
||||
"Console.Copy": "Copier",
|
||||
"Console.Clear": "Effacer",
|
||||
"Console.WindowTitle": "Console SharpEmu",
|
||||
|
||||
"Launch.NoGameSelected": "Aucun jeu sélectionné",
|
||||
"Launch.NoGameHint": "Choisissez un jeu dans la bibliothèque ou ouvrez directement un fichier eboot.bin.",
|
||||
"Launch.Idle": "Inactif",
|
||||
"Launch.Console": "≡ Console",
|
||||
"Launch.Launch": "▶ Lancer",
|
||||
"Launch.Stop": "■ Arrêter",
|
||||
"Launch.Running": "En cours d’exécution — {0}",
|
||||
"Launch.Stopping": "Arrêt en cours…",
|
||||
"Launch.Exited": "Processus terminé avec le code {0} ({1})",
|
||||
"Launch.ExeNotFound": "L’exécutable SharpEmu est introuvable. Compilez d’abord le projet SharpEmu.CLI (dotnet build).",
|
||||
"Launch.LogFile": "Fichier journal : {0}",
|
||||
"Launch.Command": "$ SharpEmu {0}",
|
||||
"Launch.StartFailed": "Impossible de démarrer l’émulateur : {0}",
|
||||
"Launch.ProcessExited": "Le processus s’est terminé avec le code {0} ({1}).",
|
||||
|
||||
"Exit.Ok": "OK",
|
||||
"Exit.InvalidArguments": "arguments non valides",
|
||||
"Exit.EbootNotFound": "eboot introuvable",
|
||||
"Exit.RuntimeException": "exception d’exécution",
|
||||
"Exit.EmulationError": "erreur d’émulation",
|
||||
"Exit.Unknown": "inconnu",
|
||||
|
||||
"Status.EmulatorLocating": "Émulateur : recherche en cours…",
|
||||
"Status.EmulatorPath": "Émulateur : {0}",
|
||||
"Status.EmulatorNotFound": "Émulateur : l’exécutable SharpEmu est introuvable — compilez d’abord SharpEmu.CLI.",
|
||||
"Status.ScanningLibrary": "Analyse de la bibliothèque…",
|
||||
"Status.AddFolderPrompt": "Ajoutez un dossier de jeux pour remplir la bibliothèque.",
|
||||
"Status.LibraryScanned": "Bibliothèque analysée : {0} jeu(x) dans {1} dossier(s).",
|
||||
"Status.CouldNotOpenFolder": "Impossible d’ouvrir le dossier : {0}",
|
||||
"Status.CopiedToClipboard": "{0} copié dans le presse-papiers.",
|
||||
"Status.RemovedFromLibrary": "« {0} » a été retiré de la bibliothèque. Ajoutez à nouveau son dossier pour le restaurer.",
|
||||
"Status.Running": "Exécution de {0}",
|
||||
"Status.Stopping": "Arrêt en cours…",
|
||||
"Status.Idle": "Inactif",
|
||||
|
||||
"Clipboard.Path": "Chemin",
|
||||
"Clipboard.TitleId": "Identifiant du jeu",
|
||||
|
||||
"Discord.Playing": "Joue à {0}",
|
||||
"Discord.Browsing": "Parcourt la bibliothèque",
|
||||
|
||||
"Dialog.ChooseGameFolder": "Choisir un dossier contenant des jeux",
|
||||
"Dialog.OpenExecutable": "Ouvrir un exécutable à lancer",
|
||||
"Dialog.PsExecutables": "Exécutables PlayStation",
|
||||
"Dialog.SaveLogFile": "Choisir l’emplacement du fichier journal",
|
||||
"Dialog.PlainTextFiles": "Fichiers texte brut",
|
||||
"Dialog.LogFiles": "Fichiers journaux"
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
{
|
||||
"_languageName": "Hungarian",
|
||||
|
||||
"Page.Library": "Könyvtár",
|
||||
"Page.Options": "Beállítások",
|
||||
"Page.GameCount.One": "1 játék",
|
||||
"Page.GameCount.Other": "{0} játékok",
|
||||
|
||||
"Library.SearchWatermark": "Keresés a könyvtárban",
|
||||
"Library.AddFolder": "+ Mappa hozzáadása",
|
||||
"Library.Rescan": "⟳ Újrakeresés",
|
||||
"Library.OpenFile": "Fájl megnyitása…",
|
||||
|
||||
"Library.Context.Launch": "Inditás",
|
||||
"Library.Context.OpenFolder": "Játékmappa megnyitása",
|
||||
"Library.Context.CopyPath": "Elérési út másolása",
|
||||
"Library.Context.CopyTitleId": "Cím ID másolása",
|
||||
"Library.Context.Remove": "Eltávolítás a Könyvtárból",
|
||||
|
||||
"Library.Empty.Title": "A könyvtárad üres",
|
||||
"Library.Empty.Hint": "Add meg a játékaidat tartalmazó mappát a kezdáshez.",
|
||||
"Library.Empty.SearchTitle": "Nincs találat a elemre",
|
||||
"Library.Empty.SearchHint": "A könyvtárban nincs olyan elem, amely egyezne a „{0}” kifejezéssel.",
|
||||
"Library.Empty.AddFolder": "+ Játékmappa hozzáadása",
|
||||
|
||||
"Library.Loading": "Könyvtár betöltése",
|
||||
|
||||
"Options.General": "Általános",
|
||||
"Options.Env.Tab": "Környezet",
|
||||
"Options.Section.Environment": "KÖRNYEZETI VÁLTOZÓK",
|
||||
"Options.Env.Desc": "Indításkor környezeti változóként az emulátorhoz átadott kapcsolók.",
|
||||
"Options.Env.Bthid.Desc": "Jelenti, amely címeknél a Bluetooth HID nem elérhető, amelyeknél a kormány/FFB-közbenső szoftver végtelenül lekérdezi az adatokat.\nNormál esetben hagyja ki. Egyes címek lefagyanak, ha az inicializálás sikertelen.",
|
||||
"Options.Env.LoopGuard.Desc": "Ne erőltesse a kilépést azoknál a címeknél, amelyek túl sokáig ismételnek ugyanazt a hívást.\nPróbálja ki ezt, ha egy játék betöltés közben magától kilép.",
|
||||
"Options.Env.VkValidation.Desc": "Engedélyezze a Vulkan-érvényesítési rétegeket a GPU hibakereséshez.\nLassú. A Vulkan SDK telepítését igényli.",
|
||||
"Options.Env.DumpSpirv.Desc": "Az AGC-shaderek és azok SPIR-V-fordításainak mentése a shader-dumps mappába.\nHasználd shader- vagy renderelési hibák jelentésekor.",
|
||||
"Options.Env.LogDirectMemory.Desc": "A közvetlen memóriaallokációk és hibák naplózása a konzolra.\nHasználd, ha egy játék a rendszerindítás során megszakad vagy kilép.",
|
||||
"Options.Env.LogNp.Desc": "Az NP (PlayStation Network) könyvtárhívásokat naplózza a konzolra.",
|
||||
"Options.Section.Emulation": "EMULÁCIÓ",
|
||||
"Options.Section.Logging": "LOGOLÁS",
|
||||
"Options.Section.Launcher": "INDITÓ",
|
||||
|
||||
"Options.CpuEngine.Label": "CPU motor",
|
||||
"Options.CpuEngine.Desc": "A játék kódjának futtatásához használt végrehajtó motor.",
|
||||
"Options.CpuEngine.Native": "Natív",
|
||||
|
||||
"Options.Strict.Label": "Szigorú dynlib felbontás",
|
||||
"Options.Strict.Desc": "Indítás megszakítása, ha egy importált szimbólum nem oldható fel.",
|
||||
|
||||
"Options.LogLevel.Label": "Naplózási szint",
|
||||
"Options.LogLevel.Desc": "Az emulátor konzol kimenetének részletessége.",
|
||||
"Options.LogLevel.Trace": "Trace",
|
||||
"Options.LogLevel.Debug": "Debug",
|
||||
"Options.LogLevel.Info": "Információ",
|
||||
"Options.LogLevel.Warning": "Figyelmeztetés",
|
||||
"Options.LogLevel.Error": "Hiba",
|
||||
"Options.LogLevel.Critical": "Kritikus",
|
||||
|
||||
"Options.TraceImports.Label": "Import trace limit",
|
||||
"Options.TraceImports.Desc": "Az első N darab import nyomon követése modulonként (0 = ki).",
|
||||
|
||||
"Options.LogToFile.Label": "Naplozás fájlba",
|
||||
"Options.LogToFile.Desc": "Az emulátor kimenetének tükrözése egy log fájlba.",
|
||||
|
||||
"Options.LogFilePath.Label": "Naplófájl elérési útja",
|
||||
"Options.LogFilePath.Default": "Nincs egyéni út — a logok az emulátor melletti user/logs mappába kerülnek.",
|
||||
"Options.LogFilePath.Select": "Kiválasztás…",
|
||||
|
||||
"Options.OverrideLogFile.Label": "Naplófájl felülírása",
|
||||
"Options.OverrideLogFile.Desc": "A pontos fájlútvonal használata a cím ID és időbélyeg hozzáfűzése helyett.",
|
||||
|
||||
"Options.TitleMusic.Label": "Címzene",
|
||||
"Options.TitleMusic.Desc": "A kiválasztott játék előnézeti zenéjének ismétlése a könyvtárban.",
|
||||
|
||||
"Options.Discord.Label": "Discord jelenlét",
|
||||
"Options.Discord.Desc": "A futó játék megjelenítése a Discord profilodon.",
|
||||
|
||||
"Options.Language.Label": "Emulátor nyelve",
|
||||
"Options.Language.Desc": "Az indítóban használt nyelv. Azonnal érvénybe lép.",
|
||||
|
||||
"Common.On": "Be",
|
||||
"Common.Off": "Ki",
|
||||
|
||||
"Console.Title": "KONZOL",
|
||||
"Console.SearchWatermark": "Keresés...",
|
||||
"Console.AutoScroll": "Automatikus görgetés",
|
||||
"Console.Split": "Felosztás",
|
||||
"Console.Copy": "Másolás",
|
||||
"Console.Clear": "Törlés",
|
||||
"Console.WindowTitle": "SharpEmu Konzol",
|
||||
|
||||
"Launch.NoGameSelected": "Nincs játék kiválasztva",
|
||||
"Launch.NoGameHint": "Válassz egy játékot a könyvtárból, vagy nyiss meg közvetlenül egy eboot.bin fájlt.",
|
||||
"Launch.Idle": "Tétlen",
|
||||
"Launch.Console": "≡ Konzol",
|
||||
"Launch.Launch": "▶ Inditás",
|
||||
"Launch.Stop": "■ Leállítás",
|
||||
"Launch.Running": "Fut — {0}",
|
||||
"Launch.Stopping": "Leállítás…",
|
||||
"Launch.Exited": "Kilépett a következő kóddal: {0} ({1})",
|
||||
"Launch.ExeNotFound": "A SharpEmu futtatható fájl nem található. Előbb építsd fel a SharpEmu.CLI projektet (dotnet build).",
|
||||
"Launch.LogFile": "Naplófájl: {0}",
|
||||
"Launch.Command": "$ SharpEmu {0}",
|
||||
"Launch.StartFailed": "Nem sikerült elindítani az emulátort: {0}",
|
||||
"Launch.ProcessExited": "A folyamat kilépett a következő kóddal: {0} ({1}).",
|
||||
|
||||
"Exit.Ok": "OK",
|
||||
"Exit.InvalidArguments": "nemérvényes argumentumok",
|
||||
"Exit.EbootNotFound": "eboot nem található",
|
||||
"Exit.RuntimeException": "runtime exception",
|
||||
"Exit.EmulationError": "emulációs hiba",
|
||||
"Exit.Unknown": "ismeretlen",
|
||||
|
||||
"Status.EmulatorLocating": "Emulátor: keresés…",
|
||||
"Status.EmulatorPath": "Emulátor: {0}",
|
||||
"Status.EmulatorNotFound": "Emulátor: a SharpEmu futtatható fájl nem található — előbb építsd fel a SharpEmu.CLI-t.",
|
||||
"Status.ScanningLibrary": "Könyvtár beolvasása…",
|
||||
"Status.AddFolderPrompt": "Adj hozzá egy játékmappát a könyvtár feltöltéséhez.",
|
||||
"Status.LibraryScanned": "Könyvtár beolvasva: {0} játék {1} mappában.",
|
||||
"Status.CouldNotOpenFolder": "Nem sikerült megnyitni a mappát: {0}",
|
||||
"Status.CopiedToClipboard": "{0} másolva a vágólapra.",
|
||||
"Status.RemovedFromLibrary": "„{0}” eltávolítva a könyvtárból. A visszaállításához add hozzá újra a mappáját.",
|
||||
"Status.Running": "Fut {0}",
|
||||
"Status.Stopping": "Leállítás…",
|
||||
"Status.Idle": "Nyugodt",
|
||||
|
||||
"Clipboard.Path": "Út",
|
||||
"Clipboard.TitleId": "Cím ID",
|
||||
|
||||
"Discord.Playing": "Játékban {0}",
|
||||
"Discord.Browsing": "Böngéssz a könyvtárban",
|
||||
|
||||
"Dialog.ChooseGameFolder": "Válassz egy mappát ami a játékaidat tartalmazza",
|
||||
"Dialog.OpenExecutable": "Futtatható fájl megnyitása az indításhoz",
|
||||
"Dialog.PsExecutables": "PS futtatható fájlok",
|
||||
"Dialog.SaveLogFile": "Válaszd ki, hogy hova szeretnéd menteni a napló fájlokat",
|
||||
"Dialog.PlainTextFiles": "Egyszerű szöveges fájlok",
|
||||
"Dialog.LogFiles": "Naplózási fájlok",
|
||||
|
||||
"Options.About" : "Erről",
|
||||
"About.Github.Label": "GitHub",
|
||||
"About.Github.Desc": "Forrás kód, hibajelentések és a projekt fejlesztése.",
|
||||
"About.Discord.Label": "Discord",
|
||||
"About.Discord.Desc": "Csatlakozz a közösséghe, kérj segítéget és kövesd nyomon a fejlesztést.",
|
||||
"About.GithubButton": "Járulj hozzá GitHubon!",
|
||||
"About.DiscordButton": "Csatlakozz a Discordunhoz!"
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
{
|
||||
"_languageName": "Italiano",
|
||||
|
||||
"Page.Library": "Libreria",
|
||||
"Page.Options": "Opzioni",
|
||||
"Page.GameCount.One": "1 gioco",
|
||||
"Page.GameCount.Other": "{0} giochi",
|
||||
|
||||
"Library.SearchWatermark": "Cerca nella libreria…",
|
||||
"Library.AddFolder": "+ Aggiungi cartella",
|
||||
"Library.Rescan": "⟳ Riscansiona",
|
||||
"Library.OpenFile": "Apri file…",
|
||||
|
||||
"Library.Context.Launch": "Avvia",
|
||||
"Library.Context.OpenFolder": "Apri cartella gioco",
|
||||
"Library.Context.CopyPath": "Copia percorso",
|
||||
"Library.Context.CopyTitleId": "Copia ID titolo",
|
||||
"Library.Context.Remove": "Rimuovi dalla libreria",
|
||||
|
||||
"Library.Empty.Title": "La tua libreria è vuota",
|
||||
"Library.Empty.Hint": "Aggiungi la cartella che contiene i tuoi giochi per partire.",
|
||||
"Library.Empty.SearchTitle": "Nessun gioco corrisponde alla ricerca",
|
||||
"Library.Empty.SearchHint": "Nulla nella libreria corrisponde a “{0}”.",
|
||||
"Library.Empty.AddFolder": "+ Aggiungi cartella giochi",
|
||||
|
||||
"Library.Loading": "Caricamento libreria…",
|
||||
|
||||
"Options.General": "Generale",
|
||||
"Options.Section.Emulation": "EMULAZIONE",
|
||||
"Options.Section.Logging": "LOG",
|
||||
"Options.Section.Launcher": "LAUNCHER",
|
||||
|
||||
"Options.CpuEngine.Label": "CPU engine",
|
||||
"Options.CpuEngine.Desc": "Motore di esecuzione utilizzato per eseguire il codice del gioco.",
|
||||
"Options.CpuEngine.Native": "Nativo",
|
||||
|
||||
"Options.Strict.Label": "Risoluzione rigorosa dynlib",
|
||||
"Options.Strict.Desc": "Interrompi l'avvio quando un simbolo importato non può essere trovato.",
|
||||
|
||||
"Options.LogLevel.Label": "Livello Log",
|
||||
"Options.LogLevel.Desc": "Livello di dettaglio dell'output console dell'emulatore.",
|
||||
"Options.LogLevel.Trace": "Trace",
|
||||
"Options.LogLevel.Debug": "Debug",
|
||||
"Options.LogLevel.Info": "Info",
|
||||
"Options.LogLevel.Warning": "Warning",
|
||||
"Options.LogLevel.Error": "Error",
|
||||
"Options.LogLevel.Critical": "Critical",
|
||||
|
||||
"Options.TraceImports.Label": "Limite tracciamento import",
|
||||
"Options.TraceImports.Desc": "Traccia i primi N import per modulo (0 = disattivato).",
|
||||
|
||||
|
||||
"Options.LogToFile.Label": "Salva log su file",
|
||||
"Options.LogToFile.Desc": "Duplica l'output dell'emulatore in un file di log.",
|
||||
|
||||
|
||||
"Options.LogFilePath.Label": "Percorso file di log",
|
||||
"Options.LogFilePath.Default": "Nessun percorso personalizzato — i log vengono salvati in user/logs accanto all'emulatore.",
|
||||
"Options.LogFilePath.Select": "Seleziona…",
|
||||
|
||||
"Options.OverrideLogFile.Label": "Sovrascrivi file di log",
|
||||
"Options.OverrideLogFile.Desc": "Usa esattamente il percorso specificato invece di aggiungere Title ID e timestamp.",
|
||||
|
||||
|
||||
"Options.TitleMusic.Label": "Musica del titolo",
|
||||
"Options.TitleMusic.Desc": "Riproduci in loop la musica di anteprima del gioco selezionato nella libreria.",
|
||||
|
||||
"Options.Discord.Label": "Presenza Discord",
|
||||
"Options.Discord.Desc": "Mostra il gioco in esecuzione sul tuo profilo Discord.",
|
||||
|
||||
"Options.Language.Label": "Lingua dell'emulatore",
|
||||
"Options.Language.Desc": "Lingua utilizzata in tutto il launcher. Viene applicata immediatamente.",
|
||||
|
||||
"Common.On": "On",
|
||||
"Common.Off": "Off",
|
||||
|
||||
"Console.Title": "CONSOLE",
|
||||
"Console.SearchWatermark": "Cerca...",
|
||||
"Console.AutoScroll": "Scorrimento automatico",
|
||||
"Console.Split": "Dividi",
|
||||
"Console.Copy": "Copia",
|
||||
"Console.Clear": "Cancella",
|
||||
"Console.WindowTitle": "Console SharpEmu",
|
||||
|
||||
"Launch.NoGameSelected": "Nessun gioco selezionato",
|
||||
"Launch.NoGameHint": "Scegli un gioco dalla libreria, oppure apri direttamente un eboot.bin.",
|
||||
"Launch.Idle": "Inattivo",
|
||||
"Launch.Console": "≡ Console",
|
||||
"Launch.Launch": "▶ Avvia",
|
||||
"Launch.Stop": "■ Ferma",
|
||||
"Launch.Running": "In esecuzione — {0}",
|
||||
"Launch.Stopping": "Arresto in corso…",
|
||||
"Launch.Exited": "Terminato con codice {0} ({1})",
|
||||
"Launch.ExeNotFound": "Eseguibile SharpEmu non trovato. Compila prima il progetto SharpEmu.CLI (dotnet build).",
|
||||
"Launch.LogFile": "File di log: {0}",
|
||||
"Launch.Command": "$ SharpEmu {0}",
|
||||
"Launch.StartFailed": "Impossibile avviare l'emulatore: {0}",
|
||||
"Launch.ProcessExited": "Processo terminato con codice {0} ({1}).",
|
||||
|
||||
|
||||
"Exit.Ok": "OK",
|
||||
"Exit.InvalidArguments": "argomenti non validi",
|
||||
"Exit.EbootNotFound": "eboot non trovato",
|
||||
"Exit.RuntimeException": "errore di runtime",
|
||||
"Exit.EmulationError": "errore di emulazione",
|
||||
"Exit.Unknown": "sconosciuto",
|
||||
|
||||
|
||||
"Status.EmulatorLocating": "Emulatore: ricerca in corso…",
|
||||
"Status.EmulatorPath": "Emulatore: {0}",
|
||||
"Status.EmulatorNotFound": "Emulatore: eseguibile SharpEmu non trovato — compila prima SharpEmu.CLI.",
|
||||
"Status.ScanningLibrary": "Scansione della libreria…",
|
||||
"Status.AddFolderPrompt": "Aggiungi una cartella di giochi per popolare la libreria.",
|
||||
"Status.LibraryScanned": "Libreria scansionata: {0} gioco/giochi in {1} cartella/e.",
|
||||
"Status.CouldNotOpenFolder": "Impossibile aprire la cartella: {0}",
|
||||
"Status.CopiedToClipboard": "{0} copiato negli appunti.",
|
||||
"Status.RemovedFromLibrary": "“{0}” rimosso dalla libreria. Riaggiungi la sua cartella per ripristinarlo.",
|
||||
"Status.Running": "In esecuzione: {0}",
|
||||
"Status.Stopping": "Arresto in corso…",
|
||||
"Status.Idle": "Inattivo",
|
||||
|
||||
"Clipboard.Path": "Percorso",
|
||||
"Clipboard.TitleId": "ID Titolo",
|
||||
|
||||
"Discord.Playing": "Sta giocando a {0}",
|
||||
"Discord.Browsing": "Sta esplorando la libreria",
|
||||
|
||||
"Dialog.ChooseGameFolder": "Scegli una cartella contenente giochi",
|
||||
"Dialog.OpenExecutable": "Apri un eseguibile da avviare",
|
||||
"Dialog.PsExecutables": "Eseguibili PS",
|
||||
"Dialog.SaveLogFile": "Scegli dove salvare il file di log",
|
||||
"Dialog.PlainTextFiles": "File di testo semplice",
|
||||
"Dialog.LogFiles": "File di log"
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
{
|
||||
"_languageName": "日本語",
|
||||
|
||||
"Page.Library": "ライブラリ",
|
||||
"Page.Options": "オプション",
|
||||
"Page.GameCount.One": "ゲーム 1本",
|
||||
"Page.GameCount.Other": "ゲーム {0}本",
|
||||
|
||||
"Library.SearchWatermark": "ライブラリを検索…",
|
||||
"Library.AddFolder": "+ フォルダーを追加",
|
||||
"Library.Rescan": "⟳ 再スキャン",
|
||||
"Library.OpenFile": "ファイルを開く…",
|
||||
|
||||
"Library.Context.Launch": "起動",
|
||||
"Library.Context.OpenFolder": "ゲームフォルダーを開く",
|
||||
"Library.Context.CopyPath": "パスをコピー",
|
||||
"Library.Context.CopyTitleId": "ゲームIDをコピー",
|
||||
"Library.Context.Remove": "ライブラリから削除",
|
||||
|
||||
"Library.Empty.Title": "ライブラリが空です",
|
||||
"Library.Empty.Hint": "開始するには、ゲームが含まれるフォルダーを追加してください。",
|
||||
"Library.Empty.SearchTitle": "検索条件に一致するゲームが見つかりません",
|
||||
"Library.Empty.SearchHint": "ライブラリに「{0}」と一致する項目はありません。",
|
||||
"Library.Empty.AddFolder": "+ ゲームフォルダーを追加",
|
||||
|
||||
"Library.Loading": "ライブラリを読み込み中…",
|
||||
|
||||
"Options.General": "一般",
|
||||
"Options.Section.Emulation": "エミュレーション",
|
||||
"Options.Section.Logging": "ロギング",
|
||||
"Options.Section.Launcher": "ランチャー",
|
||||
|
||||
"Options.CpuEngine.Label": "CPUエンジン",
|
||||
"Options.CpuEngine.Desc": "ゲームコードを実行するために使用される実行エンジン。",
|
||||
"Options.CpuEngine.Native": "ネイティブ",
|
||||
|
||||
"Options.Strict.Label": "厳格な動的ライブラリ解決",
|
||||
"Options.Strict.Desc": "インポートされたシンボルが解決できない場合、起動を中断します。",
|
||||
|
||||
"Options.LogLevel.Label": "ログレベル",
|
||||
"Options.LogLevel.Desc": "エミュレータコンソールに表示されるメッセージの詳細度。",
|
||||
"Options.LogLevel.Trace": "トレース",
|
||||
"Options.LogLevel.Debug": "デバッグ",
|
||||
"Options.LogLevel.Info": "情報",
|
||||
"Options.LogLevel.Warning": "警告",
|
||||
"Options.LogLevel.Error": "エラー",
|
||||
"Options.LogLevel.Critical": "致命的なエラー",
|
||||
|
||||
"Options.TraceImports.Label": "インポートトレース制限",
|
||||
"Options.TraceImports.Desc": "各モジュールの最初のN個のインポートをトレースします(0 = 無効)。",
|
||||
|
||||
"Options.LogToFile.Label": "ファイルに保存",
|
||||
"Options.LogToFile.Desc": "エミュレータの出力をログファイルにコピーします。",
|
||||
|
||||
"Options.LogFilePath.Label": "ログファイルのパス",
|
||||
"Options.LogFilePath.Default": "カスタムパスなし — ログはエミュレータと同じ場所の user/logs フォルダーに保存されます。",
|
||||
"Options.LogFilePath.Select": "選択…",
|
||||
|
||||
"Options.OverrideLogFile.Label": "ログファイルを上書き",
|
||||
"Options.OverrideLogFile.Desc": "ゲームIDやタイムスタンプを追加せず、指定されたパスをそのまま使用します。",
|
||||
|
||||
"Options.TitleMusic.Label": "ゲーム内音楽",
|
||||
"Options.TitleMusic.Desc": "ライブラリで選択したゲームのプレビュー音楽をループ再生します。",
|
||||
|
||||
"Options.Discord.Label": "Discordステータス表示",
|
||||
"Options.Discord.Desc": "現在プレイ中のゲームをDiscordのプロフィールに表示します。",
|
||||
|
||||
"Options.Language.Label": "エミュレータの言語",
|
||||
"Options.Language.Desc": "ランチャー全体で使用される言語。変更はすぐに適用されます。",
|
||||
|
||||
"Common.On": "オン",
|
||||
"Common.Off": "オフ",
|
||||
|
||||
"Console.Title": "コンソール",
|
||||
"Console.SearchWatermark": "検索…",
|
||||
"Console.AutoScroll": "自動スクロール",
|
||||
"Console.Split": "ウィンドウを分離",
|
||||
"Console.Copy": "コピー",
|
||||
"Console.Clear": "消去",
|
||||
"Console.WindowTitle": "SharpEmu コンソール",
|
||||
|
||||
"Launch.NoGameSelected": "ゲームが選択されていません",
|
||||
"Launch.NoGameHint": "ライブラリからゲームを選択するか、eboot.bin ファイルを直接開いてください。",
|
||||
"Launch.Idle": "待機中",
|
||||
"Launch.Console": "≡ コンソール",
|
||||
"Launch.Launch": "▶ 起動",
|
||||
"Launch.Stop": "■ 停止",
|
||||
"Launch.Running": "実行中 — {0}",
|
||||
"Launch.Stopping": "停止中…",
|
||||
"Launch.Exited": "プロセスがコード {0} ({1}) で終了しました",
|
||||
"Launch.ExeNotFound": "SharpEmuの実行ファイルが見つかりません。先に SharpEmu.CLI プロジェクトをビルドしてください(dotnet build)。",
|
||||
"Launch.LogFile": "ログファイル: {0}",
|
||||
"Launch.Command": "$ SharpEmu {0}",
|
||||
"Launch.StartFailed": "エミュレータを起動できませんでした: {0}",
|
||||
"Launch.ProcessExited": "プロセスがコード {0} ({1}) で終了しました。",
|
||||
|
||||
"Exit.Ok": "OK",
|
||||
"Exit.InvalidArguments": "無効な引数",
|
||||
"Exit.EbootNotFound": "eboot が見つかりません",
|
||||
"Exit.RuntimeException": "ランタイム例外",
|
||||
"Exit.EmulationError": "エミュレーションエラー",
|
||||
"Exit.Unknown": "不明",
|
||||
|
||||
"Status.EmulatorLocating": "エミュレータ: 位置を検索中…",
|
||||
"Status.EmulatorPath": "エミュレータ: {0}",
|
||||
"Status.EmulatorNotFound": "エミュレータ: SharpEmuの実行ファイルが見つかりません — 先に SharpEmu.CLI をビルドしてください。",
|
||||
"Status.ScanningLibrary": "ライブラリをスキャン中…",
|
||||
"Status.AddFolderPrompt": "ライブラリに表示するゲームフォルダーを追加してください。",
|
||||
"Status.LibraryScanned": "ライブラリのスキャン完了: {1} 個のフォルダーから {0} 本のゲームを検出。",
|
||||
"Status.CouldNotOpenFolder": "フォルダーを開けませんでした: {0}",
|
||||
"Status.CopiedToClipboard": "「{0}」をクリップボードにコピーしました。",
|
||||
"Status.RemovedFromLibrary": "「{0}」がライブラリから削除されました。復元するにはフォルダーを再追加してください。",
|
||||
"Status.Running": "{0} を実行中",
|
||||
"Status.Stopping": "停止中…",
|
||||
"Status.Idle": "待機中",
|
||||
|
||||
"Clipboard.Path": "パス",
|
||||
"Clipboard.TitleId": "ゲームID",
|
||||
|
||||
"Discord.Playing": "{0} をプレイ中",
|
||||
"Discord.Browsing": "ライブラリを閲覧中",
|
||||
|
||||
"Dialog.ChooseGameFolder": "ゲームが含まれるフォルダーを選択",
|
||||
"Dialog.OpenExecutable": "起動する実行ファイルを開く",
|
||||
"Dialog.PsExecutables": "PlayStation 実行ファイル",
|
||||
"Dialog.SaveLogFile": "ログファイルの保存先を選択",
|
||||
"Dialog.PlainTextFiles": "プレーンテキストファイル",
|
||||
"Dialog.LogFiles": "ログファイル"
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
{
|
||||
"_languageName": "한국어",
|
||||
|
||||
"Page.Library": "라이브러리",
|
||||
"Page.Options": "옵션",
|
||||
"Page.GameCount.One": "게임 1개",
|
||||
"Page.GameCount.Other": "게임 {0}개",
|
||||
|
||||
"Library.SearchWatermark": "라이브러리 검색…",
|
||||
"Library.AddFolder": "+ 폴더 추가",
|
||||
"Library.Rescan": "⟳ 다시 스캔",
|
||||
"Library.OpenFile": "파일 열기…",
|
||||
|
||||
"Library.Context.Launch": "실행",
|
||||
"Library.Context.OpenFolder": "게임 폴더 열기",
|
||||
"Library.Context.CopyPath": "경로 복사",
|
||||
"Library.Context.CopyTitleId": "게임 ID 복사",
|
||||
"Library.Context.Remove": "라이브러리에서 제거",
|
||||
|
||||
"Library.Empty.Title": "라이브러리가 비어 있습니다",
|
||||
"Library.Empty.Hint": "시작하려면 게임이 포함된 폴더를 추가하세요.",
|
||||
"Library.Empty.SearchTitle": "검색 결과와 일치하는 게임이 없습니다",
|
||||
"Library.Empty.SearchHint": "라이브러리에 '{0}'와(과) 일치하는 항목이 없습니다.",
|
||||
"Library.Empty.AddFolder": "+ 게임 폴더 추가",
|
||||
|
||||
"Library.Loading": "라이브러리 불러오는 중…",
|
||||
|
||||
"Options.General": "일반",
|
||||
"Options.Section.Emulation": "에뮬레이션",
|
||||
"Options.Section.Logging": "로깅",
|
||||
"Options.Section.Launcher": "런처",
|
||||
|
||||
"Options.CpuEngine.Label": "CPU 엔진",
|
||||
"Options.CpuEngine.Desc": "게임 코드를 실행하는 데 사용되는 실행 엔진입니다.",
|
||||
"Options.CpuEngine.Native": "네이티브",
|
||||
|
||||
"Options.Strict.Label": "엄격한 동적 라이브러리 해석",
|
||||
"Options.Strict.Desc": "가져온 심볼을 해석할 수 없는 경우 실행을 중단합니다.",
|
||||
|
||||
"Options.LogLevel.Label": "로그 수준",
|
||||
"Options.LogLevel.Desc": "에뮬레이터 콘솔에 표시할 메시지의 세부 정보 수준입니다.",
|
||||
"Options.LogLevel.Trace": "트레이스",
|
||||
"Options.LogLevel.Debug": "디버그",
|
||||
"Options.LogLevel.Info": "정보",
|
||||
"Options.LogLevel.Warning": "경고",
|
||||
"Options.LogLevel.Error": "오류",
|
||||
"Options.LogLevel.Critical": "치명적 오류",
|
||||
|
||||
"Options.TraceImports.Label": "가져오기 트레이스 한도",
|
||||
"Options.TraceImports.Desc": "각 모듈의 처음 N개 가져오기를 트레이스합니다 (0 = 비활성화).",
|
||||
|
||||
"Options.LogToFile.Label": "파일로 저장",
|
||||
"Options.LogToFile.Desc": "에뮬레이터 출력을 로그 파일에 복사합니다.",
|
||||
|
||||
"Options.LogFilePath.Label": "로그 파일 경로",
|
||||
"Options.LogFilePath.Default": "사용자 지정 경로 없음 — 로그는 에뮬레이터 옆의 user/logs 폴더에 저장됩니다.",
|
||||
"Options.LogFilePath.Select": "선택…",
|
||||
|
||||
"Options.OverrideLogFile.Label": "로그 파일 덮어쓰기",
|
||||
"Options.OverrideLogFile.Desc": "게임 ID와 타임스탬프를 추가하는 대신 정확히 이 경로를 사용합니다.",
|
||||
|
||||
"Options.TitleMusic.Label": "게임 음악",
|
||||
"Options.TitleMusic.Desc": "라이브러리에서 선택한 게임의 미리보기 음악을 반복 재생합니다.",
|
||||
|
||||
"Options.Discord.Label": "디스코드 상태 표시",
|
||||
"Options.Discord.Desc": "디스코드 프로필에 현재 실행 중인 게임을 표시합니다.",
|
||||
|
||||
"Options.Language.Label": "에뮬레이터 언어",
|
||||
"Options.Language.Desc": "런처 전체에 사용되는 언어입니다. 변경 사항은 즉시 적용됩니다.",
|
||||
|
||||
"Common.On": "켬",
|
||||
"Common.Off": "끔",
|
||||
|
||||
"Console.Title": "콘솔",
|
||||
"Console.SearchWatermark": "검색…",
|
||||
"Console.AutoScroll": "자동 스크롤",
|
||||
"Console.Split": "창 분리",
|
||||
"Console.Copy": "복사",
|
||||
"Console.Clear": "지우기",
|
||||
"Console.WindowTitle": "SharpEmu 콘솔",
|
||||
|
||||
"Launch.NoGameSelected": "선택된 게임 없음",
|
||||
"Launch.NoGameHint": "라이브러리에서 게임을 선택하거나 eboot.bin 파일을 직접 여세요.",
|
||||
"Launch.Idle": "대기 중",
|
||||
"Launch.Console": "≡ 콘솔",
|
||||
"Launch.Launch": "▶ 실행",
|
||||
"Launch.Stop": "■ 중지",
|
||||
"Launch.Running": "실행 중 — {0}",
|
||||
"Launch.Stopping": "중지 중…",
|
||||
"Launch.Exited": "프로세스가 코드 {0} ({1})(으)로 종료되었습니다",
|
||||
"Launch.ExeNotFound": "SharpEmu 실행 파일을 찾을 수 없습니다. 먼저 SharpEmu.CLI 프로젝트를 컴파일하세요 (dotnet build).",
|
||||
"Launch.LogFile": "로그 파일: {0}",
|
||||
"Launch.Command": "$ SharpEmu {0}",
|
||||
"Launch.StartFailed": "에뮬레이터를 시작할 수 없습니다: {0}",
|
||||
"Launch.ProcessExited": "프로세스가 코드 {0} ({1})(으)로 종료되었습니다.",
|
||||
|
||||
"Exit.Ok": "확인",
|
||||
"Exit.InvalidArguments": "잘못된 인수",
|
||||
"Exit.EbootNotFound": "eboot을 찾을 수 없음",
|
||||
"Exit.RuntimeException": "런타임 예외",
|
||||
"Exit.EmulationError": "에뮬레이션 오류",
|
||||
"Exit.Unknown": "알 수 없음",
|
||||
|
||||
"Status.EmulatorLocating": "에뮬레이터: 위치 검색 중…",
|
||||
"Status.EmulatorPath": "에뮬레이터: {0}",
|
||||
"Status.EmulatorNotFound": "에뮬레이터: SharpEmu 실행 파일을 찾을 수 없습니다 — 먼저 SharpEmu.CLI를 컴파일하세요.",
|
||||
"Status.ScanningLibrary": "라이브러리 스캔 중…",
|
||||
"Status.AddFolderPrompt": "라이브러리를 채우려면 게임 폴더를 추가하세요.",
|
||||
"Status.LibraryScanned": "라이브러리 스캔 완료: {1}개 폴더에서 {0}개 게임 발견.",
|
||||
"Status.CouldNotOpenFolder": "폴더를 열 수 없습니다: {0}",
|
||||
"Status.CopiedToClipboard": "{0}이(가) 클립보드에 복사되었습니다.",
|
||||
"Status.RemovedFromLibrary": "'{0}'이(가) 라이브러리에서 제거되었습니다. 복구하려면 폴더를 다시 추가하세요.",
|
||||
"Status.Running": "{0} 실행 중",
|
||||
"Status.Stopping": "중지 중…",
|
||||
"Status.Idle": "대기 중",
|
||||
|
||||
"Clipboard.Path": "경로",
|
||||
"Clipboard.TitleId": "게임 ID",
|
||||
|
||||
"Discord.Playing": "{0} 플레이 중",
|
||||
"Discord.Browsing": "라이브러리 둘러보는 중",
|
||||
|
||||
"Dialog.ChooseGameFolder": "게임이 포함된 폴더 선택",
|
||||
"Dialog.OpenExecutable": "실행할 파일 열기",
|
||||
"Dialog.PsExecutables": "PlayStation 실행 파일",
|
||||
"Dialog.SaveLogFile": "로그 파일 저장 위치 선택",
|
||||
"Dialog.PlainTextFiles": "일반 텍스트 파일",
|
||||
"Dialog.LogFiles": "로그 파일"
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
{
|
||||
"_languageName": "Nederlands",
|
||||
|
||||
"Page.Library": "Bibliotheek",
|
||||
"Page.Options": "Opties",
|
||||
"Page.GameCount.One": "1 game",
|
||||
"Page.GameCount.Other": "{0} games",
|
||||
|
||||
"Library.SearchWatermark": "Zoeken in bibliotheek…",
|
||||
"Library.AddFolder": "+ Map toevoegen",
|
||||
"Library.Rescan": "⟳ Opnieuw scannen",
|
||||
"Library.OpenFile": "Bestand openen…",
|
||||
|
||||
"Library.Context.Launch": "Starten",
|
||||
"Library.Context.OpenFolder": "Gamemap openen",
|
||||
"Library.Context.CopyPath": "Pad kopiëren",
|
||||
"Library.Context.CopyTitleId": "Titel-ID kopiëren",
|
||||
"Library.Context.Remove": "Verwijderen uit bibliotheek",
|
||||
|
||||
"Library.Empty.Title": "Je bibliotheek is leeg",
|
||||
"Library.Empty.Hint": "Voeg een map met je games toe om te beginnen.",
|
||||
"Library.Empty.SearchTitle": "Geen games komen overeen met je zoekopdracht",
|
||||
"Library.Empty.SearchHint": "Niets in de bibliotheek komt overeen met “{0}”.",
|
||||
"Library.Empty.AddFolder": "+ Gamemap toevoegen",
|
||||
|
||||
"Library.Loading": "Bibliotheek laden…",
|
||||
|
||||
"Options.General": "Algemeen",
|
||||
"Options.Section.Emulation": "EMULATIE",
|
||||
"Options.Section.Logging": "LOGGING",
|
||||
"Options.Section.Launcher": "LAUNCHER",
|
||||
|
||||
"Options.CpuEngine.Label": "CPU-engine",
|
||||
"Options.CpuEngine.Desc": "Engine die wordt gebruikt om gamecode uit te voeren.",
|
||||
"Options.CpuEngine.Native": "Native",
|
||||
|
||||
"Options.Strict.Label": "Strikte dynlib-resolutie",
|
||||
"Options.Strict.Desc": "Laat het opstarten mislukken wanneer een geïmporteerd symbool niet kan worden opgelost.",
|
||||
|
||||
"Options.LogLevel.Label": "Logniveau",
|
||||
"Options.LogLevel.Desc": "Uitgebreidheid van de console-uitvoer van de emulator.",
|
||||
"Options.LogLevel.Trace": "Trace",
|
||||
"Options.LogLevel.Debug": "Debug",
|
||||
"Options.LogLevel.Info": "Info",
|
||||
"Options.LogLevel.Warning": "Waarschuwing",
|
||||
"Options.LogLevel.Error": "Fout",
|
||||
"Options.LogLevel.Critical": "Kritiek",
|
||||
|
||||
"Options.TraceImports.Label": "Tracelimiet voor imports",
|
||||
"Options.TraceImports.Desc": "Traceer de eerste N imports per module (0 = uit).",
|
||||
|
||||
"Options.LogToFile.Label": "Loggen naar bestand",
|
||||
"Options.LogToFile.Desc": "Stuur de uitvoer van de emulator ook naar een logbestand.",
|
||||
|
||||
"Options.LogFilePath.Label": "Pad naar logbestand",
|
||||
"Options.LogFilePath.Default": "Geen aangepast pad — logs komen terecht in user/logs naast de emulator.",
|
||||
"Options.LogFilePath.Select": "Selecteren…",
|
||||
|
||||
"Options.OverrideLogFile.Label": "Logbestand overschrijven",
|
||||
"Options.OverrideLogFile.Desc": "Gebruik het exacte bestandspad in plaats van de titel-ID en tijdstempel toe te voegen.",
|
||||
|
||||
"Options.TitleMusic.Label": "Titelmuziek",
|
||||
"Options.TitleMusic.Desc": "Herhaal de voorbeeldmuziek van de geselecteerde game in de bibliotheek.",
|
||||
|
||||
"Options.Discord.Label": "Discord-aanwezigheid",
|
||||
"Options.Discord.Desc": "Toon de actieve game op je Discord-profiel.",
|
||||
|
||||
"Options.Language.Label": "Taal van de emulator",
|
||||
"Options.Language.Desc": "Taal die in de hele launcher wordt gebruikt. Wordt direct toegepast.",
|
||||
|
||||
"Common.On": "Aan",
|
||||
"Common.Off": "Uit",
|
||||
|
||||
"Console.Title": "CONSOLE",
|
||||
"Console.SearchWatermark": "Zoeken...",
|
||||
"Console.AutoScroll": "Automatisch scrollen",
|
||||
"Console.Split": "Splitsen",
|
||||
"Console.Copy": "Kopiëren",
|
||||
"Console.Clear": "Wissen",
|
||||
"Console.WindowTitle": "SharpEmu-console",
|
||||
|
||||
"Launch.NoGameSelected": "Geen game geselecteerd",
|
||||
"Launch.NoGameHint": "Kies een game uit de bibliotheek, of open direct een eboot.bin-bestand.",
|
||||
"Launch.Idle": "Inactief",
|
||||
"Launch.Console": "≡ Console",
|
||||
"Launch.Launch": "▶ Starten",
|
||||
"Launch.Stop": "■ Stoppen",
|
||||
"Launch.Running": "Actief — {0}",
|
||||
"Launch.Stopping": "Stoppen…",
|
||||
"Launch.Exited": "Afgesloten met code {0} ({1})",
|
||||
"Launch.ExeNotFound": "SharpEmu-uitvoerbaar bestand niet gevonden. Bouw eerst het SharpEmu.CLI-project (dotnet build).",
|
||||
"Launch.LogFile": "Logbestand: {0}",
|
||||
"Launch.Command": "$ SharpEmu {0}",
|
||||
"Launch.StartFailed": "Starten van de emulator mislukt: {0}",
|
||||
"Launch.ProcessExited": "Proces afgesloten met code {0} ({1}).",
|
||||
|
||||
"Exit.Ok": "OK",
|
||||
"Exit.InvalidArguments": "ongeldige argumenten",
|
||||
"Exit.EbootNotFound": "eboot niet gevonden",
|
||||
"Exit.RuntimeException": "runtime-uitzondering",
|
||||
"Exit.EmulationError": "emulatiefout",
|
||||
"Exit.Unknown": "onbekend",
|
||||
|
||||
"Status.EmulatorLocating": "Emulator: zoeken…",
|
||||
"Status.EmulatorPath": "Emulator: {0}",
|
||||
"Status.EmulatorNotFound": "Emulator: SharpEmu-uitvoerbaar bestand niet gevonden — bouw eerst SharpEmu.CLI.",
|
||||
"Status.ScanningLibrary": "Bibliotheek scannen…",
|
||||
"Status.AddFolderPrompt": "Voeg een gamemap toe om de bibliotheek te vullen.",
|
||||
"Status.LibraryScanned": "Bibliotheek gescand: {0} game(s) in {1} map(pen).",
|
||||
"Status.CouldNotOpenFolder": "Kan map niet openen: {0}",
|
||||
"Status.CopiedToClipboard": "{0} gekopieerd naar klembord.",
|
||||
"Status.RemovedFromLibrary": "“{0}” verwijderd uit de bibliotheek. Voeg de map opnieuw toe om dit te herstellen.",
|
||||
"Status.Running": "Actief {0}",
|
||||
"Status.Stopping": "Stoppen…",
|
||||
"Status.Idle": "Inactief",
|
||||
|
||||
"Clipboard.Path": "Pad",
|
||||
"Clipboard.TitleId": "Titel-ID",
|
||||
|
||||
"Discord.Playing": "Speelt {0}",
|
||||
"Discord.Browsing": "Bladert door de bibliotheek",
|
||||
|
||||
"Dialog.ChooseGameFolder": "Kies een map met games",
|
||||
"Dialog.OpenExecutable": "Open een uitvoerbaar bestand om te starten",
|
||||
"Dialog.PsExecutables": "PS-uitvoerbare bestanden",
|
||||
"Dialog.SaveLogFile": "Selecteer waar het logbestand moet worden opgeslagen",
|
||||
"Dialog.PlainTextFiles": "Platte tekstbestanden",
|
||||
"Dialog.LogFiles": "Logbestanden"
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
{
|
||||
"_languageName": "Português (Portugal)",
|
||||
|
||||
"Page.Library": "Biblioteca",
|
||||
"Page.Options": "Opções",
|
||||
"Page.GameCount.One": "1 jogo",
|
||||
"Page.GameCount.Other": "{0} jogos",
|
||||
|
||||
"Library.SearchWatermark": "Pesquisar biblioteca…",
|
||||
"Library.AddFolder": "+ Adicionar pasta",
|
||||
"Library.Rescan": "⟳ Reanalisar",
|
||||
"Library.OpenFile": "Abrir ficheiro…",
|
||||
|
||||
"Library.Context.Launch": "Iniciar",
|
||||
"Library.Context.OpenFolder": "Abrir pasta do jogo",
|
||||
"Library.Context.CopyPath": "Copiar caminho",
|
||||
"Library.Context.CopyTitleId": "Copiar ID do título",
|
||||
"Library.Context.Remove": "Remover da biblioteca",
|
||||
|
||||
"Library.Empty.Title": "A sua biblioteca está vazia",
|
||||
"Library.Empty.Hint": "Adicione uma pasta com os seus jogos para começar.",
|
||||
"Library.Empty.SearchTitle": "Nenhum jogo corresponde à sua pesquisa",
|
||||
"Library.Empty.SearchHint": "Nada na biblioteca corresponde a “{0}”.",
|
||||
"Library.Empty.AddFolder": "+ Adicionar pasta de jogos",
|
||||
|
||||
"Library.Loading": "A carregar biblioteca…",
|
||||
|
||||
"Options.General": "Geral",
|
||||
"Options.Env.Tab": "Ambiente",
|
||||
"Options.Section.Environment": "VARIÁVEIS DE AMBIENTE",
|
||||
"Options.Env.Desc": "Switches passados ao emulador como variáveis de ambiente no arranque.",
|
||||
"Options.Env.Bthid.Desc": "Reporta o Bluetooth HID como indisponível para títulos cujo middleware de volante/FFB fica à espera indefinidamente.\nDeixe desativado normalmente. Alguns títulos bloqueiam quando a inicialização falha.",
|
||||
"Options.Env.LoopGuard.Desc": "Não force o encerramento de títulos que repetem a mesma chamada durante demasiado tempo.\nExperimente isto quando um jogo fecha sozinho durante o carregamento.",
|
||||
"Options.Env.VkValidation.Desc": "Ativa as camadas de validação do Vulkan para depuração da GPU.\nLento. Requer que o Vulkan SDK esteja instalado.",
|
||||
"Options.Env.DumpSpirv.Desc": "Extrai os shaders AGC e as respetivas traduções SPIR-V para a pasta shader-dumps.\nUtilize ao reportar problemas de shaders ou renderização.",
|
||||
"Options.Env.LogDirectMemory.Desc": "Regista alocações de memória direta e falhas na consola.\nUtilize quando um jogo aborta ou fecha durante o arranque.",
|
||||
"Options.Env.LogNp.Desc": "Regista chamadas da biblioteca NP (PlayStation Network) na consola.",
|
||||
"Options.Section.Emulation": "EMULAÇÃO",
|
||||
"Options.Section.Logging": "REGISTOS",
|
||||
"Options.Section.Launcher": "LANÇADOR",
|
||||
|
||||
"Options.CpuEngine.Label": "Motor de CPU",
|
||||
"Options.CpuEngine.Desc": "Motor de execução utilizado para correr o código do jogo.",
|
||||
"Options.CpuEngine.Native": "Nativo",
|
||||
|
||||
"Options.Strict.Label": "Resolução estrita de dynlib",
|
||||
"Options.Strict.Desc": "Falha o arranque quando um símbolo importado não pode ser resolvido.",
|
||||
|
||||
"Options.LogLevel.Label": "Nível de registo",
|
||||
"Options.LogLevel.Desc": "Nível de detalhe da saída da consola do emulador.",
|
||||
"Options.LogLevel.Trace": "Rastreio",
|
||||
"Options.LogLevel.Debug": "Depuração",
|
||||
"Options.LogLevel.Info": "Informação",
|
||||
"Options.LogLevel.Warning": "Aviso",
|
||||
"Options.LogLevel.Error": "Erro",
|
||||
"Options.LogLevel.Critical": "Crítico",
|
||||
|
||||
"Options.TraceImports.Label": "Limite de rastreio de importações",
|
||||
"Options.TraceImports.Desc": "Rastreia as primeiras N importações por módulo (0 = desativado).",
|
||||
|
||||
"Options.LogToFile.Label": "Registar para ficheiro",
|
||||
"Options.LogToFile.Desc": "Duplicar a saída do emulador para um ficheiro de registo.",
|
||||
|
||||
"Options.LogFilePath.Label": "Caminho do ficheiro de registo",
|
||||
"Options.LogFilePath.Default": "Sem caminho personalizado — os registos vão para user/logs junto ao emulador.",
|
||||
"Options.LogFilePath.Select": "Selecionar…",
|
||||
|
||||
"Options.OverrideLogFile.Label": "Substituir ficheiro de registo",
|
||||
"Options.OverrideLogFile.Desc": "Utilizar o caminho de ficheiro exato em vez de acrescentar o ID do título e a hora.",
|
||||
|
||||
"Options.TitleMusic.Label": "Música do título",
|
||||
"Options.TitleMusic.Desc": "Repetir em loop a música de pré-visualização do jogo selecionado na biblioteca.",
|
||||
|
||||
"Options.Discord.Label": "Presença no Discord",
|
||||
"Options.Discord.Desc": "Mostrar o jogo em execução no seu perfil do Discord.",
|
||||
|
||||
"Options.Language.Label": "Idioma do emulador",
|
||||
"Options.Language.Desc": "Idioma utilizado em todo o lançador. Aplica-se de imediato.",
|
||||
|
||||
"Common.On": "Ativado",
|
||||
"Common.Off": "Desativado",
|
||||
|
||||
"Console.Title": "CONSOLA",
|
||||
"Console.SearchWatermark": "Pesquisar...",
|
||||
"Console.AutoScroll": "Deslocamento automático",
|
||||
"Console.Split": "Dividir",
|
||||
"Console.Copy": "Copiar",
|
||||
"Console.Clear": "Limpar",
|
||||
"Console.WindowTitle": "Consola do SharpEmu",
|
||||
|
||||
"Launch.NoGameSelected": "Nenhum jogo selecionado",
|
||||
"Launch.NoGameHint": "Escolha um jogo da biblioteca ou abra um eboot.bin diretamente.",
|
||||
"Launch.Idle": "Inativo",
|
||||
"Launch.Console": "≡ Consola",
|
||||
"Launch.Launch": "▶ Iniciar",
|
||||
"Launch.Stop": "■ Parar",
|
||||
"Launch.Running": "Em execução — {0}",
|
||||
"Launch.Stopping": "A parar…",
|
||||
"Launch.Exited": "Terminou com o código {0} ({1})",
|
||||
"Launch.ExeNotFound": "Executável do SharpEmu não encontrado. Compile primeiro o projeto SharpEmu.CLI (dotnet build).",
|
||||
"Launch.LogFile": "Ficheiro de registo: {0}",
|
||||
"Launch.Command": "$ SharpEmu {0}",
|
||||
"Launch.StartFailed": "Falha ao iniciar o emulador: {0}",
|
||||
"Launch.ProcessExited": "O processo terminou com o código {0} ({1}).",
|
||||
|
||||
"Exit.Ok": "OK",
|
||||
"Exit.InvalidArguments": "argumentos inválidos",
|
||||
"Exit.EbootNotFound": "eboot não encontrado",
|
||||
"Exit.RuntimeException": "exceção em tempo de execução",
|
||||
"Exit.EmulationError": "erro de emulação",
|
||||
"Exit.Unknown": "desconhecido",
|
||||
|
||||
"Status.EmulatorLocating": "Emulador: a localizar…",
|
||||
"Status.EmulatorPath": "Emulador: {0}",
|
||||
"Status.EmulatorNotFound": "Emulador: executável do SharpEmu não encontrado — compile primeiro o SharpEmu.CLI.",
|
||||
"Status.ScanningLibrary": "A analisar biblioteca…",
|
||||
"Status.AddFolderPrompt": "Adicione uma pasta de jogos para preencher a biblioteca.",
|
||||
"Status.LibraryScanned": "Biblioteca analisada: {0} jogo(s) em {1} pasta(s).",
|
||||
"Status.CouldNotOpenFolder": "Não foi possível abrir a pasta: {0}",
|
||||
"Status.CopiedToClipboard": "{0} copiado para a área de transferência.",
|
||||
"Status.RemovedFromLibrary": "“{0}” removido da biblioteca. Adicione novamente a pasta para o restaurar.",
|
||||
"Status.Running": "A executar {0}",
|
||||
"Status.Stopping": "A parar…",
|
||||
"Status.Idle": "Inativo",
|
||||
|
||||
"Clipboard.Path": "Caminho",
|
||||
"Clipboard.TitleId": "ID do título",
|
||||
|
||||
"Discord.Playing": "A jogar {0}",
|
||||
"Discord.Browsing": "A navegar na biblioteca",
|
||||
|
||||
"Dialog.ChooseGameFolder": "Escolha uma pasta com jogos",
|
||||
"Dialog.OpenExecutable": "Abrir um executável para iniciar",
|
||||
"Dialog.PsExecutables": "Executáveis PS",
|
||||
"Dialog.SaveLogFile": "Selecione onde guardar o ficheiro de registo",
|
||||
"Dialog.PlainTextFiles": "Ficheiros de Texto Simples",
|
||||
"Dialog.LogFiles": "Ficheiros de Registo",
|
||||
|
||||
"Options.About" : "Sobre",
|
||||
"About.Github.Label": "GitHub",
|
||||
"About.Github.Desc": "Código-fonte, problemas e desenvolvimento do projeto.",
|
||||
"About.Discord.Label": "Discord",
|
||||
"About.Discord.Desc": "Junte-se à comunidade, obtenha suporte e acompanhe o desenvolvimento.",
|
||||
"About.GithubButton": "Contribua no GitHub!",
|
||||
"About.DiscordButton": "Junte-se ao nosso Discord!"
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
{
|
||||
"_languageName": "Русский",
|
||||
|
||||
"Page.Library": "Библиотека",
|
||||
"Page.Options": "Настройки",
|
||||
"Page.GameCount.One": "1 игра",
|
||||
"Page.GameCount.Other": "Игр: {0}",
|
||||
|
||||
"Library.SearchWatermark": "Поиск…",
|
||||
"Library.AddFolder": "+ Добавить папку",
|
||||
"Library.Rescan": "⟳ Сканировать",
|
||||
"Library.OpenFile": "Открыть файл…",
|
||||
|
||||
"Library.Context.Launch": "Запустить",
|
||||
"Library.Context.OpenFolder": "Открыть папку с игрой",
|
||||
"Library.Context.CopyPath": "Скопировать путь",
|
||||
"Library.Context.CopyTitleId": "Скопировать ID игры",
|
||||
"Library.Context.Remove": "Удалить из библиотеки",
|
||||
|
||||
"Library.Empty.Title": "Ваша библиотека пуста",
|
||||
"Library.Empty.Hint": "Добавьте папку с играми, чтобы начать.",
|
||||
"Library.Empty.SearchTitle": "По вашему запросу ничего не найдено",
|
||||
"Library.Empty.SearchHint": "В библиотеке нет игр, соответствующих запросу «{0}».",
|
||||
"Library.Empty.AddFolder": "+ Добавить папку с играми",
|
||||
|
||||
"Library.Loading": "Загрузка библиотеки…",
|
||||
|
||||
"Options.General": "Основные",
|
||||
"Options.Section.Emulation": "ЭМУЛЯЦИЯ",
|
||||
"Options.Section.Logging": "ЛОГГИРОВАНИЕ",
|
||||
"Options.Section.Launcher": "ЛАУНЧЕР",
|
||||
|
||||
"Options.CpuEngine.Label": "Движок ЦП",
|
||||
"Options.CpuEngine.Desc": "Движок выполнения, используемый для запуска игрового кода.",
|
||||
"Options.CpuEngine.Native": "Нативный",
|
||||
|
||||
"Options.Strict.Label": "Строгое разрешение динамических библиотек",
|
||||
"Options.Strict.Desc": "Не запускать игру, если не удается найти или связать импортируемую функцию/переменную.",
|
||||
|
||||
"Options.LogLevel.Label": "Уровень логгирования",
|
||||
"Options.LogLevel.Desc": "Подробность вывода в консоль эмулятора.",
|
||||
"Options.LogLevel.Trace": "Trace",
|
||||
"Options.LogLevel.Debug": "Debug",
|
||||
"Options.LogLevel.Info": "Info",
|
||||
"Options.LogLevel.Warning": "Warning",
|
||||
"Options.LogLevel.Error": "Error",
|
||||
"Options.LogLevel.Critical": "Critical",
|
||||
|
||||
"Options.TraceImports.Label": "Лимит трассировки импортов",
|
||||
"Options.TraceImports.Desc": "Трассировать первые N импортов в каждом модуле (0 - выключено).",
|
||||
|
||||
"Options.LogToFile.Label": "Запись лога в файл",
|
||||
"Options.LogToFile.Desc": "Дублировать вывод эмулятора в файл лога.",
|
||||
|
||||
"Options.LogFilePath.Label": "Путь к файлу лога",
|
||||
"Options.LogFilePath.Default": "Пользовательский путь не задан: логи сохраняются в user/logs рядом с эмулятором.",
|
||||
"Options.LogFilePath.Select": "Выбрать…",
|
||||
|
||||
"Options.OverrideLogFile.Label": "Переопределить файл лога",
|
||||
"Options.OverrideLogFile.Desc": "Использовать указанный путь к файлу без добавления ID игры и метки времени.",
|
||||
|
||||
"Options.TitleMusic.Label": "Музыка игры",
|
||||
"Options.TitleMusic.Desc": "Зацикленно воспроизводить музыку предпросмотра выбранной игры в библиотеке.",
|
||||
|
||||
"Options.Discord.Label": "Статус Discord",
|
||||
"Options.Discord.Desc": "Показывать запущенную игру в профиле Discord.",
|
||||
|
||||
"Options.Language.Label": "Язык эмулятора",
|
||||
"Options.Language.Desc": "Язык интерфейса лаунчера. Изменение применяется сразу.",
|
||||
|
||||
"Common.On": "Включено",
|
||||
"Common.Off": "Выключено",
|
||||
|
||||
"Console.Title": "КОНСОЛЬ",
|
||||
"Console.SearchWatermark": "Поиск...",
|
||||
"Console.AutoScroll": "Авто-прокрутка",
|
||||
"Console.Split": "Разделить",
|
||||
"Console.Copy": "Скопировать",
|
||||
"Console.Clear": "Очистить",
|
||||
"Console.WindowTitle": "Консоль SharpEmu",
|
||||
|
||||
"Launch.NoGameSelected": "Ничего не выбрано",
|
||||
"Launch.NoGameHint": "Выберите игру из библиотеки или откройте eboot.bin напрямую.",
|
||||
"Launch.Idle": "Ожидание",
|
||||
"Launch.Console": "≡ Консоль",
|
||||
"Launch.Launch": "▶ Запустить",
|
||||
"Launch.Stop": "■ Остановить",
|
||||
"Launch.Running": "Запущено - {0}",
|
||||
"Launch.Stopping": "Остановка…",
|
||||
"Launch.Exited": "Завершено с кодом {0} ({1})",
|
||||
"Launch.ExeNotFound": "Исполняемый файл SharpEmu не найден. Скомпилируйте сначала проект SharpEmu.CLI (dotnet build).",
|
||||
"Launch.LogFile": "Лог: {0}",
|
||||
"Launch.Command": "$ SharpEmu {0}",
|
||||
"Launch.StartFailed": "Не удалось запустить эмулятор: {0}",
|
||||
"Launch.ProcessExited": "Процесс завершился с кодом {0} ({1}).",
|
||||
|
||||
"Exit.Ok": "OK",
|
||||
"Exit.InvalidArguments": "некорректные аргументы",
|
||||
"Exit.EbootNotFound": "eboot не найден",
|
||||
"Exit.RuntimeException": "ошибка выполнения",
|
||||
"Exit.EmulationError": "ошибка эмуляции",
|
||||
"Exit.Unknown": "неизвестная ошибка",
|
||||
|
||||
"Status.EmulatorLocating": "Эмулятор: поиск…",
|
||||
"Status.EmulatorPath": "Эмулятор: {0}",
|
||||
"Status.EmulatorNotFound": "Эмулятор: исполняемый файл SharpEmu не был найден - скомпилируйте сначала SharpEmu.CLI.",
|
||||
"Status.ScanningLibrary": "Сканирование библиотеки…",
|
||||
"Status.AddFolderPrompt": "Добавьте папку с играми, чтобы заполнить библиотеку.",
|
||||
"Status.LibraryScanned": "Сканирование библиотеки завершено: игр: {0}, папок: {1}.",
|
||||
"Status.CouldNotOpenFolder": "Не удалось открыть папку: {0}",
|
||||
"Status.CopiedToClipboard": "{0}: скопировано в буфер обмена.",
|
||||
"Status.RemovedFromLibrary": "Игра «{0}» удалена из библиотеки. Добавьте её папку заново, чтобы вернуть.",
|
||||
"Status.Running": "Запущено: {0}",
|
||||
"Status.Stopping": "Остановка…",
|
||||
"Status.Idle": "Ожидание",
|
||||
|
||||
"Clipboard.Path": "Путь",
|
||||
"Clipboard.TitleId": "ID игры",
|
||||
|
||||
"Discord.Playing": "Играет в {0}",
|
||||
"Discord.Browsing": "Просматривает библиотеку",
|
||||
|
||||
"Dialog.ChooseGameFolder": "Выберите папку, содержащую игры",
|
||||
"Dialog.OpenExecutable": "Открыть исполняемый файл для запуска",
|
||||
"Dialog.PsExecutables": "Исполняемые файлы PS",
|
||||
"Dialog.SaveLogFile": "Выберите, куда сохранить файл с логами",
|
||||
"Dialog.PlainTextFiles": "Текстовые файлы",
|
||||
"Dialog.LogFiles": "Логи"
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
{
|
||||
"_languageName": "Türkçe",
|
||||
|
||||
"Page.Library": "Kütüphane",
|
||||
"Page.Options": "Ayarlar",
|
||||
"Page.GameCount.One": "1 oyun",
|
||||
"Page.GameCount.Other": "{0} oyun",
|
||||
|
||||
"Library.SearchWatermark": "Kütüphanede ara…",
|
||||
"Library.AddFolder": "+ Klasör ekle",
|
||||
"Library.Rescan": "⟳ Yeniden tara",
|
||||
"Library.OpenFile": "Dosya aç…",
|
||||
|
||||
"Library.Context.Launch": "Başlat",
|
||||
"Library.Context.OpenFolder": "Oyun klasörünü aç",
|
||||
"Library.Context.CopyPath": "Yolu kopyala",
|
||||
"Library.Context.CopyTitleId": "Title ID'yi kopyala",
|
||||
"Library.Context.Remove": "Kütüphaneden kaldır",
|
||||
|
||||
"Library.Empty.Title": "Kütüphaneniz boş",
|
||||
"Library.Empty.Hint": "Başlamak için oyunlarınızı içeren bir klasör ekleyin.",
|
||||
"Library.Empty.SearchTitle": "Aramanızla eşleşen oyun yok",
|
||||
"Library.Empty.SearchHint": "Kütüphanede “{0}” ile eşleşen bir şey yok.",
|
||||
"Library.Empty.AddFolder": "+ Oyun klasörü ekle",
|
||||
|
||||
"Library.Loading": "Kütüphane yükleniyor…",
|
||||
|
||||
"Options.General": "Genel",
|
||||
"Options.Section.Emulation": "EMÜLASYON",
|
||||
"Options.Section.Logging": "GÜNLÜKLEME",
|
||||
"Options.Section.Launcher": "BAŞLATICI",
|
||||
|
||||
"Options.CpuEngine.Label": "CPU motoru",
|
||||
"Options.CpuEngine.Desc": "Oyun kodunu çalıştırmak için kullanılan yürütme motoru.",
|
||||
"Options.CpuEngine.Native": "Native",
|
||||
|
||||
"Options.Strict.Label": "Katı dynlib çözümü",
|
||||
"Options.Strict.Desc": "İçe aktarılan bir sembol çözümlenemediğinde başlatmayı başarısız kılar.",
|
||||
|
||||
"Options.LogLevel.Label": "Günlük seviyesi",
|
||||
"Options.LogLevel.Desc": "Emülatör konsol çıktısının ayrıntı düzeyi.",
|
||||
"Options.LogLevel.Trace": "Trace",
|
||||
"Options.LogLevel.Debug": "Debug",
|
||||
"Options.LogLevel.Info": "Info",
|
||||
"Options.LogLevel.Warning": "Warning",
|
||||
"Options.LogLevel.Error": "Error",
|
||||
"Options.LogLevel.Critical": "Critical",
|
||||
|
||||
"Options.TraceImports.Label": "Import izleme sınırı",
|
||||
"Options.TraceImports.Desc": "Modül başına ilk N import'u izle (0 = kapalı).",
|
||||
|
||||
"Options.LogToFile.Label": "Dosyaya günlükle",
|
||||
"Options.LogToFile.Desc": "Emülatör çıktısını bir günlük dosyasına yansıt.",
|
||||
|
||||
"Options.LogFilePath.Label": "Günlük dosyası yolu",
|
||||
"Options.LogFilePath.Default": "Özel yol yok — günlükler emülatörün yanındaki user/logs klasörüne yazılır.",
|
||||
"Options.LogFilePath.Select": "Seç…",
|
||||
|
||||
"Options.OverrideLogFile.Label": "Günlük dosyasının üzerine yaz",
|
||||
"Options.OverrideLogFile.Desc": "Title ID ve zaman damgası eklemek yerine tam dosya yolunu kullan.",
|
||||
|
||||
"Options.TitleMusic.Label": "Oyun müziği",
|
||||
"Options.TitleMusic.Desc": "Kütüphanede seçili oyunun önizleme müziğini döngüye al.",
|
||||
|
||||
"Options.Discord.Label": "Discord durumu",
|
||||
"Options.Discord.Desc": "Discord profilinde çalışan oyunu göster.",
|
||||
|
||||
"Options.Language.Label": "Emülatör dili",
|
||||
"Options.Language.Desc": "Başlatıcı genelinde kullanılan dil. Hemen uygulanır.",
|
||||
|
||||
"Common.On": "Açık",
|
||||
"Common.Off": "Kapalı",
|
||||
|
||||
"Console.Title": "KONSOL",
|
||||
"Console.SearchWatermark": "Ara...",
|
||||
"Console.AutoScroll": "Otomatik kaydır",
|
||||
"Console.Split": "Ayır",
|
||||
"Console.Copy": "Kopyala",
|
||||
"Console.Clear": "Temizle",
|
||||
"Console.WindowTitle": "SharpEmu Konsol",
|
||||
|
||||
"Launch.NoGameSelected": "Oyun seçilmedi",
|
||||
"Launch.NoGameHint": "Kütüphaneden bir oyun seçin veya doğrudan bir eboot.bin açın.",
|
||||
"Launch.Idle": "Boşta",
|
||||
"Launch.Console": "≡ Konsol",
|
||||
"Launch.Launch": "▶ Başlat",
|
||||
"Launch.Stop": "■ Durdur",
|
||||
"Launch.Running": "Çalışıyor — {0}",
|
||||
"Launch.Stopping": "Durduruluyor…",
|
||||
"Launch.Exited": "Çıkış kodu {0} ({1})",
|
||||
"Launch.ExeNotFound": "SharpEmu çalıştırılabilir dosyası bulunamadı. Önce SharpEmu.CLI projesini derleyin (dotnet build).",
|
||||
"Launch.LogFile": "Günlük dosyası: {0}",
|
||||
"Launch.Command": "$ SharpEmu {0}",
|
||||
"Launch.StartFailed": "Emülatör başlatılamadı: {0}",
|
||||
"Launch.ProcessExited": "İşlem {0} kodla sonlandı ({1}).",
|
||||
|
||||
"Exit.Ok": "Tamam",
|
||||
"Exit.InvalidArguments": "geçersiz argümanlar",
|
||||
"Exit.EbootNotFound": "eboot bulunamadı",
|
||||
"Exit.RuntimeException": "çalışma zamanı hatası",
|
||||
"Exit.EmulationError": "emülasyon hatası",
|
||||
"Exit.Unknown": "bilinmiyor",
|
||||
|
||||
"Status.EmulatorLocating": "Emülatör: bulunuyor…",
|
||||
"Status.EmulatorPath": "Emülatör: {0}",
|
||||
"Status.EmulatorNotFound": "Emülatör: SharpEmu çalıştırılabilir dosyası bulunamadı — önce SharpEmu.CLI'yi derleyin.",
|
||||
"Status.ScanningLibrary": "Kütüphane taranıyor…",
|
||||
"Status.AddFolderPrompt": "Kütüphaneyi doldurmak için bir oyun klasörü ekleyin.",
|
||||
"Status.LibraryScanned": "Kütüphane tarandı: {1} klasörde {0} oyun.",
|
||||
"Status.CouldNotOpenFolder": "Klasör açılamadı: {0}",
|
||||
"Status.CopiedToClipboard": "{0} panoya kopyalandı.",
|
||||
"Status.RemovedFromLibrary": "“{0}” kütüphaneden kaldırıldı. Geri getirmek için klasörünü yeniden ekleyin.",
|
||||
"Status.Running": "{0} çalışıyor",
|
||||
"Status.Stopping": "Durduruluyor…",
|
||||
"Status.Idle": "Boşta",
|
||||
|
||||
"Clipboard.Path": "Yol",
|
||||
"Clipboard.TitleId": "Title ID",
|
||||
|
||||
"Discord.Playing": "{0} oynuyor",
|
||||
"Discord.Browsing": "Kütüphaneye göz atıyor",
|
||||
|
||||
"Dialog.ChooseGameFolder": "Oyunlarınızı içeren bir klasör seçin",
|
||||
"Dialog.OpenExecutable": "Başlatılacak bir çalıştırılabilir dosya aç",
|
||||
"Dialog.PsExecutables": "PS çalıştırılabilirleri",
|
||||
"Dialog.SaveLogFile": "Günlük dosyasının kaydedileceği yeri seçin",
|
||||
"Dialog.PlainTextFiles": "Düz Metin Dosyaları",
|
||||
"Dialog.LogFiles": "Günlük Dosyaları"
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Text.Json;
|
||||
|
||||
namespace SharpEmu.GUI;
|
||||
|
||||
/// <summary>
|
||||
/// Loads UI strings for the launcher. Every language ships embedded in the
|
||||
/// assembly (see SharpEmu.GUI.csproj) so a release build is fully
|
||||
/// self-contained; an optional Languages/<code>.json file next to the
|
||||
/// executable overrides the embedded copy for that code, so a translation
|
||||
/// fix or a brand-new language never needs a rebuild.
|
||||
/// </summary>
|
||||
public sealed class Localization
|
||||
{
|
||||
public static Localization Instance { get; } = new();
|
||||
|
||||
public sealed record LanguageInfo(string Code, string NativeName);
|
||||
|
||||
private const string EmbeddedResourcePrefix = "Languages.";
|
||||
private const string EmbeddedResourceSuffix = ".json";
|
||||
|
||||
private Dictionary<string, string> _strings = new();
|
||||
private Dictionary<string, string> _fallbackStrings = new();
|
||||
|
||||
|
||||
private Localization()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Directory holding optional *.json language overrides, next to the executable.</summary>
|
||||
public static string LanguagesDirectory => Path.Combine(AppContext.BaseDirectory, "Languages");
|
||||
|
||||
public string CurrentCode { get; private set; } = "en";
|
||||
|
||||
public string Get(string key)
|
||||
{
|
||||
if (_strings.TryGetValue(key, out var value))
|
||||
return value;
|
||||
|
||||
if (_fallbackStrings.TryGetValue(key, out var fallbackValue))
|
||||
return fallbackValue;
|
||||
|
||||
return key;
|
||||
}
|
||||
|
||||
public string Format(string key, params object?[] args) => string.Format(Get(key), args);
|
||||
|
||||
/// <summary>
|
||||
/// Languages available either embedded in the binary or as a loose
|
||||
/// override file, sorted by code. A loose file's declared name wins when
|
||||
/// the same code exists in both places.
|
||||
/// </summary>
|
||||
public List<LanguageInfo> DiscoverLanguages()
|
||||
{
|
||||
var languages = new Dictionary<string, LanguageInfo>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
foreach (var code in EmbeddedLanguageCodes())
|
||||
{
|
||||
using var stream = OpenEmbeddedLanguageStream(code);
|
||||
if (stream is not null)
|
||||
{
|
||||
languages[code] = new LanguageInfo(code, ReadLanguageName(stream) ?? code);
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
foreach (var file in Directory.EnumerateFiles(LanguagesDirectory, "*.json"))
|
||||
{
|
||||
var code = Path.GetFileNameWithoutExtension(file);
|
||||
using var stream = File.OpenRead(file);
|
||||
languages[code] = new LanguageInfo(code, ReadLanguageName(stream) ?? code);
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// No loose Languages directory: the embedded languages still stand.
|
||||
}
|
||||
|
||||
var result = languages.Values.ToList();
|
||||
result.Sort((a, b) => string.CompareOrdinal(a.Code, b.Code));
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Loads a language by code (e.g. "en"): a loose override file first, then the embedded copy.</summary>
|
||||
/// english is the fallback language
|
||||
public void Load(string code)
|
||||
{
|
||||
if (_fallbackStrings.Count == 0 && !string.Equals(code, "en", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (!TryLoadLooseFile("en", out var fallback) && !TryLoadEmbedded("en", out fallback))
|
||||
{
|
||||
fallback = new Dictionary<string, string>();
|
||||
}
|
||||
_fallbackStrings = fallback;
|
||||
}
|
||||
else if (string.Equals(code, "en", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (TryLoadLooseFile("en", out var enDict) || TryLoadEmbedded("en", out enDict))
|
||||
{
|
||||
_strings = enDict;
|
||||
_fallbackStrings = enDict;
|
||||
}
|
||||
else
|
||||
{
|
||||
_strings = new Dictionary<string, string>();
|
||||
_fallbackStrings = new Dictionary<string, string>();
|
||||
}
|
||||
CurrentCode = "en";
|
||||
return;
|
||||
}
|
||||
|
||||
// Load the requested language
|
||||
if (TryLoadLooseFile(code, out var loaded) || TryLoadEmbedded(code, out loaded))
|
||||
{
|
||||
_strings = loaded;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_fallbackStrings.Count > 0)
|
||||
_strings = new Dictionary<string, string>(_fallbackStrings);
|
||||
else
|
||||
_strings = new Dictionary<string, string>();
|
||||
}
|
||||
CurrentCode = code;
|
||||
}
|
||||
|
||||
private static IEnumerable<string> EmbeddedLanguageCodes()
|
||||
{
|
||||
foreach (var name in typeof(Localization).Assembly.GetManifestResourceNames())
|
||||
{
|
||||
if (name.StartsWith(EmbeddedResourcePrefix, StringComparison.Ordinal) &&
|
||||
name.EndsWith(EmbeddedResourceSuffix, StringComparison.Ordinal))
|
||||
{
|
||||
yield return name[EmbeddedResourcePrefix.Length..^EmbeddedResourceSuffix.Length];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream? OpenEmbeddedLanguageStream(string code) =>
|
||||
typeof(Localization).Assembly.GetManifestResourceStream($"{EmbeddedResourcePrefix}{code}{EmbeddedResourceSuffix}");
|
||||
|
||||
private static string? ReadLanguageName(Stream stream)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(stream);
|
||||
if (document.RootElement.TryGetProperty("_languageName", out var name) &&
|
||||
name.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
return name.GetString();
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Malformed file: fall back to the code as its own display name.
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private bool TryLoadLooseFile(string code)
|
||||
{
|
||||
try
|
||||
{
|
||||
var path = Path.Combine(LanguagesDirectory, $"{code}.json");
|
||||
return File.Exists(path) && TryLoad(code, File.ReadAllText(path));
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryLoadEmbedded(string code)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var stream = OpenEmbeddedLanguageStream(code);
|
||||
if (stream is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
using var reader = new StreamReader(stream);
|
||||
return TryLoad(code, reader.ReadToEnd());
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryLoadLooseFile(string code, out Dictionary<string, string> result)
|
||||
{
|
||||
result = new Dictionary<string, string>();
|
||||
try
|
||||
{
|
||||
var path = Path.Combine(LanguagesDirectory, $"{code}.json");
|
||||
if (!File.Exists(path))
|
||||
return false;
|
||||
|
||||
var json = File.ReadAllText(path);
|
||||
return TryLoad(json, out result);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryLoadEmbedded(string code, out Dictionary<string, string> result)
|
||||
{
|
||||
result = new Dictionary<string, string>();
|
||||
try
|
||||
{
|
||||
using var stream = OpenEmbeddedLanguageStream(code);
|
||||
if (stream is null)
|
||||
return false;
|
||||
|
||||
using var reader = new StreamReader(stream);
|
||||
var json = reader.ReadToEnd();
|
||||
return TryLoad(json, out result);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryLoad(string json, out Dictionary<string, string> result)
|
||||
{
|
||||
var loaded = JsonSerializer.Deserialize<Dictionary<string, string>>(json);
|
||||
if (loaded is null)
|
||||
{
|
||||
result = new Dictionary<string, string>();
|
||||
return false;
|
||||
}
|
||||
|
||||
result = loaded;
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryLoad(string code, string json)
|
||||
{
|
||||
if (TryLoad(json, out var dict))
|
||||
{
|
||||
_strings = dict;
|
||||
CurrentCode = code;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+446
-157
@@ -9,6 +9,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
Title="SharpEmu"
|
||||
Width="1280" Height="820"
|
||||
MinWidth="980" MinHeight="640"
|
||||
WindowState="Maximized"
|
||||
WindowStartupLocation="CenterScreen"
|
||||
Background="{StaticResource BgBrush}"
|
||||
ExtendClientAreaToDecorationsHint="True"
|
||||
@@ -17,7 +18,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
Icon="avares://SharpEmu.GUI/Assets/SharpEmu.ico"
|
||||
KeyDown="OnKeyDown">
|
||||
|
||||
<Grid RowDefinitions="44,*,32">
|
||||
<Grid RowDefinitions="Auto,*,Auto">
|
||||
|
||||
<!-- Selected-game backdrop: key art behind the main content, dimmed by
|
||||
a scrim so tiles and text stay readable. Fades on selection. -->
|
||||
@@ -41,8 +42,9 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
</Border>
|
||||
</Panel>
|
||||
|
||||
<!-- Title bar -->
|
||||
<Grid x:Name="TitleBar" Grid.Row="0" Background="{StaticResource ChromeBrush}">
|
||||
<!-- Title bar; hidden in fullscreen (F11) along with the status bar, so
|
||||
the game gets the whole screen. -->
|
||||
<Grid x:Name="TitleBar" Grid.Row="0" Height="44" Background="{StaticResource ChromeBrush}">
|
||||
<StackPanel Orientation="Horizontal" Spacing="10" Margin="16,0" VerticalAlignment="Center">
|
||||
<Image Source="avares://SharpEmu.GUI/Assets/SharpEmu.ico" Width="20" Height="20"
|
||||
RenderOptions.BitmapInterpolationMode="HighQuality" />
|
||||
@@ -54,106 +56,421 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
</Grid>
|
||||
|
||||
<!-- Main content -->
|
||||
<Grid Grid.Row="1" Margin="18,14,18,14" RowDefinitions="Auto,*,Auto,Auto">
|
||||
<Grid Grid.Row="1" Margin="32,24,32,20" RowDefinitions="Auto,*,Auto,Auto">
|
||||
|
||||
<!-- Library toolbar -->
|
||||
<Grid Grid.Row="0" ColumnDefinitions="Auto,Auto,*,Auto,Auto,Auto,Auto" Margin="6,0,6,12">
|
||||
<TextBlock Grid.Column="0" Text="Library" FontSize="22" FontWeight="Bold" VerticalAlignment="Center" />
|
||||
<Border Grid.Column="1" Classes="pill" Margin="12,2,0,0" VerticalAlignment="Center">
|
||||
<TextBlock x:Name="GameCountText" Text="0 games" FontSize="11" Foreground="{StaticResource MutedBrush}" />
|
||||
</Border>
|
||||
<TextBox Grid.Column="3" x:Name="SearchBox" Watermark="Search library…" Width="280"
|
||||
VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
<Button Grid.Column="4" x:Name="AddFolderButton" Classes="ghost" Content="+ Add folder"
|
||||
VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<Button Grid.Column="5" x:Name="RescanButton" Classes="ghost" Content="⟳ Rescan"
|
||||
VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<Button Grid.Column="6" x:Name="OpenFileButton" Classes="ghost" Content="Open file…"
|
||||
VerticalAlignment="Center" />
|
||||
<!-- Library / Options page switcher, with the library toolbar sharing
|
||||
the same row on the right. Plain buttons (not TabItem) so there is
|
||||
no underline; LB/RB hint chips flank the pair and the gamepad's
|
||||
shoulder buttons actually switch pages from anywhere. -->
|
||||
<Grid Grid.Row="0" ColumnDefinitions="Auto,*,Auto" Margin="0,0,0,20">
|
||||
<StackPanel Grid.Column="0" Orientation="Horizontal" Spacing="14" VerticalAlignment="Center">
|
||||
<Border Classes="padHint" VerticalAlignment="Center">
|
||||
<TextBlock Text="LB" FontSize="11" FontWeight="Bold" Foreground="{StaticResource MutedBrush}" />
|
||||
</Border>
|
||||
<Button x:Name="LibraryTabButton" Classes="segment active" Content="Library" />
|
||||
<Button x:Name="OptionsTabButton" Classes="segment" Content="Options" />
|
||||
<Border Classes="padHint" VerticalAlignment="Center">
|
||||
<TextBlock Text="RB" FontSize="11" FontWeight="Bold" Foreground="{StaticResource MutedBrush}" />
|
||||
</Border>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Column="2" x:Name="LibraryToolbar" Orientation="Horizontal" Spacing="8"
|
||||
VerticalAlignment="Center">
|
||||
<TextBox x:Name="SearchBox" Watermark="Search library…" Width="240" VerticalAlignment="Center" />
|
||||
<Button x:Name="AddFolderButton" Classes="ghost" Content="+ Add folder" VerticalAlignment="Center" />
|
||||
<Button x:Name="RescanButton" Classes="ghost" Content="⟳ Rescan" VerticalAlignment="Center" />
|
||||
<Button x:Name="OpenFileButton" Classes="ghost" Content="Open file…" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
<!-- Cover-art grid -->
|
||||
<Panel Grid.Row="1">
|
||||
<ListBox x:Name="GameList" Classes="tileGrid" Background="Transparent"
|
||||
SelectionMode="Single" Padding="0">
|
||||
<ListBox.ContextMenu>
|
||||
<ContextMenu x:Name="GameContextMenu" Placement="Pointer">
|
||||
<MenuItem x:Name="CtxLaunch" Header="Launch" FontWeight="SemiBold">
|
||||
<MenuItem.Icon>
|
||||
<TextBlock Text="▶" FontSize="11" Foreground="{StaticResource AccentHoverBrush}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</MenuItem.Icon>
|
||||
</MenuItem>
|
||||
<MenuItem x:Name="CtxOpenFolder" Header="Open game folder">
|
||||
<MenuItem.Icon>
|
||||
<TextBlock Text="📂" FontSize="12" HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</MenuItem.Icon>
|
||||
</MenuItem>
|
||||
<Separator />
|
||||
<MenuItem x:Name="CtxCopyPath" Header="Copy path">
|
||||
<MenuItem.Icon>
|
||||
<TextBlock Text="⧉" FontSize="13" Foreground="{StaticResource MutedBrush}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</MenuItem.Icon>
|
||||
</MenuItem>
|
||||
<MenuItem x:Name="CtxCopyTitleId" Header="Copy title ID">
|
||||
<MenuItem.Icon>
|
||||
<TextBlock Text="⧉" FontSize="13" Foreground="{StaticResource MutedBrush}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</MenuItem.Icon>
|
||||
</MenuItem>
|
||||
<Separator />
|
||||
<MenuItem x:Name="CtxRemove" Header="Remove from library"
|
||||
Foreground="{StaticResource DangerHoverBrush}">
|
||||
<MenuItem.Icon>
|
||||
<TextBlock Text="✕" FontSize="12" Foreground="{StaticResource DangerHoverBrush}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</MenuItem.Icon>
|
||||
</MenuItem>
|
||||
</ContextMenu>
|
||||
</ListBox.ContextMenu>
|
||||
<ListBox.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel />
|
||||
</ItemsPanelTemplate>
|
||||
</ListBox.ItemsPanel>
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<StackPanel Width="128" Height="186" Spacing="7">
|
||||
<Border Classes="coverShadow" Width="128" Height="128">
|
||||
<Border Classes="coverClip">
|
||||
<Panel>
|
||||
<Border Background="{Binding PlaceholderBrush}" IsVisible="{Binding !HasCover}">
|
||||
<TextBlock Text="{Binding Initials}" FontSize="36" FontWeight="Bold"
|
||||
Foreground="#E8ECF4" Opacity="0.85"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<Image Source="{Binding Cover}" Stretch="UniformToFill" IsVisible="{Binding HasCover}" />
|
||||
</Panel>
|
||||
</Border>
|
||||
</Border>
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="{Binding Name}" FontSize="13" FontWeight="SemiBold"
|
||||
TextWrapping="Wrap" MaxLines="2" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding Detail}" FontSize="11" Foreground="{StaticResource MutedBrush}"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
|
||||
<!-- Empty state -->
|
||||
<StackPanel x:Name="EmptyState" Spacing="10" HorizontalAlignment="Center" VerticalAlignment="Center"
|
||||
IsVisible="False">
|
||||
<TextBlock Text="🎮" FontSize="44" HorizontalAlignment="Center" Opacity="0.7" />
|
||||
<TextBlock x:Name="EmptyStateTitle" Text="Your library is empty" FontSize="18" FontWeight="SemiBold"
|
||||
HorizontalAlignment="Center" />
|
||||
<TextBlock x:Name="EmptyStateHint" Text="Add a folder containing your games to get started."
|
||||
FontSize="13" Foreground="{StaticResource MutedBrush}" HorizontalAlignment="Center" />
|
||||
<Button x:Name="EmptyAddFolderButton" Classes="accent" Content="+ Add game folder"
|
||||
HorizontalAlignment="Center" Margin="0,8,0,0" />
|
||||
</StackPanel>
|
||||
<!-- Library page. The tile row gets extra top margin so it sits
|
||||
closer to eye level (PS5 home-screen style) instead of hugging
|
||||
the Library/Options switcher above it. -->
|
||||
<Panel x:Name="LibraryPage" Margin="0,64,0,0">
|
||||
<ListBox x:Name="GameList" Classes="tileGrid" Background="Transparent"
|
||||
SelectionMode="Single" Padding="0">
|
||||
<ListBox.ContextMenu>
|
||||
<ContextMenu x:Name="GameContextMenu" Placement="Pointer">
|
||||
<MenuItem x:Name="CtxLaunch" Header="Launch" FontWeight="SemiBold">
|
||||
<MenuItem.Icon>
|
||||
<TextBlock Text="▶" FontSize="11" Foreground="{StaticResource AccentHoverBrush}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</MenuItem.Icon>
|
||||
</MenuItem>
|
||||
<MenuItem x:Name="CtxOpenFolder" Header="Open game folder">
|
||||
<MenuItem.Icon>
|
||||
<TextBlock Text="📂" FontSize="12" HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</MenuItem.Icon>
|
||||
</MenuItem>
|
||||
<Separator />
|
||||
<MenuItem x:Name="CtxCopyPath" Header="Copy path">
|
||||
<MenuItem.Icon>
|
||||
<TextBlock Text="⧉" FontSize="13" Foreground="{StaticResource MutedBrush}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</MenuItem.Icon>
|
||||
</MenuItem>
|
||||
<MenuItem x:Name="CtxCopyTitleId" Header="Copy title ID">
|
||||
<MenuItem.Icon>
|
||||
<TextBlock Text="⧉" FontSize="13" Foreground="{StaticResource MutedBrush}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</MenuItem.Icon>
|
||||
</MenuItem>
|
||||
<Separator />
|
||||
<MenuItem x:Name="CtxRemove" Header="Remove from library"
|
||||
Foreground="{StaticResource DangerHoverBrush}">
|
||||
<MenuItem.Icon>
|
||||
<TextBlock Text="✕" FontSize="12" Foreground="{StaticResource DangerHoverBrush}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</MenuItem.Icon>
|
||||
</MenuItem>
|
||||
</ContextMenu>
|
||||
</ListBox.ContextMenu>
|
||||
<ListBox.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel />
|
||||
</ItemsPanelTemplate>
|
||||
</ListBox.ItemsPanel>
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<StackPanel Width="128" Height="172" Spacing="7">
|
||||
<Border Classes="coverShadow" Width="128" Height="128">
|
||||
<Border Classes="coverClip">
|
||||
<Panel>
|
||||
<Border Background="{Binding PlaceholderBrush}" IsVisible="{Binding !HasCover}">
|
||||
<TextBlock Text="{Binding Initials}" FontSize="36" FontWeight="Bold"
|
||||
Foreground="#E8ECF4" Opacity="0.85"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<Image Source="{Binding Cover}" Stretch="UniformToFill" IsVisible="{Binding HasCover}" />
|
||||
</Panel>
|
||||
</Border>
|
||||
</Border>
|
||||
<TextBlock Text="{Binding Name}" FontSize="13" FontWeight="SemiBold"
|
||||
TextWrapping="Wrap" MaxLines="2" TextTrimming="CharacterEllipsis"
|
||||
TextAlignment="Center" HorizontalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
|
||||
<!-- Empty state -->
|
||||
<StackPanel x:Name="EmptyState" Spacing="10" HorizontalAlignment="Center" VerticalAlignment="Center"
|
||||
IsVisible="False">
|
||||
<TextBlock Text="🎮" FontSize="44" HorizontalAlignment="Center" Opacity="0.7" />
|
||||
<TextBlock x:Name="EmptyStateTitle" Text="Your library is empty" FontSize="18" FontWeight="SemiBold"
|
||||
HorizontalAlignment="Center" />
|
||||
<TextBlock x:Name="EmptyStateHint" Text="Add a folder containing your games to get started."
|
||||
FontSize="13" Foreground="{StaticResource MutedBrush}" HorizontalAlignment="Center" />
|
||||
<Button x:Name="EmptyAddFolderButton" Classes="accent" Content="+ Add game folder"
|
||||
HorizontalAlignment="Center" Margin="0,8,0,0" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Loading state: covers the grid while a scan (initial load,
|
||||
rescan, or a just-added folder) is in flight, so the screen
|
||||
never looks blank mid-scan. -->
|
||||
<StackPanel x:Name="LoadingState" Spacing="14" HorizontalAlignment="Center" VerticalAlignment="Center"
|
||||
IsVisible="False">
|
||||
<ProgressBar IsIndeterminate="True" Width="180" Height="3" />
|
||||
<TextBlock x:Name="LoadingStateText" Text="Loading library…" FontSize="13"
|
||||
Foreground="{StaticResource MutedBrush}" HorizontalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</Panel>
|
||||
|
||||
<!-- Options page: sub-tabs so future categories (Graphics, …) slot
|
||||
in next to General. Card-grouped sections match the visual
|
||||
language used by the console panel and launch bar below. -->
|
||||
<Grid x:Name="OptionsPage" IsVisible="False">
|
||||
<TabControl>
|
||||
<TabItem x:Name="GeneralTabItem" Header="General" FontSize="15">
|
||||
<ScrollViewer>
|
||||
<StackPanel Margin="0,14,0,16" Spacing="16" MaxWidth="1280" HorizontalAlignment="Left">
|
||||
|
||||
<Border Classes="card">
|
||||
<StackPanel Spacing="14">
|
||||
<TextBlock x:Name="EmulationSectionTitle" Classes="sectionTitle" Text="EMULATION" />
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock x:Name="CpuEngineLabel" Text="CPU engine" FontSize="13" />
|
||||
<TextBlock x:Name="CpuEngineDesc" Text="Execution engine used to run game code."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ComboBox Grid.Column="1" x:Name="CpuEngineBox" Width="160" SelectedIndex="0"
|
||||
VerticalAlignment="Center" CornerRadius="8">
|
||||
<ComboBoxItem x:Name="CpuEngineNativeItem" Content="Native" />
|
||||
</ComboBox>
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock x:Name="StrictLabel" Text="Strict dynlib resolution" FontSize="13" />
|
||||
<TextBlock x:Name="StrictDesc" Text="Fail the launch when an imported symbol cannot be resolved."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ToggleSwitch Grid.Column="1" x:Name="StrictToggle" OnContent="On" OffContent="Off"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<Border Classes="card">
|
||||
<StackPanel Spacing="14">
|
||||
<TextBlock x:Name="LoggingSectionTitle" Classes="sectionTitle" Text="LOGGING" />
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock x:Name="LogLevelLabel" Text="Log level" FontSize="13" />
|
||||
<TextBlock x:Name="LogLevelDesc" Text="Verbosity of the emulator console output."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ComboBox Grid.Column="1" x:Name="LogLevelBox" Width="160" SelectedIndex="2"
|
||||
VerticalAlignment="Center" CornerRadius="8">
|
||||
<ComboBoxItem x:Name="LogLevelTraceItem" Content="Trace" />
|
||||
<ComboBoxItem x:Name="LogLevelDebugItem" Content="Debug" />
|
||||
<ComboBoxItem x:Name="LogLevelInfoItem" Content="Info" />
|
||||
<ComboBoxItem x:Name="LogLevelWarningItem" Content="Warning" />
|
||||
<ComboBoxItem x:Name="LogLevelErrorItem" Content="Error" />
|
||||
<ComboBoxItem x:Name="LogLevelCriticalItem" Content="Critical" />
|
||||
</ComboBox>
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock x:Name="TraceImportsLabel" Text="Import trace limit" FontSize="13" />
|
||||
<TextBlock x:Name="TraceImportsDesc" Text="Trace the first N imports per module (0 = off)."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<NumericUpDown Grid.Column="1" x:Name="TraceImportsBox" Width="160" Minimum="0"
|
||||
Maximum="4096" Increment="16" Value="0" FormatString="0"
|
||||
VerticalAlignment="Center" CornerRadius="8" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock x:Name="LogToFileLabel" Text="Log to file" FontSize="13" />
|
||||
<TextBlock x:Name="LogToFileDesc" Text="Mirror emulator output to a log file."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ToggleSwitch Grid.Column="1" x:Name="LogToFileToggle" OnContent="On" OffContent="Off"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock x:Name="LogFilePathLabel" Text="Log file path" FontSize="13" />
|
||||
<TextBlock x:Name="LogFilePathText" Text="No custom path"
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<Button Grid.Column="1" x:Name="SelectLogFilePathButton" Classes="ghost" Content="Select…"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock x:Name="OverrideLogFileLabel" Text="Override log file" FontSize="13" />
|
||||
<TextBlock x:Name="OverrideLogFileDesc"
|
||||
Text="Use the exact file path instead of appending title ID and timestamp."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ToggleSwitch Grid.Column="1" x:Name="OverrideLogFileToggle" OnContent="On" OffContent="Off"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<Border Classes="card">
|
||||
<StackPanel Spacing="14">
|
||||
<TextBlock x:Name="LauncherSectionTitle" Classes="sectionTitle" Text="LAUNCHER" />
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock x:Name="LanguageLabel" Text="Emulator language" FontSize="13" />
|
||||
<TextBlock x:Name="LanguageDesc"
|
||||
Text="Language used throughout the launcher. Applies immediately."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ComboBox Grid.Column="1" x:Name="LanguageBox" Width="160"
|
||||
VerticalAlignment="Center" CornerRadius="8"
|
||||
DisplayMemberBinding="{Binding NativeName}" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock x:Name="TitleMusicLabel" Text="Title music" FontSize="13" />
|
||||
<TextBlock x:Name="TitleMusicDesc" Text="Loop the selected game's preview music in the library."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ToggleSwitch Grid.Column="1" x:Name="TitleMusicToggle" OnContent="On" OffContent="Off"
|
||||
IsChecked="True" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock x:Name="DiscordLabel" Text="Discord presence" FontSize="13" />
|
||||
<TextBlock x:Name="DiscordDesc" Text="Show the running game on your Discord profile."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ToggleSwitch Grid.Column="1" x:Name="DiscordToggle" OnContent="On" OffContent="Off"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Border Classes="card">
|
||||
<StackPanel Spacing="14">
|
||||
<TextBlock x:Name="AboutSectionTitle"
|
||||
Classes="sectionTitle"
|
||||
Text="ABOUT" />
|
||||
|
||||
<!--Github-->
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel Grid.Column="0"
|
||||
Orientation="Horizontal"
|
||||
Spacing="8"
|
||||
VerticalAlignment="Center">
|
||||
<Image Source="avares://SharpEmu.GUI/Assets/github.png"
|
||||
Width="20"
|
||||
Height="20"
|
||||
VerticalAlignment="Center" />
|
||||
<StackPanel VerticalAlignment="Center"
|
||||
Spacing="2">
|
||||
<TextBlock x:Name="GithubLabel"
|
||||
Text="GitHub"
|
||||
FontSize="13" />
|
||||
<TextBlock x:Name="GithubDesc"
|
||||
Text="Source code, issues and project development."
|
||||
FontSize="11"
|
||||
Foreground="{StaticResource MutedBrush}"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
<Button Grid.Column="1"
|
||||
x:Name="GithubButton"
|
||||
Classes="ghost"
|
||||
Content="Open"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<!--Discord-->
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel Grid.Column="0"
|
||||
Orientation="Horizontal"
|
||||
Spacing="8"
|
||||
VerticalAlignment="Center">
|
||||
<Image Source="avares://SharpEmu.GUI/Assets/discord.png"
|
||||
Width="20"
|
||||
Height="20"
|
||||
VerticalAlignment="Center" />
|
||||
<StackPanel VerticalAlignment="Center"
|
||||
Spacing="2">
|
||||
<TextBlock x:Name="DiscordServerLabel"
|
||||
Text="Discord"
|
||||
FontSize="13" />
|
||||
<TextBlock x:Name="DiscordServerDesc"
|
||||
Text="Join the community, get support and follow development."
|
||||
FontSize="11"
|
||||
Foreground="{StaticResource MutedBrush}"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
<Button Grid.Column="1"
|
||||
x:Name="DiscordButton"
|
||||
Classes="ghost"
|
||||
Content="Join"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</TabItem>
|
||||
<TabItem x:Name="EnvTabItem" Header="Environment" FontSize="15">
|
||||
<ScrollViewer>
|
||||
<StackPanel Margin="0,14,0,16" Spacing="16" MaxWidth="1280" HorizontalAlignment="Left">
|
||||
|
||||
<Border Classes="card">
|
||||
<StackPanel Spacing="14">
|
||||
<TextBlock x:Name="EnvSectionTitle" Classes="sectionTitle" Text="ENVIRONMENT VARIABLES" />
|
||||
<TextBlock x:Name="EnvDesc"
|
||||
Text="Switches passed to the emulator as environment variables at launch."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock Text="SHARPEMU_BTHID_UNAVAILABLE" FontSize="13" FontFamily="Consolas,monospace" />
|
||||
<TextBlock x:Name="EnvBthidDesc"
|
||||
Text="Report Bluetooth HID as unavailable for titles whose wheel/FFB middleware polls forever. Leave off normally. Some titles freeze when init fails."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ToggleSwitch Grid.Column="1" x:Name="EnvBthidToggle" OnContent="On" OffContent="Off"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock Text="SHARPEMU_DISABLE_IMPORT_LOOP_GUARD" FontSize="13" FontFamily="Consolas,monospace" />
|
||||
<TextBlock x:Name="EnvLoopGuardDesc"
|
||||
Text="Do not force quit titles that repeat the same call for too long. Try this when a game exits on its own while loading."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ToggleSwitch Grid.Column="1" x:Name="EnvLoopGuardToggle" OnContent="On" OffContent="Off"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock Text="SHARPEMU_VK_VALIDATION" FontSize="13" FontFamily="Consolas,monospace" />
|
||||
<TextBlock x:Name="EnvVkValidationDesc"
|
||||
Text="Enable Vulkan validation layers for GPU debugging. Slow. Requires the Vulkan SDK to be installed."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ToggleSwitch Grid.Column="1" x:Name="EnvVkValidationToggle" OnContent="On" OffContent="Off"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock Text="SHARPEMU_DUMP_SPIRV" FontSize="13" FontFamily="Consolas,monospace" />
|
||||
<TextBlock x:Name="EnvDumpSpirvDesc"
|
||||
Text="Dump AGC shaders and their SPIR-V translations to the shader-dumps folder. Use when reporting shader or rendering bugs."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ToggleSwitch Grid.Column="1" x:Name="EnvDumpSpirvToggle" OnContent="On" OffContent="Off"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock Text="SHARPEMU_LOG_DIRECT_MEMORY" FontSize="13" FontFamily="Consolas,monospace" />
|
||||
<TextBlock x:Name="EnvLogDirectMemoryDesc"
|
||||
Text="Log direct memory allocations and failures to the console. Use when a game aborts or exits during boot."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ToggleSwitch Grid.Column="1" x:Name="EnvLogDirectMemoryToggle" OnContent="On" OffContent="Off"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock Text="SHARPEMU_LOG_NP" FontSize="13" FontFamily="Consolas,monospace" />
|
||||
<TextBlock x:Name="EnvLogNpDesc"
|
||||
Text="Log NP (PlayStation Network) library calls to the console."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ToggleSwitch Grid.Column="1" x:Name="EnvLogNpToggle" OnContent="On" OffContent="Off"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</TabItem>
|
||||
</TabControl>
|
||||
</Grid>
|
||||
</Panel>
|
||||
|
||||
<!-- Console (collapsible) -->
|
||||
@@ -161,7 +478,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
Margin="0,12,0,0" IsVisible="False">
|
||||
<Grid RowDefinitions="Auto,*">
|
||||
<Grid Grid.Row="0" ColumnDefinitions="*,Auto,Auto,Auto,Auto,Auto" Margin="16,12,16,8">
|
||||
<TextBlock Classes="sectionTitle" Text="CONSOLE" VerticalAlignment="Center" />
|
||||
<TextBlock x:Name="ConsoleSectionTitle" Classes="sectionTitle" Text="CONSOLE" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Column="1" FontSize="12" Margin="0,0,12,0" x:Name="ConsoleSearchBox"
|
||||
Watermark="Search..." Width="320" />
|
||||
<CheckBox Grid.Column="2" x:Name="AutoScrollCheck" Content="Auto-scroll" IsChecked="True"
|
||||
@@ -184,8 +501,8 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Launch bar -->
|
||||
<Border Grid.Row="3" Classes="card" Margin="0,12,0,0" Padding="14">
|
||||
<!-- Launch bar; capped so it does not sprawl on a maximized window. -->
|
||||
<Border Grid.Row="3" Classes="card" Margin="0,12,0,0" Padding="14" MaxWidth="1280">
|
||||
<StackPanel Spacing="14">
|
||||
<Grid ColumnDefinitions="Auto,*,Auto">
|
||||
|
||||
@@ -204,9 +521,32 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
</Panel>
|
||||
</Border>
|
||||
|
||||
<StackPanel Grid.Column="1" Spacing="3" VerticalAlignment="Center" Margin="14,0,14,0">
|
||||
<TextBlock x:Name="SelectedGameTitle" Text="No game selected" FontSize="16" FontWeight="Bold"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
<StackPanel Grid.Column="1" Spacing="4" VerticalAlignment="Center" Margin="14,0,14,0">
|
||||
<Grid ColumnDefinitions="Auto,Auto,*">
|
||||
<TextBlock Grid.Column="0" x:Name="SelectedGameTitle" Text="No game selected" FontSize="16"
|
||||
FontWeight="Bold" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"
|
||||
MaxWidth="340" Margin="0,0,10,0" />
|
||||
|
||||
<!-- Title id / version / size badges, right next to the
|
||||
title. The title's own MaxWidth (not a "*" column) is
|
||||
what keeps them from drifting to the far right. -->
|
||||
<StackPanel Grid.Column="1" x:Name="SelectedBadgesRow" Orientation="Horizontal" Spacing="6"
|
||||
IsVisible="False" VerticalAlignment="Center">
|
||||
<Border Classes="pill" IsVisible="{Binding HasTitleId, FallbackValue=False}">
|
||||
<TextBlock Text="{Binding TitleId}" FontSize="10" FontWeight="SemiBold"
|
||||
Foreground="{StaticResource MutedBrush}" />
|
||||
</Border>
|
||||
<Border Classes="pill" IsVisible="{Binding HasVersion, FallbackValue=False}">
|
||||
<TextBlock Text="{Binding VersionText}" FontSize="10" FontWeight="SemiBold"
|
||||
Foreground="{StaticResource MutedBrush}" />
|
||||
</Border>
|
||||
<Border Classes="pill">
|
||||
<TextBlock Text="{Binding SizeText, FallbackValue=''}" FontSize="10" FontWeight="SemiBold"
|
||||
Foreground="{StaticResource MutedBrush}" />
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
<TextBlock x:Name="SelectedGamePath" Text="Pick a game from the library, or open an eboot.bin directly."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextTrimming="CharacterEllipsis" />
|
||||
<StackPanel Orientation="Horizontal" Spacing="7">
|
||||
@@ -218,69 +558,18 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Column="2" Orientation="Horizontal" Spacing="8" VerticalAlignment="Center">
|
||||
<ToggleButton x:Name="OptionsToggle" Classes="ghost" Content="⚙ Options" />
|
||||
<ToggleButton x:Name="ConsoleToggle" Classes="ghost" Content="≡ Console" />
|
||||
<Button x:Name="LaunchButton" Classes="accent" Content="▶ Launch" IsEnabled="False" />
|
||||
<Button x:Name="StopButton" Classes="danger" Content="■ Stop" IsEnabled="False" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
<!-- Launch options (collapsible) -->
|
||||
<WrapPanel x:Name="OptionsPanel" IsVisible="False">
|
||||
<StackPanel Margin="0,0,24,0">
|
||||
<TextBlock Classes="fieldLabel" Text="CPU engine" />
|
||||
<ComboBox x:Name="CpuEngineBox" Width="150" SelectedIndex="0" CornerRadius="8">
|
||||
<ComboBoxItem Content="Native" />
|
||||
</ComboBox>
|
||||
</StackPanel>
|
||||
<StackPanel Margin="0,0,24,0">
|
||||
<TextBlock Classes="fieldLabel" Text="Log level" />
|
||||
<ComboBox x:Name="LogLevelBox" Width="150" SelectedIndex="2" CornerRadius="8">
|
||||
<ComboBoxItem Content="Trace" />
|
||||
<ComboBoxItem Content="Debug" />
|
||||
<ComboBoxItem Content="Info" />
|
||||
<ComboBoxItem Content="Warning" />
|
||||
<ComboBoxItem Content="Error" />
|
||||
<ComboBoxItem Content="Critical" />
|
||||
</ComboBox>
|
||||
</StackPanel>
|
||||
<StackPanel Margin="0,0,24,0">
|
||||
<TextBlock Classes="fieldLabel" Text="Import trace limit (0 = off)" />
|
||||
<NumericUpDown x:Name="TraceImportsBox" Width="170" Minimum="0" Maximum="4096" Increment="16"
|
||||
Value="0" FormatString="0" CornerRadius="8" />
|
||||
</StackPanel>
|
||||
<StackPanel Margin="0,0,24,0">
|
||||
<TextBlock Classes="fieldLabel" Text="Strict dynlib resolution" />
|
||||
<ToggleSwitch x:Name="StrictToggle" OnContent="On" OffContent="Off" />
|
||||
</StackPanel>
|
||||
<StackPanel Margin="0,0,24,0">
|
||||
<TextBlock Classes="fieldLabel" Text="Log to file" />
|
||||
<ToggleSwitch x:Name="LogToFileToggle" OnContent="On" OffContent="Off" />
|
||||
</StackPanel>
|
||||
<StackPanel Margin="0,0,24,0">
|
||||
<TextBlock Classes="fieldLabel" Text="Log file path" />
|
||||
<Button x:Name="SelectLogFilePathButton" Classes="ghost" Content="Select…"
|
||||
VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
<StackPanel Margin="0,0,24,0">
|
||||
<TextBlock Classes="fieldLabel" Text="Override log file" />
|
||||
<ToggleSwitch x:Name="OverrideLogFileToggle" OnContent="On" OffContent="Off" />
|
||||
</StackPanel>
|
||||
<StackPanel Margin="0,0,24,0">
|
||||
<TextBlock Classes="fieldLabel" Text="Title music" />
|
||||
<ToggleSwitch x:Name="TitleMusicToggle" OnContent="On" OffContent="Off" IsChecked="True" />
|
||||
</StackPanel>
|
||||
<StackPanel>
|
||||
<TextBlock Classes="fieldLabel" Text="Discord presence" />
|
||||
<ToggleSwitch x:Name="DiscordToggle" OnContent="On" OffContent="Off" />
|
||||
</StackPanel>
|
||||
</WrapPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
|
||||
<!-- Status bar -->
|
||||
<Grid Grid.Row="2" Background="{StaticResource ChromeBrush}" ColumnDefinitions="*,Auto">
|
||||
<Grid x:Name="StatusBar" Grid.Row="2" Height="32" Background="{StaticResource ChromeBrush}"
|
||||
ColumnDefinitions="*,Auto">
|
||||
<TextBlock x:Name="EmulatorPathText" Grid.Column="0" Text="Emulator: locating…" FontSize="11"
|
||||
Foreground="{StaticResource FaintBrush}" VerticalAlignment="Center" Margin="16,0"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
|
||||
@@ -12,7 +12,8 @@ using Avalonia.Platform;
|
||||
using Avalonia.Platform.Storage;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
using SharpEmu.Libs.Pad;
|
||||
using SharpEmu.HLE.Host;
|
||||
using SharpEmu.HLE.Host.Windows;
|
||||
using SharpEmu.Logging;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.ObjectModel;
|
||||
@@ -25,6 +26,7 @@ namespace SharpEmu.GUI;
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
private const int MaxConsoleLines = 4000;
|
||||
private const int MaxConsoleLinesPerFlush = 500;
|
||||
|
||||
private static readonly IBrush DefaultLineBrush = new SolidColorBrush(Color.Parse("#C7CFDE"));
|
||||
private static readonly IBrush DimLineBrush = new SolidColorBrush(Color.Parse("#6B7488"));
|
||||
@@ -48,6 +50,7 @@ public partial class MainWindow : Window
|
||||
private string? _emulatorExePath;
|
||||
private bool _isRunning;
|
||||
private int _autoScrollTicks;
|
||||
private int _activePageIndex;
|
||||
|
||||
// Discord Rich Presence state.
|
||||
private readonly long _launcherStartUnixSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
@@ -60,7 +63,7 @@ public partial class MainWindow : Window
|
||||
|
||||
// Controller navigation state.
|
||||
private readonly DispatcherTimer _gamepadTimer;
|
||||
private uint _previousPadButtons;
|
||||
private HostGamepadButtons _previousPadButtons;
|
||||
private long _navLeftNextAt;
|
||||
private long _navRightNextAt;
|
||||
private long _navUpNextAt;
|
||||
@@ -100,36 +103,121 @@ public partial class MainWindow : Window
|
||||
ClearLogButton.Click += (_, _) => _consoleLines.Clear();
|
||||
CopyLogButton.Click += async (_, _) => await CopyConsoleAsync();
|
||||
DetachConsoleButton.Click += (_, _) => ShowConsoleWindow();
|
||||
OptionsToggle.IsCheckedChanged += (_, _) => OptionsPanel.IsVisible = OptionsToggle.IsChecked == true;
|
||||
LibraryTabButton.Click += (_, _) => SetActivePage(0);
|
||||
OptionsTabButton.Click += (_, _) => SetActivePage(1);
|
||||
ConsoleToggle.IsCheckedChanged += (_, _) => ConsolePanel.IsVisible = ConsoleToggle.IsChecked == true && _consoleWindow is null;
|
||||
SelectLogFilePathButton.Click += async (_, _) => await SelectFilePathAsync();
|
||||
TitleMusicToggle.IsCheckedChanged += (_, _) => OnTitleMusicToggled();
|
||||
|
||||
// The settings page edits _settings live, so a launch started while
|
||||
// it is open already uses the new values.
|
||||
LogLevelBox.SelectionChanged += (_, _) => _settings.LogLevel = SelectedLogLevel();
|
||||
TraceImportsBox.ValueChanged += (_, _) => _settings.ImportTraceLimit = (int)(TraceImportsBox.Value ?? 0);
|
||||
StrictToggle.IsCheckedChanged += (_, _) => _settings.StrictDynlibResolution = StrictToggle.IsChecked == true;
|
||||
LogToFileToggle.IsCheckedChanged += (_, _) => _settings.LogToFile = LogToFileToggle.IsChecked == true;
|
||||
OverrideLogFileToggle.IsCheckedChanged += (_, _) =>
|
||||
_settings.OverrideLogFile = OverrideLogFileToggle.IsChecked == true;
|
||||
TitleMusicToggle.IsCheckedChanged += (_, _) =>
|
||||
{
|
||||
_settings.PlayTitleMusic = TitleMusicToggle.IsChecked == true;
|
||||
OnTitleMusicSettingChanged();
|
||||
};
|
||||
DiscordToggle.IsCheckedChanged += (_, _) =>
|
||||
{
|
||||
_settings.DiscordRichPresence = DiscordToggle.IsChecked == true;
|
||||
UpdateDiscordPresence();
|
||||
};
|
||||
SelectLogFilePathButton.Click += async (_, _) => await SelectLogFilePathAsync();
|
||||
EnvBthidToggle.IsCheckedChanged += (_, _) =>
|
||||
SetEnvironmentToggle("SHARPEMU_BTHID_UNAVAILABLE", EnvBthidToggle.IsChecked == true);
|
||||
EnvLoopGuardToggle.IsCheckedChanged += (_, _) =>
|
||||
SetEnvironmentToggle("SHARPEMU_DISABLE_IMPORT_LOOP_GUARD", EnvLoopGuardToggle.IsChecked == true);
|
||||
EnvVkValidationToggle.IsCheckedChanged += (_, _) =>
|
||||
SetEnvironmentToggle("SHARPEMU_VK_VALIDATION", EnvVkValidationToggle.IsChecked == true);
|
||||
EnvDumpSpirvToggle.IsCheckedChanged += (_, _) =>
|
||||
SetEnvironmentToggle("SHARPEMU_DUMP_SPIRV", EnvDumpSpirvToggle.IsChecked == true);
|
||||
EnvLogDirectMemoryToggle.IsCheckedChanged += (_, _) =>
|
||||
SetEnvironmentToggle("SHARPEMU_LOG_DIRECT_MEMORY", EnvLogDirectMemoryToggle.IsChecked == true);
|
||||
EnvLogNpToggle.IsCheckedChanged += (_, _) =>
|
||||
SetEnvironmentToggle("SHARPEMU_LOG_NP", EnvLogNpToggle.IsChecked == true);
|
||||
LanguageBox.SelectionChanged += (_, _) => OnLanguageChanged();
|
||||
|
||||
GameList.AddHandler(ContextRequestedEvent, OnGameContextRequested, RoutingStrategies.Tunnel);
|
||||
CtxLaunch.Click += (_, _) => LaunchSelected();
|
||||
CtxOpenFolder.Click += (_, _) => OpenSelectedGameFolder();
|
||||
CtxCopyPath.Click += async (_, _) =>
|
||||
await CopyToClipboardAsync((GameList.SelectedItem as GameEntry)?.Path, "Path");
|
||||
await CopyToClipboardAsync((GameList.SelectedItem as GameEntry)?.Path, "Clipboard.Path");
|
||||
CtxCopyTitleId.Click += async (_, _) =>
|
||||
await CopyToClipboardAsync((GameList.SelectedItem as GameEntry)?.TitleId, "Title ID");
|
||||
await CopyToClipboardAsync((GameList.SelectedItem as GameEntry)?.TitleId, "Clipboard.TitleId");
|
||||
CtxRemove.Click += (_, _) => RemoveSelectedFromLibrary();
|
||||
|
||||
Opened += async (_, _) => await OnOpenedAsync();
|
||||
Closing += (_, _) => OnWindowClosing();
|
||||
|
||||
DualSenseReader.EnsureStarted();
|
||||
XInputReader.EnsureStarted();
|
||||
WindowsDualSenseReader.EnsureStarted();
|
||||
WindowsXInputReader.EnsureStarted();
|
||||
_gamepadTimer = new DispatcherTimer
|
||||
{
|
||||
Interval = TimeSpan.FromMilliseconds(50),
|
||||
};
|
||||
_gamepadTimer.Tick += (_, _) => PollGamepad();
|
||||
_gamepadTimer.Start();
|
||||
|
||||
|
||||
GithubButton.Click += (_, _) =>
|
||||
{
|
||||
Process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = "https://github.com/par274/sharpemu",
|
||||
UseShellExecute = true
|
||||
});
|
||||
};
|
||||
|
||||
DiscordButton.Click += (_, _) =>
|
||||
{
|
||||
Process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = "https://discord.com/invite/6GejPEDqpc",
|
||||
UseShellExecute = true
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Switches between the Library and Options pages. Also reachable via
|
||||
/// the gamepad's shoulder buttons (LB/RB, L1/R1) from <see cref="PollGamepad"/>.
|
||||
/// </summary>
|
||||
private void SetActivePage(int index)
|
||||
{
|
||||
if (index == _activePageIndex)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_activePageIndex == 1)
|
||||
{
|
||||
_settings.Save(); // leaving the Options page
|
||||
}
|
||||
|
||||
_activePageIndex = index;
|
||||
SetActiveClass(LibraryTabButton, index == 0);
|
||||
SetActiveClass(OptionsTabButton, index == 1);
|
||||
LibraryPage.IsVisible = index == 0;
|
||||
LibraryToolbar.IsVisible = index == 0;
|
||||
OptionsPage.IsVisible = index == 1;
|
||||
}
|
||||
|
||||
private static void SetActiveClass(Button button, bool active)
|
||||
{
|
||||
if (active)
|
||||
{
|
||||
if (!button.Classes.Contains("active"))
|
||||
{
|
||||
button.Classes.Add("active");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
button.Classes.Remove("active");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Controller navigation ----
|
||||
@@ -137,25 +225,42 @@ public partial class MainWindow : Window
|
||||
private void PollGamepad()
|
||||
{
|
||||
// DualSense wins when both are connected; XInput covers Xbox pads.
|
||||
if (!DualSenseReader.TryGetState(out var pad) && !XInputReader.TryGetState(out pad))
|
||||
if (!WindowsDualSenseReader.TryGetState(out var pad) && !WindowsXInputReader.TryGetState(out pad))
|
||||
{
|
||||
_previousPadButtons = 0;
|
||||
_previousPadButtons = HostGamepadButtons.None;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!IsActive)
|
||||
{
|
||||
// Ignore input while the launcher is in the background (e.g. the
|
||||
// game window is focused and using the same controller).
|
||||
// Ignore input while the launcher is in the background, e.g. the
|
||||
// game window is focused and using the same controller.
|
||||
_previousPadButtons = pad.Buttons;
|
||||
return;
|
||||
}
|
||||
|
||||
var shoulderPressed = pad.Buttons & ~_previousPadButtons;
|
||||
if ((shoulderPressed & HostGamepadButtons.L1) != 0)
|
||||
{
|
||||
SetActivePage(0);
|
||||
}
|
||||
|
||||
if ((shoulderPressed & HostGamepadButtons.R1) != 0)
|
||||
{
|
||||
SetActivePage(1);
|
||||
}
|
||||
|
||||
if (_activePageIndex != 0)
|
||||
{
|
||||
_previousPadButtons = pad.Buttons;
|
||||
return;
|
||||
}
|
||||
|
||||
var now = Environment.TickCount64;
|
||||
var left = (pad.Buttons & 0x0080) != 0 || pad.LeftX < 64;
|
||||
var right = (pad.Buttons & 0x0020) != 0 || pad.LeftX > 192;
|
||||
var up = (pad.Buttons & 0x0010) != 0 || pad.LeftY < 64;
|
||||
var down = (pad.Buttons & 0x0040) != 0 || pad.LeftY > 192;
|
||||
var left = (pad.Buttons & HostGamepadButtons.Left) != 0 || pad.LeftX < 64;
|
||||
var right = (pad.Buttons & HostGamepadButtons.Right) != 0 || pad.LeftX > 192;
|
||||
var up = (pad.Buttons & HostGamepadButtons.Up) != 0 || pad.LeftY < 64;
|
||||
var down = (pad.Buttons & HostGamepadButtons.Down) != 0 || pad.LeftY > 192;
|
||||
|
||||
if (ShouldNavigate(left, ref _navLeftNextAt, now))
|
||||
{
|
||||
@@ -178,12 +283,12 @@ public partial class MainWindow : Window
|
||||
}
|
||||
|
||||
var pressed = pad.Buttons & ~_previousPadButtons;
|
||||
if ((pressed & 0x4000) != 0) // Cross
|
||||
if ((pressed & HostGamepadButtons.Cross) != 0)
|
||||
{
|
||||
LaunchSelected();
|
||||
}
|
||||
|
||||
if ((pressed & 0x2000) != 0) // Circle
|
||||
if ((pressed & HostGamepadButtons.Circle) != 0)
|
||||
{
|
||||
StopEmulator();
|
||||
}
|
||||
@@ -254,12 +359,143 @@ public partial class MainWindow : Window
|
||||
ToolTip.SetTip(VersionText, BuildInfo.Banner);
|
||||
|
||||
_settings = GuiSettings.Load();
|
||||
Localization.Instance.Load(_settings.Language);
|
||||
PopulateLanguageBox();
|
||||
ApplyLocalization();
|
||||
ApplySettingsToControls();
|
||||
LocateEmulator();
|
||||
UpdateDiscordPresence();
|
||||
await RescanLibraryAsync();
|
||||
}
|
||||
|
||||
private void PopulateLanguageBox()
|
||||
{
|
||||
var languages = Localization.Instance.DiscoverLanguages();
|
||||
LanguageBox.ItemsSource = languages;
|
||||
LanguageBox.SelectedItem = languages.FirstOrDefault(language =>
|
||||
string.Equals(language.Code, _settings.Language, StringComparison.OrdinalIgnoreCase))
|
||||
?? languages.FirstOrDefault();
|
||||
}
|
||||
|
||||
private void OnLanguageChanged()
|
||||
{
|
||||
if (LanguageBox.SelectedItem is not Localization.LanguageInfo language)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_settings.Language = language.Code;
|
||||
Localization.Instance.Load(language.Code);
|
||||
ApplyLocalization();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Re-applies every UI string from the current language, so switching
|
||||
/// languages in Options takes effect immediately without reopening the
|
||||
/// window.
|
||||
/// </summary>
|
||||
private void ApplyLocalization()
|
||||
{
|
||||
var loc = Localization.Instance;
|
||||
|
||||
LibraryTabButton.Content = loc.Get("Page.Library");
|
||||
OptionsTabButton.Content = loc.Get("Page.Options");
|
||||
|
||||
SearchBox.Watermark = loc.Get("Library.SearchWatermark");
|
||||
AddFolderButton.Content = loc.Get("Library.AddFolder");
|
||||
RescanButton.Content = loc.Get("Library.Rescan");
|
||||
OpenFileButton.Content = loc.Get("Library.OpenFile");
|
||||
|
||||
CtxLaunch.Header = loc.Get("Library.Context.Launch");
|
||||
CtxOpenFolder.Header = loc.Get("Library.Context.OpenFolder");
|
||||
CtxCopyPath.Header = loc.Get("Library.Context.CopyPath");
|
||||
CtxCopyTitleId.Header = loc.Get("Library.Context.CopyTitleId");
|
||||
CtxRemove.Header = loc.Get("Library.Context.Remove");
|
||||
|
||||
EmptyAddFolderButton.Content = loc.Get("Library.Empty.AddFolder");
|
||||
LoadingStateText.Text = loc.Get("Library.Loading");
|
||||
|
||||
GeneralTabItem.Header = loc.Get("Options.General");
|
||||
EnvTabItem.Header = loc.Get("Options.Env.Tab");
|
||||
EnvSectionTitle.Text = loc.Get("Options.Section.Environment");
|
||||
EnvDesc.Text = loc.Get("Options.Env.Desc");
|
||||
EnvBthidDesc.Text = loc.Get("Options.Env.Bthid.Desc");
|
||||
EnvLoopGuardDesc.Text = loc.Get("Options.Env.LoopGuard.Desc");
|
||||
EnvVkValidationDesc.Text = loc.Get("Options.Env.VkValidation.Desc");
|
||||
EnvDumpSpirvDesc.Text = loc.Get("Options.Env.DumpSpirv.Desc");
|
||||
EnvLogDirectMemoryDesc.Text = loc.Get("Options.Env.LogDirectMemory.Desc");
|
||||
EnvLogNpDesc.Text = loc.Get("Options.Env.LogNp.Desc");
|
||||
EmulationSectionTitle.Text = loc.Get("Options.Section.Emulation");
|
||||
LoggingSectionTitle.Text = loc.Get("Options.Section.Logging");
|
||||
LauncherSectionTitle.Text = loc.Get("Options.Section.Launcher");
|
||||
|
||||
CpuEngineLabel.Text = loc.Get("Options.CpuEngine.Label");
|
||||
CpuEngineDesc.Text = loc.Get("Options.CpuEngine.Desc");
|
||||
CpuEngineNativeItem.Content = loc.Get("Options.CpuEngine.Native");
|
||||
|
||||
StrictLabel.Text = loc.Get("Options.Strict.Label");
|
||||
StrictDesc.Text = loc.Get("Options.Strict.Desc");
|
||||
|
||||
LogLevelLabel.Text = loc.Get("Options.LogLevel.Label");
|
||||
LogLevelDesc.Text = loc.Get("Options.LogLevel.Desc");
|
||||
LogLevelTraceItem.Content = loc.Get("Options.LogLevel.Trace");
|
||||
LogLevelDebugItem.Content = loc.Get("Options.LogLevel.Debug");
|
||||
LogLevelInfoItem.Content = loc.Get("Options.LogLevel.Info");
|
||||
LogLevelWarningItem.Content = loc.Get("Options.LogLevel.Warning");
|
||||
LogLevelErrorItem.Content = loc.Get("Options.LogLevel.Error");
|
||||
LogLevelCriticalItem.Content = loc.Get("Options.LogLevel.Critical");
|
||||
|
||||
TraceImportsLabel.Text = loc.Get("Options.TraceImports.Label");
|
||||
TraceImportsDesc.Text = loc.Get("Options.TraceImports.Desc");
|
||||
|
||||
LogToFileLabel.Text = loc.Get("Options.LogToFile.Label");
|
||||
LogToFileDesc.Text = loc.Get("Options.LogToFile.Desc");
|
||||
|
||||
LogFilePathLabel.Text = loc.Get("Options.LogFilePath.Label");
|
||||
SelectLogFilePathButton.Content = loc.Get("Options.LogFilePath.Select");
|
||||
UpdateLogFilePathText();
|
||||
|
||||
OverrideLogFileLabel.Text = loc.Get("Options.OverrideLogFile.Label");
|
||||
OverrideLogFileDesc.Text = loc.Get("Options.OverrideLogFile.Desc");
|
||||
|
||||
LanguageLabel.Text = loc.Get("Options.Language.Label");
|
||||
LanguageDesc.Text = loc.Get("Options.Language.Desc");
|
||||
|
||||
TitleMusicLabel.Text = loc.Get("Options.TitleMusic.Label");
|
||||
TitleMusicDesc.Text = loc.Get("Options.TitleMusic.Desc");
|
||||
|
||||
DiscordLabel.Text = loc.Get("Options.Discord.Label");
|
||||
DiscordDesc.Text = loc.Get("Options.Discord.Desc");
|
||||
|
||||
foreach (var toggle in new[] { StrictToggle, LogToFileToggle, OverrideLogFileToggle, TitleMusicToggle, DiscordToggle })
|
||||
{
|
||||
toggle.OnContent = loc.Get("Common.On");
|
||||
toggle.OffContent = loc.Get("Common.Off");
|
||||
}
|
||||
|
||||
ConsoleSectionTitle.Text = loc.Get("Console.Title");
|
||||
ConsoleSearchBox.Watermark = loc.Get("Console.SearchWatermark");
|
||||
AutoScrollCheck.Content = loc.Get("Console.AutoScroll");
|
||||
DetachConsoleButton.Content = loc.Get("Console.Split");
|
||||
CopyLogButton.Content = loc.Get("Console.Copy");
|
||||
ClearLogButton.Content = loc.Get("Console.Clear");
|
||||
|
||||
ConsoleToggle.Content = loc.Get("Launch.Console");
|
||||
LaunchButton.Content = loc.Get("Launch.Launch");
|
||||
StopButton.Content = loc.Get("Launch.Stop");
|
||||
|
||||
AboutSectionTitle.Text = loc.Get("Options.About");
|
||||
GithubLabel.Text = loc.Get("About.Github.Label");
|
||||
GithubDesc.Text = loc.Get("About.Github.Desc");
|
||||
DiscordServerLabel.Text = loc.Get("About.Discord.Label");
|
||||
DiscordServerDesc.Text = loc.Get("About.Discord.Desc");
|
||||
GithubButton.Content = loc.Get("About.GithubButton");
|
||||
DiscordButton.Content = loc.Get("About.DiscordButton");
|
||||
|
||||
UpdateEmptyStateTexts();
|
||||
UpdateSelectedGameTexts();
|
||||
}
|
||||
|
||||
// ---- Discord Rich Presence ----
|
||||
|
||||
/// <summary>
|
||||
@@ -280,7 +516,7 @@ public partial class MainWindow : Window
|
||||
if (_isRunning && _runningGameName is { } gameName)
|
||||
{
|
||||
_discord.SetPresence(
|
||||
$"Playing {gameName}",
|
||||
Localization.Instance.Format("Discord.Playing", gameName),
|
||||
_runningGameTitleId,
|
||||
_runningSinceUnixSeconds);
|
||||
}
|
||||
@@ -288,9 +524,12 @@ public partial class MainWindow : Window
|
||||
{
|
||||
// Discord does not render activities without timestamps, so the
|
||||
// browsing state carries the launcher's start time.
|
||||
var count = _allGames.Count == 1
|
||||
? Localization.Instance.Get("Page.GameCount.One")
|
||||
: Localization.Instance.Format("Page.GameCount.Other", _allGames.Count);
|
||||
_discord.SetPresence(
|
||||
"Browsing the library",
|
||||
$"{_allGames.Count} game(s)",
|
||||
Localization.Instance.Get("Discord.Browsing"),
|
||||
count,
|
||||
_launcherStartUnixSeconds);
|
||||
}
|
||||
}
|
||||
@@ -315,17 +554,20 @@ public partial class MainWindow : Window
|
||||
{
|
||||
WindowState = WindowState.Normal;
|
||||
ExtendClientAreaChromeHints = ExtendClientAreaChromeHints.PreferSystemChrome;
|
||||
TitleBar.IsVisible = true;
|
||||
StatusBar.IsVisible = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
WindowState = WindowState.FullScreen;
|
||||
ExtendClientAreaChromeHints = ExtendClientAreaChromeHints.NoChrome;
|
||||
TitleBar.IsVisible = false;
|
||||
StatusBar.IsVisible = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnWindowClosing()
|
||||
{
|
||||
ReadControlsIntoSettings();
|
||||
_settings.Save();
|
||||
_consoleFlushTimer.Stop();
|
||||
_gamepadTimer.Stop();
|
||||
@@ -344,7 +586,7 @@ public partial class MainWindow : Window
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Settings <-> controls ----
|
||||
// ---- Settings ----
|
||||
|
||||
private void ApplySettingsToControls()
|
||||
{
|
||||
@@ -363,19 +605,33 @@ public partial class MainWindow : Window
|
||||
LogToFileToggle.IsChecked = _settings.LogToFile;
|
||||
OverrideLogFileToggle.IsChecked = _settings.OverrideLogFile;
|
||||
TitleMusicToggle.IsChecked = _settings.PlayTitleMusic;
|
||||
ToolTip.SetTip(SelectLogFilePathButton, string.IsNullOrWhiteSpace(_settings.LogFilePath) ? "No path selected" : _settings.LogFilePath);
|
||||
DiscordToggle.IsChecked = _settings.DiscordRichPresence;
|
||||
EnvBthidToggle.IsChecked = _settings.EnvironmentToggles.Contains("SHARPEMU_BTHID_UNAVAILABLE");
|
||||
EnvLoopGuardToggle.IsChecked = _settings.EnvironmentToggles.Contains("SHARPEMU_DISABLE_IMPORT_LOOP_GUARD");
|
||||
EnvVkValidationToggle.IsChecked = _settings.EnvironmentToggles.Contains("SHARPEMU_VK_VALIDATION");
|
||||
EnvDumpSpirvToggle.IsChecked = _settings.EnvironmentToggles.Contains("SHARPEMU_DUMP_SPIRV");
|
||||
EnvLogDirectMemoryToggle.IsChecked = _settings.EnvironmentToggles.Contains("SHARPEMU_LOG_DIRECT_MEMORY");
|
||||
EnvLogNpToggle.IsChecked = _settings.EnvironmentToggles.Contains("SHARPEMU_LOG_NP");
|
||||
UpdateLogFilePathText();
|
||||
}
|
||||
|
||||
private void ReadControlsIntoSettings()
|
||||
// Environment variables set on this process at the previous launch; children
|
||||
// inherit the process environment, so stale names must be cleared explicitly.
|
||||
private readonly HashSet<string> _appliedEnvironmentVariables = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private void SetEnvironmentToggle(string name, bool enabled)
|
||||
{
|
||||
_settings.LogLevel = SelectedLogLevel();
|
||||
_settings.ImportTraceLimit = (int)(TraceImportsBox.Value ?? 0);
|
||||
_settings.StrictDynlibResolution = StrictToggle.IsChecked == true;
|
||||
_settings.LogToFile = LogToFileToggle.IsChecked == true;
|
||||
_settings.OverrideLogFile = OverrideLogFileToggle.IsChecked == true;
|
||||
_settings.PlayTitleMusic = TitleMusicToggle.IsChecked == true;
|
||||
_settings.DiscordRichPresence = DiscordToggle.IsChecked == true;
|
||||
if (enabled)
|
||||
{
|
||||
if (!_settings.EnvironmentToggles.Contains(name))
|
||||
{
|
||||
_settings.EnvironmentToggles.Add(name);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_settings.EnvironmentToggles.Remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
private string SelectedLogLevel()
|
||||
@@ -392,6 +648,35 @@ public partial class MainWindow : Window
|
||||
};
|
||||
}
|
||||
|
||||
private void UpdateLogFilePathText()
|
||||
{
|
||||
LogFilePathText.Text = string.IsNullOrWhiteSpace(_settings.LogFilePath)
|
||||
? Localization.Instance.Get("Options.LogFilePath.Default")
|
||||
: _settings.LogFilePath;
|
||||
}
|
||||
|
||||
private async Task SelectLogFilePathAsync()
|
||||
{
|
||||
var loc = Localization.Instance;
|
||||
SaveFilePickerResult result = await StorageProvider.SaveFilePickerWithResultAsync(new FilePickerSaveOptions
|
||||
{
|
||||
Title = loc.Get("Dialog.SaveLogFile"),
|
||||
SuggestedFileName = "SharpEmuLog",
|
||||
DefaultExtension = "log",
|
||||
FileTypeChoices =
|
||||
[
|
||||
new FilePickerFileType(loc.Get("Dialog.PlainTextFiles")) { Patterns = ["*.txt"] },
|
||||
new FilePickerFileType(loc.Get("Dialog.LogFiles")) { Patterns = ["*.log"] }
|
||||
]
|
||||
});
|
||||
|
||||
if (result.File is not null)
|
||||
{
|
||||
_settings.LogFilePath = result.File.Path.LocalPath;
|
||||
UpdateLogFilePathText();
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Emulator discovery ----
|
||||
|
||||
private void LocateEmulator()
|
||||
@@ -421,8 +706,8 @@ public partial class MainWindow : Window
|
||||
: null;
|
||||
|
||||
EmulatorPathText.Text = _emulatorExePath is not null
|
||||
? $"Emulator: {_emulatorExePath}"
|
||||
: "Emulator: SharpEmu executable not found — build SharpEmu.CLI first.";
|
||||
? Localization.Instance.Format("Status.EmulatorPath", _emulatorExePath)
|
||||
: Localization.Instance.Get("Status.EmulatorNotFound");
|
||||
}
|
||||
|
||||
// ---- Game library ----
|
||||
@@ -431,7 +716,7 @@ public partial class MainWindow : Window
|
||||
{
|
||||
var folders = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions
|
||||
{
|
||||
Title = "Choose a folder containing games",
|
||||
Title = Localization.Instance.Get("Dialog.ChooseGameFolder"),
|
||||
AllowMultiple = false,
|
||||
});
|
||||
|
||||
@@ -466,18 +751,21 @@ public partial class MainWindow : Window
|
||||
{
|
||||
var folders = _settings.GameFolders.ToArray();
|
||||
var excluded = new HashSet<string>(_settings.ExcludedGames, StringComparer.OrdinalIgnoreCase);
|
||||
StatusBarRight.Text = "Scanning library…";
|
||||
StatusBarRight.Text = Localization.Instance.Get("Status.ScanningLibrary");
|
||||
EmptyState.IsVisible = false;
|
||||
LoadingState.IsVisible = true;
|
||||
|
||||
var games = await Task.Run(() => ScanFolders(folders, excluded));
|
||||
|
||||
_allGames.Clear();
|
||||
_allGames.AddRange(games);
|
||||
RefreshVisibleGames();
|
||||
LoadingState.IsVisible = false;
|
||||
LoadGameDetailsInBackground(games);
|
||||
UpdateDiscordPresence();
|
||||
StatusBarRight.Text = folders.Length == 0
|
||||
? "Add a game folder to populate the library."
|
||||
: $"Library scanned: {games.Count} game(s) in {folders.Length} folder(s).";
|
||||
? Localization.Instance.Get("Status.AddFolderPrompt")
|
||||
: Localization.Instance.Format("Status.LibraryScanned", games.Count, folders.Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -614,9 +902,9 @@ public partial class MainWindow : Window
|
||||
{
|
||||
}
|
||||
|
||||
var (title, titleId) = TryReadParamJson(fullPath);
|
||||
var (title, titleId, version) = TryReadParamJson(fullPath);
|
||||
games.Add(new GameEntry(
|
||||
title ?? GameNameFor(fullPath), titleId, fullPath, size,
|
||||
title ?? GameNameFor(fullPath), titleId, version, fullPath, size,
|
||||
FindCoverFor(fullPath), FindBackgroundFor(fullPath)));
|
||||
}
|
||||
}
|
||||
@@ -631,23 +919,23 @@ public partial class MainWindow : Window
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the game title and title id from sce_sys/param.json next to the
|
||||
/// executable, when present.
|
||||
/// Reads the game title, title id and content version from
|
||||
/// sce_sys/param.json next to the executable, when present.
|
||||
/// </summary>
|
||||
private static (string? Title, string? TitleId) TryReadParamJson(string ebootPath)
|
||||
private static (string? Title, string? TitleId, string? Version) TryReadParamJson(string ebootPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
var directory = Path.GetDirectoryName(ebootPath);
|
||||
if (directory is null)
|
||||
{
|
||||
return (null, null);
|
||||
return (null, null, null);
|
||||
}
|
||||
|
||||
var paramPath = Path.Combine(directory, "sce_sys", "param.json");
|
||||
if (!File.Exists(paramPath))
|
||||
{
|
||||
return (null, null);
|
||||
return (null, null, null);
|
||||
}
|
||||
|
||||
// ReadAllText handles a UTF-8 BOM, which JsonDocument rejects in
|
||||
@@ -661,6 +949,20 @@ public partial class MainWindow : Window
|
||||
titleId = idElement.GetString();
|
||||
}
|
||||
|
||||
// contentVersion carries the installed app version
|
||||
// ("01.000.000"); masterVersion is the fallback on older dumps.
|
||||
string? version = null;
|
||||
if (root.TryGetProperty("contentVersion", out var versionElement) &&
|
||||
versionElement.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
version = versionElement.GetString();
|
||||
}
|
||||
else if (root.TryGetProperty("masterVersion", out var masterElement) &&
|
||||
masterElement.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
version = masterElement.GetString();
|
||||
}
|
||||
|
||||
string? title = null;
|
||||
if (root.TryGetProperty("localizedParameters", out var localized) &&
|
||||
localized.ValueKind == JsonValueKind.Object)
|
||||
@@ -691,11 +993,12 @@ public partial class MainWindow : Window
|
||||
|
||||
return (
|
||||
string.IsNullOrWhiteSpace(title) ? null : title,
|
||||
string.IsNullOrWhiteSpace(titleId) ? null : titleId);
|
||||
string.IsNullOrWhiteSpace(titleId) ? null : titleId,
|
||||
string.IsNullOrWhiteSpace(version) ? null : version.Trim());
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return (null, null);
|
||||
return (null, null, null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -806,11 +1109,12 @@ public partial class MainWindow : Window
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
StatusBarRight.Text = $"Could not open folder: {ex.Message}";
|
||||
StatusBarRight.Text = Localization.Instance.Format("Status.CouldNotOpenFolder", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CopyToClipboardAsync(string? text, string what)
|
||||
/// <summary>Copies <paramref name="text"/> and reports it via <paramref name="whatKey"/>, e.g. "Clipboard.Path".</summary>
|
||||
private async Task CopyToClipboardAsync(string? text, string whatKey)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text) || Clipboard is null)
|
||||
{
|
||||
@@ -818,7 +1122,7 @@ public partial class MainWindow : Window
|
||||
}
|
||||
|
||||
await Clipboard.SetTextAsync(text);
|
||||
StatusBarRight.Text = $"{what} copied to clipboard.";
|
||||
StatusBarRight.Text = Localization.Instance.Format("Status.CopiedToClipboard", Localization.Instance.Get(whatKey));
|
||||
}
|
||||
|
||||
private void RemoveSelectedFromLibrary()
|
||||
@@ -837,7 +1141,7 @@ public partial class MainWindow : Window
|
||||
_allGames.RemoveAll(g => string.Equals(g.Path, game.Path, StringComparison.OrdinalIgnoreCase));
|
||||
GameList.SelectedItem = null;
|
||||
RefreshVisibleGames();
|
||||
StatusBarRight.Text = $"Removed “{game.Name}” from the library. Re-add its folder to restore it.";
|
||||
StatusBarRight.Text = Localization.Instance.Format("Status.RemovedFromLibrary", game.Name);
|
||||
}
|
||||
|
||||
private void RefreshVisibleGames()
|
||||
@@ -857,8 +1161,6 @@ public partial class MainWindow : Window
|
||||
}
|
||||
}
|
||||
|
||||
GameCountText.Text = _visibleGames.Count == 1 ? "1 game" : $"{_visibleGames.Count} games";
|
||||
|
||||
if (selectedPath is not null &&
|
||||
_visibleGames.FirstOrDefault(g => g.Path.Equals(selectedPath, StringComparison.OrdinalIgnoreCase))
|
||||
is { } reselected)
|
||||
@@ -867,34 +1169,50 @@ public partial class MainWindow : Window
|
||||
}
|
||||
|
||||
EmptyState.IsVisible = _visibleGames.Count == 0;
|
||||
if (_visibleGames.Count == 0)
|
||||
{
|
||||
var hasFilter = query.Length > 0;
|
||||
EmptyStateTitle.Text = hasFilter ? "No games match your search" : "Your library is empty";
|
||||
EmptyStateHint.Text = hasFilter
|
||||
? $"Nothing in the library matches “{query}”."
|
||||
: "Add a folder containing your games to get started.";
|
||||
EmptyAddFolderButton.IsVisible = !hasFilter;
|
||||
}
|
||||
UpdateEmptyStateTexts();
|
||||
|
||||
UpdateSelectedGame();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refreshes the empty-state title/hint from the current language and
|
||||
/// search text; a no-op while the empty state is not showing.
|
||||
/// </summary>
|
||||
private void UpdateEmptyStateTexts()
|
||||
{
|
||||
if (_visibleGames.Count != 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var query = SearchBox.Text?.Trim() ?? string.Empty;
|
||||
var hasFilter = query.Length > 0;
|
||||
EmptyStateTitle.Text = hasFilter
|
||||
? Localization.Instance.Get("Library.Empty.SearchTitle")
|
||||
: Localization.Instance.Get("Library.Empty.Title");
|
||||
EmptyStateHint.Text = hasFilter
|
||||
? Localization.Instance.Format("Library.Empty.SearchHint", query)
|
||||
: Localization.Instance.Get("Library.Empty.Hint");
|
||||
EmptyAddFolderButton.IsVisible = !hasFilter;
|
||||
}
|
||||
|
||||
private void UpdateSelectedGame()
|
||||
{
|
||||
if (GameList.SelectedItem is GameEntry game)
|
||||
{
|
||||
SelectedGameTitle.Text = game.Name;
|
||||
SelectedGamePath.Text = game.Path;
|
||||
UpdateSelectedGameTexts();
|
||||
SelectedCoverPanel.DataContext = game;
|
||||
SelectedBadgesRow.DataContext = game;
|
||||
SelectedBadgesRow.IsVisible = true;
|
||||
_ = UpdateBackdropAsync(game);
|
||||
PlaySelectedGamePreview(game);
|
||||
}
|
||||
else
|
||||
{
|
||||
SelectedGameTitle.Text = "No game selected";
|
||||
SelectedGamePath.Text = "Pick a game from the library, or open an eboot.bin directly.";
|
||||
UpdateSelectedGameTexts();
|
||||
SelectedCoverPanel.DataContext = null;
|
||||
SelectedBadgesRow.DataContext = null;
|
||||
SelectedBadgesRow.IsVisible = false;
|
||||
_ = UpdateBackdropAsync(null);
|
||||
_sndPreview.Stop();
|
||||
}
|
||||
@@ -902,6 +1220,25 @@ public partial class MainWindow : Window
|
||||
UpdateRunButtons();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Text-only refresh of the launch bar's title/path, split out of
|
||||
/// <see cref="UpdateSelectedGame"/> so a language change can re-apply it
|
||||
/// without restarting the backdrop fade or preview music.
|
||||
/// </summary>
|
||||
private void UpdateSelectedGameTexts()
|
||||
{
|
||||
if (GameList.SelectedItem is GameEntry game)
|
||||
{
|
||||
SelectedGameTitle.Text = game.Name;
|
||||
SelectedGamePath.Text = game.Path;
|
||||
}
|
||||
else
|
||||
{
|
||||
SelectedGameTitle.Text = Localization.Instance.Get("Launch.NoGameSelected");
|
||||
SelectedGamePath.Text = Localization.Instance.Get("Launch.NoGameHint");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loops the selected game's sce_sys/snd0.at9 preview music, console
|
||||
/// home screen style. Silent while a game is running or when disabled
|
||||
@@ -926,9 +1263,8 @@ public partial class MainWindow : Window
|
||||
}
|
||||
}
|
||||
|
||||
private void OnTitleMusicToggled()
|
||||
private void OnTitleMusicSettingChanged()
|
||||
{
|
||||
_settings.PlayTitleMusic = TitleMusicToggle.IsChecked == true;
|
||||
if (!_settings.PlayTitleMusic)
|
||||
{
|
||||
_sndPreview.Stop();
|
||||
@@ -1001,11 +1337,12 @@ public partial class MainWindow : Window
|
||||
{
|
||||
var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
|
||||
{
|
||||
Title = "Open an executable to launch",
|
||||
Title = Localization.Instance.Get("Dialog.OpenExecutable"),
|
||||
AllowMultiple = false,
|
||||
FileTypeFilter = new[]
|
||||
{
|
||||
new FilePickerFileType("PS executables") { Patterns = new[] { "eboot.bin", "*.bin", "*.self", "*.elf" } },
|
||||
new FilePickerFileType(Localization.Instance.Get("Dialog.PsExecutables"))
|
||||
{ Patterns = new[] { "eboot.bin", "*.bin", "*.self", "*.elf" } },
|
||||
FilePickerFileTypes.All,
|
||||
},
|
||||
});
|
||||
@@ -1037,14 +1374,12 @@ public partial class MainWindow : Window
|
||||
LocateEmulator();
|
||||
if (_emulatorExePath is null)
|
||||
{
|
||||
AppendConsoleLine("SharpEmu executable not found. Build the SharpEmu.CLI project first (dotnet build).", ErrorLineBrush);
|
||||
AppendConsoleLine(Localization.Instance.Get("Launch.ExeNotFound"), ErrorLineBrush);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_sndPreview.Stop();
|
||||
ReadControlsIntoSettings();
|
||||
_settings.Save();
|
||||
|
||||
var arguments = new List<string>
|
||||
{
|
||||
@@ -1061,13 +1396,10 @@ public partial class MainWindow : Window
|
||||
arguments.Add($"--trace-imports={_settings.ImportTraceLimit}");
|
||||
}
|
||||
|
||||
arguments.Add(ebootPath);
|
||||
|
||||
_consoleLines.Clear();
|
||||
ConsoleToggle.IsChecked = true;
|
||||
|
||||
// Mirror everything the console pane shows into a log file for the
|
||||
// duration of the run, regardless of the emulator's log level.
|
||||
// Let the CLI mirror stdout/stderr itself; it sees loader/native
|
||||
// diagnostics before the GUI pipe reader can filter or batch them.
|
||||
DropFileLog();
|
||||
if (_settings.LogToFile)
|
||||
{
|
||||
@@ -1105,19 +1437,35 @@ public partial class MainWindow : Window
|
||||
|
||||
if (!string.IsNullOrEmpty(filePath))
|
||||
{
|
||||
try
|
||||
{
|
||||
_fileLog = new StreamWriter(filePath, append: false);
|
||||
AppendConsoleLine($"Log file: {filePath}", DimLineBrush);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppendConsoleLine($"Could not open the log file: {ex.Message}", WarningLineBrush);
|
||||
}
|
||||
arguments.Add("--log-file");
|
||||
arguments.Add(filePath);
|
||||
AppendConsoleLine(Localization.Instance.Format("Launch.LogFile", filePath), DimLineBrush);
|
||||
}
|
||||
}
|
||||
|
||||
AppendConsoleLine($"$ SharpEmu {string.Join(' ', arguments)}", DimLineBrush);
|
||||
arguments.Add(ebootPath);
|
||||
|
||||
AppendConsoleLine(
|
||||
Localization.Instance.Format("Launch.Command", string.Join(' ', arguments)),
|
||||
DimLineBrush);
|
||||
|
||||
// Apply the enabled switches to this process; both emulator launch paths
|
||||
// (CreateProcessW and Process.Start) inherit it. Clear switches turned
|
||||
// off since the previous launch.
|
||||
foreach (var staleName in _appliedEnvironmentVariables)
|
||||
{
|
||||
if (!_settings.EnvironmentToggles.Contains(staleName))
|
||||
{
|
||||
Environment.SetEnvironmentVariable(staleName, null);
|
||||
}
|
||||
}
|
||||
|
||||
_appliedEnvironmentVariables.Clear();
|
||||
foreach (var name in _settings.EnvironmentToggles)
|
||||
{
|
||||
Environment.SetEnvironmentVariable(name, "1");
|
||||
_appliedEnvironmentVariables.Add(name);
|
||||
}
|
||||
|
||||
var emulator = new EmulatorProcess();
|
||||
emulator.OutputReceived += (line, isError) => _pendingLines.Enqueue((line, isError));
|
||||
@@ -1130,7 +1478,7 @@ public partial class MainWindow : Window
|
||||
catch (Exception ex)
|
||||
{
|
||||
emulator.Dispose();
|
||||
AppendConsoleLine($"Failed to start the emulator: {ex.Message}", ErrorLineBrush);
|
||||
AppendConsoleLine(Localization.Instance.Format("Launch.StartFailed", ex.Message), ErrorLineBrush);
|
||||
DropFileLog();
|
||||
return;
|
||||
}
|
||||
@@ -1143,8 +1491,8 @@ public partial class MainWindow : Window
|
||||
.TitleId;
|
||||
_runningSinceUnixSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
StatusDot.Fill = SuccessLineBrush;
|
||||
StatusText.Text = $"Running — {displayName}";
|
||||
StatusBarRight.Text = $"Running {displayName}";
|
||||
StatusText.Text = Localization.Instance.Format("Launch.Running", displayName);
|
||||
StatusBarRight.Text = Localization.Instance.Format("Status.Running", displayName);
|
||||
UpdateRunButtons();
|
||||
UpdateDiscordPresence();
|
||||
}
|
||||
@@ -1166,8 +1514,8 @@ public partial class MainWindow : Window
|
||||
_emulator?.Stop();
|
||||
_runningGameName = null;
|
||||
_runningGameTitleId = null;
|
||||
StatusText.Text = "Stopping…";
|
||||
StatusBarRight.Text = "Stopping…";
|
||||
StatusText.Text = Localization.Instance.Get("Launch.Stopping");
|
||||
StatusBarRight.Text = Localization.Instance.Get("Status.Stopping");
|
||||
UpdateDiscordPresence();
|
||||
}
|
||||
|
||||
@@ -1209,22 +1557,24 @@ public partial class MainWindow : Window
|
||||
_emulator?.Dispose();
|
||||
_emulator = null;
|
||||
|
||||
var meaning = exitCode switch
|
||||
var meaningKey = exitCode switch
|
||||
{
|
||||
0 => "OK",
|
||||
1 => "invalid arguments",
|
||||
2 => "eboot not found",
|
||||
3 => "runtime exception",
|
||||
4 => "emulation error",
|
||||
_ => "unknown",
|
||||
0 => "Exit.Ok",
|
||||
1 => "Exit.InvalidArguments",
|
||||
2 => "Exit.EbootNotFound",
|
||||
3 => "Exit.RuntimeException",
|
||||
4 => "Exit.EmulationError",
|
||||
-1073741819 => "Exit.EmulationError",
|
||||
_ => "Exit.Unknown",
|
||||
};
|
||||
var meaning = Localization.Instance.Get(meaningKey);
|
||||
var brush = exitCode == 0 ? SuccessLineBrush : ErrorLineBrush;
|
||||
AppendConsoleLine($"Process exited with code {exitCode} ({meaning}).", brush);
|
||||
AppendConsoleLine(Localization.Instance.Format("Launch.ProcessExited", exitCode, meaning), brush);
|
||||
CloseFileLogSoon();
|
||||
|
||||
StatusDot.Fill = exitCode == 0 ? (IBrush)SuccessLineBrush : ErrorLineBrush;
|
||||
StatusText.Text = $"Exited with code {exitCode} ({meaning})";
|
||||
StatusBarRight.Text = "Idle";
|
||||
StatusText.Text = Localization.Instance.Format("Launch.Exited", exitCode, meaning);
|
||||
StatusBarRight.Text = Localization.Instance.Get("Status.Idle");
|
||||
_runningGameName = null;
|
||||
_runningGameTitleId = null;
|
||||
UpdateRunButtons();
|
||||
@@ -1238,27 +1588,6 @@ public partial class MainWindow : Window
|
||||
OpenFileButton.IsEnabled = !_isRunning;
|
||||
}
|
||||
|
||||
private async Task SelectFilePathAsync()
|
||||
{
|
||||
SaveFilePickerResult result = await StorageProvider.SaveFilePickerWithResultAsync(new FilePickerSaveOptions
|
||||
{
|
||||
Title = "Select where to save the Log file",
|
||||
SuggestedFileName = "SharpEmuLog",
|
||||
DefaultExtension = "log",
|
||||
FileTypeChoices =
|
||||
[
|
||||
new FilePickerFileType("Plain Text Files") { Patterns = ["*.txt"] },
|
||||
new FilePickerFileType("Log Files") { Patterns = ["*.log"] }
|
||||
]
|
||||
});
|
||||
|
||||
if (result.File is not null)
|
||||
{
|
||||
_settings.LogFilePath = result.File.Path.LocalPath;
|
||||
ToolTip.SetTip(SelectLogFilePathButton, _settings.LogFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Console ----
|
||||
|
||||
private void FlushPendingConsoleLines()
|
||||
@@ -1269,7 +1598,8 @@ public partial class MainWindow : Window
|
||||
}
|
||||
|
||||
var incoming = new List<LogLine>();
|
||||
while (_pendingLines.TryDequeue(out var pending))
|
||||
while (incoming.Count < MaxConsoleLinesPerFlush &&
|
||||
_pendingLines.TryDequeue(out var pending))
|
||||
{
|
||||
WriteFileLog(pending.Line);
|
||||
incoming.Add(new LogLine(pending.Line, BrushForLine(pending.Line)));
|
||||
|
||||
@@ -9,7 +9,9 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
the executable is started without arguments. -->
|
||||
<PropertyGroup>
|
||||
<GenerateDocumentationFile>false</GenerateDocumentationFile>
|
||||
<Version>0.0.1</Version>
|
||||
<!-- Required by the source-generated LibraryImport stubs in the linked
|
||||
controller readers below. -->
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Dependency-free; provides the BuildInfo provenance shown in the
|
||||
@@ -28,17 +30,27 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
<ItemGroup>
|
||||
<AvaloniaResource Include="..\..\assets\images\SharpEmu.ico" Link="Assets/SharpEmu.ico" />
|
||||
<AvaloniaResource Include="..\..\assets\images\github.png" Link="Assets/github.png" />
|
||||
<AvaloniaResource Include="..\..\assets\images\discord.png" Link="Assets/discord.png" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- The controller readers (DualSense raw HID + Xbox XInput) are shared
|
||||
with the emulator's pad HLE. They are dependency-free, so they are
|
||||
compiled in directly rather than pulling a reference to all of
|
||||
SharpEmu.Libs into the launcher. -->
|
||||
<ItemGroup>
|
||||
<Compile Include="..\SharpEmu.Libs\Pad\PadState.cs" Link="Input/PadState.cs" />
|
||||
<Compile Include="..\SharpEmu.Libs\Pad\HidNative.cs" Link="Input/HidNative.cs" />
|
||||
<Compile Include="..\SharpEmu.Libs\Pad\DualSenseReader.cs" Link="Input/DualSenseReader.cs" />
|
||||
<Compile Include="..\SharpEmu.Libs\Pad\XInputReader.cs" Link="Input/XInputReader.cs" />
|
||||
<EmbeddedResource Include="Languages\*.json">
|
||||
<LogicalName>Languages.%(Filename)%(Extension)</LogicalName>
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
|
||||
<!-- The controller readers (DualSense raw HID + Xbox XInput) are shared
|
||||
with the emulator's host input backend. They are dependency-free, so
|
||||
they are compiled in directly rather than pulling a reference to all
|
||||
of SharpEmu.HLE into the launcher. -->
|
||||
<ItemGroup>
|
||||
<Compile Include="..\SharpEmu.HLE\Host\HostGamepadState.cs" Link="Input/HostGamepadState.cs" />
|
||||
<Compile Include="..\SharpEmu.HLE\Host\Windows\WindowsHidNative.cs" Link="Input/WindowsHidNative.cs" />
|
||||
<Compile Include="..\SharpEmu.HLE\Host\Windows\WindowsDualSenseReader.cs" Link="Input/WindowsDualSenseReader.cs" />
|
||||
<Compile Include="..\SharpEmu.HLE\Host\Windows\WindowsXInputReader.cs" Link="Input/WindowsXInputReader.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -47,7 +47,7 @@ internal sealed class SndPreviewPlayer
|
||||
{
|
||||
// Debounce so skimming through the library does not decode (or
|
||||
// start) a preview per tile.
|
||||
await Task.Delay(300).ConfigureAwait(false);
|
||||
await Task.Delay(120).ConfigureAwait(false);
|
||||
|
||||
byte[]? wav;
|
||||
lock (_sync)
|
||||
|
||||
Binary file not shown.
@@ -1,6 +1,7 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Buffers;
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
|
||||
@@ -238,23 +239,63 @@ public sealed class CpuContext(ICpuMemory memory, Generation generation)
|
||||
return false;
|
||||
}
|
||||
|
||||
var bytes = new byte[capacity];
|
||||
for (var index = 0; index < bytes.Length; index++)
|
||||
const int StackBufferLength = 512;
|
||||
const int ReadChunkLength = 128;
|
||||
var rented = capacity > StackBufferLength ? ArrayPool<byte>.Shared.Rent(capacity) : null;
|
||||
Span<byte> bytes = rented is null ? stackalloc byte[StackBufferLength] : rented;
|
||||
try
|
||||
{
|
||||
if (!Memory.TryRead(address + (ulong)index, bytes.AsSpan(index, 1)))
|
||||
var length = 0;
|
||||
while (length < capacity)
|
||||
{
|
||||
return false;
|
||||
// Bulk-read in bounded chunks rather than the full capacity: the string
|
||||
// may end just before unmapped memory, and overreading past the
|
||||
// terminator by more than a chunk could fault where the old
|
||||
// byte-by-byte loop succeeded.
|
||||
var chunk = Math.Min(ReadChunkLength, capacity - length);
|
||||
var span = bytes.Slice(length, chunk);
|
||||
if (Memory.TryRead(address + (ulong)length, span))
|
||||
{
|
||||
var terminator = span.IndexOf((byte)0);
|
||||
if (terminator >= 0)
|
||||
{
|
||||
value = Encoding.UTF8.GetString(bytes[..(length + terminator)]);
|
||||
return true;
|
||||
}
|
||||
|
||||
length += chunk;
|
||||
continue;
|
||||
}
|
||||
|
||||
// The chunk touches an unreadable range; fall back to per-byte reads so a
|
||||
// terminator sitting before the bad byte still yields the string.
|
||||
for (var i = 0; i < chunk; i++)
|
||||
{
|
||||
if (!Memory.TryRead(address + (ulong)(length + i), bytes.Slice(length + i, 1)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (bytes[length + i] == 0)
|
||||
{
|
||||
value = Encoding.UTF8.GetString(bytes[..(length + i)]);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
length += chunk;
|
||||
}
|
||||
|
||||
if (bytes[index] == 0)
|
||||
value = Encoding.UTF8.GetString(bytes[..capacity]);
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (rented is not null)
|
||||
{
|
||||
value = Encoding.UTF8.GetString(bytes, 0, index);
|
||||
return true;
|
||||
ArrayPool<byte>.Shared.Return(rented);
|
||||
}
|
||||
}
|
||||
|
||||
value = Encoding.UTF8.GetString(bytes);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool PushUInt64(ulong value)
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE;
|
||||
|
||||
[Flags]
|
||||
public enum GuestPageProtection
|
||||
{
|
||||
None = 0,
|
||||
Read = 1,
|
||||
Write = 2,
|
||||
Execute = 4,
|
||||
}
|
||||
@@ -23,6 +23,20 @@ public readonly record struct GuestThreadSnapshot(
|
||||
ulong LastReturnRip,
|
||||
string? BlockReason);
|
||||
|
||||
/// <summary>
|
||||
/// Continuation state for a blocked guest thread, replacing the closure pair a blocking
|
||||
/// wait used to allocate. TryWake runs under the scheduler's guest-thread gate and
|
||||
/// returns true when the waiter has a final result and the thread should be re-readied;
|
||||
/// false leaves it parked. Resume runs later on the woken thread outside that gate, and
|
||||
/// its return value becomes the guest's RAX for the resumed call.
|
||||
/// </summary>
|
||||
public interface IGuestThreadBlockWaiter
|
||||
{
|
||||
int Resume();
|
||||
|
||||
bool TryWake();
|
||||
}
|
||||
|
||||
public interface IGuestThreadScheduler
|
||||
{
|
||||
bool SupportsGuestContextTransfer { get; }
|
||||
@@ -106,10 +120,7 @@ public static class GuestThreadExecution
|
||||
private static string? _pendingBlockWakeKey;
|
||||
|
||||
[ThreadStatic]
|
||||
private static Func<int>? _pendingBlockResumeHandler;
|
||||
|
||||
[ThreadStatic]
|
||||
private static Func<bool>? _pendingBlockWakeHandler;
|
||||
private static IGuestThreadBlockWaiter? _pendingBlockWaiter;
|
||||
|
||||
[ThreadStatic]
|
||||
private static long _pendingBlockDeadlineTimestamp;
|
||||
@@ -157,8 +168,7 @@ public static class GuestThreadExecution
|
||||
_pendingBlockContinuationValid = false;
|
||||
_pendingBlockContinuation = default;
|
||||
_pendingBlockWakeKey = null;
|
||||
_pendingBlockResumeHandler = null;
|
||||
_pendingBlockWakeHandler = null;
|
||||
_pendingBlockWaiter = null;
|
||||
_pendingBlockDeadlineTimestamp = 0;
|
||||
_pendingEntryExit = false;
|
||||
_pendingEntryExitValue = 0;
|
||||
@@ -179,8 +189,7 @@ public static class GuestThreadExecution
|
||||
_pendingBlockContinuationValid = false;
|
||||
_pendingBlockContinuation = default;
|
||||
_pendingBlockWakeKey = null;
|
||||
_pendingBlockResumeHandler = null;
|
||||
_pendingBlockWakeHandler = null;
|
||||
_pendingBlockWaiter = null;
|
||||
_pendingBlockDeadlineTimestamp = 0;
|
||||
_pendingEntryExit = false;
|
||||
_pendingEntryExitValue = 0;
|
||||
@@ -211,8 +220,7 @@ public static class GuestThreadExecution
|
||||
CpuContext? context,
|
||||
string reason,
|
||||
string? wakeKey = null,
|
||||
Func<int>? resumeHandler = null,
|
||||
Func<bool>? wakeHandler = null,
|
||||
IGuestThreadBlockWaiter? waiter = null,
|
||||
long blockDeadlineTimestamp = 0)
|
||||
{
|
||||
if (!IsGuestThread)
|
||||
@@ -222,8 +230,7 @@ public static class GuestThreadExecution
|
||||
|
||||
_pendingBlockReason = string.IsNullOrWhiteSpace(reason) ? "guest_thread_blocked" : reason;
|
||||
_pendingBlockWakeKey = string.IsNullOrWhiteSpace(wakeKey) ? _pendingBlockReason : wakeKey;
|
||||
_pendingBlockResumeHandler = resumeHandler;
|
||||
_pendingBlockWakeHandler = wakeHandler;
|
||||
_pendingBlockWaiter = waiter;
|
||||
_pendingBlockDeadlineTimestamp = blockDeadlineTimestamp;
|
||||
if (context is not null && TryCaptureCurrentBlockContinuation(context, out var continuation))
|
||||
{
|
||||
@@ -255,7 +262,6 @@ public static class GuestThreadExecution
|
||||
out hasContinuation,
|
||||
out _,
|
||||
out _,
|
||||
out _,
|
||||
out _);
|
||||
}
|
||||
|
||||
@@ -264,16 +270,14 @@ public static class GuestThreadExecution
|
||||
out GuestCpuContinuation continuation,
|
||||
out bool hasContinuation,
|
||||
out string wakeKey,
|
||||
out Func<int>? resumeHandler,
|
||||
out Func<bool>? wakeHandler)
|
||||
out IGuestThreadBlockWaiter? waiter)
|
||||
{
|
||||
return TryConsumeCurrentThreadBlock(
|
||||
out reason,
|
||||
out continuation,
|
||||
out hasContinuation,
|
||||
out wakeKey,
|
||||
out resumeHandler,
|
||||
out wakeHandler,
|
||||
out waiter,
|
||||
out _);
|
||||
}
|
||||
|
||||
@@ -282,8 +286,7 @@ public static class GuestThreadExecution
|
||||
out GuestCpuContinuation continuation,
|
||||
out bool hasContinuation,
|
||||
out string wakeKey,
|
||||
out Func<int>? resumeHandler,
|
||||
out Func<bool>? wakeHandler,
|
||||
out IGuestThreadBlockWaiter? waiter,
|
||||
out long blockDeadlineTimestamp)
|
||||
{
|
||||
reason = _pendingBlockReason ?? string.Empty;
|
||||
@@ -292,8 +295,7 @@ public static class GuestThreadExecution
|
||||
continuation = default;
|
||||
hasContinuation = false;
|
||||
wakeKey = string.Empty;
|
||||
resumeHandler = null;
|
||||
wakeHandler = null;
|
||||
waiter = null;
|
||||
blockDeadlineTimestamp = 0;
|
||||
return false;
|
||||
}
|
||||
@@ -301,15 +303,13 @@ public static class GuestThreadExecution
|
||||
continuation = _pendingBlockContinuation;
|
||||
hasContinuation = _pendingBlockContinuationValid;
|
||||
wakeKey = _pendingBlockWakeKey ?? reason;
|
||||
resumeHandler = _pendingBlockResumeHandler;
|
||||
wakeHandler = _pendingBlockWakeHandler;
|
||||
waiter = _pendingBlockWaiter;
|
||||
blockDeadlineTimestamp = _pendingBlockDeadlineTimestamp;
|
||||
_pendingBlockReason = null;
|
||||
_pendingBlockContinuation = default;
|
||||
_pendingBlockContinuationValid = false;
|
||||
_pendingBlockWakeKey = null;
|
||||
_pendingBlockResumeHandler = null;
|
||||
_pendingBlockWakeHandler = null;
|
||||
_pendingBlockWaiter = null;
|
||||
_pendingBlockDeadlineTimestamp = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host;
|
||||
|
||||
/// <summary>
|
||||
/// General-purpose register snapshot of a suspended thread, produced by
|
||||
/// <see cref="IHostThreading.TryCaptureThreadRegisters"/>. Registers are named
|
||||
/// after the guest ISA (x86-64), which every supported host executes natively.
|
||||
/// </summary>
|
||||
public readonly record struct HostCapturedRegisters(
|
||||
ulong Rip,
|
||||
ulong Rsp,
|
||||
ulong Rbp,
|
||||
ulong Rax,
|
||||
ulong Rbx,
|
||||
ulong Rcx,
|
||||
ulong Rdx);
|
||||
@@ -0,0 +1,46 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host;
|
||||
|
||||
/// <summary>
|
||||
/// Host-neutral gamepad button flags. Named after the PlayStation layout the guest API
|
||||
/// exposes, but the numeric values are the seam's own — the HLE pad exports translate
|
||||
/// them to SCE_PAD_BUTTON bits, so guest ABI values never leak into host backends.
|
||||
/// </summary>
|
||||
[Flags]
|
||||
public enum HostGamepadButtons : uint
|
||||
{
|
||||
None = 0,
|
||||
Up = 1 << 0,
|
||||
Down = 1 << 1,
|
||||
Left = 1 << 2,
|
||||
Right = 1 << 3,
|
||||
Cross = 1 << 4,
|
||||
Circle = 1 << 5,
|
||||
Square = 1 << 6,
|
||||
Triangle = 1 << 7,
|
||||
L1 = 1 << 8,
|
||||
R1 = 1 << 9,
|
||||
L2 = 1 << 10,
|
||||
R2 = 1 << 11,
|
||||
L3 = 1 << 12,
|
||||
R3 = 1 << 13,
|
||||
Options = 1 << 14,
|
||||
TouchPad = 1 << 15,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Snapshot of one host gamepad: sticks are 0..255 with 128 centered and Y growing
|
||||
/// downward; triggers 0..255. Unmanaged on purpose so per-frame polls can stackalloc
|
||||
/// snapshot buffers.
|
||||
/// </summary>
|
||||
public readonly record struct HostGamepadState(
|
||||
bool Connected,
|
||||
HostGamepadButtons Buttons,
|
||||
byte LeftX,
|
||||
byte LeftY,
|
||||
byte RightX,
|
||||
byte RightY,
|
||||
byte LeftTrigger,
|
||||
byte RightTrigger);
|
||||
@@ -0,0 +1,20 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host;
|
||||
|
||||
/// <summary>
|
||||
/// Platform-neutral page protection. Values intentionally enumerate the exact
|
||||
/// combinations the emulator uses today so each maps 1:1 onto a single native
|
||||
/// protection constant (PAGE_* on Windows, PROT_* elsewhere).
|
||||
/// </summary>
|
||||
public enum HostPageProtection
|
||||
{
|
||||
NoAccess,
|
||||
ReadOnly,
|
||||
ReadWrite,
|
||||
Execute,
|
||||
ReadExecute,
|
||||
ReadWriteExecute,
|
||||
ExecuteWriteCopy,
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
using SharpEmu.HLE.Host.Posix;
|
||||
using SharpEmu.HLE.Host.Windows;
|
||||
|
||||
namespace SharpEmu.HLE.Host;
|
||||
|
||||
/// <summary>
|
||||
/// Process-wide access point for the host platform backend. Static HLE export
|
||||
/// classes (which cannot receive constructor injection) resolve host primitives
|
||||
/// through <see cref="Current"/>; injectable components should instead accept an
|
||||
/// <see cref="IHostPlatform"/> and merely default to this.
|
||||
/// </summary>
|
||||
public static class HostPlatform
|
||||
{
|
||||
private static readonly Lazy<IHostPlatform> Instance = new(Create);
|
||||
|
||||
public static IHostPlatform Current => Instance.Value;
|
||||
|
||||
private static IHostPlatform Create()
|
||||
{
|
||||
// The Windows backend executes guest x86-64 natively and emits x86-64
|
||||
// stubs, so a native ARM64 process must be rejected here rather than
|
||||
// crash undefined later (x64 processes under emulation report X64).
|
||||
if (OperatingSystem.IsWindows() && RuntimeInformation.ProcessArchitecture == Architecture.X64)
|
||||
{
|
||||
return new WindowsHostPlatform();
|
||||
}
|
||||
|
||||
if ((OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) &&
|
||||
RuntimeInformation.ProcessArchitecture == Architecture.X64)
|
||||
{
|
||||
return new PosixHostPlatform();
|
||||
}
|
||||
|
||||
throw new PlatformNotSupportedException(
|
||||
"SharpEmu native guest execution requires an x86-64 process on Windows, Linux, or macOS. " +
|
||||
"On Apple Silicon, use the osx-x64 build under Rosetta 2.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host;
|
||||
|
||||
/// <summary>
|
||||
/// Result of <see cref="IHostMemory.Query"/>. The Raw* fields carry the
|
||||
/// untranslated OS values so call sites migrated from direct VirtualQuery use
|
||||
/// keep comparing (and logging) the exact native words they did before;
|
||||
/// <see cref="State"/> and <see cref="Protection"/> are neutral views.
|
||||
/// </summary>
|
||||
public readonly record struct HostRegionInfo(
|
||||
ulong BaseAddress,
|
||||
ulong AllocationBase,
|
||||
ulong RegionSize,
|
||||
HostRegionState State,
|
||||
uint RawState,
|
||||
HostPageProtection Protection,
|
||||
uint RawProtection,
|
||||
uint RawAllocationProtection);
|
||||
@@ -0,0 +1,11 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host;
|
||||
|
||||
public enum HostRegionState
|
||||
{
|
||||
Free,
|
||||
Reserved,
|
||||
Committed,
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host;
|
||||
|
||||
/// <summary>
|
||||
/// Host functions whose addresses the execution engine bakes into emitted
|
||||
/// stubs (spin-waits, worker run loops, TLS reads). Enum-keyed rather than a
|
||||
/// free-form name lookup: each platform's emitters need their own specific
|
||||
/// functions, and this set is exactly what the current emitters consume.
|
||||
/// </summary>
|
||||
public enum HostRuntimeFunction
|
||||
{
|
||||
TlsGetValue,
|
||||
QueryPerformanceCounter,
|
||||
SwitchToThread,
|
||||
Sleep,
|
||||
WaitForSingleObject,
|
||||
SetEvent,
|
||||
ExitThread,
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host;
|
||||
|
||||
/// <summary>
|
||||
/// Host audio-output device access. The HLE audio exports convert guest submissions to
|
||||
/// interleaved stereo 16-bit PCM (the format every backend accepts) and feed them through
|
||||
/// streams opened here; everything device-specific — queueing, backpressure, native
|
||||
/// buffer lifetime — lives behind <see cref="IHostAudioStream"/>.
|
||||
/// </summary>
|
||||
public interface IHostAudioOutput
|
||||
{
|
||||
/// <summary>Backend identifier for diagnostics (e.g. "winmm").</summary>
|
||||
string BackendName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Opens an interleaved stereo 16-bit PCM output stream at the given sample rate.
|
||||
/// Throws when the host has no usable output device; callers degrade to a silent
|
||||
/// port and pace the guest instead.
|
||||
/// </summary>
|
||||
IHostAudioStream OpenStereoPcm16Stream(uint sampleRate);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host;
|
||||
|
||||
/// <summary>
|
||||
/// One open host audio output stream. Submissions are interleaved stereo 16-bit PCM at
|
||||
/// the sample rate the stream was opened with.
|
||||
/// </summary>
|
||||
public interface IHostAudioStream : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Submits one buffer. May block briefly while the device drains its queue (this is
|
||||
/// what paces the guest's audio loop); returns false when the stream cannot accept
|
||||
/// audio, in which case the caller paces the guest itself.
|
||||
/// </summary>
|
||||
bool Submit(ReadOnlySpan<byte> stereoPcm16);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host;
|
||||
|
||||
/// <summary>
|
||||
/// Installation mechanics for the process-wide fault interception the execution
|
||||
/// engine relies on to catch guest faults. Deliberately thin: the managed
|
||||
/// handlers keep receiving the platform's raw exception data, and the emitted
|
||||
/// pre-filter thunk is an opaque per-platform unit. Implementations live next
|
||||
/// to the execution backend (SharpEmu.Core), not behind HostPlatform.Current.
|
||||
/// </summary>
|
||||
public interface IHostFaultHandling
|
||||
{
|
||||
/// <summary>
|
||||
/// Emits the native thunk that wraps a managed fault handler: it pre-filters
|
||||
/// exception codes that must never enter managed code and, when the fault
|
||||
/// happened on a guest stack, switches to the host stack saved in
|
||||
/// <paramref name="hostRspSwitchTlsSlot"/> before the call. Returns 0 on failure.
|
||||
/// </summary>
|
||||
nint CreateHandlerThunk(nint managedCallback, uint hostRspSwitchTlsSlot, nint tlsGetValueAddress);
|
||||
|
||||
void FreeThunk(nint thunk);
|
||||
|
||||
/// <summary>Installs a first-chance handler ahead of existing ones; returns a removal handle (0 on failure).</summary>
|
||||
nint AddFirstChanceHandler(nint thunk);
|
||||
|
||||
void RemoveHandler(nint handle);
|
||||
|
||||
/// <summary>Installs the last-resort filter; pass 0 to clear.</summary>
|
||||
void SetUnhandledFilter(nint thunk);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host;
|
||||
|
||||
/// <summary>
|
||||
/// Host input devices: gamepad state snapshots, force-feedback/lightbar sinks, and the
|
||||
/// keyboard-fallback queries. Which physical readers exist (DualSense over raw HID,
|
||||
/// XInput, evdev, ...) is a backend detail; merge policy between devices and the
|
||||
/// keyboard lives in the HLE pad exports.
|
||||
/// </summary>
|
||||
public interface IHostInput
|
||||
{
|
||||
/// <summary>Starts the background device readers once; safe to call repeatedly.</summary>
|
||||
void EnsureStarted();
|
||||
|
||||
/// <summary>
|
||||
/// Fills <paramref name="destination"/> with snapshots of currently connected
|
||||
/// gamepads and returns how many were written (0 when none are connected).
|
||||
/// </summary>
|
||||
int GetGamepadStates(Span<HostGamepadState> destination);
|
||||
|
||||
/// <summary>Human-readable name of the first connected gamepad, or null.</summary>
|
||||
string? DescribeConnectedGamepad();
|
||||
|
||||
/// <summary>Sets rumble on all connected gamepads; large = strong/left motor.</summary>
|
||||
void SetRumble(byte largeMotor, byte smallMotor);
|
||||
|
||||
/// <summary>
|
||||
/// Approximates per-trigger vibration on gamepads without independent trigger
|
||||
/// actuators; null leaves that trigger's current value unchanged.
|
||||
/// </summary>
|
||||
void SetTriggerRumble(byte? leftTrigger, byte? rightTrigger);
|
||||
|
||||
void SetLightbar(byte red, byte green, byte blue);
|
||||
|
||||
void ResetLightbar();
|
||||
|
||||
/// <summary>True when a window of this process has keyboard focus.</summary>
|
||||
bool IsHostWindowFocused();
|
||||
|
||||
/// <summary>Windows virtual-key code semantics; other backends translate.</summary>
|
||||
bool IsKeyDown(int virtualKey);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host;
|
||||
|
||||
/// <summary>
|
||||
/// Host page-allocation primitives used by the native execution engine.
|
||||
/// Allocate/Reserve/Commit are deliberately separate members (rather than a
|
||||
/// flags parameter) so every call site maps 1:1 onto the exact native call it
|
||||
/// replaced, keeping the Windows behavior byte-for-byte identical.
|
||||
/// </summary>
|
||||
public interface IHostMemory
|
||||
{
|
||||
/// <summary>
|
||||
/// Reserves and commits pages in one step. <paramref name="desiredAddress"/> of 0
|
||||
/// lets the OS choose the address. Returns the base address, or 0 on failure.
|
||||
/// The OS may satisfy the request at a different address than desired; callers
|
||||
/// that require an exact placement must check the result themselves.
|
||||
/// </summary>
|
||||
ulong Allocate(ulong desiredAddress, ulong size, HostPageProtection protection);
|
||||
|
||||
/// <summary>Reserves address space without committing pages (lazy regions).</summary>
|
||||
ulong Reserve(ulong desiredAddress, ulong size, HostPageProtection protection);
|
||||
|
||||
/// <summary>Commits pages inside a previously reserved range (fault-path lazy commit).</summary>
|
||||
bool Commit(ulong address, ulong size, HostPageProtection protection);
|
||||
|
||||
/// <summary>Releases an entire allocation or reservation by its base address.</summary>
|
||||
bool Free(ulong address);
|
||||
|
||||
/// <summary>
|
||||
/// Changes protection on committed pages. <paramref name="rawOldProtection"/> is the
|
||||
/// untranslated previous OS protection value (see <see cref="HostRegionInfo.RawProtection"/>).
|
||||
/// </summary>
|
||||
bool Protect(ulong address, ulong size, HostPageProtection protection, out uint rawOldProtection);
|
||||
|
||||
/// <summary>
|
||||
/// Restores a raw protection value previously returned by <see cref="Protect"/> or
|
||||
/// <see cref="Query"/> on this same platform. Raw values are opaque to callers and
|
||||
/// must never cross platforms; this exists so save/restore protection sequences
|
||||
/// round-trip OS-specific modifier bits the neutral enum cannot represent.
|
||||
/// </summary>
|
||||
bool ProtectRaw(ulong address, ulong size, uint rawProtection, out uint rawOldProtection);
|
||||
|
||||
bool Query(ulong address, out HostRegionInfo info);
|
||||
|
||||
void FlushInstructionCache(ulong address, ulong size);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host;
|
||||
|
||||
/// <summary>
|
||||
/// Aggregates the host-OS primitives the native execution engine depends on.
|
||||
/// Each supported platform provides one implementation; consumers reach the
|
||||
/// process-wide instance through <see cref="HostPlatform.Current"/> or accept
|
||||
/// one by injection.
|
||||
/// </summary>
|
||||
public interface IHostPlatform
|
||||
{
|
||||
IHostMemory Memory { get; }
|
||||
|
||||
IHostThreading Threading { get; }
|
||||
|
||||
IHostSymbolResolver Symbols { get; }
|
||||
|
||||
IHostAudioOutput Audio { get; }
|
||||
|
||||
IHostInput Input { get; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host;
|
||||
|
||||
public interface IHostSymbolResolver
|
||||
{
|
||||
/// <summary>Returns the native address of the function, or 0 if unavailable.</summary>
|
||||
nint GetAddress(HostRuntimeFunction function);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host;
|
||||
|
||||
/// <summary>
|
||||
/// Raw host thread and native-TLS primitives for the execution engine. Guest
|
||||
/// code must run on threads the CLR did not create (no managed frames below
|
||||
/// guest frames), so thread creation takes a native entry point and is not
|
||||
/// expressible with managed threads.
|
||||
/// </summary>
|
||||
public interface IHostThreading
|
||||
{
|
||||
/// <summary>Allocates a native TLS slot; returns <see cref="uint.MaxValue"/> on failure.</summary>
|
||||
uint AllocateTlsSlot();
|
||||
|
||||
bool FreeTlsSlot(uint slot);
|
||||
|
||||
bool SetTlsValue(uint slot, nint value);
|
||||
|
||||
nint GetTlsValue(uint slot);
|
||||
|
||||
uint CurrentThreadId { get; }
|
||||
|
||||
bool TrySetCurrentThreadAffinity(nuint affinityMask);
|
||||
|
||||
/// <summary>
|
||||
/// Asks the OS for ~1 ms timed-wait granularity for the life of the process
|
||||
/// (idempotent; best-effort). No-op on platforms whose default is already fine.
|
||||
/// </summary>
|
||||
void RequestTimerResolution();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a raw OS thread executing native code at <paramref name="entry"/> with
|
||||
/// <paramref name="stackReserveBytes"/> of reserved (not committed) stack.
|
||||
/// Returns the thread handle, or 0 on failure.
|
||||
/// </summary>
|
||||
nint CreateNativeThread(nint entry, nint parameter, nuint stackReserveBytes, out uint threadId);
|
||||
|
||||
/// <summary>Waits for the thread to exit; true when it did within the timeout.</summary>
|
||||
bool WaitForThreadExit(nint threadHandle, uint timeoutMilliseconds);
|
||||
|
||||
void CloseThreadHandle(nint threadHandle);
|
||||
|
||||
/// <summary>
|
||||
/// Suspends the thread, snapshots its general-purpose registers, and resumes it —
|
||||
/// one indivisible operation (diagnostics only). The caller must not pass the
|
||||
/// current thread. Returns false if the thread cannot be opened or suspended.
|
||||
/// </summary>
|
||||
bool TryCaptureThreadRegisters(uint threadId, out HostCapturedRegisters registers);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SharpEmu.HLE.Host.Posix;
|
||||
|
||||
/// <summary>
|
||||
/// ALSA-based playback for Linux. The PCM device is opened in blocking mode
|
||||
/// with a device buffer sized to match the 32KB queue the other backends
|
||||
/// keep, so snd_pcm_writei itself provides the backpressure pacing. The
|
||||
/// "default" device routes through PulseAudio/PipeWire on desktops and to
|
||||
/// the hardware on bare ALSA setups; SHARPEMU_ALSA_DEVICE overrides it.
|
||||
/// </summary>
|
||||
internal sealed unsafe class PosixAlsaAudioStream : IHostAudioStream
|
||||
{
|
||||
// 32KB of stereo PCM16 at 48kHz is ~170ms; keep the same device-side
|
||||
// queue depth the WinMM/CoreAudio ports enforce in managed code.
|
||||
private const uint DeviceLatencyMicroseconds = 170_000;
|
||||
private const int StreamPlayback = 0;
|
||||
private const int FormatS16LittleEndian = 2;
|
||||
private const int AccessReadWriteInterleaved = 3;
|
||||
private const int ErrorPipe = -32; // -EPIPE, underrun
|
||||
private const int ErrorStreamPipe = -86; // -ESTRPIPE, suspended
|
||||
|
||||
private readonly object _gate = new();
|
||||
private nint _pcm;
|
||||
private bool _disposed;
|
||||
|
||||
public PosixAlsaAudioStream(uint sampleRate)
|
||||
{
|
||||
if (!OperatingSystem.IsLinux())
|
||||
{
|
||||
throw new PlatformNotSupportedException("ALSA audio is only available on Linux.");
|
||||
}
|
||||
|
||||
var device = Environment.GetEnvironmentVariable("SHARPEMU_ALSA_DEVICE");
|
||||
if (string.IsNullOrWhiteSpace(device))
|
||||
{
|
||||
device = "default";
|
||||
}
|
||||
|
||||
var status = snd_pcm_open(out _pcm, device, StreamPlayback, 0);
|
||||
if (status != 0)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"snd_pcm_open(\"{device}\") failed: {DescribeError(status)}.");
|
||||
}
|
||||
|
||||
status = snd_pcm_set_params(
|
||||
_pcm,
|
||||
FormatS16LittleEndian,
|
||||
AccessReadWriteInterleaved,
|
||||
2,
|
||||
sampleRate,
|
||||
1,
|
||||
DeviceLatencyMicroseconds);
|
||||
if (status != 0)
|
||||
{
|
||||
_ = snd_pcm_close(_pcm);
|
||||
_pcm = 0;
|
||||
throw new InvalidOperationException(
|
||||
$"snd_pcm_set_params({sampleRate} Hz) failed: {DescribeError(status)}.");
|
||||
}
|
||||
}
|
||||
|
||||
public bool Submit(ReadOnlySpan<byte> stereoPcm16)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return WritePcm(stereoPcm16, (uint)(stereoPcm16.Length / 4));
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
if (_pcm != 0)
|
||||
{
|
||||
_ = snd_pcm_drop(_pcm);
|
||||
_ = snd_pcm_close(_pcm);
|
||||
_pcm = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bool WritePcm(ReadOnlySpan<byte> pcm, uint frames)
|
||||
{
|
||||
var recovered = false;
|
||||
fixed (byte* data = pcm)
|
||||
{
|
||||
var offset = 0L;
|
||||
while (offset < frames)
|
||||
{
|
||||
var written = snd_pcm_writei(
|
||||
_pcm,
|
||||
data + (offset * 4),
|
||||
(nuint)(frames - offset));
|
||||
if (written >= 0)
|
||||
{
|
||||
offset += written;
|
||||
continue;
|
||||
}
|
||||
|
||||
// One recovery attempt per submit covers underruns (-EPIPE)
|
||||
// and suspend/resume (-ESTRPIPE); anything else, or a second
|
||||
// failure, drops the buffer rather than stalling the guest.
|
||||
if (recovered ||
|
||||
(written != ErrorPipe && written != ErrorStreamPipe) ||
|
||||
snd_pcm_recover(_pcm, (int)written, 1) != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
recovered = true;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static string DescribeError(long status)
|
||||
{
|
||||
var message = Marshal.PtrToStringUTF8(snd_strerror((int)status));
|
||||
return $"{message ?? "unknown error"} ({status})";
|
||||
}
|
||||
|
||||
private const string Alsa = "libasound.so.2";
|
||||
|
||||
[DllImport(Alsa)]
|
||||
private static extern int snd_pcm_open(
|
||||
out nint pcm,
|
||||
[MarshalAs(UnmanagedType.LPUTF8Str)] string name,
|
||||
int stream,
|
||||
int mode);
|
||||
|
||||
[DllImport(Alsa)]
|
||||
private static extern int snd_pcm_set_params(
|
||||
nint pcm,
|
||||
int format,
|
||||
int access,
|
||||
uint channels,
|
||||
uint rate,
|
||||
int softResample,
|
||||
uint latencyUs);
|
||||
|
||||
[DllImport(Alsa)]
|
||||
private static extern long snd_pcm_writei(nint pcm, byte* buffer, nuint frames);
|
||||
|
||||
[DllImport(Alsa)]
|
||||
private static extern int snd_pcm_recover(nint pcm, int error, int silent);
|
||||
|
||||
[DllImport(Alsa)]
|
||||
private static extern int snd_pcm_drop(nint pcm);
|
||||
|
||||
[DllImport(Alsa)]
|
||||
private static extern int snd_pcm_close(nint pcm);
|
||||
|
||||
[DllImport(Alsa)]
|
||||
private static extern nint snd_strerror(int error);
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SharpEmu.HLE.Host.Posix;
|
||||
|
||||
/// <summary>
|
||||
/// AudioQueue-based playback for macOS. Buffers are enqueued as stereo PCM16
|
||||
/// and returned by the queue's internal thread through the output callback;
|
||||
/// Submit applies the same 32KB backpressure the WinMM backend uses so guest
|
||||
/// pacing works identically.
|
||||
/// </summary>
|
||||
internal sealed unsafe class PosixCoreAudioStream : IHostAudioStream
|
||||
{
|
||||
private const int MaximumQueuedPcmBytes = 32 * 1024;
|
||||
private const uint FormatLinearPcm = 0x6C70636D; // 'lpcm'
|
||||
private const uint FlagIsSignedInteger = 0x4;
|
||||
private const uint FlagIsPacked = 0x8;
|
||||
|
||||
private readonly object _gate = new();
|
||||
private readonly AutoResetEvent _completion = new(false);
|
||||
private readonly Queue<nint> _freeBuffers = new();
|
||||
private GCHandle _selfHandle;
|
||||
private nint _queue;
|
||||
private int _queuedPcmBytes;
|
||||
private bool _started;
|
||||
private bool _disposed;
|
||||
|
||||
public PosixCoreAudioStream(uint sampleRate)
|
||||
{
|
||||
if (!OperatingSystem.IsMacOS())
|
||||
{
|
||||
throw new PlatformNotSupportedException("CoreAudio is only available on macOS.");
|
||||
}
|
||||
|
||||
var format = new AudioStreamBasicDescription
|
||||
{
|
||||
SampleRate = sampleRate,
|
||||
FormatId = FormatLinearPcm,
|
||||
FormatFlags = FlagIsSignedInteger | FlagIsPacked,
|
||||
BytesPerPacket = 4,
|
||||
FramesPerPacket = 1,
|
||||
BytesPerFrame = 4,
|
||||
ChannelsPerFrame = 2,
|
||||
BitsPerChannel = 16,
|
||||
};
|
||||
|
||||
_selfHandle = GCHandle.Alloc(this);
|
||||
var status = AudioQueueNewOutput(
|
||||
&format,
|
||||
&OutputCallback,
|
||||
GCHandle.ToIntPtr(_selfHandle),
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
out _queue);
|
||||
if (status != 0)
|
||||
{
|
||||
_selfHandle.Free();
|
||||
throw new InvalidOperationException($"AudioQueueNewOutput failed with OSStatus {status}.");
|
||||
}
|
||||
}
|
||||
|
||||
public bool Submit(ReadOnlySpan<byte> stereoPcm16)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed || _queue == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var outputLength = stereoPcm16.Length;
|
||||
while (_queuedPcmBytes != 0 &&
|
||||
_queuedPcmBytes + outputLength > MaximumQueuedPcmBytes)
|
||||
{
|
||||
Monitor.Exit(_gate);
|
||||
try
|
||||
{
|
||||
// Dispose can free the event while this thread waits
|
||||
// outside the gate; treat that like a timed-out wait.
|
||||
if (!_completion.WaitOne(TimeSpan.FromSeconds(1)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Monitor.Enter(_gate);
|
||||
}
|
||||
|
||||
if (_disposed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!TryTakeBuffer(outputLength, out var buffer))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var audioData = ((AudioQueueBuffer*)buffer)->AudioData;
|
||||
stereoPcm16.CopyTo(new Span<byte>(audioData, outputLength));
|
||||
|
||||
((AudioQueueBuffer*)buffer)->AudioDataByteSize = (uint)outputLength;
|
||||
if (AudioQueueEnqueueBuffer(_queue, buffer, 0, 0) != 0)
|
||||
{
|
||||
_freeBuffers.Enqueue(buffer);
|
||||
return false;
|
||||
}
|
||||
|
||||
_queuedPcmBytes += outputLength;
|
||||
if (!_started)
|
||||
{
|
||||
if (AudioQueueStart(_queue, 0) != 0)
|
||||
{
|
||||
// A queue that never starts never drains, so later
|
||||
// submits would block on backpressure until their
|
||||
// timeout. Tear the queue down and fail fast instead.
|
||||
_ = AudioQueueDispose(_queue, true);
|
||||
_queue = 0;
|
||||
_queuedPcmBytes = 0;
|
||||
_freeBuffers.Clear();
|
||||
return false;
|
||||
}
|
||||
|
||||
_started = true;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
if (_queue != 0)
|
||||
{
|
||||
// Synchronous dispose stops the queue, frees its buffers, and
|
||||
// guarantees no further callbacks reference this instance.
|
||||
_ = AudioQueueDispose(_queue, true);
|
||||
_queue = 0;
|
||||
}
|
||||
|
||||
_freeBuffers.Clear();
|
||||
// Wake any submitter waiting on backpressure before the event
|
||||
// goes away; a late waiter observes ObjectDisposedException and
|
||||
// bails out in Submit.
|
||||
_completion.Set();
|
||||
_completion.Dispose();
|
||||
if (_selfHandle.IsAllocated)
|
||||
{
|
||||
_selfHandle.Free();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryTakeBuffer(int length, out nint buffer)
|
||||
{
|
||||
while (_freeBuffers.TryDequeue(out buffer))
|
||||
{
|
||||
if (((AudioQueueBuffer*)buffer)->AudioDataBytesCapacity >= (uint)length)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
_ = AudioQueueFreeBuffer(_queue, buffer);
|
||||
}
|
||||
|
||||
return AudioQueueAllocateBuffer(_queue, (uint)length, out buffer) == 0;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly]
|
||||
private static void OutputCallback(nint userData, nint queue, nint buffer)
|
||||
{
|
||||
if (GCHandle.FromIntPtr(userData).Target is not PosixCoreAudioStream port)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (port._gate)
|
||||
{
|
||||
if (port._disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
port._queuedPcmBytes -= checked((int)((AudioQueueBuffer*)buffer)->AudioDataByteSize);
|
||||
port._freeBuffers.Enqueue(buffer);
|
||||
}
|
||||
|
||||
port._completion.Set();
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct AudioStreamBasicDescription
|
||||
{
|
||||
public double SampleRate;
|
||||
public uint FormatId;
|
||||
public uint FormatFlags;
|
||||
public uint BytesPerPacket;
|
||||
public uint FramesPerPacket;
|
||||
public uint BytesPerFrame;
|
||||
public uint ChannelsPerFrame;
|
||||
public uint BitsPerChannel;
|
||||
public uint Reserved;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct AudioQueueBuffer
|
||||
{
|
||||
public uint AudioDataBytesCapacity;
|
||||
public void* AudioData;
|
||||
public uint AudioDataByteSize;
|
||||
public nint UserData;
|
||||
public uint PacketDescriptionCapacity;
|
||||
public nint PacketDescriptions;
|
||||
public uint PacketDescriptionCount;
|
||||
}
|
||||
|
||||
private const string AudioToolbox =
|
||||
"/System/Library/Frameworks/AudioToolbox.framework/AudioToolbox";
|
||||
|
||||
[DllImport(AudioToolbox)]
|
||||
private static extern int AudioQueueNewOutput(
|
||||
AudioStreamBasicDescription* format,
|
||||
delegate* unmanaged<nint, nint, nint, void> callback,
|
||||
nint userData,
|
||||
nint callbackRunLoop,
|
||||
nint runLoopMode,
|
||||
uint flags,
|
||||
out nint queue);
|
||||
|
||||
[DllImport(AudioToolbox)]
|
||||
private static extern int AudioQueueAllocateBuffer(nint queue, uint bufferByteSize, out nint buffer);
|
||||
|
||||
[DllImport(AudioToolbox)]
|
||||
private static extern int AudioQueueFreeBuffer(nint queue, nint buffer);
|
||||
|
||||
[DllImport(AudioToolbox)]
|
||||
private static extern int AudioQueueEnqueueBuffer(nint queue, nint buffer, uint packetDescriptionCount, nint packetDescriptions);
|
||||
|
||||
[DllImport(AudioToolbox)]
|
||||
private static extern int AudioQueueStart(nint queue, nint startTime);
|
||||
|
||||
[DllImport(AudioToolbox)]
|
||||
private static extern int AudioQueueDispose(nint queue, [MarshalAs(UnmanagedType.I1)] bool immediate);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host.Posix;
|
||||
|
||||
/// <summary>
|
||||
/// POSIX audio output: CoreAudio (AudioQueue) on macOS, ALSA on Linux. Both
|
||||
/// streams accept the seam's interleaved stereo PCM16 and pace the guest via
|
||||
/// device-queue backpressure.
|
||||
/// </summary>
|
||||
internal sealed class PosixHostAudio : IHostAudioOutput
|
||||
{
|
||||
public string BackendName => OperatingSystem.IsMacOS() ? "coreaudio" : "alsa";
|
||||
|
||||
public IHostAudioStream OpenStereoPcm16Stream(uint sampleRate)
|
||||
{
|
||||
return OperatingSystem.IsMacOS()
|
||||
? new PosixCoreAudioStream(sampleRate)
|
||||
: new PosixAlsaAudioStream(sampleRate);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host.Posix;
|
||||
|
||||
/// <summary>
|
||||
/// Bridges a window-provided input source into the host input seam. POSIX
|
||||
/// hosts have no user32/XInput/raw-HID readers; keyboard and gamepad state
|
||||
/// come from the presenter's GLFW window instead, which registers itself via
|
||||
/// <see cref="SetSource"/> once the window exists. Until then (and with no
|
||||
/// window at all, e.g. headless runs) every query reports neutral input.
|
||||
/// Rumble and lightbar are unsupported by the GLFW input layer and no-op.
|
||||
/// </summary>
|
||||
public interface IPosixWindowInputSource
|
||||
{
|
||||
/// <summary>True while the window's keyboard is delivering events.</summary>
|
||||
bool HasKeyboardFocus { get; }
|
||||
|
||||
/// <summary>Windows virtual-key semantics; the source translates.</summary>
|
||||
bool IsKeyDown(int virtualKey);
|
||||
|
||||
/// <summary>Same contract as <see cref="IHostInput.GetGamepadStates"/>.</summary>
|
||||
int GetGamepadStates(Span<HostGamepadState> destination);
|
||||
|
||||
string? DescribeConnectedGamepad();
|
||||
}
|
||||
|
||||
// Public so the presenter's window layer (SharpEmu.Libs) can register its
|
||||
// input source; the platform still constructs the singleton itself.
|
||||
public sealed class PosixHostInput : IHostInput
|
||||
{
|
||||
private static volatile IPosixWindowInputSource? _source;
|
||||
|
||||
/// <summary>Called by the presenter's window layer when input is ready.</summary>
|
||||
public static void SetSource(IPosixWindowInputSource source)
|
||||
{
|
||||
_source = source;
|
||||
}
|
||||
|
||||
public void EnsureStarted()
|
||||
{
|
||||
// Device readers are event-driven off the window thread; nothing to start.
|
||||
}
|
||||
|
||||
public int GetGamepadStates(Span<HostGamepadState> destination)
|
||||
{
|
||||
return _source?.GetGamepadStates(destination) ?? 0;
|
||||
}
|
||||
|
||||
public string? DescribeConnectedGamepad() => _source?.DescribeConnectedGamepad();
|
||||
|
||||
public void SetRumble(byte largeMotor, byte smallMotor)
|
||||
{
|
||||
}
|
||||
|
||||
public void SetTriggerRumble(byte? leftTrigger, byte? rightTrigger)
|
||||
{
|
||||
}
|
||||
|
||||
public void SetLightbar(byte red, byte green, byte blue)
|
||||
{
|
||||
}
|
||||
|
||||
public void ResetLightbar()
|
||||
{
|
||||
}
|
||||
|
||||
public bool IsHostWindowFocused()
|
||||
{
|
||||
// GLFW only delivers key events to the focused window, so a
|
||||
// delivering keyboard implies focus.
|
||||
return _source?.HasKeyboardFocus ?? false;
|
||||
}
|
||||
|
||||
public bool IsKeyDown(int virtualKey)
|
||||
{
|
||||
return _source?.IsKeyDown(virtualKey) ?? false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,508 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SharpEmu.HLE.Host.Posix;
|
||||
|
||||
/// <summary>
|
||||
/// POSIX virtual memory backend implemented over mmap/mprotect/munmap with a
|
||||
/// shadow region table that answers VirtualQuery-style questions and tracks
|
||||
/// page protections.
|
||||
/// POSIX anonymous mappings are demand-paged by the kernel, so Win32
|
||||
/// "reserve-only" regions are mapped as committed memory directly and
|
||||
/// commit requests become protection changes.
|
||||
/// </summary>
|
||||
internal sealed unsafe class PosixHostMemory : IHostMemory
|
||||
{
|
||||
private const uint MEM_COMMIT = 0x1000;
|
||||
private const uint MEM_RESERVE = 0x2000;
|
||||
private const uint MEM_RELEASE = 0x8000;
|
||||
private const uint MEM_FREE_STATE = 0x10000;
|
||||
private const uint MEM_PRIVATE = 0x20000;
|
||||
|
||||
private const uint PAGE_NOACCESS = 0x01;
|
||||
private const uint PAGE_READONLY = 0x02;
|
||||
private const uint PAGE_READWRITE = 0x04;
|
||||
private const uint PAGE_EXECUTE = 0x10;
|
||||
private const uint PAGE_EXECUTE_READ = 0x20;
|
||||
private const uint PAGE_EXECUTE_READWRITE = 0x40;
|
||||
|
||||
private const ulong PageSize = 0x1000;
|
||||
|
||||
private struct BasicInfo
|
||||
{
|
||||
public ulong BaseAddress;
|
||||
public ulong AllocationBase;
|
||||
public uint AllocationProtect;
|
||||
public ulong RegionSize;
|
||||
public uint State;
|
||||
public uint Protect;
|
||||
public uint Type;
|
||||
}
|
||||
|
||||
public ulong Allocate(ulong desiredAddress, ulong size, HostPageProtection protection)
|
||||
{
|
||||
return (ulong)Posix.Alloc(
|
||||
(void*)desiredAddress,
|
||||
(nuint)size,
|
||||
MEM_COMMIT | MEM_RESERVE,
|
||||
ToNativeProtection(protection));
|
||||
}
|
||||
|
||||
public ulong Reserve(ulong desiredAddress, ulong size, HostPageProtection protection)
|
||||
{
|
||||
return (ulong)Posix.Alloc(
|
||||
(void*)desiredAddress,
|
||||
(nuint)size,
|
||||
MEM_RESERVE,
|
||||
ToNativeProtection(protection));
|
||||
}
|
||||
|
||||
public bool Commit(ulong address, ulong size, HostPageProtection protection)
|
||||
{
|
||||
return Posix.Alloc(
|
||||
(void*)address,
|
||||
(nuint)size,
|
||||
MEM_COMMIT,
|
||||
ToNativeProtection(protection)) != null;
|
||||
}
|
||||
|
||||
public bool Free(ulong address)
|
||||
{
|
||||
return Posix.Free((void*)address, 0, MEM_RELEASE);
|
||||
}
|
||||
|
||||
public bool Protect(
|
||||
ulong address,
|
||||
ulong size,
|
||||
HostPageProtection protection,
|
||||
out uint rawOldProtection)
|
||||
{
|
||||
return Posix.Protect(
|
||||
(void*)address,
|
||||
(nuint)size,
|
||||
ToNativeProtection(protection),
|
||||
out rawOldProtection);
|
||||
}
|
||||
|
||||
public bool ProtectRaw(
|
||||
ulong address,
|
||||
ulong size,
|
||||
uint rawProtection,
|
||||
out uint rawOldProtection)
|
||||
{
|
||||
return Posix.Protect(
|
||||
(void*)address,
|
||||
(nuint)size,
|
||||
rawProtection,
|
||||
out rawOldProtection);
|
||||
}
|
||||
|
||||
public bool Query(ulong address, out HostRegionInfo info)
|
||||
{
|
||||
if (Posix.Query((void*)address, out var nativeInfo) == 0)
|
||||
{
|
||||
info = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
info = new HostRegionInfo(
|
||||
nativeInfo.BaseAddress,
|
||||
nativeInfo.AllocationBase,
|
||||
nativeInfo.RegionSize,
|
||||
nativeInfo.State switch
|
||||
{
|
||||
MEM_COMMIT => HostRegionState.Committed,
|
||||
MEM_RESERVE => HostRegionState.Reserved,
|
||||
_ => HostRegionState.Free,
|
||||
},
|
||||
nativeInfo.State,
|
||||
ToHostProtection(nativeInfo.Protect),
|
||||
nativeInfo.Protect,
|
||||
nativeInfo.AllocationProtect);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void FlushInstructionCache(ulong address, ulong size)
|
||||
{
|
||||
_ = address;
|
||||
_ = size;
|
||||
// The supported POSIX process is x86-64 (including Rosetta 2), whose
|
||||
// instruction cache is coherent. A future arm64 backend must call the
|
||||
// platform instruction-cache invalidation API here.
|
||||
}
|
||||
|
||||
private static uint ToNativeProtection(HostPageProtection protection) => protection switch
|
||||
{
|
||||
HostPageProtection.NoAccess => PAGE_NOACCESS,
|
||||
HostPageProtection.ReadOnly => PAGE_READONLY,
|
||||
HostPageProtection.ReadWrite => PAGE_READWRITE,
|
||||
HostPageProtection.Execute => PAGE_EXECUTE,
|
||||
HostPageProtection.ReadExecute => PAGE_EXECUTE_READ,
|
||||
HostPageProtection.ReadWriteExecute => PAGE_EXECUTE_READWRITE,
|
||||
HostPageProtection.ExecuteWriteCopy => PAGE_EXECUTE_READWRITE,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(protection), protection, null),
|
||||
};
|
||||
|
||||
private static HostPageProtection ToHostProtection(uint protection) => protection switch
|
||||
{
|
||||
PAGE_READONLY => HostPageProtection.ReadOnly,
|
||||
PAGE_READWRITE => HostPageProtection.ReadWrite,
|
||||
PAGE_EXECUTE => HostPageProtection.Execute,
|
||||
PAGE_EXECUTE_READ => HostPageProtection.ReadExecute,
|
||||
PAGE_EXECUTE_READWRITE => HostPageProtection.ReadWriteExecute,
|
||||
_ => HostPageProtection.NoAccess,
|
||||
};
|
||||
|
||||
private static class Posix
|
||||
{
|
||||
private const int PROT_NONE = 0x0;
|
||||
private const int PROT_READ = 0x1;
|
||||
private const int PROT_WRITE = 0x2;
|
||||
private const int PROT_EXEC = 0x4;
|
||||
|
||||
private const int MAP_PRIVATE = 0x02;
|
||||
private const int MAP_FIXED = 0x10;
|
||||
private static readonly int MAP_ANON = OperatingSystem.IsMacOS() ? 0x1000 : 0x20;
|
||||
private static readonly int MAP_NORESERVE = OperatingSystem.IsMacOS() ? 0 : 0x4000;
|
||||
|
||||
// Linux-only: fail instead of clobbering an existing mapping.
|
||||
private const int MAP_FIXED_NOREPLACE = 0x100000;
|
||||
|
||||
private static readonly nint MAP_FAILED = -1;
|
||||
|
||||
private static readonly object Gate = new();
|
||||
private static readonly SortedList<ulong, Region> Regions = new();
|
||||
|
||||
private sealed class Region
|
||||
{
|
||||
public ulong Base;
|
||||
public ulong Size;
|
||||
public uint DefaultProtect;
|
||||
public Dictionary<ulong, uint>? PageProtects;
|
||||
|
||||
public ulong End => Base + Size;
|
||||
|
||||
public uint ProtectAt(ulong pageAddress)
|
||||
{
|
||||
if (PageProtects is not null && PageProtects.TryGetValue(pageAddress, out var overriden))
|
||||
{
|
||||
return overriden;
|
||||
}
|
||||
|
||||
return DefaultProtect;
|
||||
}
|
||||
}
|
||||
|
||||
public static void* Alloc(void* address, nuint size, uint allocationType, uint protect)
|
||||
{
|
||||
if (size == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var alignedSize = AlignUp((ulong)size, PageSize);
|
||||
|
||||
lock (Gate)
|
||||
{
|
||||
if (allocationType == MEM_COMMIT && address != null &&
|
||||
TryFindRegionLocked((ulong)address, out var existing))
|
||||
{
|
||||
// Note: MEM_RESERVE requests that overlap an existing
|
||||
// region must fail like Win32 does; only a pure commit
|
||||
// may target pages inside a tracked mapping.
|
||||
// Commit inside an existing mapping: the pages are already
|
||||
// backed (demand paged), so only apply the protection.
|
||||
var start = AlignDown((ulong)address, PageSize);
|
||||
var end = AlignUp((ulong)address + alignedSize, PageSize);
|
||||
if (end <= start || end > existing.End)
|
||||
{
|
||||
// Win32 fails a commit that runs past its reservation
|
||||
// instead of committing a prefix; committing partially
|
||||
// here would let callers believe the whole range is
|
||||
// usable.
|
||||
return null;
|
||||
}
|
||||
|
||||
if (mprotect((nint)start, (nuint)(end - start), ToPosixProtect(protect)) != 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
SetProtectRangeLocked(existing, start, end - start, protect);
|
||||
return address;
|
||||
}
|
||||
|
||||
if ((allocationType & MEM_RESERVE) == 0)
|
||||
{
|
||||
// MEM_COMMIT alone outside any known region is invalid here.
|
||||
return null;
|
||||
}
|
||||
|
||||
var posixProtect = ToPosixProtect(protect);
|
||||
var flags = MAP_PRIVATE | MAP_ANON;
|
||||
if ((allocationType & MEM_COMMIT) == 0)
|
||||
{
|
||||
// Reserve-only: keep the requested protection so the region
|
||||
// is usable without a separate commit step, but tell the
|
||||
// kernel not to account swap for it where supported.
|
||||
flags |= MAP_NORESERVE;
|
||||
}
|
||||
|
||||
nint result;
|
||||
if (address != null)
|
||||
{
|
||||
// Win32 maps at exactly the requested address or fails
|
||||
// without touching existing mappings. Fail up front on
|
||||
// any overlap we track, then place the mapping: Linux
|
||||
// gets MAP_FIXED_NOREPLACE (fails cleanly on host
|
||||
// mappings too). Darwin lacks NOREPLACE and plain
|
||||
// MAP_FIXED would silently clobber untracked host
|
||||
// memory (dyld, the runtime's JIT heap, Rosetta), so
|
||||
// pass the address as a hint instead -- the kernel
|
||||
// honors it when the range is free and relocates the
|
||||
// mapping otherwise, which we treat as failure.
|
||||
if (OverlapsTrackedRegionLocked((ulong)address, alignedSize))
|
||||
{
|
||||
Trace($"exact overlap: addr=0x{(ulong)address:X16} size=0x{alignedSize:X}");
|
||||
return null;
|
||||
}
|
||||
|
||||
var exactFlags = OperatingSystem.IsMacOS() ? flags : flags | MAP_FIXED_NOREPLACE;
|
||||
result = mmap((nint)address, (nuint)alignedSize, posixProtect, exactFlags, -1, 0);
|
||||
if (result == MAP_FAILED || (ulong)result != (ulong)address)
|
||||
{
|
||||
Trace($"exact mmap failed: addr=0x{(ulong)address:X16} got=0x{(ulong)result:X16} size=0x{alignedSize:X} errno={Marshal.GetLastPInvokeError()}");
|
||||
if (result != MAP_FAILED)
|
||||
{
|
||||
munmap(result, (nuint)alignedSize);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
result = mmap(0, (nuint)alignedSize, posixProtect, flags, -1, 0);
|
||||
if (result == MAP_FAILED)
|
||||
{
|
||||
Trace($"mmap failed: size=0x{alignedSize:X} errno={Marshal.GetLastPInvokeError()}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Regions[(ulong)result] = new Region
|
||||
{
|
||||
Base = (ulong)result,
|
||||
Size = alignedSize,
|
||||
DefaultProtect = protect
|
||||
};
|
||||
|
||||
return (void*)result;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool Free(void* address, nuint size, uint freeType)
|
||||
{
|
||||
_ = size;
|
||||
_ = freeType;
|
||||
|
||||
lock (Gate)
|
||||
{
|
||||
if (!Regions.TryGetValue((ulong)address, out var region))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Regions.Remove((ulong)address);
|
||||
return munmap((nint)address, (nuint)region.Size) == 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool Protect(void* address, nuint size, uint newProtect, out uint oldProtect)
|
||||
{
|
||||
oldProtect = PAGE_NOACCESS;
|
||||
if (size == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var start = AlignDown((ulong)address, PageSize);
|
||||
var end = AlignUp((ulong)address + size, PageSize);
|
||||
|
||||
lock (Gate)
|
||||
{
|
||||
if (!TryFindRegionLocked(start, out var region) || end > region.End)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
oldProtect = region.ProtectAt(start);
|
||||
if (mprotect((nint)start, (nuint)(end - start), ToPosixProtect(newProtect)) != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
SetProtectRangeLocked(region, start, end - start, newProtect);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static nuint Query(void* address, out BasicInfo info)
|
||||
{
|
||||
info = default;
|
||||
var pageAddress = AlignDown((ulong)address, PageSize);
|
||||
|
||||
lock (Gate)
|
||||
{
|
||||
if (TryFindRegionLocked(pageAddress, out var region))
|
||||
{
|
||||
// Win32 VirtualQuery reports a run of pages sharing the
|
||||
// same protection, so stop the run where it changes.
|
||||
var protect = region.ProtectAt(pageAddress);
|
||||
var runEnd = pageAddress + PageSize;
|
||||
while (runEnd < region.End && region.ProtectAt(runEnd) == protect)
|
||||
{
|
||||
runEnd += PageSize;
|
||||
}
|
||||
|
||||
info.BaseAddress = pageAddress;
|
||||
info.AllocationBase = region.Base;
|
||||
info.AllocationProtect = region.DefaultProtect;
|
||||
info.RegionSize = runEnd - pageAddress;
|
||||
info.State = MEM_COMMIT;
|
||||
info.Protect = protect;
|
||||
info.Type = MEM_PRIVATE;
|
||||
return (nuint)sizeof(BasicInfo);
|
||||
}
|
||||
|
||||
// Untracked host memory (runtime heaps, stacks, libraries) is
|
||||
// reported as a free block reaching to the next tracked region
|
||||
// so scanning callers keep advancing.
|
||||
var nextBase = ulong.MaxValue;
|
||||
foreach (var regionBase in Regions.Keys)
|
||||
{
|
||||
if (regionBase > pageAddress)
|
||||
{
|
||||
nextBase = regionBase;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
info.BaseAddress = pageAddress;
|
||||
info.AllocationBase = 0;
|
||||
info.AllocationProtect = PAGE_NOACCESS;
|
||||
info.RegionSize = (nextBase == ulong.MaxValue ? pageAddress + PageSize : nextBase) - pageAddress;
|
||||
info.State = MEM_FREE_STATE;
|
||||
info.Protect = PAGE_NOACCESS;
|
||||
info.Type = 0;
|
||||
return (nuint)sizeof(BasicInfo);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool OverlapsTrackedRegionLocked(ulong start, ulong size)
|
||||
{
|
||||
var end = start + size;
|
||||
foreach (var region in Regions.Values)
|
||||
{
|
||||
if (region.Base < end && start < region.End)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryFindRegionLocked(ulong address, out Region region)
|
||||
{
|
||||
region = null!;
|
||||
var keys = Regions.Keys;
|
||||
var low = 0;
|
||||
var high = keys.Count - 1;
|
||||
Region? candidate = null;
|
||||
while (low <= high)
|
||||
{
|
||||
var middle = low + ((high - low) >> 1);
|
||||
var entry = Regions.Values[middle];
|
||||
if (entry.Base <= address)
|
||||
{
|
||||
candidate = entry;
|
||||
low = middle + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
high = middle - 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (candidate is null || address >= candidate.End)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
region = candidate;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void SetProtectRangeLocked(Region region, ulong start, ulong size, uint protect)
|
||||
{
|
||||
if (start == region.Base && size >= region.Size)
|
||||
{
|
||||
region.DefaultProtect = protect;
|
||||
region.PageProtects = null;
|
||||
return;
|
||||
}
|
||||
|
||||
region.PageProtects ??= new Dictionary<ulong, uint>();
|
||||
var end = start + size;
|
||||
for (var pageAddress = start; pageAddress < end; pageAddress += PageSize)
|
||||
{
|
||||
if (protect == region.DefaultProtect)
|
||||
{
|
||||
region.PageProtects.Remove(pageAddress);
|
||||
}
|
||||
else
|
||||
{
|
||||
region.PageProtects[pageAddress] = protect;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int ToPosixProtect(uint win32Protect)
|
||||
{
|
||||
return win32Protect switch
|
||||
{
|
||||
PAGE_NOACCESS => PROT_NONE,
|
||||
PAGE_READONLY => PROT_READ,
|
||||
PAGE_READWRITE => PROT_READ | PROT_WRITE,
|
||||
PAGE_EXECUTE => PROT_READ | PROT_EXEC,
|
||||
PAGE_EXECUTE_READ => PROT_READ | PROT_EXEC,
|
||||
PAGE_EXECUTE_READWRITE => PROT_READ | PROT_WRITE | PROT_EXEC,
|
||||
_ => PROT_READ | PROT_WRITE
|
||||
};
|
||||
}
|
||||
|
||||
private static void Trace(string message)
|
||||
{
|
||||
if (string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_VMEM"), "1", StringComparison.Ordinal))
|
||||
{
|
||||
Console.Error.WriteLine($"[HOSTMEM] {message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static ulong AlignDown(ulong value, ulong alignment) => value & ~(alignment - 1);
|
||||
|
||||
private static ulong AlignUp(ulong value, ulong alignment) => checked((value + alignment - 1) & ~(alignment - 1));
|
||||
|
||||
[DllImport("libc", SetLastError = true)]
|
||||
private static extern nint mmap(nint addr, nuint length, int prot, int flags, int fd, long offset);
|
||||
|
||||
[DllImport("libc", SetLastError = true)]
|
||||
private static extern int munmap(nint addr, nuint length);
|
||||
|
||||
[DllImport("libc", SetLastError = true)]
|
||||
private static extern int mprotect(nint addr, nuint length, int prot);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host.Posix;
|
||||
|
||||
internal sealed class PosixHostPlatform : IHostPlatform
|
||||
{
|
||||
public IHostMemory Memory { get; } = new PosixHostMemory();
|
||||
|
||||
public IHostThreading Threading { get; } = new PosixHostThreading();
|
||||
|
||||
public IHostSymbolResolver Symbols { get; } = new PosixHostSymbolResolver();
|
||||
|
||||
public IHostAudioOutput Audio { get; } = new PosixHostAudio();
|
||||
|
||||
public IHostInput Input { get; } = new PosixHostInput();
|
||||
}
|
||||
@@ -0,0 +1,657 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SharpEmu.HLE.Host.Posix;
|
||||
|
||||
/// <summary>
|
||||
/// POSIX replacements for the kernel32 helpers the native backend embeds in
|
||||
/// emitted x86-64 code. Every stub exposed here follows the Win64 calling
|
||||
/// convention the emitted call sites were written for (first argument in
|
||||
/// ECX, result in RAX, Win64 non-volatile registers preserved), so the
|
||||
/// emission code stays identical across platforms.
|
||||
/// </summary>
|
||||
internal static unsafe class PosixHostStubs
|
||||
{
|
||||
private static readonly object Gate = new();
|
||||
private static bool _initialized;
|
||||
private static nint _tlsGetValueStub;
|
||||
private static nint _queryPerformanceCounterStub;
|
||||
private static nint _switchToThreadStub;
|
||||
private static nint _sleepStub;
|
||||
private static nint _waitForSingleObjectStub;
|
||||
private static nint _setEventStub;
|
||||
private static nint _exitThreadStub;
|
||||
|
||||
public static nint TlsGetValueStubAddress
|
||||
{
|
||||
get { EnsureInitialized(); return _tlsGetValueStub; }
|
||||
}
|
||||
|
||||
public static nint QueryPerformanceCounterStubAddress
|
||||
{
|
||||
get { EnsureInitialized(); return _queryPerformanceCounterStub; }
|
||||
}
|
||||
|
||||
public static nint SwitchToThreadStubAddress
|
||||
{
|
||||
get { EnsureInitialized(); return _switchToThreadStub; }
|
||||
}
|
||||
|
||||
public static nint SleepStubAddress
|
||||
{
|
||||
get { EnsureInitialized(); return _sleepStub; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Win64-convention replacements for the kernel32 event/thread helpers the
|
||||
/// native guest worker loop embeds. The "handle" they take is a worker
|
||||
/// event created by <see cref="CreateWorkerEvent"/>: a dispatch semaphore
|
||||
/// on macOS, an unnamed POSIX semaphore on Linux. The wait stub always
|
||||
/// waits forever (the worker loop passes INFINITE) and retries EINTR.
|
||||
/// </summary>
|
||||
public static nint WaitForSingleObjectStubAddress
|
||||
{
|
||||
get { EnsureInitialized(); return _waitForSingleObjectStub; }
|
||||
}
|
||||
|
||||
public static nint SetEventStubAddress
|
||||
{
|
||||
get { EnsureInitialized(); return _setEventStub; }
|
||||
}
|
||||
|
||||
public static nint ExitThreadStubAddress
|
||||
{
|
||||
get { EnsureInitialized(); return _exitThreadStub; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a binary-semaphore worker event signalable/waitable both from
|
||||
/// managed code and from emitted native code (via the stub addresses
|
||||
/// above). Returns 0 on failure.
|
||||
/// </summary>
|
||||
public static nint CreateWorkerEvent()
|
||||
{
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
return dispatch_semaphore_create(0);
|
||||
}
|
||||
|
||||
var semaphore = Marshal.AllocHGlobal(64);
|
||||
if (sem_init(semaphore, 0, 0) != 0)
|
||||
{
|
||||
Marshal.FreeHGlobal(semaphore);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return semaphore;
|
||||
}
|
||||
|
||||
public static bool SignalWorkerEvent(nint handle)
|
||||
{
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
_ = dispatch_semaphore_signal(handle);
|
||||
return true;
|
||||
}
|
||||
|
||||
return sem_post(handle) == 0;
|
||||
}
|
||||
|
||||
/// <summary>Waits for a worker event; a negative timeout waits forever.</summary>
|
||||
public static bool WaitWorkerEvent(nint handle, int timeoutMilliseconds)
|
||||
{
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
if (timeoutMilliseconds < 0)
|
||||
{
|
||||
return dispatch_semaphore_wait(handle, ulong.MaxValue) == 0;
|
||||
}
|
||||
|
||||
var deadline = dispatch_time(0, timeoutMilliseconds * 1_000_000L);
|
||||
return dispatch_semaphore_wait(handle, deadline) == 0;
|
||||
}
|
||||
|
||||
if (timeoutMilliseconds < 0)
|
||||
{
|
||||
while (sem_wait(handle) != 0)
|
||||
{
|
||||
// EINTR: retry.
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
var deadlineTicks = Environment.TickCount64 + timeoutMilliseconds;
|
||||
while (sem_trywait(handle) != 0)
|
||||
{
|
||||
if (Environment.TickCount64 >= deadlineTicks)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
System.Threading.Thread.Sleep(1);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void DestroyWorkerEvent(nint handle)
|
||||
{
|
||||
if (handle == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
dispatch_release(handle);
|
||||
return;
|
||||
}
|
||||
|
||||
_ = sem_destroy(handle);
|
||||
Marshal.FreeHGlobal(handle);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts a raw pthread at a native entry point (pthread entries take their
|
||||
/// argument in RDI; the worker loop stub ignores it). Returns an opaque
|
||||
/// handle for <see cref="WaitForWorkerThreadExit"/>/<see cref="CloseWorkerThreadHandle"/>,
|
||||
/// or 0 on failure.
|
||||
/// </summary>
|
||||
public static nint CreateWorkerThread(nint entry, nint parameter, nuint stackReserveBytes, out uint threadId)
|
||||
{
|
||||
threadId = 0;
|
||||
byte* attr = stackalloc byte[512];
|
||||
if (pthread_attr_init(attr) != 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (stackReserveBytes != 0)
|
||||
{
|
||||
_ = pthread_attr_setstacksize(attr, nuint.Max(stackReserveBytes, 512 * 1024));
|
||||
}
|
||||
|
||||
nint thread;
|
||||
if (pthread_create(&thread, attr, entry, parameter) != 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
ulong numericId;
|
||||
if (pthread_threadid_np(thread, &numericId) == 0)
|
||||
{
|
||||
threadId = unchecked((uint)numericId);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
threadId = unchecked((uint)thread);
|
||||
}
|
||||
|
||||
var holder = (nint*)Marshal.AllocHGlobal(sizeof(nint) * 2);
|
||||
holder[0] = thread;
|
||||
holder[1] = 0; // joined flag
|
||||
return (nint)holder;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_ = pthread_attr_destroy(attr);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for a worker thread to exit. Liveness is probed with
|
||||
/// pthread_kill(thread, 0) (ESRCH once the thread has terminated) because
|
||||
/// neither platform offers a portable timed join; the exited thread is then
|
||||
/// joined so its resources are reclaimed.
|
||||
/// </summary>
|
||||
public static bool WaitForWorkerThreadExit(nint threadHandle, uint timeoutMilliseconds)
|
||||
{
|
||||
var holder = (nint*)threadHandle;
|
||||
if (holder == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (holder[1] != 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var thread = holder[0];
|
||||
var deadline = Environment.TickCount64 + timeoutMilliseconds;
|
||||
while (pthread_kill(thread, 0) == 0)
|
||||
{
|
||||
if (Environment.TickCount64 >= deadline)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
System.Threading.Thread.Sleep(1);
|
||||
}
|
||||
|
||||
_ = pthread_join(thread, null);
|
||||
holder[1] = 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void CloseWorkerThreadHandle(nint threadHandle)
|
||||
{
|
||||
var holder = (nint*)threadHandle;
|
||||
if (holder == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (holder[1] == 0)
|
||||
{
|
||||
// Never observed exiting: detach so the thread does not leak a
|
||||
// zombie join target when it eventually terminates.
|
||||
_ = pthread_detach(holder[0]);
|
||||
}
|
||||
|
||||
Marshal.FreeHGlobal(threadHandle);
|
||||
}
|
||||
|
||||
/// <summary>Allocates a pthread TLS key, mirroring kernel32!TlsAlloc.</summary>
|
||||
public static uint TlsAlloc()
|
||||
{
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
nuint key;
|
||||
return pthread_key_create_mac(&key, 0) == 0 ? (uint)key : uint.MaxValue;
|
||||
}
|
||||
|
||||
uint key32;
|
||||
return pthread_key_create_linux(&key32, 0) == 0 ? key32 : uint.MaxValue;
|
||||
}
|
||||
|
||||
public static bool TlsFree(uint key)
|
||||
{
|
||||
return OperatingSystem.IsMacOS()
|
||||
? pthread_key_delete_mac((nuint)key) == 0
|
||||
: pthread_key_delete_linux(key) == 0;
|
||||
}
|
||||
|
||||
public static bool TlsSetValue(uint key, nint value)
|
||||
{
|
||||
return OperatingSystem.IsMacOS()
|
||||
? pthread_setspecific_mac((nuint)key, value) == 0
|
||||
: pthread_setspecific_linux(key, value) == 0;
|
||||
}
|
||||
|
||||
public static nint TlsGetValue(uint key)
|
||||
{
|
||||
return OperatingSystem.IsMacOS()
|
||||
? pthread_getspecific_mac((nuint)key)
|
||||
: pthread_getspecific_linux(key);
|
||||
}
|
||||
|
||||
/// <summary>Stable numeric id of the calling thread (kernel32!GetCurrentThreadId).</summary>
|
||||
public static uint GetCurrentThreadId()
|
||||
{
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
ulong tid;
|
||||
return pthread_threadid_np(0, &tid) == 0 ? unchecked((uint)tid) : 0u;
|
||||
}
|
||||
|
||||
return unchecked((uint)gettid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wraps a managed callback (compiled for the SysV ABI on POSIX .NET) in a
|
||||
/// thunk that accepts up to four integer arguments in the Win64 ABI the
|
||||
/// emitted x86-64 call sites use. Win64 passes args in rcx/rdx/r8/r9 and
|
||||
/// treats rdi/rsi as non-volatile; SysV expects rdi/rsi/rdx/rcx and
|
||||
/// clobbers them, so the thunk saves rdi/rsi, shuffles the registers, keeps
|
||||
/// the stack 16-byte aligned for the call, and forwards the rax result.
|
||||
/// </summary>
|
||||
public static nint CreateWin64ToSysVThunk(nint sysvTarget)
|
||||
{
|
||||
var memory = HostPlatform.Current.Memory;
|
||||
var page = (byte*)memory.Allocate(
|
||||
0,
|
||||
4096,
|
||||
HostPageProtection.ReadWriteExecute);
|
||||
if (page == null)
|
||||
{
|
||||
throw new OutOfMemoryException("Failed to allocate Win64->SysV thunk page");
|
||||
}
|
||||
|
||||
var offset = 0;
|
||||
Emit(page, ref offset, 0x57); // push rdi
|
||||
Emit(page, ref offset, 0x56); // push rsi
|
||||
Emit(page, ref offset, 0x48, 0x89, 0xCF); // mov rdi, rcx
|
||||
Emit(page, ref offset, 0x48, 0x89, 0xD6); // mov rsi, rdx
|
||||
Emit(page, ref offset, 0x4C, 0x89, 0xC2); // mov rdx, r8
|
||||
Emit(page, ref offset, 0x4C, 0x89, 0xC9); // mov rcx, r9
|
||||
Emit(page, ref offset, 0x48, 0x83, 0xEC, 0x08); // sub rsp, 8 (realign to 16)
|
||||
EmitMovRaxImm64(page, ref offset, sysvTarget); // mov rax, target
|
||||
Emit(page, ref offset, 0xFF, 0xD0); // call rax
|
||||
Emit(page, ref offset, 0x48, 0x83, 0xC4, 0x08); // add rsp, 8
|
||||
Emit(page, ref offset, 0x5E); // pop rsi
|
||||
Emit(page, ref offset, 0x5F); // pop rdi
|
||||
Emit(page, ref offset, 0xC3); // ret
|
||||
|
||||
if (!memory.Protect((ulong)page, 4096, HostPageProtection.ReadExecute, out _))
|
||||
{
|
||||
throw new InvalidOperationException("Failed to protect Win64->SysV thunk page");
|
||||
}
|
||||
|
||||
memory.FlushInstructionCache((ulong)page, (ulong)offset);
|
||||
return (nint)page;
|
||||
}
|
||||
|
||||
private static void EnsureInitialized()
|
||||
{
|
||||
if (_initialized)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (Gate)
|
||||
{
|
||||
if (_initialized)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
BuildStubs();
|
||||
_initialized = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static void BuildStubs()
|
||||
{
|
||||
var memory = HostPlatform.Current.Memory;
|
||||
var page = (byte*)memory.Allocate(
|
||||
0,
|
||||
4096,
|
||||
HostPageProtection.ReadWriteExecute);
|
||||
if (page == null)
|
||||
{
|
||||
throw new OutOfMemoryException("Failed to allocate POSIX host helper stub page");
|
||||
}
|
||||
|
||||
var offset = 0;
|
||||
_tlsGetValueStub = EmitTlsGetValue(page, ref offset);
|
||||
_queryPerformanceCounterStub = EmitQueryPerformanceCounter(page, ref offset);
|
||||
_switchToThreadStub = EmitSwitchToThread(page, ref offset);
|
||||
_sleepStub = EmitSleep(page, ref offset);
|
||||
_waitForSingleObjectStub = EmitWaitForSingleObject(page, ref offset);
|
||||
_setEventStub = EmitSetEvent(page, ref offset);
|
||||
_exitThreadStub = EmitExitThread(page, ref offset);
|
||||
|
||||
if (!memory.Protect((ulong)page, 4096, HostPageProtection.ReadExecute, out _))
|
||||
{
|
||||
throw new InvalidOperationException("Failed to protect POSIX host helper stub page");
|
||||
}
|
||||
|
||||
memory.FlushInstructionCache((ulong)page, (ulong)offset);
|
||||
}
|
||||
|
||||
private static nint EmitTlsGetValue(byte* page, ref int offset)
|
||||
{
|
||||
var start = (nint)(page + offset);
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
// On macOS x86-64 pthread keys index the gs-based thread specific
|
||||
// data array directly, so TlsGetValue(index in ecx) collapses to a
|
||||
// single load that clobbers nothing but RAX.
|
||||
Emit(page, ref offset, 0x89, 0xC8); // mov eax, ecx
|
||||
Emit(page, ref offset, 0x65, 0x48, 0x8B, 0x04, 0xC5, 0, 0, 0, 0); // mov rax, gs:[rax*8]
|
||||
Emit(page, ref offset, 0xC3); // ret
|
||||
return start;
|
||||
}
|
||||
|
||||
// Linux: call pthread_getspecific, preserving the registers that are
|
||||
// volatile in SysV but non-volatile in Win64 (rsi, rdi).
|
||||
var pthreadGetSpecific = ResolveLibcExport("pthread_getspecific");
|
||||
Emit(page, ref offset, 0x56); // push rsi
|
||||
Emit(page, ref offset, 0x57); // push rdi
|
||||
Emit(page, ref offset, 0x48, 0x83, 0xEC, 0x08); // sub rsp, 8
|
||||
Emit(page, ref offset, 0x89, 0xCF); // mov edi, ecx
|
||||
EmitMovRaxImm64(page, ref offset, pthreadGetSpecific); // mov rax, imm64
|
||||
Emit(page, ref offset, 0xFF, 0xD0); // call rax
|
||||
Emit(page, ref offset, 0x48, 0x83, 0xC4, 0x08); // add rsp, 8
|
||||
Emit(page, ref offset, 0x5F); // pop rdi
|
||||
Emit(page, ref offset, 0x5E); // pop rsi
|
||||
Emit(page, ref offset, 0xC3); // ret
|
||||
return start;
|
||||
}
|
||||
|
||||
private static nint EmitQueryPerformanceCounter(byte* page, ref int offset)
|
||||
{
|
||||
// BOOL QueryPerformanceCounter(LARGE_INTEGER* out in rcx): the emitted
|
||||
// consumers only need a monotonically increasing counter, which rdtsc
|
||||
// provides without leaving Win64-safe registers.
|
||||
var start = (nint)(page + offset);
|
||||
Emit(page, ref offset, 0x0F, 0x31); // rdtsc
|
||||
Emit(page, ref offset, 0x48, 0xC1, 0xE2, 0x20); // shl rdx, 32
|
||||
Emit(page, ref offset, 0x48, 0x09, 0xD0); // or rax, rdx
|
||||
Emit(page, ref offset, 0x48, 0x89, 0x01); // mov [rcx], rax
|
||||
Emit(page, ref offset, 0xB8, 0x01, 0x00, 0x00, 0x00); // mov eax, 1
|
||||
Emit(page, ref offset, 0xC3); // ret
|
||||
return start;
|
||||
}
|
||||
|
||||
private static nint EmitSwitchToThread(byte* page, ref int offset)
|
||||
{
|
||||
var schedYield = ResolveLibcExport("sched_yield");
|
||||
var start = (nint)(page + offset);
|
||||
Emit(page, ref offset, 0x56); // push rsi
|
||||
Emit(page, ref offset, 0x57); // push rdi
|
||||
Emit(page, ref offset, 0x48, 0x83, 0xEC, 0x08); // sub rsp, 8
|
||||
EmitMovRaxImm64(page, ref offset, schedYield); // mov rax, imm64
|
||||
Emit(page, ref offset, 0xFF, 0xD0); // call rax
|
||||
Emit(page, ref offset, 0x48, 0x83, 0xC4, 0x08); // add rsp, 8
|
||||
Emit(page, ref offset, 0x5F); // pop rdi
|
||||
Emit(page, ref offset, 0x5E); // pop rsi
|
||||
Emit(page, ref offset, 0xB8, 0x01, 0x00, 0x00, 0x00); // mov eax, 1
|
||||
Emit(page, ref offset, 0xC3); // ret
|
||||
return start;
|
||||
}
|
||||
|
||||
private static nint EmitSleep(byte* page, ref int offset)
|
||||
{
|
||||
// void Sleep(DWORD milliseconds in ecx) -> usleep(microseconds in edi).
|
||||
var usleep = ResolveLibcExport("usleep");
|
||||
var start = (nint)(page + offset);
|
||||
Emit(page, ref offset, 0x56); // push rsi
|
||||
Emit(page, ref offset, 0x57); // push rdi
|
||||
Emit(page, ref offset, 0x48, 0x83, 0xEC, 0x08); // sub rsp, 8
|
||||
Emit(page, ref offset, 0x89, 0xCF); // mov edi, ecx
|
||||
Emit(page, ref offset, 0x81, 0xFF, 0xFF, 0x0F, 0x00, 0x00); // cmp edi, 0xFFF
|
||||
Emit(page, ref offset, 0x76, 0x05); // jbe +5
|
||||
Emit(page, ref offset, 0xBF, 0xFF, 0x0F, 0x00, 0x00); // mov edi, 0xFFF (cap at ~4s)
|
||||
Emit(page, ref offset, 0x69, 0xFF, 0xE8, 0x03, 0x00, 0x00); // imul edi, edi, 1000
|
||||
EmitMovRaxImm64(page, ref offset, usleep); // mov rax, imm64
|
||||
Emit(page, ref offset, 0xFF, 0xD0); // call rax
|
||||
Emit(page, ref offset, 0x48, 0x83, 0xC4, 0x08); // add rsp, 8
|
||||
Emit(page, ref offset, 0x5F); // pop rdi
|
||||
Emit(page, ref offset, 0x5E); // pop rsi
|
||||
Emit(page, ref offset, 0xC3); // ret
|
||||
return start;
|
||||
}
|
||||
|
||||
private static nint EmitWaitForSingleObject(byte* page, ref int offset)
|
||||
{
|
||||
// DWORD WaitForSingleObject(worker event in rcx, timeout in edx): the
|
||||
// worker loop only ever waits forever, so the timeout is ignored.
|
||||
// macOS waits on a dispatch semaphore (needs DISPATCH_TIME_FOREVER in
|
||||
// rsi), Linux on a sem_t; both retry until the wait succeeds (EINTR).
|
||||
var wait = ResolveLibcExport(
|
||||
OperatingSystem.IsMacOS() ? "dispatch_semaphore_wait" : "sem_wait");
|
||||
var start = (nint)(page + offset);
|
||||
Emit(page, ref offset, 0x56); // push rsi
|
||||
Emit(page, ref offset, 0x57); // push rdi
|
||||
Emit(page, ref offset, 0x53); // push rbx
|
||||
Emit(page, ref offset, 0x48, 0x89, 0xCB); // mov rbx, rcx
|
||||
var retry = offset;
|
||||
Emit(page, ref offset, 0x48, 0x89, 0xDF); // mov rdi, rbx
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
Emit(page, ref offset, 0x48, 0xC7, 0xC6, 0xFF, 0xFF, 0xFF, 0xFF); // mov rsi, DISPATCH_TIME_FOREVER
|
||||
}
|
||||
EmitMovRaxImm64(page, ref offset, wait); // mov rax, imm64
|
||||
Emit(page, ref offset, 0xFF, 0xD0); // call rax
|
||||
Emit(page, ref offset, 0x85, 0xC0); // test eax, eax
|
||||
Emit(page, ref offset, 0x75, unchecked((byte)(retry - (offset + 2)))); // jnz retry
|
||||
Emit(page, ref offset, 0x31, 0xC0); // xor eax, eax (WAIT_OBJECT_0)
|
||||
Emit(page, ref offset, 0x5B); // pop rbx
|
||||
Emit(page, ref offset, 0x5F); // pop rdi
|
||||
Emit(page, ref offset, 0x5E); // pop rsi
|
||||
Emit(page, ref offset, 0xC3); // ret
|
||||
return start;
|
||||
}
|
||||
|
||||
private static nint EmitSetEvent(byte* page, ref int offset)
|
||||
{
|
||||
// BOOL SetEvent(worker event in rcx) -> dispatch_semaphore_signal /
|
||||
// sem_post.
|
||||
var signal = ResolveLibcExport(
|
||||
OperatingSystem.IsMacOS() ? "dispatch_semaphore_signal" : "sem_post");
|
||||
var start = (nint)(page + offset);
|
||||
Emit(page, ref offset, 0x56); // push rsi
|
||||
Emit(page, ref offset, 0x57); // push rdi
|
||||
Emit(page, ref offset, 0x48, 0x83, 0xEC, 0x08); // sub rsp, 8
|
||||
Emit(page, ref offset, 0x48, 0x89, 0xCF); // mov rdi, rcx
|
||||
EmitMovRaxImm64(page, ref offset, signal); // mov rax, imm64
|
||||
Emit(page, ref offset, 0xFF, 0xD0); // call rax
|
||||
Emit(page, ref offset, 0x48, 0x83, 0xC4, 0x08); // add rsp, 8
|
||||
Emit(page, ref offset, 0x5F); // pop rdi
|
||||
Emit(page, ref offset, 0x5E); // pop rsi
|
||||
Emit(page, ref offset, 0xB8, 0x01, 0x00, 0x00, 0x00); // mov eax, 1
|
||||
Emit(page, ref offset, 0xC3); // ret
|
||||
return start;
|
||||
}
|
||||
|
||||
private static nint EmitExitThread(byte* page, ref int offset)
|
||||
{
|
||||
// void ExitThread(code in ecx) -> pthread_exit(NULL); never returns,
|
||||
// so no registers need preserving. pthread_exit runs the thread's TSD
|
||||
// destructors, which detaches the CLR if the thread lazily attached.
|
||||
var pthreadExit = ResolveLibcExport("pthread_exit");
|
||||
var start = (nint)(page + offset);
|
||||
Emit(page, ref offset, 0x48, 0x83, 0xEC, 0x08); // sub rsp, 8
|
||||
Emit(page, ref offset, 0x31, 0xFF); // xor edi, edi
|
||||
EmitMovRaxImm64(page, ref offset, pthreadExit); // mov rax, imm64
|
||||
Emit(page, ref offset, 0xFF, 0xD0); // call rax
|
||||
Emit(page, ref offset, 0xCC); // int3 (never returns)
|
||||
return start;
|
||||
}
|
||||
|
||||
private static nint ResolveLibcExport(string name)
|
||||
{
|
||||
var libc = NativeLibrary.Load(OperatingSystem.IsMacOS() ? "libSystem.dylib" : "libc.so.6");
|
||||
return NativeLibrary.GetExport(libc, name);
|
||||
}
|
||||
|
||||
private static void Emit(byte* page, ref int offset, params byte[] bytes)
|
||||
{
|
||||
foreach (var value in bytes)
|
||||
{
|
||||
page[offset++] = value;
|
||||
}
|
||||
}
|
||||
|
||||
private static void EmitMovRaxImm64(byte* page, ref int offset, nint value)
|
||||
{
|
||||
Emit(page, ref offset, 0x48, 0xB8);
|
||||
*(long*)(page + offset) = value;
|
||||
offset += sizeof(long);
|
||||
}
|
||||
|
||||
[DllImport("libc", EntryPoint = "pthread_key_create", SetLastError = true)]
|
||||
private static extern int pthread_key_create_mac(nuint* key, nint destructor);
|
||||
|
||||
[DllImport("libc", EntryPoint = "pthread_key_create", SetLastError = true)]
|
||||
private static extern int pthread_key_create_linux(uint* key, nint destructor);
|
||||
|
||||
[DllImport("libc", EntryPoint = "pthread_key_delete")]
|
||||
private static extern int pthread_key_delete_mac(nuint key);
|
||||
|
||||
[DllImport("libc", EntryPoint = "pthread_key_delete")]
|
||||
private static extern int pthread_key_delete_linux(uint key);
|
||||
|
||||
[DllImport("libc", EntryPoint = "pthread_setspecific")]
|
||||
private static extern int pthread_setspecific_mac(nuint key, nint value);
|
||||
|
||||
[DllImport("libc", EntryPoint = "pthread_setspecific")]
|
||||
private static extern int pthread_setspecific_linux(uint key, nint value);
|
||||
|
||||
[DllImport("libc", EntryPoint = "pthread_getspecific")]
|
||||
private static extern nint pthread_getspecific_mac(nuint key);
|
||||
|
||||
[DllImport("libc", EntryPoint = "pthread_getspecific")]
|
||||
private static extern nint pthread_getspecific_linux(uint key);
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern int pthread_threadid_np(nint thread, ulong* threadId);
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern int gettid();
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern int pthread_attr_init(byte* attr);
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern int pthread_attr_destroy(byte* attr);
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern int pthread_attr_setstacksize(byte* attr, nuint stackSize);
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern int pthread_create(nint* thread, byte* attr, nint startRoutine, nint arg);
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern int pthread_join(nint thread, nint* returnValue);
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern int pthread_detach(nint thread);
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern int pthread_kill(nint thread, int signal);
|
||||
|
||||
// macOS: dispatch semaphores back the worker events (unnamed sem_init is
|
||||
// unsupported on Darwin). libSystem reexports libdispatch, so "libc"
|
||||
// resolves these like the pthread imports above.
|
||||
[DllImport("libc")]
|
||||
private static extern nint dispatch_semaphore_create(long value);
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern nint dispatch_semaphore_signal(nint semaphore);
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern nint dispatch_semaphore_wait(nint semaphore, ulong timeout);
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern ulong dispatch_time(ulong when, long deltaNanoseconds);
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern void dispatch_release(nint handle);
|
||||
|
||||
// Linux: unnamed POSIX semaphores.
|
||||
[DllImport("libc")]
|
||||
private static extern int sem_init(nint semaphore, int shared, uint value);
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern int sem_post(nint semaphore);
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern int sem_wait(nint semaphore);
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern int sem_trywait(nint semaphore);
|
||||
|
||||
[DllImport("libc")]
|
||||
private static extern int sem_destroy(nint semaphore);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host.Posix;
|
||||
|
||||
internal sealed class PosixHostSymbolResolver : IHostSymbolResolver
|
||||
{
|
||||
public nint GetAddress(HostRuntimeFunction function) => function switch
|
||||
{
|
||||
HostRuntimeFunction.TlsGetValue => PosixHostStubs.TlsGetValueStubAddress,
|
||||
HostRuntimeFunction.QueryPerformanceCounter => PosixHostStubs.QueryPerformanceCounterStubAddress,
|
||||
HostRuntimeFunction.SwitchToThread => PosixHostStubs.SwitchToThreadStubAddress,
|
||||
HostRuntimeFunction.Sleep => PosixHostStubs.SleepStubAddress,
|
||||
HostRuntimeFunction.WaitForSingleObject => PosixHostStubs.WaitForSingleObjectStubAddress,
|
||||
HostRuntimeFunction.SetEvent => PosixHostStubs.SetEventStubAddress,
|
||||
HostRuntimeFunction.ExitThread => PosixHostStubs.ExitThreadStubAddress,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(function), function, null),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host.Posix;
|
||||
|
||||
internal sealed class PosixHostThreading : IHostThreading
|
||||
{
|
||||
public uint AllocateTlsSlot() => PosixHostStubs.TlsAlloc();
|
||||
|
||||
public bool FreeTlsSlot(uint slot) => PosixHostStubs.TlsFree(slot);
|
||||
|
||||
public bool SetTlsValue(uint slot, nint value) => PosixHostStubs.TlsSetValue(slot, value);
|
||||
|
||||
public nint GetTlsValue(uint slot) => PosixHostStubs.TlsGetValue(slot);
|
||||
|
||||
public uint CurrentThreadId => PosixHostStubs.GetCurrentThreadId();
|
||||
|
||||
public void RequestTimerResolution()
|
||||
{
|
||||
// POSIX sleep primitives are already high-resolution; there is no
|
||||
// timeBeginPeriod equivalent to request.
|
||||
}
|
||||
|
||||
// Thread affinity is advisory on POSIX hosts (macOS offers no
|
||||
// pthread-level affinity API); callers treat false as "not applied".
|
||||
public bool TrySetCurrentThreadAffinity(nuint affinityMask)
|
||||
{
|
||||
_ = affinityMask;
|
||||
return false;
|
||||
}
|
||||
|
||||
public nint CreateNativeThread(
|
||||
nint entry,
|
||||
nint parameter,
|
||||
nuint stackReserveBytes,
|
||||
out uint threadId)
|
||||
{
|
||||
return PosixHostStubs.CreateWorkerThread(entry, parameter, stackReserveBytes, out threadId);
|
||||
}
|
||||
|
||||
public bool WaitForThreadExit(nint threadHandle, uint timeoutMilliseconds)
|
||||
{
|
||||
return PosixHostStubs.WaitForWorkerThreadExit(threadHandle, timeoutMilliseconds);
|
||||
}
|
||||
|
||||
public void CloseThreadHandle(nint threadHandle)
|
||||
{
|
||||
PosixHostStubs.CloseWorkerThreadHandle(threadHandle);
|
||||
}
|
||||
|
||||
public bool TryCaptureThreadRegisters(uint threadId, out HostCapturedRegisters registers)
|
||||
{
|
||||
_ = threadId;
|
||||
registers = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+51
-49
@@ -3,21 +3,21 @@
|
||||
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
namespace SharpEmu.Libs.Pad;
|
||||
namespace SharpEmu.HLE.Host.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// Reads a DualSense controller over raw HID on a background thread.
|
||||
/// Supports USB (input report 0x01) and Bluetooth (extended report 0x31,
|
||||
/// activated by requesting feature report 0x05), with hot-plug retry.
|
||||
/// </summary>
|
||||
internal static class DualSenseReader
|
||||
internal static class WindowsDualSenseReader
|
||||
{
|
||||
private const ushort SonyVendorId = 0x054C;
|
||||
private const ushort DualSenseProductId = 0x0CE6;
|
||||
private const ushort DualSenseEdgeProductId = 0x0DF2;
|
||||
|
||||
private static readonly object Gate = new();
|
||||
private static PadState _state;
|
||||
private static HostGamepadState _state;
|
||||
private static bool _started;
|
||||
|
||||
// Output (rumble/lightbar) state, all guarded by Gate.
|
||||
@@ -37,6 +37,8 @@ internal static class DualSenseReader
|
||||
/// <summary>Starts the background reader once; safe to call repeatedly.</summary>
|
||||
internal static void EnsureStarted()
|
||||
{
|
||||
// The GUI source-links this reader and calls it directly, without the
|
||||
// host-platform resolution that otherwise guarantees Windows.
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
return;
|
||||
@@ -59,7 +61,7 @@ internal static class DualSenseReader
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool TryGetState(out PadState state)
|
||||
internal static bool TryGetState(out HostGamepadState state)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
@@ -69,7 +71,7 @@ internal static class DualSenseReader
|
||||
return state.Connected;
|
||||
}
|
||||
|
||||
private static void SetState(in PadState state)
|
||||
private static void SetState(in HostGamepadState state)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
@@ -148,11 +150,11 @@ internal static class DualSenseReader
|
||||
{
|
||||
if (_outputStream is null)
|
||||
{
|
||||
var handle = HidNative.CreateFile(
|
||||
var handle = WindowsHidNative.CreateFile(
|
||||
_devicePath,
|
||||
HidNative.GenericRead | HidNative.GenericWrite,
|
||||
HidNative.FileShareRead | HidNative.FileShareWrite,
|
||||
0, HidNative.OpenExisting, 0, 0);
|
||||
WindowsHidNative.GenericRead | WindowsHidNative.GenericWrite,
|
||||
WindowsHidNative.FileShareRead | WindowsHidNative.FileShareWrite,
|
||||
0, WindowsHidNative.OpenExisting, 0, 0);
|
||||
if (handle.IsInvalid)
|
||||
{
|
||||
handle.Dispose();
|
||||
@@ -262,7 +264,7 @@ internal static class DualSenseReader
|
||||
// to the full 0x31 input report. Harmless over USB.
|
||||
var feature = new byte[41];
|
||||
feature[0] = 0x05;
|
||||
_ = HidNative.HidD_GetFeature(handle, feature, feature.Length);
|
||||
_ = WindowsHidNative.HidD_GetFeature(handle, feature, feature.Length);
|
||||
|
||||
if (!announcedConnect)
|
||||
{
|
||||
@@ -320,18 +322,18 @@ internal static class DualSenseReader
|
||||
private static SafeFileHandle? OpenDualSense(out string? devicePath)
|
||||
{
|
||||
devicePath = null;
|
||||
foreach (var path in HidNative.EnumerateHidDevicePaths())
|
||||
foreach (var path in WindowsHidNative.EnumerateHidDevicePaths())
|
||||
{
|
||||
// Open without access rights just to query VID/PID.
|
||||
using var probe = HidNative.CreateFile(
|
||||
path, 0, HidNative.FileShareRead | HidNative.FileShareWrite, 0, HidNative.OpenExisting, 0, 0);
|
||||
using var probe = WindowsHidNative.CreateFile(
|
||||
path, 0, WindowsHidNative.FileShareRead | WindowsHidNative.FileShareWrite, 0, WindowsHidNative.OpenExisting, 0, 0);
|
||||
if (probe.IsInvalid)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var attributes = new HidNative.HiddAttributes { Size = 12 };
|
||||
if (!HidNative.HidD_GetAttributes(probe, ref attributes) ||
|
||||
var attributes = new WindowsHidNative.HiddAttributes { Size = 12 };
|
||||
if (!WindowsHidNative.HidD_GetAttributes(probe, ref attributes) ||
|
||||
attributes.VendorId != SonyVendorId ||
|
||||
(attributes.ProductId != DualSenseProductId && attributes.ProductId != DualSenseEdgeProductId))
|
||||
{
|
||||
@@ -339,19 +341,19 @@ internal static class DualSenseReader
|
||||
}
|
||||
|
||||
// Read+write so feature reports work; fall back to read-only.
|
||||
var handle = HidNative.CreateFile(
|
||||
var handle = WindowsHidNative.CreateFile(
|
||||
path,
|
||||
HidNative.GenericRead | HidNative.GenericWrite,
|
||||
HidNative.FileShareRead | HidNative.FileShareWrite,
|
||||
0, HidNative.OpenExisting, 0, 0);
|
||||
WindowsHidNative.GenericRead | WindowsHidNative.GenericWrite,
|
||||
WindowsHidNative.FileShareRead | WindowsHidNative.FileShareWrite,
|
||||
0, WindowsHidNative.OpenExisting, 0, 0);
|
||||
if (handle.IsInvalid)
|
||||
{
|
||||
handle.Dispose();
|
||||
handle = HidNative.CreateFile(
|
||||
handle = WindowsHidNative.CreateFile(
|
||||
path,
|
||||
HidNative.GenericRead,
|
||||
HidNative.FileShareRead | HidNative.FileShareWrite,
|
||||
0, HidNative.OpenExisting, 0, 0);
|
||||
WindowsHidNative.GenericRead,
|
||||
WindowsHidNative.FileShareRead | WindowsHidNative.FileShareWrite,
|
||||
0, WindowsHidNative.OpenExisting, 0, 0);
|
||||
}
|
||||
|
||||
if (!handle.IsInvalid)
|
||||
@@ -366,7 +368,7 @@ internal static class DualSenseReader
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool TryParseReport(ReadOnlySpan<byte> report, out PadState state)
|
||||
private static bool TryParseReport(ReadOnlySpan<byte> report, out HostGamepadState state)
|
||||
{
|
||||
// USB: report id 0x01, payload starts at [1].
|
||||
// Bluetooth extended: report id 0x31, sequence byte at [1], payload at [2].
|
||||
@@ -395,43 +397,43 @@ internal static class DualSenseReader
|
||||
var buttons1 = report[offset + 8];
|
||||
var buttons2 = report[offset + 9];
|
||||
|
||||
uint buttons = 0;
|
||||
buttons |= (buttons0 & 0x10) != 0 ? OrbisPadButton.Square : 0;
|
||||
buttons |= (buttons0 & 0x20) != 0 ? OrbisPadButton.Cross : 0;
|
||||
buttons |= (buttons0 & 0x40) != 0 ? OrbisPadButton.Circle : 0;
|
||||
buttons |= (buttons0 & 0x80) != 0 ? OrbisPadButton.Triangle : 0;
|
||||
var buttons = HostGamepadButtons.None;
|
||||
buttons |= (buttons0 & 0x10) != 0 ? HostGamepadButtons.Square : 0;
|
||||
buttons |= (buttons0 & 0x20) != 0 ? HostGamepadButtons.Cross : 0;
|
||||
buttons |= (buttons0 & 0x40) != 0 ? HostGamepadButtons.Circle : 0;
|
||||
buttons |= (buttons0 & 0x80) != 0 ? HostGamepadButtons.Triangle : 0;
|
||||
buttons |= HatToButtons(buttons0 & 0x0F);
|
||||
buttons |= (buttons1 & 0x01) != 0 ? OrbisPadButton.L1 : 0;
|
||||
buttons |= (buttons1 & 0x02) != 0 ? OrbisPadButton.R1 : 0;
|
||||
buttons |= (buttons1 & 0x04) != 0 ? OrbisPadButton.L2 : 0;
|
||||
buttons |= (buttons1 & 0x08) != 0 ? OrbisPadButton.R2 : 0;
|
||||
buttons |= (buttons1 & 0x20) != 0 ? OrbisPadButton.Options : 0;
|
||||
buttons |= (buttons1 & 0x40) != 0 ? OrbisPadButton.L3 : 0;
|
||||
buttons |= (buttons1 & 0x80) != 0 ? OrbisPadButton.R3 : 0;
|
||||
buttons |= (buttons2 & 0x02) != 0 ? OrbisPadButton.TouchPad : 0;
|
||||
buttons |= (buttons1 & 0x01) != 0 ? HostGamepadButtons.L1 : 0;
|
||||
buttons |= (buttons1 & 0x02) != 0 ? HostGamepadButtons.R1 : 0;
|
||||
buttons |= (buttons1 & 0x04) != 0 ? HostGamepadButtons.L2 : 0;
|
||||
buttons |= (buttons1 & 0x08) != 0 ? HostGamepadButtons.R2 : 0;
|
||||
buttons |= (buttons1 & 0x20) != 0 ? HostGamepadButtons.Options : 0;
|
||||
buttons |= (buttons1 & 0x40) != 0 ? HostGamepadButtons.L3 : 0;
|
||||
buttons |= (buttons1 & 0x80) != 0 ? HostGamepadButtons.R3 : 0;
|
||||
buttons |= (buttons2 & 0x02) != 0 ? HostGamepadButtons.TouchPad : 0;
|
||||
|
||||
state = new PadState(
|
||||
state = new HostGamepadState(
|
||||
Connected: true,
|
||||
Buttons: buttons,
|
||||
LeftX: leftX,
|
||||
LeftY: leftY,
|
||||
RightX: rightX,
|
||||
RightY: rightY,
|
||||
L2: l2,
|
||||
R2: r2);
|
||||
LeftTrigger: l2,
|
||||
RightTrigger: r2);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static uint HatToButtons(int hat) => hat switch
|
||||
private static HostGamepadButtons HatToButtons(int hat) => hat switch
|
||||
{
|
||||
0 => OrbisPadButton.Up,
|
||||
1 => OrbisPadButton.Up | OrbisPadButton.Right,
|
||||
2 => OrbisPadButton.Right,
|
||||
3 => OrbisPadButton.Right | OrbisPadButton.Down,
|
||||
4 => OrbisPadButton.Down,
|
||||
5 => OrbisPadButton.Down | OrbisPadButton.Left,
|
||||
6 => OrbisPadButton.Left,
|
||||
7 => OrbisPadButton.Left | OrbisPadButton.Up,
|
||||
0 => HostGamepadButtons.Up,
|
||||
1 => HostGamepadButtons.Up | HostGamepadButtons.Right,
|
||||
2 => HostGamepadButtons.Right,
|
||||
3 => HostGamepadButtons.Right | HostGamepadButtons.Down,
|
||||
4 => HostGamepadButtons.Down,
|
||||
5 => HostGamepadButtons.Down | HostGamepadButtons.Left,
|
||||
6 => HostGamepadButtons.Left,
|
||||
7 => HostGamepadButtons.Left | HostGamepadButtons.Up,
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
+23
-18
@@ -4,13 +4,13 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
namespace SharpEmu.Libs.Pad;
|
||||
namespace SharpEmu.HLE.Host.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// Minimal Win32 HID interop used to talk to a DualSense controller
|
||||
/// directly, without any external input library.
|
||||
/// </summary>
|
||||
internal static partial class HidNative
|
||||
internal static partial class WindowsHidNative
|
||||
{
|
||||
internal const int DigcfPresent = 0x02;
|
||||
internal const int DigcfDeviceInterface = 0x10;
|
||||
@@ -38,28 +38,32 @@ internal static partial class HidNative
|
||||
public ushort VersionNumber;
|
||||
}
|
||||
|
||||
[DllImport("hid.dll")]
|
||||
internal static extern void HidD_GetHidGuid(out Guid hidGuid);
|
||||
[LibraryImport("hid.dll")]
|
||||
internal static partial void HidD_GetHidGuid(out Guid hidGuid);
|
||||
|
||||
[DllImport("hid.dll")]
|
||||
internal static extern bool HidD_GetAttributes(SafeFileHandle hidDeviceObject, ref HiddAttributes attributes);
|
||||
[LibraryImport("hid.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static partial bool HidD_GetAttributes(SafeFileHandle hidDeviceObject, ref HiddAttributes attributes);
|
||||
|
||||
[DllImport("hid.dll")]
|
||||
internal static extern bool HidD_GetFeature(SafeFileHandle hidDeviceObject, byte[] reportBuffer, int reportBufferLength);
|
||||
[LibraryImport("hid.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static partial bool HidD_GetFeature(SafeFileHandle hidDeviceObject, [In, Out] byte[] reportBuffer, int reportBufferLength);
|
||||
|
||||
[DllImport("setupapi.dll", CharSet = CharSet.Unicode)]
|
||||
internal static extern nint SetupDiGetClassDevs(ref Guid classGuid, nint enumerator, nint hwndParent, int flags);
|
||||
[LibraryImport("setupapi.dll", EntryPoint = "SetupDiGetClassDevsW")]
|
||||
internal static partial nint SetupDiGetClassDevs(ref Guid classGuid, nint enumerator, nint hwndParent, int flags);
|
||||
|
||||
[DllImport("setupapi.dll")]
|
||||
internal static extern bool SetupDiEnumDeviceInterfaces(
|
||||
[LibraryImport("setupapi.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static partial bool SetupDiEnumDeviceInterfaces(
|
||||
nint deviceInfoSet,
|
||||
nint deviceInfoData,
|
||||
ref Guid interfaceClassGuid,
|
||||
int memberIndex,
|
||||
ref SpDeviceInterfaceData deviceInterfaceData);
|
||||
|
||||
[DllImport("setupapi.dll", CharSet = CharSet.Unicode)]
|
||||
internal static extern bool SetupDiGetDeviceInterfaceDetail(
|
||||
[LibraryImport("setupapi.dll", EntryPoint = "SetupDiGetDeviceInterfaceDetailW")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static partial bool SetupDiGetDeviceInterfaceDetail(
|
||||
nint deviceInfoSet,
|
||||
ref SpDeviceInterfaceData deviceInterfaceData,
|
||||
nint deviceInterfaceDetailData,
|
||||
@@ -67,11 +71,12 @@ internal static partial class HidNative
|
||||
out int requiredSize,
|
||||
nint deviceInfoData);
|
||||
|
||||
[DllImport("setupapi.dll")]
|
||||
internal static extern bool SetupDiDestroyDeviceInfoList(nint deviceInfoSet);
|
||||
[LibraryImport("setupapi.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static partial bool SetupDiDestroyDeviceInfoList(nint deviceInfoSet);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
internal static extern SafeFileHandle CreateFile(
|
||||
[LibraryImport("kernel32.dll", EntryPoint = "CreateFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
|
||||
internal static partial SafeFileHandle CreateFile(
|
||||
string fileName,
|
||||
uint desiredAccess,
|
||||
uint shareMode,
|
||||
@@ -0,0 +1,84 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SharpEmu.HLE.Host.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// Windows input backend: DualSense over raw HID plus XInput controllers for gamepads,
|
||||
/// user32 for the keyboard-fallback queries. Rumble fans out to every reader; lightbar
|
||||
/// only exists on the DualSense.
|
||||
/// </summary>
|
||||
internal sealed partial class WindowsHostInput : IHostInput
|
||||
{
|
||||
public void EnsureStarted()
|
||||
{
|
||||
WindowsDualSenseReader.EnsureStarted();
|
||||
WindowsXInputReader.EnsureStarted();
|
||||
}
|
||||
|
||||
public int GetGamepadStates(Span<HostGamepadState> destination)
|
||||
{
|
||||
var count = 0;
|
||||
if (count < destination.Length && WindowsDualSenseReader.TryGetState(out var dualSense))
|
||||
{
|
||||
destination[count++] = dualSense;
|
||||
}
|
||||
|
||||
if (count < destination.Length && WindowsXInputReader.TryGetState(out var xinput))
|
||||
{
|
||||
destination[count++] = xinput;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
public string? DescribeConnectedGamepad()
|
||||
{
|
||||
if (WindowsDualSenseReader.TryGetState(out _))
|
||||
{
|
||||
return "DualSense";
|
||||
}
|
||||
|
||||
return WindowsXInputReader.TryGetState(out _) ? "Xbox controller" : null;
|
||||
}
|
||||
|
||||
public void SetRumble(byte largeMotor, byte smallMotor)
|
||||
{
|
||||
WindowsDualSenseReader.SetRumble(largeMotor, smallMotor);
|
||||
WindowsXInputReader.SetRumble(largeMotor, smallMotor);
|
||||
}
|
||||
|
||||
public void SetTriggerRumble(byte? leftTrigger, byte? rightTrigger) =>
|
||||
WindowsXInputReader.SetTriggerRumble(leftTrigger, rightTrigger);
|
||||
|
||||
public void SetLightbar(byte red, byte green, byte blue) =>
|
||||
WindowsDualSenseReader.SetLightbar(red, green, blue);
|
||||
|
||||
public void ResetLightbar() => WindowsDualSenseReader.ResetLightbar();
|
||||
|
||||
public bool IsHostWindowFocused()
|
||||
{
|
||||
var foregroundWindow = GetForegroundWindow();
|
||||
if (foregroundWindow == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
GetWindowThreadProcessId(foregroundWindow, out var processId);
|
||||
return processId == (uint)Environment.ProcessId;
|
||||
}
|
||||
|
||||
public bool IsKeyDown(int virtualKey) =>
|
||||
(GetAsyncKeyState(virtualKey) & 0x8000) != 0;
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial short GetAsyncKeyState(int vKey);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial nint GetForegroundWindow();
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial uint GetWindowThreadProcessId(nint hWnd, out uint processId);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SharpEmu.HLE.Host.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// Windows implementation over VirtualAlloc/VirtualFree/VirtualProtect/VirtualQuery.
|
||||
/// Sealed so the JIT can devirtualize interface calls on fault-handling hot paths.
|
||||
/// </summary>
|
||||
internal sealed unsafe partial class WindowsHostMemory : IHostMemory
|
||||
{
|
||||
private const uint MEM_COMMIT = 0x1000;
|
||||
private const uint MEM_RESERVE = 0x2000;
|
||||
private const uint MEM_RELEASE = 0x8000;
|
||||
private const uint MEM_FREE = 0x10000;
|
||||
|
||||
private const uint PAGE_NOACCESS = 0x01;
|
||||
private const uint PAGE_READONLY = 0x02;
|
||||
private const uint PAGE_READWRITE = 0x04;
|
||||
private const uint PAGE_WRITECOPY = 0x08;
|
||||
private const uint PAGE_EXECUTE = 0x10;
|
||||
private const uint PAGE_EXECUTE_READ = 0x20;
|
||||
private const uint PAGE_EXECUTE_READWRITE = 0x40;
|
||||
private const uint PAGE_EXECUTE_WRITECOPY = 0x80;
|
||||
|
||||
public ulong Allocate(ulong desiredAddress, ulong size, HostPageProtection protection)
|
||||
{
|
||||
return (ulong)VirtualAlloc((void*)desiredAddress, (nuint)size, MEM_COMMIT | MEM_RESERVE, ToNativeProtection(protection));
|
||||
}
|
||||
|
||||
public ulong Reserve(ulong desiredAddress, ulong size, HostPageProtection protection)
|
||||
{
|
||||
return (ulong)VirtualAlloc((void*)desiredAddress, (nuint)size, MEM_RESERVE, ToNativeProtection(protection));
|
||||
}
|
||||
|
||||
public bool Commit(ulong address, ulong size, HostPageProtection protection)
|
||||
{
|
||||
return VirtualAlloc((void*)address, (nuint)size, MEM_COMMIT, ToNativeProtection(protection)) != null;
|
||||
}
|
||||
|
||||
public bool Free(ulong address)
|
||||
{
|
||||
return VirtualFree((void*)address, 0, MEM_RELEASE);
|
||||
}
|
||||
|
||||
public bool Protect(ulong address, ulong size, HostPageProtection protection, out uint rawOldProtection)
|
||||
{
|
||||
return VirtualProtect((void*)address, (nuint)size, ToNativeProtection(protection), out rawOldProtection);
|
||||
}
|
||||
|
||||
public bool ProtectRaw(ulong address, ulong size, uint rawProtection, out uint rawOldProtection)
|
||||
{
|
||||
return VirtualProtect((void*)address, (nuint)size, rawProtection, out rawOldProtection);
|
||||
}
|
||||
|
||||
public bool Query(ulong address, out HostRegionInfo info)
|
||||
{
|
||||
if (VirtualQuery((void*)address, out var mbi, (nuint)sizeof(MemoryBasicInformation64)) == 0)
|
||||
{
|
||||
info = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
info = new HostRegionInfo(
|
||||
mbi.BaseAddress,
|
||||
mbi.AllocationBase,
|
||||
mbi.RegionSize,
|
||||
ToRegionState(mbi.State),
|
||||
mbi.State,
|
||||
ToHostProtection(mbi.Protect),
|
||||
mbi.Protect,
|
||||
mbi.AllocationProtect);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void FlushInstructionCache(ulong address, ulong size)
|
||||
{
|
||||
FlushInstructionCache(GetCurrentProcess(), (void*)address, (nuint)size);
|
||||
}
|
||||
|
||||
private static uint ToNativeProtection(HostPageProtection protection) => protection switch
|
||||
{
|
||||
HostPageProtection.NoAccess => PAGE_NOACCESS,
|
||||
HostPageProtection.ReadOnly => PAGE_READONLY,
|
||||
HostPageProtection.ReadWrite => PAGE_READWRITE,
|
||||
HostPageProtection.Execute => PAGE_EXECUTE,
|
||||
HostPageProtection.ReadExecute => PAGE_EXECUTE_READ,
|
||||
HostPageProtection.ReadWriteExecute => PAGE_EXECUTE_READWRITE,
|
||||
HostPageProtection.ExecuteWriteCopy => PAGE_EXECUTE_WRITECOPY,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(protection), protection, null),
|
||||
};
|
||||
|
||||
private static HostRegionState ToRegionState(uint state) => state switch
|
||||
{
|
||||
MEM_COMMIT => HostRegionState.Committed,
|
||||
MEM_RESERVE => HostRegionState.Reserved,
|
||||
MEM_FREE => HostRegionState.Free,
|
||||
_ => HostRegionState.Free,
|
||||
};
|
||||
|
||||
private static HostPageProtection ToHostProtection(uint rawProtection)
|
||||
{
|
||||
// Strip PAGE_GUARD/PAGE_NOCACHE/PAGE_WRITECOMBINE modifiers; callers needing
|
||||
// them compare HostRegionInfo.RawProtection directly.
|
||||
return (rawProtection & 0xFF) switch
|
||||
{
|
||||
PAGE_READONLY => HostPageProtection.ReadOnly,
|
||||
PAGE_READWRITE => HostPageProtection.ReadWrite,
|
||||
PAGE_WRITECOPY => HostPageProtection.ReadWrite,
|
||||
PAGE_EXECUTE => HostPageProtection.Execute,
|
||||
PAGE_EXECUTE_READ => HostPageProtection.ReadExecute,
|
||||
PAGE_EXECUTE_READWRITE => HostPageProtection.ReadWriteExecute,
|
||||
PAGE_EXECUTE_WRITECOPY => HostPageProtection.ExecuteWriteCopy,
|
||||
_ => HostPageProtection.NoAccess,
|
||||
};
|
||||
}
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
private static partial void* VirtualAlloc(void* lpAddress, nuint dwSize, uint flAllocationType, uint flProtect);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool VirtualFree(void* lpAddress, nuint dwSize, uint dwFreeType);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool VirtualProtect(void* lpAddress, nuint dwSize, uint flNewProtect, out uint lpflOldProtect);
|
||||
|
||||
[LibraryImport("kernel32.dll")]
|
||||
private static partial nuint VirtualQuery(void* lpAddress, out MemoryBasicInformation64 lpBuffer, nuint dwLength);
|
||||
|
||||
[LibraryImport("kernel32.dll")]
|
||||
private static partial void* GetCurrentProcess();
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool FlushInstructionCache(void* hProcess, void* lpBaseAddress, nuint dwSize);
|
||||
|
||||
private struct MemoryBasicInformation64
|
||||
{
|
||||
public ulong BaseAddress;
|
||||
public ulong AllocationBase;
|
||||
public uint AllocationProtect;
|
||||
public uint Alignment1;
|
||||
public ulong RegionSize;
|
||||
public uint State;
|
||||
public uint Protect;
|
||||
public uint Type;
|
||||
public uint Alignment2;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE.Host.Windows;
|
||||
|
||||
internal sealed class WindowsHostPlatform : IHostPlatform
|
||||
{
|
||||
public IHostMemory Memory { get; } = new WindowsHostMemory();
|
||||
|
||||
public IHostThreading Threading { get; } = new WindowsHostThreading();
|
||||
|
||||
public IHostSymbolResolver Symbols { get; } = new WindowsHostSymbolResolver();
|
||||
|
||||
public IHostAudioOutput Audio { get; } = new WindowsWaveOutAudio();
|
||||
|
||||
public IHostInput Input { get; } = new WindowsHostInput();
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SharpEmu.HLE.Host.Windows;
|
||||
|
||||
internal sealed partial class WindowsHostSymbolResolver : IHostSymbolResolver
|
||||
{
|
||||
public nint GetAddress(HostRuntimeFunction function)
|
||||
{
|
||||
var kernel32 = GetModuleHandle("kernel32.dll");
|
||||
if (kernel32 == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
return GetProcAddress(kernel32, function switch
|
||||
{
|
||||
HostRuntimeFunction.TlsGetValue => "TlsGetValue",
|
||||
HostRuntimeFunction.QueryPerformanceCounter => "QueryPerformanceCounter",
|
||||
HostRuntimeFunction.SwitchToThread => "SwitchToThread",
|
||||
HostRuntimeFunction.Sleep => "Sleep",
|
||||
HostRuntimeFunction.WaitForSingleObject => "WaitForSingleObject",
|
||||
HostRuntimeFunction.SetEvent => "SetEvent",
|
||||
HostRuntimeFunction.ExitThread => "ExitThread",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(function), function, null),
|
||||
});
|
||||
}
|
||||
|
||||
// Utf16 marshalling pins the managed string and passes its address directly
|
||||
// (no copy); Utf8 stack-allocates the transient buffer for these short
|
||||
// ASCII export names. LibraryImport is exact-spelling, hence the W entry point.
|
||||
[LibraryImport("kernel32.dll", EntryPoint = "GetModuleHandleW", StringMarshalling = StringMarshalling.Utf16)]
|
||||
private static partial nint GetModuleHandle(string lpModuleName);
|
||||
|
||||
[LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf8)]
|
||||
private static partial nint GetProcAddress(nint hModule, string procName);
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SharpEmu.HLE.Host.Windows;
|
||||
|
||||
internal sealed unsafe partial class WindowsHostThreading : IHostThreading
|
||||
{
|
||||
private const uint StackSizeParamIsAReservation = 0x00010000u;
|
||||
private const uint ThreadGetContext = 0x0008u;
|
||||
private const uint ThreadSuspendResume = 0x0002u;
|
||||
|
||||
// Win64 CONTEXT layout (CONTROL | INTEGER only — no XMM state is requested).
|
||||
private const int Win64ContextSize = 0x4D0;
|
||||
private const int Win64ContextFlagsOffset = 0x30;
|
||||
private const uint ContextAmd64ControlInteger = 0x00100003u;
|
||||
private const int CtxRax = 120;
|
||||
private const int CtxRcx = 128;
|
||||
private const int CtxRdx = 136;
|
||||
private const int CtxRbx = 144;
|
||||
private const int CtxRsp = 152;
|
||||
private const int CtxRbp = 160;
|
||||
private const int CtxRip = 248;
|
||||
|
||||
private static int _timerResolutionRequested;
|
||||
|
||||
public void RequestTimerResolution()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _timerResolutionRequested, 1) != 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (TimeBeginPeriod(1) != 0)
|
||||
{
|
||||
Console.Error.WriteLine(
|
||||
"[LOADER][WARN] Host timer resolution request rejected; " +
|
||||
"timed waits keep the default ~15.6 ms granularity.");
|
||||
}
|
||||
}
|
||||
catch (DllNotFoundException exception)
|
||||
{
|
||||
Console.Error.WriteLine(
|
||||
$"[LOADER][WARN] Host timer resolution unavailable: {exception.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public uint AllocateTlsSlot() => TlsAlloc();
|
||||
|
||||
public bool FreeTlsSlot(uint slot) => TlsFree(slot);
|
||||
|
||||
public bool SetTlsValue(uint slot, nint value) => TlsSetValue(slot, value);
|
||||
|
||||
public nint GetTlsValue(uint slot) => TlsGetValue(slot);
|
||||
|
||||
public uint CurrentThreadId => GetCurrentThreadId();
|
||||
|
||||
public bool TrySetCurrentThreadAffinity(nuint affinityMask)
|
||||
{
|
||||
return SetThreadAffinityMask(GetCurrentThread(), affinityMask) != 0;
|
||||
}
|
||||
|
||||
public nint CreateNativeThread(nint entry, nint parameter, nuint stackReserveBytes, out uint threadId)
|
||||
{
|
||||
return CreateThread(0, stackReserveBytes, entry, parameter, StackSizeParamIsAReservation, out threadId);
|
||||
}
|
||||
|
||||
public bool WaitForThreadExit(nint threadHandle, uint timeoutMilliseconds)
|
||||
{
|
||||
return WaitForSingleObject(threadHandle, timeoutMilliseconds) == 0u;
|
||||
}
|
||||
|
||||
public void CloseThreadHandle(nint threadHandle)
|
||||
{
|
||||
_ = CloseHandle(threadHandle);
|
||||
}
|
||||
|
||||
public bool TryCaptureThreadRegisters(uint threadId, out HostCapturedRegisters registers)
|
||||
{
|
||||
registers = default;
|
||||
var threadHandle = OpenThread(ThreadGetContext | ThreadSuspendResume, false, threadId);
|
||||
if (threadHandle == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
void* contextRecord = null;
|
||||
var suspended = false;
|
||||
try
|
||||
{
|
||||
if (SuspendThread(threadHandle) == uint.MaxValue)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
suspended = true;
|
||||
// CONTEXT requires 16-byte alignment (it embeds M128A fields);
|
||||
// NativeMemory.AllocZeroed guarantees max_align_t, stackalloc only
|
||||
// pointer-size — so this stays a native allocation.
|
||||
contextRecord = NativeMemory.AllocZeroed((nuint)Win64ContextSize);
|
||||
*(uint*)((byte*)contextRecord + Win64ContextFlagsOffset) = ContextAmd64ControlInteger;
|
||||
if (!GetThreadContext(threadHandle, contextRecord))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
registers = new HostCapturedRegisters(
|
||||
ReadU64(contextRecord, CtxRip),
|
||||
ReadU64(contextRecord, CtxRsp),
|
||||
ReadU64(contextRecord, CtxRbp),
|
||||
ReadU64(contextRecord, CtxRax),
|
||||
ReadU64(contextRecord, CtxRbx),
|
||||
ReadU64(contextRecord, CtxRcx),
|
||||
ReadU64(contextRecord, CtxRdx));
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (contextRecord != null)
|
||||
{
|
||||
NativeMemory.Free(contextRecord);
|
||||
}
|
||||
if (suspended)
|
||||
{
|
||||
_ = ResumeThread(threadHandle);
|
||||
}
|
||||
_ = CloseHandle(threadHandle);
|
||||
}
|
||||
}
|
||||
|
||||
private static ulong ReadU64(void* contextRecord, int offset)
|
||||
{
|
||||
return *(ulong*)((byte*)contextRecord + offset);
|
||||
}
|
||||
|
||||
[LibraryImport("kernel32.dll")]
|
||||
private static partial uint TlsAlloc();
|
||||
|
||||
[LibraryImport("kernel32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool TlsFree(uint dwTlsIndex);
|
||||
|
||||
[LibraryImport("kernel32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool TlsSetValue(uint dwTlsIndex, nint lpTlsValue);
|
||||
|
||||
[LibraryImport("kernel32.dll")]
|
||||
private static partial nint TlsGetValue(uint dwTlsIndex);
|
||||
|
||||
[LibraryImport("kernel32.dll")]
|
||||
private static partial uint GetCurrentThreadId();
|
||||
|
||||
[LibraryImport("kernel32.dll")]
|
||||
private static partial nint GetCurrentThread();
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
private static partial nuint SetThreadAffinityMask(nint hThread, nuint dwThreadAffinityMask);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
private static partial nint CreateThread(
|
||||
nint lpThreadAttributes,
|
||||
nuint dwStackSize,
|
||||
nint lpStartAddress,
|
||||
nint lpParameter,
|
||||
uint dwCreationFlags,
|
||||
out uint lpThreadId);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
private static partial uint WaitForSingleObject(nint hHandle, uint dwMilliseconds);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
private static partial nint OpenThread(uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwThreadId);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
private static partial uint SuspendThread(nint hThread);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
private static partial uint ResumeThread(nint hThread);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool GetThreadContext(nint hThread, void* lpContext);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool CloseHandle(nint hObject);
|
||||
|
||||
[LibraryImport("winmm.dll", EntryPoint = "timeBeginPeriod")]
|
||||
private static partial uint TimeBeginPeriod(uint uPeriod);
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SharpEmu.HLE.Host.Windows;
|
||||
|
||||
internal sealed partial class WindowsWaveOutAudio : IHostAudioOutput
|
||||
{
|
||||
public string BackendName => "winmm";
|
||||
|
||||
public IHostAudioStream OpenStereoPcm16Stream(uint sampleRate) => new WaveOutStream(sampleRate);
|
||||
|
||||
private sealed partial class WaveOutStream : IHostAudioStream
|
||||
{
|
||||
private const uint WaveMapper = uint.MaxValue;
|
||||
private const uint CallbackEvent = 0x0005_0000;
|
||||
private const ushort WaveFormatPcm = 1;
|
||||
private const uint WaveHeaderDone = 0x0000_0001;
|
||||
private const int MaximumQueuedPcmBytes = 32 * 1024;
|
||||
|
||||
private readonly object _gate = new();
|
||||
private readonly AutoResetEvent _completion = new(false);
|
||||
private readonly Queue<NativeBuffer> _buffers = new();
|
||||
private IntPtr _device;
|
||||
private int _queuedPcmBytes;
|
||||
private bool _disposed;
|
||||
|
||||
public WaveOutStream(uint sampleRate)
|
||||
{
|
||||
var format = new WaveFormat
|
||||
{
|
||||
FormatTag = WaveFormatPcm,
|
||||
Channels = 2,
|
||||
SamplesPerSecond = sampleRate,
|
||||
AverageBytesPerSecond = checked(sampleRate * 4),
|
||||
BlockAlign = 4,
|
||||
BitsPerSample = 16,
|
||||
ExtraSize = 0,
|
||||
};
|
||||
var result = WaveOutOpen(
|
||||
out _device,
|
||||
WaveMapper,
|
||||
ref format,
|
||||
_completion.SafeWaitHandle.DangerousGetHandle(),
|
||||
IntPtr.Zero,
|
||||
CallbackEvent);
|
||||
if (result != 0)
|
||||
{
|
||||
throw new InvalidOperationException($"waveOutOpen failed with MMRESULT {result}.");
|
||||
}
|
||||
}
|
||||
|
||||
public bool Submit(ReadOnlySpan<byte> stereoPcm16)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
ReapCompletedBuffers();
|
||||
while (_queuedPcmBytes != 0 &&
|
||||
_queuedPcmBytes + stereoPcm16.Length > MaximumQueuedPcmBytes)
|
||||
{
|
||||
if (!_completion.WaitOne(TimeSpan.FromSeconds(1)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
ReapCompletedBuffers();
|
||||
}
|
||||
|
||||
return QueueBuffer(stereoPcm16);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
if (_device != IntPtr.Zero)
|
||||
{
|
||||
WaveOutReset(_device);
|
||||
while (_buffers.TryDequeue(out var buffer))
|
||||
{
|
||||
ReleaseBuffer(buffer);
|
||||
}
|
||||
|
||||
WaveOutClose(_device);
|
||||
_device = IntPtr.Zero;
|
||||
}
|
||||
|
||||
_completion.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private bool QueueBuffer(ReadOnlySpan<byte> data)
|
||||
{
|
||||
var dataAddress = Marshal.AllocHGlobal(data.Length);
|
||||
var headerAddress = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
data.CopyTo(new Span<byte>((void*)dataAddress, data.Length));
|
||||
}
|
||||
|
||||
var header = new WaveHeader
|
||||
{
|
||||
Data = dataAddress,
|
||||
BufferLength = checked((uint)data.Length),
|
||||
};
|
||||
headerAddress = Marshal.AllocHGlobal(Marshal.SizeOf<WaveHeader>());
|
||||
Marshal.StructureToPtr(header, headerAddress, false);
|
||||
|
||||
var result = WaveOutPrepareHeader(
|
||||
_device,
|
||||
headerAddress,
|
||||
checked((uint)Marshal.SizeOf<WaveHeader>()));
|
||||
if (result != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
result = WaveOutWrite(
|
||||
_device,
|
||||
headerAddress,
|
||||
checked((uint)Marshal.SizeOf<WaveHeader>()));
|
||||
if (result != 0)
|
||||
{
|
||||
WaveOutUnprepareHeader(
|
||||
_device,
|
||||
headerAddress,
|
||||
checked((uint)Marshal.SizeOf<WaveHeader>()));
|
||||
return false;
|
||||
}
|
||||
|
||||
_buffers.Enqueue(new NativeBuffer(dataAddress, headerAddress, data.Length));
|
||||
_queuedPcmBytes += data.Length;
|
||||
dataAddress = IntPtr.Zero;
|
||||
headerAddress = IntPtr.Zero;
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (headerAddress != IntPtr.Zero)
|
||||
{
|
||||
Marshal.FreeHGlobal(headerAddress);
|
||||
}
|
||||
|
||||
if (dataAddress != IntPtr.Zero)
|
||||
{
|
||||
Marshal.FreeHGlobal(dataAddress);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ReapCompletedBuffers()
|
||||
{
|
||||
while (_buffers.TryPeek(out var buffer))
|
||||
{
|
||||
var header = Marshal.PtrToStructure<WaveHeader>(buffer.Header);
|
||||
if ((header.Flags & WaveHeaderDone) == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_buffers.Dequeue();
|
||||
ReleaseBuffer(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
private void ReleaseBuffer(NativeBuffer buffer)
|
||||
{
|
||||
WaveOutUnprepareHeader(
|
||||
_device,
|
||||
buffer.Header,
|
||||
checked((uint)Marshal.SizeOf<WaveHeader>()));
|
||||
_queuedPcmBytes -= buffer.Length;
|
||||
Marshal.FreeHGlobal(buffer.Header);
|
||||
Marshal.FreeHGlobal(buffer.Data);
|
||||
}
|
||||
|
||||
private readonly record struct NativeBuffer(IntPtr Data, IntPtr Header, int Length);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 2)]
|
||||
private struct WaveFormat
|
||||
{
|
||||
public ushort FormatTag;
|
||||
public ushort Channels;
|
||||
public uint SamplesPerSecond;
|
||||
public uint AverageBytesPerSecond;
|
||||
public ushort BlockAlign;
|
||||
public ushort BitsPerSample;
|
||||
public ushort ExtraSize;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct WaveHeader
|
||||
{
|
||||
public IntPtr Data;
|
||||
public uint BufferLength;
|
||||
public uint BytesRecorded;
|
||||
public nuint User;
|
||||
public uint Flags;
|
||||
public uint Loops;
|
||||
public IntPtr Next;
|
||||
public nuint Reserved;
|
||||
}
|
||||
|
||||
[LibraryImport("winmm.dll", EntryPoint = "waveOutOpen")]
|
||||
private static partial uint WaveOutOpen(
|
||||
out IntPtr device,
|
||||
uint deviceId,
|
||||
ref WaveFormat format,
|
||||
IntPtr callback,
|
||||
IntPtr instance,
|
||||
uint flags);
|
||||
|
||||
[LibraryImport("winmm.dll", EntryPoint = "waveOutPrepareHeader")]
|
||||
private static partial uint WaveOutPrepareHeader(IntPtr device, IntPtr header, uint headerSize);
|
||||
|
||||
[LibraryImport("winmm.dll", EntryPoint = "waveOutWrite")]
|
||||
private static partial uint WaveOutWrite(IntPtr device, IntPtr header, uint headerSize);
|
||||
|
||||
[LibraryImport("winmm.dll", EntryPoint = "waveOutUnprepareHeader")]
|
||||
private static partial uint WaveOutUnprepareHeader(IntPtr device, IntPtr header, uint headerSize);
|
||||
|
||||
[LibraryImport("winmm.dll", EntryPoint = "waveOutReset")]
|
||||
private static partial uint WaveOutReset(IntPtr device);
|
||||
|
||||
[LibraryImport("winmm.dll", EntryPoint = "waveOutClose")]
|
||||
private static partial uint WaveOutClose(IntPtr device);
|
||||
}
|
||||
}
|
||||
+67
-36
@@ -3,15 +3,15 @@
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SharpEmu.Libs.Pad;
|
||||
namespace SharpEmu.HLE.Host.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// Reads Xbox 360 / Xbox One (and other XInput-compatible) controllers via
|
||||
/// the Windows XInput API on a background thread, translated to the same
|
||||
/// ORBIS pad conventions as <see cref="DualSenseReader"/>. Supports rumble
|
||||
/// and hot-plug retry; the first connected slot (of four) is used.
|
||||
/// the Windows XInput API on a background thread, translated to
|
||||
/// <see cref="HostGamepadState"/> conventions. Supports rumble and hot-plug
|
||||
/// retry; the first connected slot (of four) is used.
|
||||
/// </summary>
|
||||
internal static class XInputReader
|
||||
internal static partial class WindowsXInputReader
|
||||
{
|
||||
private const uint ErrorSuccess = 0;
|
||||
private const int SlotCount = 4;
|
||||
@@ -34,15 +34,19 @@ internal static class XInputReader
|
||||
private const ushort XinputY = 0x8000;
|
||||
|
||||
private static readonly object Gate = new();
|
||||
private static PadState _state;
|
||||
private static HostGamepadState _state;
|
||||
private static bool _started;
|
||||
private static int _slot = -1; // connected XInput user index, -1 when none
|
||||
private static byte _motorLeft;
|
||||
private static byte _motorRight;
|
||||
private static byte _triggerLeft;
|
||||
private static byte _triggerRight;
|
||||
|
||||
/// <summary>Starts the background reader once; safe to call repeatedly.</summary>
|
||||
internal static void EnsureStarted()
|
||||
{
|
||||
// The GUI source-links this reader and calls it directly, without the
|
||||
// host-platform resolution that otherwise guarantees Windows.
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
return;
|
||||
@@ -65,7 +69,7 @@ internal static class XInputReader
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool TryGetState(out PadState state)
|
||||
internal static bool TryGetState(out HostGamepadState state)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
@@ -75,7 +79,7 @@ internal static class XInputReader
|
||||
return state.Connected;
|
||||
}
|
||||
|
||||
private static void SetState(in PadState state)
|
||||
private static void SetState(in HostGamepadState state)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
@@ -99,6 +103,31 @@ internal static class XInputReader
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Approximates per-trigger vibration on the two XInput body motors.</summary>
|
||||
internal static void SetTriggerRumble(byte? leftTrigger, byte? rightTrigger)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
var changed = false;
|
||||
if (leftTrigger is { } left)
|
||||
{
|
||||
changed |= _triggerLeft != left;
|
||||
_triggerLeft = left;
|
||||
}
|
||||
|
||||
if (rightTrigger is { } right)
|
||||
{
|
||||
changed |= _triggerRight != right;
|
||||
_triggerRight = right;
|
||||
}
|
||||
|
||||
if (changed)
|
||||
{
|
||||
SendRumbleLocked();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void SendRumbleLocked()
|
||||
{
|
||||
if (_slot < 0)
|
||||
@@ -108,8 +137,8 @@ internal static class XInputReader
|
||||
|
||||
var vibration = new XInputVibration
|
||||
{
|
||||
LeftMotorSpeed = (ushort)(_motorLeft * 257), // 0..255 -> 0..65535
|
||||
RightMotorSpeed = (ushort)(_motorRight * 257),
|
||||
LeftMotorSpeed = (ushort)(Math.Max(_motorLeft, _triggerLeft) * 257),
|
||||
RightMotorSpeed = (ushort)(Math.Max(_motorRight, _triggerRight) * 257),
|
||||
};
|
||||
_ = XInputSetState((uint)_slot, ref vibration);
|
||||
}
|
||||
@@ -147,6 +176,8 @@ internal static class XInputReader
|
||||
_slot = -1;
|
||||
_motorLeft = 0;
|
||||
_motorRight = 0;
|
||||
_triggerLeft = 0;
|
||||
_triggerRight = 0;
|
||||
_state = default;
|
||||
}
|
||||
|
||||
@@ -175,40 +206,40 @@ internal static class XInputReader
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static PadState Translate(in XInputGamepad pad)
|
||||
private static HostGamepadState Translate(in XInputGamepad pad)
|
||||
{
|
||||
uint buttons = 0;
|
||||
buttons |= (pad.Buttons & XinputDpadUp) != 0 ? OrbisPadButton.Up : 0;
|
||||
buttons |= (pad.Buttons & XinputDpadDown) != 0 ? OrbisPadButton.Down : 0;
|
||||
buttons |= (pad.Buttons & XinputDpadLeft) != 0 ? OrbisPadButton.Left : 0;
|
||||
buttons |= (pad.Buttons & XinputDpadRight) != 0 ? OrbisPadButton.Right : 0;
|
||||
buttons |= (pad.Buttons & XinputStart) != 0 ? OrbisPadButton.Options : 0;
|
||||
buttons |= (pad.Buttons & XinputBack) != 0 ? OrbisPadButton.TouchPad : 0;
|
||||
buttons |= (pad.Buttons & XinputLeftThumb) != 0 ? OrbisPadButton.L3 : 0;
|
||||
buttons |= (pad.Buttons & XinputRightThumb) != 0 ? OrbisPadButton.R3 : 0;
|
||||
buttons |= (pad.Buttons & XinputLeftShoulder) != 0 ? OrbisPadButton.L1 : 0;
|
||||
buttons |= (pad.Buttons & XinputRightShoulder) != 0 ? OrbisPadButton.R1 : 0;
|
||||
buttons |= (pad.Buttons & XinputA) != 0 ? OrbisPadButton.Cross : 0;
|
||||
buttons |= (pad.Buttons & XinputB) != 0 ? OrbisPadButton.Circle : 0;
|
||||
buttons |= (pad.Buttons & XinputX) != 0 ? OrbisPadButton.Square : 0;
|
||||
buttons |= (pad.Buttons & XinputY) != 0 ? OrbisPadButton.Triangle : 0;
|
||||
buttons |= pad.LeftTrigger > TriggerThreshold ? OrbisPadButton.L2 : 0;
|
||||
buttons |= pad.RightTrigger > TriggerThreshold ? OrbisPadButton.R2 : 0;
|
||||
var buttons = HostGamepadButtons.None;
|
||||
buttons |= (pad.Buttons & XinputDpadUp) != 0 ? HostGamepadButtons.Up : 0;
|
||||
buttons |= (pad.Buttons & XinputDpadDown) != 0 ? HostGamepadButtons.Down : 0;
|
||||
buttons |= (pad.Buttons & XinputDpadLeft) != 0 ? HostGamepadButtons.Left : 0;
|
||||
buttons |= (pad.Buttons & XinputDpadRight) != 0 ? HostGamepadButtons.Right : 0;
|
||||
buttons |= (pad.Buttons & XinputStart) != 0 ? HostGamepadButtons.Options : 0;
|
||||
buttons |= (pad.Buttons & XinputBack) != 0 ? HostGamepadButtons.TouchPad : 0;
|
||||
buttons |= (pad.Buttons & XinputLeftThumb) != 0 ? HostGamepadButtons.L3 : 0;
|
||||
buttons |= (pad.Buttons & XinputRightThumb) != 0 ? HostGamepadButtons.R3 : 0;
|
||||
buttons |= (pad.Buttons & XinputLeftShoulder) != 0 ? HostGamepadButtons.L1 : 0;
|
||||
buttons |= (pad.Buttons & XinputRightShoulder) != 0 ? HostGamepadButtons.R1 : 0;
|
||||
buttons |= (pad.Buttons & XinputA) != 0 ? HostGamepadButtons.Cross : 0;
|
||||
buttons |= (pad.Buttons & XinputB) != 0 ? HostGamepadButtons.Circle : 0;
|
||||
buttons |= (pad.Buttons & XinputX) != 0 ? HostGamepadButtons.Square : 0;
|
||||
buttons |= (pad.Buttons & XinputY) != 0 ? HostGamepadButtons.Triangle : 0;
|
||||
buttons |= pad.LeftTrigger > TriggerThreshold ? HostGamepadButtons.L2 : 0;
|
||||
buttons |= pad.RightTrigger > TriggerThreshold ? HostGamepadButtons.R2 : 0;
|
||||
|
||||
return new PadState(
|
||||
return new HostGamepadState(
|
||||
Connected: true,
|
||||
Buttons: buttons,
|
||||
LeftX: AxisToByte(pad.ThumbLX),
|
||||
LeftY: AxisToByteInverted(pad.ThumbLY),
|
||||
RightX: AxisToByte(pad.ThumbRX),
|
||||
RightY: AxisToByteInverted(pad.ThumbRY),
|
||||
L2: pad.LeftTrigger,
|
||||
R2: pad.RightTrigger);
|
||||
LeftTrigger: pad.LeftTrigger,
|
||||
RightTrigger: pad.RightTrigger);
|
||||
}
|
||||
|
||||
private static byte AxisToByte(short value) => (byte)((value + 32768) >> 8);
|
||||
|
||||
// XInput Y grows upward, ORBIS pads report Y growing downward.
|
||||
// XInput Y grows upward, host pad conventions report Y growing downward.
|
||||
private static byte AxisToByteInverted(short value) => (byte)(255 - ((value + 32768) >> 8));
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
@@ -238,9 +269,9 @@ internal static class XInputReader
|
||||
}
|
||||
|
||||
// xinput1_4.dll ships with Windows 8 and later.
|
||||
[DllImport("xinput1_4.dll")]
|
||||
private static extern uint XInputGetState(uint userIndex, out XInputState state);
|
||||
[LibraryImport("xinput1_4.dll")]
|
||||
private static partial uint XInputGetState(uint userIndex, out XInputState state);
|
||||
|
||||
[DllImport("xinput1_4.dll")]
|
||||
private static extern uint XInputSetState(uint userIndex, ref XInputVibration vibration);
|
||||
[LibraryImport("xinput1_4.dll")]
|
||||
private static partial uint XInputSetState(uint userIndex, ref XInputVibration vibration);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace SharpEmu.HLE;
|
||||
|
||||
/// <summary>
|
||||
/// Runs work on the real process main thread. GLFW windowing must live on
|
||||
/// that thread on macOS (AppKit) and Linux (X11's single event queue), so the
|
||||
/// CLI moves emulation onto a worker thread, parks the main thread in
|
||||
/// <see cref="Pump"/>, and the video presenter posts its window loop here. On
|
||||
/// Windows <see cref="IsAvailable"/> stays false and the window keeps its own
|
||||
/// thread.
|
||||
/// </summary>
|
||||
public static class HostMainThread
|
||||
{
|
||||
private static readonly BlockingCollection<Action> _work = new();
|
||||
private static Action? _shutdownRequestHandler;
|
||||
|
||||
public static bool IsAvailable { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Registers a callback invoked by <see cref="Shutdown"/> so a
|
||||
/// long-running posted work item (the presenter's window loop) can be
|
||||
/// asked to return to the pump.
|
||||
/// </summary>
|
||||
public static void SetShutdownRequestHandler(Action handler) =>
|
||||
_shutdownRequestHandler = handler;
|
||||
|
||||
/// <summary>Marks the pump as present. Call before guest code can run.</summary>
|
||||
public static void Enable() => IsAvailable = true;
|
||||
|
||||
public static void Post(Action work)
|
||||
{
|
||||
try
|
||||
{
|
||||
_work.Add(work);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// Shutdown already requested; the process is exiting.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Services posted work on the calling (main) thread until
|
||||
/// <see cref="Shutdown"/> is called and the queue drains.
|
||||
/// </summary>
|
||||
public static void Pump()
|
||||
{
|
||||
foreach (var work in _work.GetConsumingEnumerable())
|
||||
{
|
||||
try
|
||||
{
|
||||
work();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Console.Error.WriteLine($"[LOADER][ERROR] Main-thread work failed: {exception}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void Shutdown()
|
||||
{
|
||||
IsAvailable = false;
|
||||
try
|
||||
{
|
||||
_shutdownRequestHandler?.Invoke();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Console.Error.WriteLine($"[LOADER][WARN] Main-thread shutdown handler failed: {exception.Message}");
|
||||
}
|
||||
|
||||
_work.CompleteAdding();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
namespace SharpEmu.HLE;
|
||||
|
||||
/// <summary>
|
||||
/// Lets host-facing libraries (VideoOut, AudioOut) request cooperative guest
|
||||
/// shutdown without taking a dependency on SharpEmu.Core.
|
||||
/// </summary>
|
||||
public static class HostSessionControl
|
||||
{
|
||||
private static Action<string>? _shutdownHandler;
|
||||
|
||||
public static void SetShutdownHandler(Action<string>? handler)
|
||||
{
|
||||
Volatile.Write(ref _shutdownHandler, handler);
|
||||
}
|
||||
|
||||
public static void RequestShutdown(string reason)
|
||||
{
|
||||
try
|
||||
{
|
||||
Volatile.Read(ref _shutdownHandler)?.Invoke(reason);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Console.Error.WriteLine(
|
||||
$"[LOADER][WARN] Host shutdown handler failed: {exception.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user