Compare commits

..

1 Commits

Author SHA1 Message Date
ParantezTech 7fe80278f1 chore: bump version to 0.0.2-beta.5 2026-07-23 03:06:53 +03:00
1118 changed files with 48136 additions and 236324 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 219 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 356 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 356 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 398 KiB

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 485 KiB

After

Width:  |  Height:  |  Size: 229 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 227 KiB

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 538 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 693 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 393 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 392 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 104 KiB

After

Width:  |  Height:  |  Size: 86 KiB

View File

@ -12,7 +12,7 @@ on:
jobs:
dispatch:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- name: Trigger sharpemu-site rebuild
env:

View File

@ -26,7 +26,7 @@ permissions:
jobs:
comment:
name: Post artifact links
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
# Only for successful PR builds — artifacts exist only when the build passed.
if: >-
github.event.workflow_run.event == 'pull_request' &&

View File

@ -34,7 +34,7 @@ concurrency:
jobs:
init:
name: Init
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
outputs:
release-name: ${{ steps.vars.outputs.release-name }}
release-tag: ${{ steps.vars.outputs.release-tag }}
@ -71,7 +71,7 @@ jobs:
reuse:
name: REUSE Compliance
needs: init
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v6
@ -80,7 +80,7 @@ jobs:
uses: fsfe/reuse-action@v6
build:
name: Build win-x64
name: Build Archive
needs:
- init
- reuse
@ -138,7 +138,7 @@ jobs:
fail-fast: false
matrix:
include:
- os: ubuntu-26.04
- os: ubuntu-latest
rid: linux-x64
- os: macos-latest
rid: osx-x64
@ -227,15 +227,10 @@ jobs:
# Versioned releases are immutable and tag-driven. Branch and manual runs
# still produce Actions artifacts without modifying a published release.
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout repository
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Download build artifacts
uses: actions/download-artifact@v8
with:
@ -263,61 +258,6 @@ jobs:
tar -czf "release-assets/sharpemu-${VERSION}-linux-x64.tar.gz" -C "${linux_dir}" .
tar -czf "release-assets/sharpemu-${VERSION}-osx-x64.tar.gz" -C "${macos_dir}" .
- name: Build release notes
shell: bash
env:
MAX_COMMITS: 200
RELEASE_TAG: ${{ needs.init.outputs.release-tag }}
REPO_URL: ${{ github.server_url }}/${{ github.repository }}
SHORT_SHA: ${{ needs.init.outputs.short-sha }}
VERSION: ${{ needs.init.outputs.version }}
run: |
set -euo pipefail
previous_tag="$(git describe --tags --abbrev=0 --match 'v*' "${RELEASE_TAG}^" 2>/dev/null || true)"
if [ -n "${previous_tag}" ]; then
range="${previous_tag}..${RELEASE_TAG}"
else
range="${RELEASE_TAG}"
fi
git log --no-merges --reverse --pretty=tformat:"%H%x1f%h%x1f%s" "${range}" > commits.txt
total="$(wc -l < commits.txt)"
{
printf 'Automated SharpEmu v%s build for commit [`%s`](%s/commit/%s).\n\n' \
"${VERSION}" "${SHORT_SHA}" "${REPO_URL}" "${GITHUB_SHA}"
if [ -n "${previous_tag}" ]; then
printf '## Changes since %s\n\n' "${previous_tag}"
else
printf '## Changes\n\n'
fi
if [ "${total}" -eq 0 ]; then
printf '_No commits since %s._\n' "${previous_tag}"
else
head -n "${MAX_COMMITS}" commits.txt | while IFS=$'\x1f' read -r sha short subject; do
printf -- '- %s ([`%s`](%s/commit/%s))\n' "${subject}" "${short}" "${REPO_URL}" "${sha}"
done
if [ "${total}" -gt "${MAX_COMMITS}" ]; then
printf '\n_…and %s more commits._\n' "$((total - MAX_COMMITS))"
fi
fi
printf '\n'
if [ -n "${previous_tag}" ]; then
printf '**Full changelog**: %s/compare/%s...%s\n' "${REPO_URL}" "${previous_tag}" "${RELEASE_TAG}"
else
printf '**Full changelog**: %s/commits/%s\n' "${REPO_URL}" "${RELEASE_TAG}"
fi
} > release-notes.md
cat release-notes.md
- name: Create release
shell: bash
env:
@ -325,6 +265,7 @@ jobs:
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: |
mapfile -t assets < <(find release-assets -maxdepth 1 -type f \( -name '*.zip' -o -name '*.tar.gz' \) | sort)
if [ "${#assets[@]}" -ne 3 ]; then
@ -332,6 +273,8 @@ jobs:
exit 1
fi
notes="Automated SharpEmu v${VERSION} build for commit ${GITHUB_SHA}."
if gh release view "${RELEASE_TAG}" >/dev/null 2>&1; then
echo "Release ${RELEASE_TAG} already exists and will not be modified." >&2
exit 1
@ -340,4 +283,4 @@ jobs:
gh release create "${RELEASE_TAG}" "${assets[@]}" \
--verify-tag \
--title "${RELEASE_NAME}" \
--notes-file release-notes.md
--notes "${notes}"

4
.gitignore vendored
View File

@ -42,6 +42,4 @@ ehthumbs.db
.vs/
.idea/
.vscode/
clean_test/
.debug/
.vscode/

View File

@ -9,7 +9,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<SharpEmuVersion>0.0.5-nexus</SharpEmuVersion>
<SharpEmuVersion>0.0.2-beta.5</SharpEmuVersion>
<Version>$(SharpEmuVersion)</Version>
<RepoRoot>$([MSBuild]::NormalizeDirectory('$(MSBuildThisFileDirectory)'))</RepoRoot>

View File

@ -7,27 +7,23 @@ SPDX-License-Identifier: GPL-2.0-or-later
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Avalonia" Version="12.1.0" />
<PackageVersion Include="Avalonia.Desktop" Version="12.1.0" />
<PackageVersion Include="Avalonia.Fonts.Inter" Version="12.1.0" />
<PackageVersion Include="Avalonia.Themes.Fluent" Version="12.1.0" />
<PackageVersion Include="Avalonia" Version="11.3.18" />
<PackageVersion Include="Avalonia.Desktop" Version="11.3.18" />
<PackageVersion Include="Avalonia.Fonts.Inter" Version="11.3.18" />
<PackageVersion Include="Avalonia.Themes.Fluent" Version="11.3.18" />
<PackageVersion Include="FFmpeg.AutoGen" Version="7.1.1" />
<PackageVersion Include="Iced" Version="1.21.0" />
<PackageVersion Include="Microsoft.Build.Framework" Version="17.14.8" />
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.11.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.12.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageVersion Include="NLayer" Version="1.14.0" />
<PackageVersion Include="ppy.SDL3-CS" Version="2026.629.0" />
<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" />
<!-- Reuse the font rasterizer already shipped with Avalonia.Skia. -->
<PackageVersion Include="SkiaSharp" Version="3.119.4" />
<PackageVersion Include="SkiaSharp.NativeAssets.Linux" Version="3.119.4" />
<PackageVersion Include="System.IO.Hashing" Version="10.0.0" />
<!-- Transitive of Avalonia.Desktop; pinned. Avalonia 12 requires 0.94.1+. -->
<PackageVersion Include="Tmds.DBus.Protocol" Version="0.94.1" />
<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>

View File

@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -13,31 +13,18 @@ SPDX-License-Identifier: GPL-2.0-or-later
An experimental PlayStation 5 emulator for Windows, Linux and macOS.
</p>
---
<p align="center">
<a href="https://discord.gg/zdTuUU9Uwn">
<a href="https://discord.gg/6GejPEDqpc">
<img src="https://img.shields.io/badge/Discord-Join%20our%20Community-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join our Discord">
</a>
</p>
<p align="center">
<strong>Join our official Discord server for development updates, compatibility discussions, support, and community chat.</strong>
<strong>Join our Discord for development updates, compatibility discussions, support, and community chat.</strong>
</p>
---
<p align="center">
<a href="#support">
<img src="https://img.shields.io/badge/Support-GitHub%20Sponsors%20%26%20Crypto-EA4AAA?style=for-the-badge&logo=githubsponsors&logoColor=white" alt="Support SharpEmu">
</a>
</p>
---
> [!IMPORTANT]
> **Official channels:** Only **sharpemu.app** and the links listed in this GitHub repository are affiliated with SharpEmu. Any other websites, accounts, or donation pages are unofficial and unauthorized.
> [!NOTE]
> SharpEmu supports Windows x64, Linux x64, and macOS x64. Apple Silicon Macs
> can run the macOS x64 build through Rosetta 2, and Windows on ARM devices
@ -58,21 +45,32 @@ Our goal is **not** to emulate PS4 games, as there is already an excellent emula
## Games Tested
| Demon's Souls Remake | ASTRO BOT |
| Demons Souls Remake | Dreaming Sarah |
| :-----------------------------------------------------------: | :--------------------------------------------------------------------------------------------: |
| ![DeS screenshot](./.github/images/demons-souls.jpg) | ![Astro Bot](./.github/images/astro-bot.jpg) |
| ![Bloodborne screenshot](./.github/images/demons-souls.jpg) | ![Dreaming Sarah](./.github/images/dreaming-sarah.jpg) |
| ASTRO's PLAYROOM | Dead Cells |
| Void Terrarium | Dead Cells |
| :------------------------------------------------------------------------: | :------------------------------------------------------------------: |
| ![Astro's Playroom](./.github/images/astros-playroom.jpg) | ![Dead Cells](./.github/images/dead-cells.jpg) |
| God of War: Sons of Sparta | Tomb Raider V Remastered |
| :------------------------------------------------------------------------: | :------------------------------------------------------------------: |
| ![GoW SOS](./.github/images/gow-sos.jpg) | ![Tomb Raider V](./.github/images/tomb-raider-v-remastered.jpg) |
| ![Void Terrarium](./.github/images/void-terrarium.jpg) | ![Dead Cells](./.github/images/dead-cells.jpg) |
## Status
The emulator can currently load the `eboot.bin` of real games, execute native CPU instructions, and partially handle gpu-related functionality. Included 3D games.
The emulator can currently load the `eboot.bin` of real games, execute native CPU instructions, and partially handle kernel-related functionality. However, several critical components are still missing.
Current capabilities include:
* Loading `eboot.bin` and `.elf` files
* Executing native CPU instructions
* Reading basic game metadata (title, version, etc.)
* Loading system modules (`prx` / `sys_module`)
* Partial support for some kernel functions
* `Fiber` and `AMPR` exports
* PlayGo scenarios
* Initial loading game files
* Shader/resource submits and AGC initial
* Video outputs in some games
Some games have reached like `sceVideoOut` and AGC stages.
SharpEmu supports Windows, Linux, and macOS hosts. Video output uses Vulkan on
Windows and Linux, and MoltenVK on macOS. Platform support is still experimental,
@ -83,12 +81,11 @@ so compatibility and performance vary by game, operating system, and GPU driver.
Download the release archive for your operating system, extract it, and launch
SharpEmu with the path to a legally obtained game's `eboot.bin`.
Or command line;
Windows PowerShell:
```powershell
.\SharpEmu.exe "C:\path\to\game\eboot.bin" --log-to-file
.\SharpEmu.exe "C:\path\to\game\eboot.bin" 2>&1 |
Tee-Object -FilePath "SharpEmu.log"
```
Linux and macOS:
@ -96,13 +93,10 @@ Linux and macOS:
```bash
chmod +x ./SharpEmu
./SharpEmu "/path/to/game/eboot.bin" --log-to-file
./SharpEmu "/path/to/game/eboot.bin" 2>&1 |
tee SharpEmu.log
```
SharpEmu supports environment variables that can be configured from the GUI. Undocumented variables are listed here: [docs/sharpemu-gui-undocumented-env-vars.md](docs/sharpemu-gui-undocumented-env-vars.md)
You can set them per game or globally in the GUI, or pass them directly through the CLI.
A Vulkan-capable GPU and current graphics driver are required. The macOS
release includes the MoltenVK Vulkan implementation.
@ -142,18 +136,6 @@ Provided valuable references for filesystem handling and low-level C# implementa
- [**GPL-2.0 license**](https://github.com/sharpemu/sharpemu/blob/main/LICENSE)
## Support
Support SharpEmu via GitHub Sponsors or cryptocurrency. Every contribution helps fund ongoing development and long-term maintenance. GitHub Sponsors is the preferred way to support the project, but cryptocurrency donations are also appreciated.
### ETH/USDT
`0xF315F5d986c790bB3A58DbE60F1B2760997dEd82`
### BTC
`bc1qmr9k8899njys5ny63xsues4jgmkk96erslrkmv`
## Contributing
Before opening an issue or pull request, please read our contribution guidelines:

View File

@ -20,13 +20,7 @@ SPDX-FileCopyrightText = "SharpEmu Emulator Project"
SPDX-License-Identifier = "GPL-2.0-or-later"
[[annotations]]
path = "src/SharpEmu.GUI/Assets/Fonts/MaterialSymbolsRounded-*.ttf"
precedence = "aggregate"
SPDX-FileCopyrightText = "2026 Google LLC"
SPDX-License-Identifier = "Apache-2.0"
[[annotations]]
path = "src/SharpEmu.LibAtrac9/**"
path = "src/SharpEmu.GUI/Atrac9/**"
precedence = "aggregate"
SPDX-FileCopyrightText = "2018 Alex Barney"
SPDX-License-Identifier = "MIT"

View File

@ -5,7 +5,6 @@ SPDX-License-Identifier: GPL-2.0-or-later
<Solution>
<Folder Name="/src/">
<Project Path="src/SharpEmu.LibAtrac9/SharpEmu.LibAtrac9.csproj" />
<Project Path="src/SharpEmu.CLI/SharpEmu.CLI.csproj" />
<Project Path="src/SharpEmu.Core/SharpEmu.Core.csproj" />
<Project Path="src/SharpEmu.DebugClient/SharpEmu.DebugClient.csproj" />
@ -22,7 +21,6 @@ SPDX-License-Identifier: GPL-2.0-or-later
<Folder Name="/tests/">
<Project Path="tests/SharpEmu.Libs.Tests/SharpEmu.Libs.Tests.csproj" />
<Project Path="tests/SharpEmu.ShaderCompiler.Metal.Tests/SharpEmu.ShaderCompiler.Metal.Tests.csproj" />
<Project Path="tests/SharpEmu.ShaderCompiler.Tests/SharpEmu.ShaderCompiler.Tests.csproj" />
<Project Path="tests/SharpEmu.SourceGenerators.Tests/SharpEmu.SourceGenerators.Tests.csproj" />
</Folder>
</Solution>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 656 KiB

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

View File

@ -12,9 +12,6 @@ python scripts/aerolib_catalog.py lookup Zxa0VhQVTsk
# Export name to NID
python scripts/aerolib_catalog.py lookup sceKernelWaitSema
# A comma can be used for multiple query strings.
python scripts/aerolib_catalog.py lookup Zxa0VhQVTsk,SaKib2Ug0yI,sceVideoOutOpen,amuBfI-AQc4
# Search export names
python scripts/aerolib_catalog.py search VideoOut --limit 20

View File

@ -9,12 +9,12 @@ Demon's Souls plays Bink 2 (.bk2) files through a Bink implementation linked
directly into eboot.bin. It does not use libSceVideodec, therefore an HLE video
decoder cannot observe or replace those frames.
By default, SharpEmu leaves Bink decoding to the implementation linked into
the game (`SHARPEMU_BINK_MODE=guest`).
SharpEmu observes successful guest .bk2 opens and, when a Bink decoder is
available, presents its decoded BGRA frames at the normal guest-flip boundary.
This preserves the game's own timing and lets the host Vulkan presenter display
the movie without trying to execute the PS5-specific Bink GPU decode path.
Set `SHARPEMU_BINK_MODE=native` to use the optional host bridge. It observes
guest .bk2 opens and presents decoded frames at the guest-flip boundary. The
host path decodes by calling FFmpeg's C API directly from managed
The default path decodes by calling FFmpeg's own C API directly from managed
code (`src/SharpEmu.Libs/Bink/FfmpegNativeBinkFrameSource.cs`, via the
[FFmpeg.AutoGen](https://github.com/Ruslan-B/FFmpeg.AutoGen) P/Invoke
bindings) against a custom FFmpeg build
@ -24,38 +24,47 @@ libraries come from. No proprietary RAD SDK is needed to build or run
SharpEmu, and there is no C/C++ code of SharpEmu's own involved in decoding
-- SharpEmu.CLI.csproj only downloads a prebuilt release archive.
Set `SHARPEMU_BINK_MODE=skip` only when explicitly testing a title whose
cinematics are optional.
Set `SHARPEMU_BINK_MODE=guest` to leave decoding to the Bink implementation
statically linked into the game instead. Set `skip` only when explicitly
testing a title whose cinematics are optional.
Set SHARPEMU_BINK_MODE=dummy to retain the open and show a built-in,
non-decoded placeholder frame. This requires no SDK, but is a visual diagnostic
only; it does not decode the movie or alter its game logic.
`SHARPEMU_BINK_MODE=ffmpeg` is an alias for `native`.
SHARPEMU_BINK_MODE=native is equivalent to the default and mainly useful for
being explicit about it.
The experimental `SHARPEMU_BINK_MODE=ffmpeg` override is unrelated to the
default path above: instead of calling into FFmpeg in-process, it spawns a
standalone `ffmpeg` executable and reads raw frames from its stdout
(`src/SharpEmu.Libs/Bink/FfmpegBinkFrameSource.cs`). SharpEmu searches
`SHARPEMU_FFMPEG_PATH`, the executable directory, its `ffmpeg` subdirectory,
and then `PATH` (plus a couple of common Homebrew paths on macOS). That
`ffmpeg` build must contain a Bink 2 decoder itself; a stock FFmpeg build that
only recognizes the Bink container is not sufficient. Most users want the
default `native` mode instead, which always has Bink 2 support since it's
built against `ffmpeg-core` specifically.
## Supplying the FFmpeg libraries
Both `dotnet build` and `dotnet publish` fetch a prebuilt release of
`github.com/sharpemu/ffmpeg-core` (the tag is pinned in
`SharpEmu.CLI.csproj`'s `FfmpegRuntimeTag`, matched to the `FFmpeg.AutoGen`
package version in `Directory.Packages.props` -- both need to agree on the
same FFmpeg ABI) and copy its dynamically linked libraries into a `plugins`
folder next to the resulting executable (`artifacts/bin/...` for build,
`artifacts/publish/...` for publish). No C toolchain is required to build
SharpEmu; both just download a zip once (cached under
`$(BaseIntermediateOutputPath)ffmpeg-runtime/`, so later builds/publishes
reuse it instead of re-fetching). `plugins` is a loose, unpacked folder
rather than something embedded in the single-file bundle, so the OS loader
can resolve the libraries' own inter-dependencies (`avcodec` depends on
`avutil`, etc.) itself.
`dotnet publish` fetches a prebuilt release of `github.com/sharpemu/ffmpeg-core`
(the tag is pinned in `SharpEmu.CLI.csproj`'s `FfmpegRuntimeTag`, matched to
the `FFmpeg.AutoGen` package version in `Directory.Packages.props` -- both
need to agree on the same FFmpeg ABI) and copies its dynamically linked
libraries into a `plugins` folder next to the published executable. No C
toolchain is required to build SharpEmu; publishing just downloads a zip.
`plugins` is a loose, unpacked folder rather than something embedded in the
single-file bundle, so the OS loader can resolve the libraries' own
inter-dependencies (`avcodec` depends on `avutil`, etc.) itself.
A plain `dotnet build`/`dotnet publish` with no `-r` still works: it defaults
to the host machine's own RID (see `Directory.Build.props`), so it fetches
the matching `ffmpeg-core` archive and populates `plugins` without any extra
flags. Passing an explicit `-r <rid>` (e.g. to cross-publish `linux-x64` from
A plain `dotnet publish` with no `-r` still works: it defaults to the host
machine's own RID (see `Directory.Build.props`), so it fetches the matching
`ffmpeg-core` archive and populates `plugins` without any extra flags.
Passing an explicit `-r <rid>` (e.g. to cross-publish `linux-x64` from
Windows) still overrides that default normally.
To use a different set of FFmpeg libraries, drop them into the build or
published `plugins` folder yourself (matching FFmpeg's own file-naming and versioning
To use a different set of FFmpeg libraries, drop them into the published
`plugins` folder yourself (matching FFmpeg's own file-naming and versioning
conventions, e.g. `avformat-61.dll` / `libavformat.so.61` / matching
`.dylib`) -- `FfmpegNativeBinkFrameSource` points `ffmpeg.RootPath` at that
folder and does not otherwise care where the files came from.

View File

@ -1,80 +0,0 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
-->
# Shader rejection diagnostics
`SHARPEMU_STRICT_COMPUTE` controls the rejections listed below for compute dispatches
and graphics draws. The existing variable name is retained; there is no separate
`SHARPEMU_STRICT_DRAW` switch. Restart the game after a change. The pipeline cache and
draw executor read the value when created.
- Unset or `1`: stop on the rejection so that the failure can be diagnosed (default).
- `0`: skip the affected dispatch or draw. Only this value enables skipping.
The GUI provides this switch under **Environment > Debug**, globally and per game.
It is on by default. Turning it off saves an explicit `0`; an inherited process
environment value does not override the GUI choice. Other values retain strict mode.
## Complete skip list
With the switch set to `0`, these are the only handled rejection categories:
| Rejection | Detection point | Operation skipped |
| --- | --- | --- |
| Resource-plan extraction throws `ResourcePlanException`, including an unsupported resource expression or a value graph that does not converge | `ShaderProgramCache.CreateEntry` | The dispatch or draw that needs the rejected shader |
| Shader compilation returns failure or no compiled program, including an unsupported opcode reported by the compiler | `ShaderProgramCache.CompilePermutation` | The dispatch or draw that needs the rejected shader |
| Indirect image candidates have incompatible image classes (`IncompatibleImageCandidates`) | `ResourceMaterializer.Materialize`, handled by `ShaderProgramCache` | The dispatch or draw that needs those resources |
| Indirect image expansion exceeds the dense image resource limit (`ImageCapacityExceeded`) | `ResourceMaterializer.Materialize`, handled by `ShaderProgramCache` | The dispatch or draw that needs those resources |
| A graphics texture's cached image type cannot support the requested view type, such as a 2D view of a 1D image | Vulkan `ValidateDrawImageTypes`, handled by `RenderExecutor.RecordDraw` | The whole indexed or automatic draw |
The last category applies to vertex and pixel resource preparation, not compute
image binding. It checks available, non-stale cache entries and excludes host movie
textures. A mismatch detected later in binding remains fatal.
The draw image-type check runs before resource binding and draw recording. Skip mode
does not create an invalid view or issue the rejected draw. The preparation scope is
released, and the caller resets the image bindings before the next operation.
## Failures that remain fatal
- Shader decoding failures and invalid shader source reads.
- Unreadable resource memory, invalid indirect table state, and materialization failures
other than the two named categories above.
- Invalid binding layouts or invalid resource snapshot state.
- Other image checks, including format, usage, aspect, component mapping, and range
checks reached during binding or view creation. The image cache checks are unchanged.
- Image-type mismatches in compute binding or outside the graphics preparation check.
- Host allocation failures, device loss, synchronization failures, and unexpected exceptions.
This is not a general exception bypass. Setting the switch to `1` also makes every
category in the skip list fatal. Supported operations use the same path in both modes.
## Warnings and test limits
Program rejections log `COMPUTE_SKIPPED` or `DRAW_SKIPPED` once per stage, shader hash,
and code size in each pipeline cache. Draw image-type rejections log `DRAW_SKIPPED`
once per shader hash, image type, and view type in each draw executor. Warning counts
are not skipped-operation counts. No rejected permutation is recorded as compiled;
a later request can retry it.
A skipped operation does not produce its outputs. Missing images, incorrect results,
later errors, and stalls are possible. FPS can rise because less work is executed.
Skip-mode smoke tests can check progress and expose other defects, but must record
the skip warnings. They do not close the skipped defects or establish a final visual
or performance baseline. This switch does not restore the old renderer.
## PowerShell
Enable strict testing in PowerShell:
```powershell
$env:SHARPEMU_STRICT_COMPUTE = '1'
```
Explicitly enable skip mode:
```powershell
$env:SHARPEMU_STRICT_COMPUTE = '0'
```

View File

@ -1,54 +0,0 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
-->
# Performance display
Open **Options → Rendering**, globally or for one game.
- **Performance display:** start with statistics on or off.
- **Display mode:** Full shows all counters and the frame graph. Minimal shows
guest FPS, process CPU usage, process GPU usage, and elapsed session time.
Title bar shows the same minimal values in the window title.
- **Screen corner:** choose any of the four corners. This setting applies only
to the on-screen panel.
F1 toggles the display for the current run. F2 cycles clockwise through the
screen corners. Neither key changes saved settings. The next run uses the saved
options again. Command+F1 retains its separate Metal HUD shortcut.
`SHARPEMU_OVERLAY=0` starts the display hidden, even when the saved option is on.
F1 can still show it. RenderDoc's F12 hint remains in the title when available.
The operating system does not show a title bar in borderless/fullscreen modes.
The launcher passes these options to the game process, including when a separate
emulator path is configured:
```text
--overlay=on|off
--overlay-mode=full|minimal|titlebar
--overlay-corner=topleft|topright|bottomright|bottomleft
```
## Usage values
The panel dimensions are separate constants in `PerfOverlay.cs`:
`PanelWidth` / `PanelHeight` for Full, and
`MinimalPanelWidth` / `MinimalPanelHeight` for Minimal. Both heights are fixed;
the renderer clips the panel only when the window is too small.
CPU usage is the emulator process's CPU time divided by wall time and the
number of logical processors. GPU usage is the busiest GPU engine used by the
emulator process, not GPU memory usage or total usage by all applications.
Windows supplies the GPU Engine performance counters. Collection runs off the
render thread and uses the existing statistics refresh interval. Rate counters
need two samples. Missing counters, unavailable samples, and other platforms
show **N/A**, not zero. No GPU waits or presentation delays are added.
The full panel keeps cache memory counters and puts CPU/GPU usage on a separate
line above elapsed time and the Vulkan allocation counters.
The counter interpretation follows [Microsoft's GPU utilization description](https://devblogs.microsoft.com/directx/gpus-in-the-task-manager/).
Wildcard samples use [PdhGetFormattedCounterArray](https://learn.microsoft.com/en-us/windows/win32/api/pdh/nf-pdh-pdhgetformattedcounterarrayw).

View File

@ -1,433 +0,0 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
-->
# SharpEmu: environment variables that are not on the GUI options pages
## Scope
This list contains each `SHARPEMU_*` environment variable in the repository that the GUI does not show.
The GUI shows 14 variables on its **Options** and **Game options** pages. This list does not contain them:
`SHARPEMU_BTHID_UNAVAILABLE`, `SHARPEMU_CRASH_CAPTURE`, `SHARPEMU_DEFAULT_PROFILE`,
`SHARPEMU_DISABLE_IMPORT_LOOP_GUARD`, `SHARPEMU_DUMP_SPIRV`, `SHARPEMU_LOG_DIRECT_MEMORY`, `SHARPEMU_LOG_IO`,
`SHARPEMU_LOG_NP`, `SHARPEMU_PROFILE_PERFORMANCE`, `SHARPEMU_PROFILE_PERFORMANCE_FRAME_TRACE`,
`SHARPEMU_RENDERDOC`, `SHARPEMU_VK_DISABLE_IMPLICITS`, `SHARPEMU_STRICT_COMPUTE`, `SHARPEMU_VK_VALIDATION`, `SHARPEMU_WRITABLE_APP0`.
The list contains 269 variables. The source was examined on 2026-09-19, branch `dev`.
The descriptions come from the code that reads each variable. The emulator was not started for this list.
## How to use a variable
1. Set the variable in the shell before you start the emulator or the GUI.
2. You can also enter additional env vars using the button next to the "Play" button from GUI.
3. The GUI also accepts a variable in the `EnvironmentToggles` list of its settings file. Write `NAME` or `NAME=value`. An entry without a value gets the value `1`.
4. The emulator reads most variables one time, when it starts. Start the game again after a change.
5. If the **Value** column shows `1`, only the value `1` turns the function on, unless the row gives other values.
## Number of variables in each group
| Group | Variables |
| --- | --- |
| Behavior switches | 19 |
| GPU and Vulkan | 59 |
| Metal | 10 |
| Audio and video | 6 |
| Input | 5 |
| Memory and CPU | 19 |
| Loader | 11 |
| Debugger | 1 |
| Log channels | 72 |
| Traces | 25 |
| Data dumps | 12 |
| Performance measurement | 17 |
| Internal | 1 |
| Tests and tools | 12 |
## Behavior switches
These variables change how the emulator operates.
| Variable | Value | Function | Code that reads it |
| --- | --- | --- | --- |
| `SHARPEMU_AGC_VERSION13_DEFAULTS` | text (`legacy`, `generic` or `0`) | Selects the register defaults for AGC version 13 requests. The default uses the version 11 compact tables. The values `legacy`, `generic` and `0` use the older generic layout. | `AgcExports.Init.cs` |
| `SHARPEMU_DISABLE_LLE_LIBC` | `1` | Stops the use of the guest libc module for libc exports. The emulator then uses its HLE handlers for these exports. | `DirectExecutionBackend.cs` |
| `SHARPEMU_HLE_FAST_MEMCPY` | `0` | Set to `0` to stop the native fast-path stub for the guest libc `memcpy` and `memmove`, so those imports use the managed HLE gateway again. | `DirectExecutionBackend.FastPath.cs` |
| `SHARPEMU_HLE_FAST_PATH` | `0` | Set to `0` to stop the native fast-path stubs for `pthread_self` and `pthread_getspecific`, so those imports use the managed HLE gateway again. The stubs are on by default on macOS x64 and are off on any run that traces imports or pthreads. | `DirectExecutionBackend.FastPath.cs` |
| `SHARPEMU_HOLD_FIRST_FLIP_MS` | number | Stops the thread that submits the flip for this number of milliseconds on one guest flip. The range is 0 to 60000 and the default is 0 (off). `SHARPEMU_HOLD_FLIP_NUMBER` selects the flip. | `VideoOutExports.cs` |
| `SHARPEMU_HOLD_FLIP_NUMBER` | number | Selects the guest flip that `SHARPEMU_HOLD_FIRST_FLIP_MS` holds. The minimum is 1 and the default is 1 (the first flip). | `VideoOutExports.cs` |
| `SHARPEMU_IGNORE_GUEST_EXCEPTIONS` | `1` | `sceKernelRaiseException` returns OK and does not call the installed guest exception handler. Default is off. | `KernelExceptionCompatExports.cs` |
| `SHARPEMU_IMPORT_LOOP_GUARD_SECONDS` | number | When `SHARPEMU_DISABLE_IMPORT_LOOP_GUARD=0` enables the guard, sets how long an import call pattern can repeat before a guest exit. The default is 5 seconds; 0 turns the guard off. | `DirectExecutionBackend.Imports.cs`, `DirectExecutionBackend.cs` |
| `SHARPEMU_NET_REDIRECT` | IP address | Sends guest `connect` and `sendto` traffic to this host IP address. When unset, the emulator permits outbound guest traffic only to loopback addresses. If the value is not a valid IP address, the emulator keeps the original destination and permits the traffic. | `KernelSocketCompatExports.cs` |
| `SHARPEMU_NO_FLIP_PACING` | `1` | Stops flip pacing. The emulator completes each flip immediately and does not wait for the display refresh time. The default is off. | `VideoOutExports.cs`, `VideoOutExports.FlipRequests.cs` |
| `SHARPEMU_OVERLAY` | `0` | Hides the performance overlay at start, even when the video options have the overlay on. All other values use the video options. | `PerfOverlay.cs`, `PerformanceOverlayState.cs` |
| `SHARPEMU_POSIX_GPU_FAULT_FAST_PATH` | `0` | Set to `0` to stop the POSIX fault bridge from offering GPU-tracked page faults to the GPU memory tracker before it builds the Win64 exception context. The fault then takes the full handler order again. | `DirectExecutionBackend.PosixSignals.cs` |
| `SHARPEMU_RETAIN_SUBMITTED_INDEX_DATA` | `0` | The default is on. The emulator keeps a copy of submitted index data until the translated draws run. Set to `0` to stop this copy. Use `0` only for a comparison test. | `AgcExports.SubmittedGeometry.cs` |
| `SHARPEMU_RETAIN_SUBMITTED_VERTEX_DATA` | `0` | The default is on. The emulator keeps a copy of submitted vertex data until the translated draws run. Set to `0` to stop this copy. Use `0` only for a comparison test. | `AgcExports.SubmittedGeometry.cs` |
| `SHARPEMU_SAVEDATA_DIR` | path | Set the root directory for save data. The default is `user/savedata` next to the executable. When this variable is set, the emulator does not move save data from the old layout. | `SaveDataStorage.cs`, `SaveDataExports.cs` |
| `SHARPEMU_STALL_WATCHDOG_SECONDS` | number (seconds) | Sets the time without import progress before the stall watchdog operates. The default is 20. The watchdog writes a snapshot and stops the process with exit code 4. It does not operate when a guest thread is ready or a known wait is in progress. `0` stops the watchdog. | `DirectExecutionBackend.cs` |
| `SHARPEMU_STRICT_RWLOCK_WRITER_PREFERENCE` | `1` | Set to `1` to make a guest thread take a free pthread rwlock as the exclusive writer. By default, the thread gets a compatibility writer record and the lock has no writer thread. | `KernelPthreadExtendedCompatExports.cs` |
| `SHARPEMU_TEMP0_DIR` | path | Set the host directory for the guest `temp0` mount. The default is `user/temp/<app name>/temp0` next to the executable. When unset, the kernel code sets this variable to the default path. | `AppContentExports.cs`, `KernelMemoryCompatExports.cs` |
| `SHARPEMU_TRACE_TITLE_SHADER_STATE` | `1` | The SPIR-V translator changes the pixel shader at address 0x0000000500781200 for diagnosis. The first float output then shows the execution state, the wave mask state, and the export state as colors. Default is off. | `Gen5SpirvTranslator.cs` |
## GPU and Vulkan
These variables change the GPU path or the Vulkan presenter.
| Variable | Value | Function | Code that reads it |
| --- | --- | --- | --- |
| `SHARPEMU_ASYNC_GUEST_READBACK` | `0` | `0` makes a guest thread that reads GPU-written buffer memory wait until the render thread has copied the data back. The default starts the copy on the render thread and lets the guest thread wait for it on a separate readback slot, so the render thread continues. | `GuestBufferCache.cs` |
| `SHARPEMU_CAPTURE_PIXEL_EXEC_PCS` | list (`pc:register` pairs) | At each given instruction PC, the pixel shader writes the execution flag to the given VGPR register. The value is 1.0 when the flag is set and 0.0 when it is not. `SHARPEMU_CAPTURE_PIXEL_VGPR_ADDRESS` must match the shader address. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_CAPTURE_PIXEL_IMAGE_ADDRESS` | hex address | Selects the pixel shader for the image capture by its program address. The default is no capture. Use it with `SHARPEMU_CAPTURE_PIXEL_IMAGE_PC`. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_CAPTURE_PIXEL_IMAGE_PC` | number (instruction PC) | Sets the image instruction whose result the SPIR-V translator copies to four VGPR registers. `SHARPEMU_CAPTURE_PIXEL_IMAGE_ADDRESS` must match the shader address. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_CAPTURE_PIXEL_IMAGE_VGPR_BASE` | number (0 to 252) | Sets the first VGPR register that receives the captured image components. The default is 248. Values above 252 use the default. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_CAPTURE_PIXEL_VGPR_ADDRESS` | hex address | Selects the pixel shader for the VGPR capture, execution capture and path marker functions by its program address. The default is no capture. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_CAPTURE_PIXEL_VGPR_DEST_BASE` | number (0 to 252) | Sets the first destination VGPR register for `SHARPEMU_CAPTURE_PIXEL_VGPR_SOURCES`. The default is 248. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_CAPTURE_PIXEL_VGPR_IGNORE_EXEC` | `1` | Makes the VGPR capture copies occur without the execution flag guard. The default applies the guard. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_CAPTURE_PIXEL_VGPR_PC` | number (instruction PC) | Sets the instruction PC at which the translator copies the source VGPR registers. `SHARPEMU_CAPTURE_PIXEL_VGPR_ADDRESS` must match the shader address. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_CAPTURE_PIXEL_VGPR_POINTS` | list (`pc:source:destination` triples) | At each given instruction PC, the pixel shader copies the source VGPR register to the destination register. Register numbers must be less than 256. `SHARPEMU_CAPTURE_PIXEL_VGPR_ADDRESS` must match the shader address. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_CAPTURE_PIXEL_VGPR_SOURCES` | list (one to four register numbers) | Gives the source VGPR registers that the translator copies at `SHARPEMU_CAPTURE_PIXEL_VGPR_PC`. The copies go to the registers that start at the destination base. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_DETILE` | `1` or `0` | Controls the detile step for tiled surfaces. The default detiles only the trusted swizzle modes. `1` also detiles the approximate modes and `0` uploads all surfaces as raw data. | `GnmTiling.cs` |
| `SHARPEMU_DISABLE_FILL_CLEAR` | `1` | Stops the adaptation that treats a transparent premultiplied fill draw as a target overwrite. The default keeps the adaptation on. | `ShaderPipelineCache.Adaptations.cs` |
| `SHARPEMU_ENABLE_CHUNKED_DRAWS` | `1` | The Vulkan presenter reads the value into a field. No code uses the field, so the variable has no effect. | `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_FORCE_ATTRIBUTE_FRAGMENT` | number (attribute location) | The Vulkan presenter reads the number into a field. No code uses the field, so the variable has no effect. | `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_FORCE_DEFAULT_RASTER_STATE` | `1` | The Vulkan presenter reads the value into a field. No code uses the field, so the variable has no effect. | `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_FORCE_FULLSCREEN_PIPELINE` | `1` | The Vulkan presenter reads the value into a field. No code uses the field, so the variable has no effect. | `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_FORCE_FULLSCREEN_VERTEX` | `1` | The Vulkan presenter reads the value into a field. No code uses the field, so the variable has no effect. | `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_FORCE_PACKED_EXPORT_ONE` | `1` | The SPIR-V translator replaces each packed half-float export component with the constant 1.0. This applies to all shaders. Default is off. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_FORCE_PACKED_EXPORT_STORE_ONE` | `1` | The SPIR-V translator writes (1.0, 1.0) to the packed half-float pair before the export reads it. This applies only to the pixel shader at guest address 0x0000000500781200. Default is off. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_FORCE_PACKED_STORE_EXEC_VALUES` | `1` | Each packed half-float store writes 1.0 when the EXEC mask is active and 0.5 when it is not. This shows the EXEC state as a color. This applies only to the pixel shader at guest address 0x0000000500781200. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_FORCE_PIXEL_EXPORT_ADDRESS` | hex address | Sets the shader address filter for the pixel export debug overrides. The value is a hex address, and the `0x` prefix is optional. When unset, the overrides apply to all pixel shaders. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_FORCE_PIXEL_EXPORT_PACK_VGPR_BASE` | number | Float pixel outputs read four vector registers that start at this base plus four times the export target. The translator packs the values to half-float and unpacks them again. The address filters select the shaders. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_FORCE_PIXEL_EXPORT_VGPR_ADDRESS` | hex address | Sets the shader address filter for the two VGPR base overrides. The `0x` prefix is optional. When unset, the filter from `SHARPEMU_FORCE_PIXEL_EXPORT_ADDRESS` applies. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_FORCE_PIXEL_EXPORT_VGPR_BASE` | number | Float pixel outputs read four vector registers that start at this base plus four times the export target. These values replace the decoded export sources. The address filters select the shaders. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_FORCE_PIXEL_MAGENTA` | `1` | Each selected pixel shader export writes opaque magenta. The control flow, EXEC mask, geometry and raster state stay the same. Use `SHARPEMU_FORCE_PIXEL_EXPORT_ADDRESS` to select one shader. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_FORCE_SOLID_FRAGMENT` | `1` | The Vulkan presenter reads the value into a field. No code uses the field, so the variable has no effect at this time. | `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_FORCE_TITLE_COMPARE_4D4` | `1` | The compare instruction at shader PC 0x4D4 always gives the result true. This applies only to the shader at guest address 0x0000000500781200. Default is off. | `Gen5SpirvTranslator.Alu.cs` |
| `SHARPEMU_FORCE_TITLE_COMPARE_540` | `1` | The compare instruction at shader PC 0x540 always gives the result true. This applies only to the shader at guest address 0x0000000500781200. Default is off. | `Gen5SpirvTranslator.Alu.cs` |
| `SHARPEMU_FORCE_TITLE_DEFAULT_RASTER_STATE` | `1` | The Vulkan presenter reads the value into a field. No code uses the field, so the variable has no effect at this time. | `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_FORCE_TITLE_EARLY_COLOR` | `1` | The pixel shader at guest address 0x0000000500781200 writes a constant to its first output and returns at once. A float output gets opaque magenta. An integer output gets zero. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_FORCE_TITLE_EXPORT_EXEC` | `1` | The translator sets the EXEC mask to true and writes 1 to 64-bit register 126 before each pixel export store. This applies only to the pixel shader at guest address 0x0000000500781200. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_FORCE_TITLE_FULLSCREEN_VERTEX` | `1` | The Vulkan presenter reads the value into a field. No code uses the field, so the variable has no effect at this time. | `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_FORCE_TITLE_SINGLE_MRT` | `1` | The translator declares only the first pixel output for the pixel shader at guest address 0x0000000500781200. It does not declare the other render target outputs. Default is off. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_FORCE_TITLE_SOLID_FRAGMENT` | `1` | The Vulkan presenter reads the value into a field. No code uses the field, so the variable has no effect at this time. | `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_FORCE_TITLE_VERTEX_OUTPUTS_ONE` | `1` | Vertex export targets 32 to 35 write the vector (1, 1, 1, 1). This applies only to the vertex shader at guest address 0x0000000500780000. Default is off. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_GPU_BACKEND` | `vulkan` or `metal` | Selects the guest GPU backend. The default is Vulkan. The value `metal` works only on macOS, and other hosts show a warning and use Vulkan. | `GuestGpu.cs` |
| `SHARPEMU_GPU_WAIT_SPIN_US` | number (microseconds) | Sets how long a wait for GPU work polls before it blocks. A short poll saves the wake-up delay when the GPU finishes soon. `0` blocks at once. The default is 150. | `GpuWaitSpin.cs` |
| `SHARPEMU_GRAPHICS_SUBGROUPS` | `0` or `1` | Set `1` to use native Vulkan subgroup operations in graphics shaders. Set `0` to use the fallback path. When unset, the presenter uses them only if the subgroup size is 32 and the vertex and fragment stages support subgroups. | `VulkanVideoPresenter.cs`, `VulkanVideoPresenter.Device.Setup.cs` |
| `SHARPEMU_IMAGE_LOOKUP_MEMO` | `0` | `0` turns off the image lookup memo. The default keeps the result of each image lookup that found an image with the same backing, and gives it again for the same request until an image is registered or removed. | `GuestImageCache.Lookup.cs` |
| `SHARPEMU_MARK_PIXEL_PCS` | list of `pc:register` pairs | Makes the SPIR-V pixel shader write the float value 1.0 to a shader register when execution reaches the given instruction PC. Use decimal numbers, a register below 256, and a comma between pairs. It has an effect only for the shader address in `SHARPEMU_CAPTURE_PIXEL_VGPR_ADDRESS`. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_MAX_GUEST_WORK_PER_RENDER` | number | Sets the maximum number of guest command stream slices that the Vulkan presenter runs in one render pass. The default is 1024, or 256 on macOS. The value must be more than 0. | `VulkanVideoPresenter.cs`, `VulkanVideoPresenter.CommandStream.cs` |
| `SHARPEMU_RENDERDOC_CAPTURE_TIMEOUT_SECONDS` | number (seconds) | Set the maximum time for a RenderDoc frame capture. The emulator discards a capture that does not end in this time. The range is 1 to 120. The default is 15. | `RenderDocCapture.cs` |
| `SHARPEMU_RENDERDOC_DLL` | path | Set the path of the RenderDoc library file. The emulator tries this path first. When unset or when the load fails, it searches the default library name and the known install paths. | `RenderDocCapture.cs` |
| `SHARPEMU_RENDERDOC_WAIT` | number (seconds) or `enter` | Set to make the emulator wait before it starts Vulkan, so that you can attach RenderDoc. `enter` waits until you press Enter. A number waits that many seconds, from 1 to 300. Other text waits 15 seconds. | `VulkanVideoPresenter.Device.Setup.cs` |
| `SHARPEMU_RENDER_WORK_BUDGET_MS` | number (milliseconds) | Set the maximum time that one render call uses for queued guest work in the Vulkan presenter. Work that remains stays in the queue for the next frame. `0` removes the limit. The default is 12 on macOS and 0 on other hosts. | `VulkanVideoPresenter.cs`, `VulkanVideoPresenter.RenderLoop.cs` |
| `SHARPEMU_RESOURCE_PREFETCH` | `0` | `0` makes the shader resource materialization read each guest word one at a time. The default reads adjacent words of descriptors and the flattened resource table in one read of resident guest memory. A range that the GPU may still own is read word by word as before. | `ShaderProgramCache.cs`, `RawReadPrefetch.cs` |
| `SHARPEMU_SHADER_MAX_STEPS` | number | Set the maximum number of dispatcher loop steps in each translated shader invocation. The limit makes sure that an incorrect loop stops. `0` removes the limit. The default is 100000. | `Gen5SpirvTranslator.cs`, `Gen5MslTranslator.cs` |
| `SHARPEMU_SHADER_PREWARM` | `0` | `0` turns off the shader prewarm list. By default, each compute program that a game compiles is added at once to `shader-prewarm.bin` in `user/pipeline_cache/<title id>/`, so a stopped game keeps the list. At the next launch after a change of the shader translator or of the GPU driver, background threads translate the listed programs again and create their pipelines, so that the driver compiles them before the game asks for them. The `shader-prewarm.stamp` file names the build and driver that last did this; with the same build and driver, the launch does no prewarm work. The log shows `Shader prewarm done` and `Shader prewarm hits`. On Windows it replaces the cache file by default; on Linux it works beside the cache file. It has no effect with the per-shader cache files of `SHARPEMU_VK_PIPELINE_CACHE_SHARDS`. | `VulkanVideoPresenter.ShaderPrewarm.cs`, `ShaderPrewarmList.cs`, `ShaderProgramCache.cs` |
| `SHARPEMU_SKIP_ALL_COMPUTE` | `1` | Set to `1` to make the Metal presenter skip all compute dispatches. The Vulkan presenter reads the value but does not use it. The default is off. | `MetalVideoPresenter.Compute.cs`, `VulkanVideoPresenter.cs` |
| `SHARPEMU_SKIP_TALL_COMPUTE_Z` | number | Effect not clear from the code. The Vulkan presenter reads the number into a field for a minimum Z group count. No code uses that field. The default is 0. | `VulkanVideoPresenter.cs` |
| `SHARPEMU_SRT_NATIVE` | `0` | `0` turns off the compiled shader resource (SRT) evaluator. By default, the resource plan of each shader is compiled once to .NET code (`DynamicMethod`) on a low-priority background thread named `SRT compiler`; until it is ready, the plan is evaluated by the interpreter, so the first use of a new shader does not wait for the compilation. With `0`, every plan always uses the interpreter. The compiled path is also off when the runtime does not support dynamic code, for example in a Native AOT build. | `CompiledResourceEvaluator.cs`, `ShaderResourcePlan.cs`, `RuntimeValueEvaluator.cs` |
| `SHARPEMU_SUSPEND_POINTS_IN_FLIGHT` | `0` | `0` makes `sceAgcSuspendPoint` wait until the frame boundary it queued is processed. The default lets one boundary wait behind the graphics commands, so the guest CPU can run one frame ahead. A wait that follows its own queue's store to the same label still sees that value when the title rewrites the label for the next frame (Dead Cells). | `CommandStreamQueue.cs`, `GpuCommandInterpreter.cs` |
| `SHARPEMU_VK_DEBUG_LABELS` | `1` | Turns on Vulkan object names and command labels for capture tools. `SHARPEMU_VK_VALIDATION=1` also turns them on. Default is off because the labels add overhead to each draw. | `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_VK_DEVICE` | text (part of a device name) | Selects the Vulkan device whose name contains this text. The comparison ignores case. When unset, the presenter gives a score to each device and prefers a discrete GPU. | `VulkanVideoPresenter.Device.Setup.cs`, `VulkanVideoPresenter.cs` |
| `SHARPEMU_VK_PIPELINE_CACHE_PATH` | path | Sets the path of the Vulkan pipeline cache file. The path can contain environment variables. Default is `user/pipeline_cache/<title id>/` below the application directory. The shader prewarm list goes to the same directory. With the per-shader cache, the files go to a `.shards` directory next to this path. | `VulkanVideoPresenter.Device.Setup.cs`, `VulkanPipelineCacheStorage.cs` |
| `SHARPEMU_VK_PIPELINE_CACHE` | `0`, `1` or `file` | Selects the Vulkan pipeline cache file, which keeps the driver's compiled pipelines. `1` or `file` saves and loads one cache file. `0` keeps the cache in memory only on every system. The default is memory only on Windows: the GPU driver keeps its own shader cache on disk, and the shader prewarm list (`SHARPEMU_SHADER_PREWARM`) rebuilds it after an update. Linux keeps a cache file by default, and macOS keeps per-shader files. | `VulkanVideoPresenter.Device.Setup.cs` |
| `SHARPEMU_VK_PIPELINE_CACHE_SHARDS` | `1` or `0` | `1` keeps one Vulkan pipeline cache file for each compute shader and for each vertex and pixel shader pair, in `vulkan-pipeline-cache.bin.shards`, also on Windows. `0` keeps the whole cache in one file. The default is `1` on macOS and `0` on other systems: NVIDIA adds about 2 MB of driver data to every cache file, so a file for each shader uses much more disk. A shard file loads when its pipeline is first created, and a save writes only the files that got new pipelines. The shard mode removes the old single file when `SHARPEMU_VK_PIPELINE_CACHE_PATH` is not set. A cache file that grows over 256 MiB is emptied, so the next launch starts it again. | `VulkanVideoPresenter.Device.Setup.cs`, `VulkanVideoPresenter.PipelineCacheShards.cs` |
| `SHARPEMU_VK_PIPELINE_CACHE_LEGACY_SHARDS` | `1` | `1` names the per-shader cache files by the guest shader hash. The default names them by a hash of the translated SPIR-V, so a translator change does not load records that no longer match. | `VulkanVideoPresenter.PipelineCacheShards.cs` |
## Metal
These variables apply to the Metal backend.
| Variable | Value | Function | Code that reads it |
| --- | --- | --- | --- |
| `SHARPEMU_GPU_DETILE` | `0` | The Metal backend decodes supported tiled texture data on the GPU by default. Set `0` to decode all tiled textures on the CPU. | `MetalTextureSnapshots.cs`, `GuestGpuTypes.cs` |
| `SHARPEMU_LOG_GPU_DETILE` | `1` | Writes each texture tile mode and each GPU detile decision one time to stderr. It applies to the Metal texture path only. The emulator reads the value one time at start. | `MetalTextureSnapshots.cs` |
| `SHARPEMU_METAL_CAP_DRAWABLE` | `1` | Limits the long edge of the Metal drawable to 1920 pixels and keeps the aspect ratio. The default is off, so the drawable uses the full window pixel size. | `MetalVideoPresenter.cs` |
| `SHARPEMU_METAL_DBG` | `solid` or `uv` | Replaces the Metal present fragment shader with a test shader. `solid` shows a green frame. `uv` shows the value of vertex attribute 0. All other values use the normal present shader. | `MetalVideoPresenter.cs` |
| `SHARPEMU_METAL_FULL_DRAWABLE` | `1` | Cancels `SHARPEMU_METAL_CAP_DRAWABLE=1`, so the Metal drawable uses the full window pixel size. It has no effect when the cap is off. | `MetalVideoPresenter.cs` |
| `SHARPEMU_NO_TEXTURE_SKIP` | `1` | Stops the reuse of cached texture snapshots in the Metal backend, so each texture is copied again. Use it to make sure that a snapshot is not stale. The default is off. | `MetalTextureSnapshots.cs` |
| `SHARPEMU_REUSE_GUEST_TEXTURE_SNAPSHOTS` | `0` | The default is on. The Metal backend uses a guest texture snapshot again when the snapshot key is the same. Set to `0` to make a new snapshot each time. | `MetalTextureSnapshots.cs` |
| `SHARPEMU_TEXTURE_DUMP_DIR` | path | Set a directory to make the Metal backend write raw texture source bytes to `.bin` files. The file name contains the address, size, pitch, format and tile mode. The limit is 200 files. | `MetalTextureSnapshots.cs` |
| `SHARPEMU_TEXTURE_LINEAR_DUMP_DIR` | path | Set a directory to make the Metal backend write the linear texture bytes to `.linear.bin` files. The file name contains the address, size, pitch, format and tile mode. The limit is 200 files. | `MetalTextureSnapshots.cs` |
| `SHARPEMU_TRACE_STORAGE_IMAGE_INIT_ADDRESS` | hex address | The Metal backend writes an `agc.storage_initial_data` trace line when it makes the texture at this guest address. The line shows the upload state and the read result of the initial data. | `MetalTextureSnapshots.cs` |
## Audio and video
These variables apply to audio output and video playback.
| Variable | Value | Function | Code that reads it |
| --- | --- | --- | --- |
| `SHARPEMU_ALSA_DEVICE` | text (ALSA device name) | Sets the ALSA playback device on Linux. The default is `default`. | `PosixAlsaAudioStream.cs` |
| `SHARPEMU_AUDIO_LATENCY_MS` | number (milliseconds) | Sets the target depth of the SDL audio queue, which is the playback latency. The default is 60. Values of zero or less use the default. | `SdlHostAudio.cs` |
| `SHARPEMU_BINK_MODE` | text (`native`, `ffmpeg`, `dummy`, `skip`, `guest`) | Selects how the emulator handles Bink movies. `native` or `ffmpeg` decodes on the host and is the default. `dummy` shows a placeholder frame, `skip` skips the movie, and `guest` lets the guest decode. | `HostMovieBridge.cs` |
| `SHARPEMU_LOG_MOVIE_SYNC` | `1` | Records the difference between the movie clock and the guest audio position during movie playback. The emulator reads the value one time at start. | `MediaFramePlayback.cs` |
| `SHARPEMU_MOVIE_CLOCK` | `wall` | Sets the time base for host-decoded movie playback. By default, playback follows the guest audio clock and uses the wall clock when no guest audio flows. `wall` makes playback always use the wall clock. | `MediaFramePlayback.cs` |
| `SHARPEMU_TRACE_AVPLAYER_IMAGES` | `1` | Set to `1` to write `[AVPLAYER][TRACE]` lines for video buffer addresses and the first 16 video frame payloads. It also marks the video buffer ranges for image traces in other components. The default is off. | `AvPlayerExports.cs` |
## Input
These variables apply to the controller and input libraries.
| Variable | Value | Function | Code that reads it |
| --- | --- | --- | --- |
| `SHARPEMU_AUTO_CROSS` | list (seconds, for example `40,52,64`) | Presses the Cross button for 0.4 seconds at each time in the list. The times are seconds from process start. The default is no automatic press. | `PadExports.cs` |
| `SHARPEMU_BTHID_CB_FAIL` | text (`nf` or `ni`) | Makes `sceBluetoothHidRegisterCallback` return an error. `nf` returns NOT_FOUND and `ni` returns NOT_IMPLEMENTED. The default returns the usual result. | `BluetoothHidExports.cs` |
| `SHARPEMU_BTHID_EVENT_CODE` | number (decimal or `0x` hex) | Sets the event code of the synthetic Bluetooth HID callback event. The default is 0. It has an effect only with `SHARPEMU_BTHID_FIRE_CALLBACK=1`. | `BluetoothHidExports.cs` |
| `SHARPEMU_BTHID_EVENT_SIZE` | number (bytes, decimal or `0x` hex) | Sets the size of the zeroed event structure for the synthetic Bluetooth HID callback. The default is 256. It has an effect only with `SHARPEMU_BTHID_FIRE_CALLBACK=1`. | `BluetoothHidExports.cs` |
| `SHARPEMU_BTHID_FIRE_CALLBACK` | `1` | Calls the registered Bluetooth HID guest callback one time with a zeroed event structure. The call occurs at the first `sceBluetoothHidRegisterDevice`. The default is off. | `BluetoothHidExports.cs` |
## Memory and CPU
These variables apply to guest memory and guest code execution.
| Variable | Value | Function | Code that reads it |
| --- | --- | --- | --- |
| `SHARPEMU_DISABLE_GUEST_ALLOCATOR_HOLE_RECOVERY` | `1` | Stops the Windows fault recovery for a guest allocator that reads an empty pool node. The default recovers the fault and continues at the allocator fallback code. | `DirectExecutionBackend.Exceptions.cs` |
| `SHARPEMU_DISABLE_MITIGATION_RELAUNCH` | `1` | Stops the Windows relaunch of the emulator as a child process with Control Flow Guard and CET shadow stacks off. The default starts the child process. | `Program.cs`, `SelfLoader.cs` |
| `SHARPEMU_DISABLE_NATIVE_GUEST_WORKERS` | `1` | Stops the use of native worker threads for guest thread execution on Windows. The default uses the native workers. | `DirectExecutionBackend.NativeWorker.cs` |
| `SHARPEMU_DISABLE_POSIX_SIGNALS` | `1` | Does not install the POSIX signal handlers on Linux and macOS. The emulator then cannot recover guest faults. | `DirectExecutionBackend.PosixSignals.cs` |
| `SHARPEMU_DISABLE_RAW_HANDLER` | `1` | Does not install the raw vectored exception handler on Windows. On POSIX hosts it stops the raw sentinel recovery. The default keeps the two functions on. | `DirectExecutionBackend.Exceptions.cs`, `DirectExecutionBackend.PosixSignals.cs` |
| `SHARPEMU_IGNORE_INT41` | `0` or `false` | The fault handler skips guest `int 0x41` instructions and continues at the next instruction by default. Set `0` or `false` to stop this recovery. The emulator shows a warning for the first 16 traps and then for each 65536th trap. | `DirectExecutionBackend.cs`, `DirectExecutionBackend.Exceptions.cs` |
| `SHARPEMU_IGNORE_STACK_CHK` | `1` | Recovers from a guest stack-protector failure call (NID `Ou3iL1abvng`) when a UD2 instruction follows the call. The emulator sets the return address to the function epilogue 20 bytes before. It does this only when the code bytes match the known pattern. | `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_LAZY_RESERVE_PRIME_MB` | number | Sets the number of megabytes that the emulator commits at the start of each reserve-only memory region. The default is 64 and the maximum is 4096. The value 0 turns the initial commit off. | `PhysicalVirtualMemory.cs` |
| `SHARPEMU_NATIVE_WORKER_MAX_CONCURRENT` | number | Sets the maximum number of native guest worker runs that execute at the same time. The default is 2. The emulator limits the value to the range 1 to 64. | `DirectExecutionBackend.NativeWorker.cs`, `DirectExecutionBackend.cs` |
| `SHARPEMU_GUEST_AFFINITY` | `1` | Applies the guest thread affinity to the host threads. The default leaves host threads unpinned, because pinning let spinning guest workers starve the render thread. | `DirectExecutionBackend.cs` |
| `SHARPEMU_RENDER_CORE` | `0` | `0` turns off the render core reservation. On Windows hosts with 8 to 64 logical processors, the default gives the render thread the last physical core of the fastest efficiency class with a high priority, and keeps guest threads off that core. | `HostLaneReservation.cs`, `VulkanVideoPresenter.Present.cs`, `DirectExecutionBackend.cs` |
| `SHARPEMU_RESERVED_HOST_LANES` | number | Set the number of host logical processors that guest thread affinity does not use. The emulator keeps these processors for its own threads. The default is three eighths of the processor count, with a minimum of 2. It has an effect only with `SHARPEMU_GUEST_AFFINITY=1`. | `DirectExecutionBackend.cs` |
| `SHARPEMU_TSC_FREQ_HZ` | number (Hz, minimum 1000000) | Sets the TSC frequency that the kernel library reports to the guest. When unset, the emulator uses the calibrated RDTSC frequency, then the CPUID frequency, then the host stopwatch frequency. | `KernelRuntimeCompatExports.cs` |
| `SHARPEMU_WATCH_BULK_DEST_HI` | hex number | Limits the `SHARPEMU_WATCH_BULK_TORN` scan to writes whose upper 32 address bits equal this value. When unset, the scan uses the direct-memory address band. | `GuestWriteWatch.cs` |
| `SHARPEMU_WATCH_BULK_TORN` | `1` | Examines each aligned 8-byte value in managed bulk writes to guest memory. It reports torn values and shifted pointer values with a stack trace. It writes a maximum of 64 reports for each kind. | `GuestWriteWatch.cs` |
| `SHARPEMU_WATCH_POOL_HEADER` | `1` | Monitors the header slot at offset 0x40 of each pool mapping with size 0x10000 and protection 0xF2. It reports each managed write to a monitored slot with a stack trace. It monitors a maximum of 64 slots. | `GuestWriteWatch.cs` |
| `SHARPEMU_WATCH_VALUE1` | `1` | Reports managed writes of 1 to 8 bytes that have the value 1 and go to the direct-memory address band. Each report has a stack trace. It writes a maximum of 128 reports. | `GuestWriteWatch.cs` |
| `SHARPEMU_WATCH_VALUE_PATTERN` | `1` | Reports each managed 8-byte write whose low half is 1 and whose high half is between 1 and 0xFFFF. Each report has a stack trace. | `GuestWriteWatch.cs` |
| `SHARPEMU_WATCH_WRITE` | hex address | Monitors the 8 bytes at this guest address. It reports each managed write that touches these bytes with the address, the length, the first value, and a stack trace. Default is off. | `GuestWriteWatch.cs` |
## Loader
These variables apply to the program loader and the module system.
| Variable | Value | Function | Code that reads it |
| --- | --- | --- | --- |
| `SHARPEMU_AMPR_INDEX_CACHE` | path (directory) | Sets the directory for the AMPR file index cache. The default is `SharpEmu/ampr-index` in the local application data folder. | `AmprFileRegistry.cs` |
| `SHARPEMU_AMPR_REINDEX` | `1` | Ignores the AMPR index cache on disk and scans the application file tree again. Use it after manual changes to the application files. | `AmprFileRegistry.cs` |
| `SHARPEMU_APP0_DIR` | path (directory) | Sets the host directory for the guest `/app0` mount. The default is the directory of the loaded executable. The directory name also identifies the per-application data folders. | `SharpEmuRuntime.cs`, `KernelMemoryCompatExports.cs`, `AppContentExports.cs` |
| `SHARPEMU_DEVLOG_APP_DIR` | path (directory) | Sets the host directory for the guest devlog application path. The default is `user/game_logs/<title id>/devlog/app` below the emulator directory. | `KernelMemoryCompatExports.cs` |
| `SHARPEMU_DISABLE_RED_ZONE_PATCH` | `1` | Stops the load-time patch that protects the guest stack red zone on Windows and macOS. The default applies the patch. The vector store split for Rosetta stays on when it is necessary. | `GuestRedZonePatcher.cs` |
| `SHARPEMU_DOWNLOAD0_DIR` | path (directory) | Sets the host directory for the guest `/download0` mount. The default is a `download0` folder in the per-application writable directory. The emulator sets the variable to the default when it is not set. | `KernelMemoryCompatExports.cs` |
| `SHARPEMU_GUEST_ARGS` | text | Adds arguments to the guest process entry frame after the image name. White space divides the arguments. The emulator uses only the first two. | `CpuDispatcher.cs` |
| `SHARPEMU_HOSTAPP_DIR` | path | Sets the host directory for the guest `/hostapp` mount. The default is `user/game_logs/<title id>/hostapp` below the emulator directory. The emulator makes the directory if it is absent. | `KernelMemoryCompatExports.cs`, `KernelGameLogPathTests.cs` |
| `SHARPEMU_LLE_LIBC_ALL` | `1` | Sends all libc imports to the guest libc module and not to the HLE handlers. `SHARPEMU_DISABLE_LLE_LIBC=1` and `SHARPEMU_LLE_LIBC_SAFE_ONLY=off` have priority. Default is off. | `DirectExecutionBackend.cs` |
| `SHARPEMU_LLE_LIBC_SAFE_ONLY` | `1`, `0`, `off`, `false` or `none` | Controls which libc imports use the guest libc module. Unset or `1` uses guest code only for exports on the safe list. `0` uses guest code for all libc exports, and `off`, `false` or `none` uses HLE for all of them. | `DirectExecutionBackend.cs` |
| `SHARPEMU_PRELOAD_ALL_SCE_MODULES` | `1` | Set to `1` to preload all system modules. When unset, the runtime does not preload the modules in its internal skip list. | `SharpEmuRuntime.cs` |
## Debugger
These variables apply to the debug server.
| Variable | Value | Function | Code that reads it |
| --- | --- | --- | --- |
| `SHARPEMU_SENTINEL_PROBE` | `1` | Set to `1` to call the native entry stub with the unresolved sentinel address 0xFFFE before the guest entry. The emulator writes a log line before and after the call. The default is off. | `DirectExecutionBackend.cs`, `Gen5NativeReturnSmokeTests.cs` |
## Log channels
Each variable adds one group of messages to the log. The default is off.
| Variable | Value | Function | Code that reads it |
| --- | --- | --- | --- |
| `SHARPEMU_LOG_ACM` | `1` | Writes `acm.` trace lines from the Acm library handlers to stderr. Default is off. | `AcmExports.cs` |
| `SHARPEMU_LOG_AGC_SHADER` | `1` | Writes only the AGC shader trace lines and the Vulkan shader trace lines. `SHARPEMU_LOG_AGC=1` also turns this on. Default is off. | `AgcExports.cs`, `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_LOG_AGC` | `1` | Starts the full AGC trace: command submissions, shader creation, draws and dispatches. It also turns on the AGC shader trace and the Vulkan shader trace. Default is off. | `AgcExports.cs`, `RenderExecutor.Trace.cs`, `AgcExports.ShaderState.cs` |
| `SHARPEMU_LOG_AJM` | `1` | Writes `ajm.` trace lines to stderr: context initialization, codec registration, split buffer descriptors and ATRAC9 decode state. Default is off. | `AjmExports.cs`, `Atrac9DecodeState.cs` |
| `SHARPEMU_LOG_ALLOC_IMPORTS` | `1` | Writes more trace lines for `sceKernelGetGPI` (the returned mask) and for the PRT aperture set call (the raw register values). Default is off. | `KernelRuntimeCompatExports.cs` |
| `SHARPEMU_LOG_ALL_IMPORTS` | `1` | Writes a debug line for each import stub during setup. The lines show if the import uses a direct bridge, a trampoline, HLE or a runtime symbol. Default is off. | `DirectExecutionBackend.cs` |
| `SHARPEMU_LOG_AMPR_READS` | `1` | Writes only the AMPR file read trace lines and the pak directory tracker lines. `SHARPEMU_LOG_AMPR=1` also turns this on. Default is off. | `AmprExports.cs`, `PakDirectoryTracker.cs` |
| `SHARPEMU_LOG_AMPR` | `1` | Writes trace lines for AMPR command buffers, APR submissions and waits, and the pak directory tracker. It also turns on the AMPR read trace. Default is off. | `AmprExports.cs`, `KernelAprCompatExports.cs`, `PakDirectoryTracker.cs` |
| `SHARPEMU_LOG_APP_CONTENT` | `1` | Writes an `app_content` trace line to stderr for each AppContent call. The default is off. | `AppContentExports.cs` |
| `SHARPEMU_LOG_AUDIO_OUT2` | `1` | Writes an `audio_out2` trace line to stderr for each AudioOut2 operation. The default is off. | `AudioOut2Exports.cs` |
| `SHARPEMU_LOG_AUDIO_OUT` | `1` | Records `sceAudioOutOutput` calls and the peak amplitude of the submitted samples. It writes the first 8 calls and then every 200th call. The emulator reads the value one time at start. | `AudioOutExports.cs` |
| `SHARPEMU_LOG_BOOTSTRAP` | `1` | Writes a trace line for each call through the bootstrap bridge import. The line shows the handle, the symbol name and the output address. | `DirectExecutionBackend.cs`, `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_LOG_CONTEXT` | `1` | Writes `guest_context` trace lines to stderr. Each import dispatch shows the NID, the return address, the managed thread, the guest thread and the fiber. | `DirectExecutionBackend.cs`, `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_LOG_DATA_REBIND` | `1` | Writes one `[RUNTIME]` line for each imported data relocation. The line shows if the relocation is rebound, unresolved or write-failed. | `SharpEmuRuntime.cs` |
| `SHARPEMU_LOG_DISCMAP` | `1` | Writes a trace line for each DiscMap call. The line shows the export name, the path, the offset and the size. | `DiscMapExports.cs` |
| `SHARPEMU_LOG_DISCORD` | `1` | Writes `[DISCORD]` messages from the rich presence client of the GUI to stderr. The default is off. | `DiscordRichPresence.cs` |
| `SHARPEMU_LOG_DLSYM` | `1` | Writes a trace line for each successful `sceKernelDlsym` call. The line shows the module handle, the symbol name and the resolved address. | `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_LOG_EQUEUE` | `1` | Writes trace lines for kernel event queue operations. The emulator reads the value one time at start. | `KernelEventQueueCompatExports.cs` |
| `SHARPEMU_LOG_EVENT_FLAG` | `1` | Writes trace lines for kernel event flag operations. The emulator reads the value one time at start. | `KernelEventFlagCompatExports.cs` |
| `SHARPEMU_LOG_EXPECTED_IMPORT_RESULTS` | `1` | Shows import error results that the emulator knows as usual, for example file-not-found probes, timeouts and busy trylocks. It shows the first 8 results for each NID and result, and then every 10000th. The default hides these results. | `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_LOG_FIBER` | `1` | Writes `fiber` trace lines for the Fiber library calls. It also writes a line for each fiber context transfer in the CPU backend. | `FiberExports.cs`, `DirectExecutionBackend.cs`, `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_LOG_FILE` | path | Writes all log entries to this file with timestamps and appends to an existing file. The file receives every log level. `SHARPEMU_LOG_LEVEL` then limits only the console output. | `SharpEmuLog.cs` |
| `SHARPEMU_LOG_FMOD` | `1` | Writes a trace line for the FMOD `system_set_output` compatibility call. The line shows the system address, the output type and the call count. | `FmodCompatExports.cs` |
| `SHARPEMU_LOG_GUARDS` | `1` | Writes a trace line for each C++ static guard operation. The line shows the guard address, the guard word, the state flags and the owner thread. | `CxxAbiExports.cs` |
| `SHARPEMU_LOG_GUEST_EXCEPTIONS` | `1` | Writes `guest_exception` trace lines when the emulator raises and delivers a guest exception. The lines show the target thread and the exception type. | `DirectExecutionBackend.cs`, `KernelExceptionCompatExports.cs` |
| `SHARPEMU_LOG_GUEST_THREADS` | `1` | Writes guest thread scheduler messages to stderr. The messages show thread state changes, yields, wakes, exits, nested callbacks and affinity failures. | `DirectExecutionBackend.cs`, `DirectExecutionBackend.Imports.cs`, `KernelRuntimeCompatExports.cs` |
| `SHARPEMU_LOG_GUEST_THREAD_SNAPSHOTS` | `1` | Writes one snapshot line for each guest thread every second. The line shows the state, the import count, the last NID, the last return address and the block reason. The ready-dispatch thread then wakes every second. | `DirectExecutionBackend.cs` |
| `SHARPEMU_LOG_HTTP2` | `1` | Writes an `http2` trace line for each Http2 library call. The line shows the operation, the id and four arguments. | `Http2Exports.cs` |
| `SHARPEMU_LOG_HTTP` | `1` | Writes an `http` trace line for each Http library call. The line shows the operation, the id and four arguments. | `HttpExports.cs` |
| `SHARPEMU_LOG_IO_FILTER` | text | Limits the `SHARPEMU_LOG_IO` output to paths that contain this text. The comparison ignores case. When unset, the emulator shows all paths. | `KernelMemoryCompatExports.cs` |
| `SHARPEMU_LOG_JSON` | `1` | Writes a `json` trace line for each Json library call. Text values show a maximum of 128 characters. | `JsonExports.cs` |
| `SHARPEMU_LOG_LAZY_COMMIT` | `1` | Writes a trace line for every lazy memory commit fault. The default shows only the first 16 faults and then every 256th fault. | `DirectExecutionBackend.Exceptions.cs` |
| `SHARPEMU_LOG_LEVEL` | text | Sets the minimum log level. The values are `Trace`, `Debug`, `Info`, `Warning` or `Warn`, `Error`, `Critical` or `Fatal`, and `None`. The default is `Info`, and the comparison ignores case. | `SharpEmuLog.cs` |
| `SHARPEMU_LOG_LIBC_ALLOC` | `1` | Writes a trace line for each guest libc allocation call. The line shows the size, the alignment, the result address and the return address of the caller. | `KernelMemoryCompatExports.cs` |
| `SHARPEMU_LOG_NET` | `1` | Writes `net` trace lines for Net library calls and debug lines for kernel socket operations. It also writes each payload that the guest sends on a connected socket to stdout as text. | `NetExports.cs`, `KernelSocketCompatExports.cs` |
| `SHARPEMU_LOG_NGS2` | `1` | Writes trace lines for Ngs2 audio library calls. The default is off. | `Ngs2Exports.cs` |
| `SHARPEMU_LOG_NO_COLOR` | `1` | Stops the use of colors in the console log. The values `1`, `true`, `yes` and `on` are accepted. The console log has no colors when the output is redirected. | `SharpEmuLog.cs` |
| `SHARPEMU_LOG_NP_WEB_API2` | `1` | Writes an `npwebapi2` trace line for each NpWebApi2 call. The line shows the operation, the id, the first argument and the initialized state. | `NpWebApi2Exports.cs` |
| `SHARPEMU_LOG_OPEN` | `1` | Writes trace lines for guest file open operations to stderr. The default is off. | `KernelMemoryCompatExports.cs` |
| `SHARPEMU_LOG_PLAYGO` | `1` | Writes `playgo` trace lines for PlayGo calls. For single-entry locus queries it shows the first 32 calls and then every 1000th call. | `PlayGoExports.cs` |
| `SHARPEMU_LOG_POINTER_WINDOW_SIZE` | hex number | Sets the byte size of each memory window that `SHARPEMU_LOG_POINTER_WINDOWS` shows after a guest fault. The value is hexadecimal, with or without `0x`. The default is 0x80. | `DirectExecutionBackend.Exceptions.cs` |
| `SHARPEMU_LOG_POSIX_SIGNALS` | `1` | Writes a trace line for every POSIX signal that the fault handler receives. When unset, the log shows only the first 16 signals and then every 1024th signal. | `DirectExecutionBackend.PosixSignals.cs` |
| `SHARPEMU_LOG_PROC_PARAM_PTRS` | `1` | Shows the pointer fields in the process parameter block. This dump is part of the `SHARPEMU_LOG_PROC_PARAM` trace, so set that variable also. | `KernelRuntimeCompatExports.cs` |
| `SHARPEMU_LOG_PROC_PARAM` | `1` | Shows the address and the contents of the process parameter block of the guest program. The default is off. | `KernelRuntimeCompatExports.cs` |
| `SHARPEMU_LOG_PS5_USER_SLOTS` | `1` | Adds four 0x60-byte memory dumps to the IL2CPP exception diagnostic. The dumps start at the fixed guest address 0x801A73110 and have a step of 0x51C8 bytes. | `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_LOG_PSML` | `1` | Writes `psml.` trace lines for the PSML library calls to stderr. The default is off. | `PsmlExports.cs` |
| `SHARPEMU_LOG_PTHREADS` | `1` | Writes trace lines for the pthread calls of the guest. It also starts the condition variable trace of `SHARPEMU_LOG_PTHREAD_CONDS`. The default is off. | `KernelPthreadCompatExports.cs`, `KernelExports.cs` |
| `SHARPEMU_LOG_PTHREAD_CONDS` | `1` | Writes a `pthread_cond_` trace line for each condition variable operation. The line shows the waiter count, the signal epoch, and the result. | `KernelPthreadCompatExports.cs` |
| `SHARPEMU_LOG_PTHREAD_FASTPATH` | `1` | Writes trace lines for the mutex fast path. It shows the first 16 fast-path unlocks with the mutex object words. It shows one busy result for each mutex address. | `KernelPthreadCompatExports.cs` |
| `SHARPEMU_LOG_PTHREAD_MUTEX_FILTER` | list of hex addresses | Limits the mutex trace to the given mutex addresses. Use a comma, a semicolon, or a space between the hexadecimal addresses. The listed mutexes are in the trace even if `SHARPEMU_LOG_PTHREADS` is not set. | `KernelPthreadCompatExports.cs` |
| `SHARPEMU_LOG_REFSCAN_ADDRS` | list of hex addresses | After a guest fault, scans executable guest memory from 0x800000000 to 0x810000000 for instructions that refer to the given addresses. It shows a maximum of 24 hits for each address. Use a comma between the hexadecimal addresses. | `DirectExecutionBackend.Exceptions.cs` |
| `SHARPEMU_LOG_REGISTER_WINDOWS` | `1` | After a guest fault, shows a 0x80-byte memory window at each general register value that is 0x10000 or more. The default is off. | `DirectExecutionBackend.Exceptions.cs` |
| `SHARPEMU_LOG_SAVEDATA` | `1` | Writes `savedata.` and `save_data_dialog.` trace lines for the save data calls to stderr. The default is off. | `SaveDataExports.cs`, `SaveDataDialogExports.cs` |
| `SHARPEMU_LOG_SEMA` | `1` | Writes trace lines for the kernel semaphore operations. The emulator reads the value one time at start. The default is off. | `KernelSemaphoreCompatExports.cs` |
| `SHARPEMU_LOG_SHARE` | `1` | Writes `share.` trace lines for the Share library calls to stderr. The default is off. | `ShareExports.cs` |
| `SHARPEMU_LOG_SSL` | `1` | Writes an `ssl.` trace line for each SSL library call. The line shows the operation, the identifier, and the first argument. | `SslExports.cs` |
| `SHARPEMU_LOG_STACK_CHK` | `1` | Writes diagnostic lines when the guest calls the stack check failure import. The lines show the return address, the guard registers, and the stack slots from rbp-0x10 to rbp-0x80. | `DirectExecutionBackend.cs`, `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_LOG_STDIO` | `1` | Writes trace lines for the libc stdio calls of the guest. The emulator reads the value one time at start. The default is off. | `LibcStdioExports.cs` |
| `SHARPEMU_LOG_STRLEN_BURSTS` | `1` | Writes a warning when the guest calls `strlen` 24 times in sequence. The warning shows the return address and the last five different imports before the burst. | `DirectExecutionBackend.cs`, `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_LOG_STRLEN` | `1` | Keeps `strlen` calls in the import trace. When unset, the import trace does not show `strlen` calls. It also starts the burst detection of `SHARPEMU_LOG_STRLEN_BURSTS`. | `DirectExecutionBackend.cs`, `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_LOG_THREAD_MODE` | `1` | Writes `[THREADMODE]` lines when a native guest worker thread is created, starts a guest run, and stops a guest run. Each line shows the host thread identifiers. | `DirectExecutionBackend.cs`, `DirectExecutionBackend.NativeWorker.cs` |
| `SHARPEMU_LOG_USER_SERVICE` | `1` | Writes trace lines for the user service library calls. Each line includes the guest return address of the call. | `UserServiceExports.cs` |
| `SHARPEMU_LOG_USLEEP` | `1` | Writes trace lines for `usleep` calls: the first 32 calls and then every 10000th call. It also stops the native inline `usleep` stub and the leaf import path, so each call goes through the traced handler. | `DirectExecutionBackend.cs`, `DirectExecutionBackend.Imports.cs`, `KernelRuntimeCompatExports.cs` |
| `SHARPEMU_LOG_VIDEOOUT_FPS` | `1` | Writes periodic frame rate lines with flip, present, draw, pipeline, and buffer pool counts. `SHARPEMU_PROFILE_PERFORMANCE=1` starts the same output. | `VideoOutExports.cs` |
| `SHARPEMU_LOG_VIDEOOUT` | `1` | Writes `videoout.` trace lines for the video output calls, such as flip events and frame dumps. The default is off. | `VideoOutExports.cs` |
| `SHARPEMU_LOG_VK_RESOURCES` | `1` | Writes a `vk.global_buffer` trace line one time for each new guest buffer that the Vulkan presenter binds. The line shows the base address and the size. | `VulkanVideoPresenter.Draws.Recording.cs`, `VulkanVideoPresenter.GuestBuffers.cs` |
| `SHARPEMU_LOG_VMEM` | `1` | Writes debug lines for guest virtual memory operations and `[HOSTMEM]` lines for host memory operations. The default is off. | `PhysicalVirtualMemory.cs`, `HostMemory.cs`, `PosixHostMemory.cs` |
| `SHARPEMU_LOG_WIDE_PRINTF_ARGS` | `1` | Writes trace lines for the arguments of printf format calls, such as string arguments. Use `SHARPEMU_LOG_WIDE_PRINTF_FILTER` to limit the output. | `KernelMemoryCompatExports.cs` |
| `SHARPEMU_LOG_WIDE_PRINTF_FILTER` | text | Limits the `SHARPEMU_LOG_WIDE_PRINTF_ARGS` trace to format strings that contain this text. The comparison is case-sensitive. When unset, the trace includes all format strings. | `KernelMemoryCompatExports.cs` |
| `SHARPEMU_LOG_WIDE_PRINTF` | `1` | Writes a trace line for each wide-character printf call. The line shows the first 160 characters of the format and of the result. | `KernelMemoryCompatExports.cs` |
| `SHARPEMU_LOG_WIDE` | `1` | Shows the first 32 bytes at the string address for each `wcslen` call. The default is off. | `KernelMemoryCompatExports.cs` |
| `SHARPEMU_PERIODIC_SNAPSHOT_SECONDS` | number (seconds) | Set a number of seconds to write the stall watchdog snapshot at that interval. The default is 0, which writes no periodic snapshot. The stall watchdog must be on. | `DirectExecutionBackend.cs` |
## Traces
Each variable records a detailed sequence of events. Traces can be large.
| Variable | Value | Function | Code that reads it |
| --- | --- | --- | --- |
| `SHARPEMU_LOG_IMPORT_FILTER` | text | Writes a trace line for each import that contains this text. The emulator compares the text with the library name, the export name and the NID, and ignores case. When unset, the filter selects no imports. | `DirectExecutionBackend.cs`, `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_LOG_IMPORT_FRAMES` | `1` | Adds the guest frame chain to each traced import. It applies only to imports that `SHARPEMU_LOG_ALL_IMPORTS` or `SHARPEMU_LOG_IMPORT_FILTER` selects. | `DirectExecutionBackend.cs`, `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_LOG_IMPORT_PERIODIC` | `1` | Starts the periodic import trace. It shows the early import bands and every 100000th import dispatch. The default is off because the stderr output decreases the speed. | `DirectExecutionBackend.cs`, `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_LOG_IMPORT_RECENT` | `1` | Writes the recent import history after each traced import. It applies only to imports that `SHARPEMU_LOG_ALL_IMPORTS` or `SHARPEMU_LOG_IMPORT_FILTER` selects. | `DirectExecutionBackend.cs`, `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_PROBE_IMPORT_RET_ADDRESS` | hex address | Set a guest return address. When an import call returns to this address, the emulator writes an `import-return-address-probe` line with the thread, NID, stack and frame values. The limit is 2048 lines. | `DirectExecutionBackend.cs`, `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_PROBE_IMPORT_RET` | text (NID or `*`) | Set an import NID, or `*` for all imports. For the first 8 applicable import calls, the emulator writes the bytes and the disassembly before the return address. The default is off. | `DirectExecutionBackend.cs`, `DirectExecutionBackend.Imports.cs`, `DirectExecutionBackend.Diagnostics.cs` |
| `SHARPEMU_RTC_PROBE_RANGE` | hex address range (`start-end`) | Set a range of guest addresses. When a caller of `sceRtcGetCurrentTick` returns into this range, the emulator writes 0x100 bytes of code near that return address. It does this one time only. | `RtcExports.cs` |
| `SHARPEMU_TRACE_AGC_EQ_ACCESSORS` | `1` | Set to `1` to write an `agc.eq_accessor` line for calls to the AGC event accessor functions. Each line shows the accessor, the event address, the result and the event bytes. After 64 lines, the emulator writes only at power-of-two counts. | `AgcExports.Events.cs` |
| `SHARPEMU_TRACE_DCC_WRITERS` | `1` | Writes a `[GPU][DCC_WRITER]` line with the shader program and a call stack for each GPU buffer write that overlaps DCC metadata. It also writes `[GPU][BOUNDED_FILL_REFUSED]` lines when a fill shader is not changed into a buffer fill. Each kind writes a maximum of 64 lines. | `DccWriterTrace.cs` |
| `SHARPEMU_TRACE_FOCUSED_CONTINUATION` | `1` | Set to `1` to write `focused_continuation` lines for guest thread continuations. The emulator writes a line only when the stack pointer is in the range 0x6FFFAC000000 to 0x6FFFAC200000. | `DirectExecutionBackend.cs` |
| `SHARPEMU_TRACE_FRAME_PACKETS` | `1` | Writes a `[FRAMEPKT]` line at a flip with the draw count and the dispatch count of the frame. It shows the first 8 flips, each 60th flip, and each flip that has no draws. Default is off. | `AgcExports.CommandStream.cs` |
| `SHARPEMU_TRACE_GPU_MEMORY_ADDRESS` | hex address or `auto` | Writes `[GPU][MEMORY_TRACE]` lines for GPU memory events that touch the page of the given address. The value `auto` selects the page of the first device-address fault. Default is off. | `GuestGpuMemoryHook.cs` |
| `SHARPEMU_TRACE_GPU_READS` | `1` | Writes a `[GPU][SYNC_READ]` line with the shader hash, the stage and the address when a shader resource read must wait for GPU-written memory. It writes one line for each shader and page, and a maximum of 64 lines. | `GpuReadTrace.cs`, `VulkanVideoPresenter.Pipelines.cs` |
| `SHARPEMU_TRACE_GUEST_IMAGES` | `1`, `present` or `every:N[@M]` | `1` and `present` write Vulkan present trace lines (`vk.present_taken`, `vk.present_dropped`, `vk.present_sample`) and up to 64 Metal `agc.texture_fallback` lines. The code reads the `every:N[@M]` form, but no code uses the result. Default is off. | `VulkanVideoPresenter.Draws.Recording.cs`, `VulkanVideoPresenter.Present.cs`, `MetalTextureSnapshots.cs` |
| `SHARPEMU_TRACE_GUEST_IMAGE_ADDRS` | list of hex addresses or `*` | The guest image write tracker writes `[WT][LIFETIME]` lines for each tracked range that contains a listed address. `*` selects all ranges. The Vulkan presenter also reads the list, but no code uses that filter. | `GuestImageWriteTracker.cs`, `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_TRACE_GUEST_IMAGE_FORMAT` | text (Vulkan format name) | Effect not clear from the code. The Vulkan presenter keeps the name for an image filter that compares the image format, but no code calls the filter. | `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_TRACE_GUEST_IMAGE_HEIGHT` | number | Effect not clear from the code. The Vulkan presenter keeps the number for an image filter that compares the image height, but no code calls the filter. | `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_TRACE_GUEST_IMAGE_WIDTH` | number | Effect not clear from the code. The Vulkan presenter keeps the number for an image filter that compares the image width, but no code calls the filter. | `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_TRACE_GUEST_MEMORY_LIFETIME` | list of source names or `*` | The guest image write tracker writes `[WT][LIFETIME]` lines for each tracked range that has a listed source name. Use a comma or a semicolon between names. `*` selects all sources. | `GuestImageWriteTracker.cs` |
| `SHARPEMU_TRACE_GUEST_WRITES` | list of hex addresses or `*` | Effect not clear from the code. The Vulkan presenter reads the list in an address filter for guest image writes, but no code calls the filter. | `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_TRACE_PACKED_EXPORT` | `1` | The SPIR-V translator writes `[AGC][PACKED-EXPORT]` and `[AGC][TITLE-IR]` lines for packed export analysis. It does this only for the shader program at address 0x0000000500781200. Default is off. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_TRACE_PRESENTED_GUEST_IMAGE_ADDRS` | list of hex addresses or `*` | Writes a `vk.present_sample` trace line when the presenter shows a guest image at a listed address. It records the first presentation of each address unless `SHARPEMU_TRACE_PRESENTED_GUEST_IMAGE_OCCURRENCE` is set. | `VulkanVideoPresenter.Draws.Recording.cs`, `VulkanVideoPresenter.RenderLoop.cs` |
| `SHARPEMU_TRACE_PRESENTED_GUEST_IMAGE_OCCURRENCE` | number | Selects which presentation of an address in `SHARPEMU_TRACE_PRESENTED_GUEST_IMAGE_ADDRS` the presenter records. Default is 0, which selects the first presentation. | `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_TRACE_TITLE_INTERFACE` | `1` | The SPIR-V translator writes `[AGC][TITLE-INTERFACE]` lines with the export and interpolation instructions of a shader. It does this only for the programs at addresses 0x0000000500780000 and 0x0000000500781200. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_TRACE_WRITER_ADDRESS` | hex address | Writes a `[GPU][TARGET_WRITER]` line with the shader program and a call stack for each GPU buffer write that covers this guest address. It writes a maximum of 64 lines. Default is off. | `DccWriterTrace.cs` |
## Data dumps
Each variable writes data to files.
| Variable | Value | Function | Code that reads it |
| --- | --- | --- | --- |
| `SHARPEMU_DUMP_FAULT_STACK_WINDOW` | `1` | Writes the full stack window from RSP-0x300 to RSP+0x100 to the error output when a guest fault report occurs. The default writes only the short stack list. | `DirectExecutionBackend.Exceptions.cs` |
| `SHARPEMU_DUMP_FIXED_SOLID_FRAGMENT` | path | The Vulkan presenter reads the value into a field. No code uses the field, so the variable has no effect. | `VulkanVideoPresenter.Draws.Recording.cs` |
| `SHARPEMU_DUMP_SPIRV_ADDRESS` | hex address | Limits the shader dump of `SHARPEMU_DUMP_SPIRV=1` to the shader at this guest address. The default writes all shaders. | `ShaderProgramCache.cs` |
| `SHARPEMU_DUMP_VIDEOOUT` | `1` | Writes submitted VideoOut frame buffers as BMP files with a text metadata file. It writes a maximum of 8 frames and skips a frame that did not change. | `VideoOutExports.cs`, `VideoOutExports.FlipRequests.cs` |
| `SHARPEMU_GUEST_IMAGE_DUMP_CONTINUOUS` | `1` | Writes a swapchain dump for each presented frame, not only for the first one. It needs `SHARPEMU_GUEST_IMAGE_DUMP_DIR` and an active presented-image trace. Each dump waits for the GPU, so the frame rate decreases. | `VulkanVideoPresenter.Present.Frames.cs` |
| `SHARPEMU_GUEST_IMAGE_DUMP_DIR` | path | Sets the directory for raw swapchain dumps. The presenter writes `present-NNNN-WxH-format.bgra` files there when `SHARPEMU_TRACE_GUEST_IMAGES` is `1` or `present`. The presenter makes the directory if it is absent. | `VulkanVideoPresenter.Present.Frames.cs` |
| `SHARPEMU_LOG_DISASM_ADDRS` | list of hex addresses | Adds more addresses to the fault disassembly dump. Use a comma between the addresses. The emulator uses this list only when `SHARPEMU_LOG_DISASM` is `1`, and it shows 48 instructions for each address. | `DirectExecutionBackend.Exceptions.cs` |
| `SHARPEMU_LOG_DISASM` | `1` | Writes guest disassembly to stderr when a guest fault, an abort or an illegal instruction occurs. It shows the code before the fault address, before the stack return address and before three frame return addresses. | `DirectExecutionBackend.Exceptions.cs` |
| `SHARPEMU_LOG_IL2CPP_EXCEPTION` | `1` | Writes a diagnostic dump when the guest calls the unresolved import with NID `cfwBSQyr5Ys`. The dump shows the registers, the code pointers on the stack and the frame pointer chain. The emulator writes a maximum of 4 dumps. | `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_LOG_POINTER_WINDOWS` | list of hex addresses | Writes a memory window for each address when a guest access fault occurs. Use a comma between the addresses. The window size is 0x80 bytes unless `SHARPEMU_LOG_POINTER_WINDOW_SIZE` sets a different size. | `DirectExecutionBackend.Exceptions.cs` |
| `SHARPEMU_SHADER_SPIRV_DUMP_DIR` | path | Set a directory for shader dumps. When set, the Vulkan presenter writes each SPIR-V module to a numbered `.spv` file. The `SHARPEMU_DUMP_SPIRV=1` dumps also use this directory. Their default is `shader-dumps` next to the executable. | `VulkanVideoPresenter.Pipelines.cs`, `ShaderProgramCache.cs`, `VulkanVideoPresenter.Device.Setup.cs` |
| `SHARPEMU_SWAPCHAIN_DUMP_EVERY` | number (frames) | Set a number N to trace the presented swapchain image at each Nth present. This operates only when `SHARPEMU_TRACE_GUEST_IMAGES` is `1` or `present`. The default is 0, which traces only the first presented image. | `VulkanVideoPresenter.Present.Frames.cs`, `VulkanVideoPresenter.Draws.Recording.cs` |
## Performance measurement
Each variable records timings or counts.
| Variable | Value | Function | Code that reads it |
| --- | --- | --- | --- |
| `SHARPEMU_LOG_AUDIO_QUEUE` | `1` | Writes one `[PERF][AUDIO]` line per second for each SDL audio stream. The line shows the queue depth in milliseconds, the submit rate, the fill percentage and the drops. The emulator reads the value one time at start. | `SdlHostAudio.cs` |
| `SHARPEMU_PERF_HLE_NODICT` | `1` | Use with `SHARPEMU_PERF_HLE=1`. Set to `1` to stop the call count dictionary and the top call count report. The dispatch time report stays on. | `DirectExecutionBackend.Diagnostics.cs` |
| `SHARPEMU_PERF_HLE` | `1` | Set to `1` to measure the time of each HLE import dispatch. After each 500000 calls, the emulator writes `[PERF][HLE]` lines with the call counts and the cost of the top exports. The default is off. | `DirectExecutionBackend.Diagnostics.cs`, `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_PERF_MEM` | `1` | Set to `1` to count the POSIX fault signals that the signal handler receives. The emulator writes a `[PERF][MEM] posix_faults` line after each 100000 signals. This has an effect only on POSIX hosts. | `DirectExecutionBackend.PosixSignals.cs` |
| `SHARPEMU_PROFILE_DCB_PARSE` | `1` | Set to `1` to measure the time to parse draw command buffers. The emulator writes `[PERF][DCB_PARSE]` lines. `SHARPEMU_PROFILE_PERFORMANCE=1` also starts this profile. | `DcbParseProfile.cs` |
| `SHARPEMU_PROFILE_DCB_SUBMISSION` | `1` | Set to `1` to measure command buffer submission and geometry snapshot work. The emulator writes `[PERF][DCB_SUBMIT]`, `[PERF][VERTEX_SNAPSHOT]` and `[PERF][SNAPSHOT_PREPASS]` lines. `SHARPEMU_PROFILE_PERFORMANCE=1` also starts this profile. | `DcbSubmissionProfile.cs` |
| `SHARPEMU_PROFILE_GPU_DRAWS` | `1` | Use with the render profile. Writes a GPU timestamp after each draw and dispatch, so that the `[PERF][GPU_INTERVAL]` lines give the GPU time of each pipeline. The default writes only two timestamps for each submission for the `[PERF][GPU_BUSY]` lines, because one timestamp for each draw can change the GPU time. | `VulkanCommandProfile.cs` |
| `SHARPEMU_PROFILE_GUEST_IMAGE_TRACKER` | `1` | Set to `1` to record counters for the guest image write tracker. The emulator writes `[PERF][GUEST_IMAGE_TRACKER]` and `[PERF][GUEST_IMAGE_TRACKER_RANGE]` lines. `SHARPEMU_PROFILE_PERFORMANCE=1` also starts this profile. | `GuestImageWriteTracker.cs` |
| `SHARPEMU_PROFILE_GUEST_RIP_INTERVAL_MS` | number (milliseconds) | Set the time between samples of the guest code profiler. The value must be more than 0. The default is 2. | `DirectExecutionBackend.GuestSampler.cs` |
| `SHARPEMU_PROFILE_GUEST_RIP_REPORT_S` | number (seconds) | Set the time between reports of the guest code profiler. The value must be more than 0. The default is 15. | `DirectExecutionBackend.GuestSampler.cs` |
| `SHARPEMU_PROFILE_GUEST_RIP_THREAD` | text | Set a text filter for the guest code profiler. The profiler samples only guest threads whose name contains this text. The comparison ignores case. When unset, the profiler samples all guest threads. | `DirectExecutionBackend.GuestSampler.cs` |
| `SHARPEMU_PROFILE_GUEST_RIP` | `1` | Set to `1` to start a sample profiler for guest code. The profiler records the instruction address of each guest thread and writes `[PERF][GUEST]` reports. The default is off. | `DirectExecutionBackend.GuestSampler.cs`, `DirectExecutionBackend.Imports.cs` |
| `SHARPEMU_PROFILE_GUEST_SCHEDULER` | `1` | Set to `1` to record guest thread scheduler statistics. The emulator writes `[PERF][GUEST_SCHED]` lines. With `SHARPEMU_PROFILE_PERFORMANCE_FRAME_TRACE=1`, it also records guest thread flow events. `SHARPEMU_PROFILE_PERFORMANCE=1` also starts this profile. | `DirectExecutionBackend.GuestSchedulerProfile.cs`, `GuestThreadFlowProfile.cs` |
| `SHARPEMU_PROFILE_RENDER_REPORT_S` | number (seconds) | Set the time between render profile reports. The value can be a decimal number and must be more than 0. The default is 5. | `RenderPhaseProfile.cs` |
| `SHARPEMU_PROFILE_RENDER` | `1` | Set to `1` to measure the time of each render thread phase. The emulator writes `[PERF][RENDER]`, `[PERF][RENDER_MS]` and related lines. With `SHARPEMU_PROFILE_PERFORMANCE_FRAME_TRACE=1`, it also records GPU memory access counters. `SHARPEMU_PROFILE_PERFORMANCE=1` also starts this profile. | `RenderPhaseProfile.cs`, `GpuMemoryAccessProfile.cs` |
| `SHARPEMU_PROFILE_SYNC_ON_ADDRESS` | `1` | Set to `1` to start the detailed sync-on-address profile. The emulator also records the guest call stack for each wait and wake call. It writes `[PERF][SYNC_ADDR]` and `[PERF][SYNC_THREAD]` lines. `SHARPEMU_PROFILE_PERFORMANCE=1` starts the profile without the call stack. | `KernelSyncOnAddressProfile.cs`, `KernelSyncOnAddressCompatExports.cs` |
| `SHARPEMU_PROFILE_TEXTURE_PREPARATION` | `1` | Set to `1` to measure texture preparation work. The emulator writes `[PERF][TEXTURE_PREP]` lines. `SHARPEMU_PROFILE_PERFORMANCE=1` also starts this profile. | `TexturePreparationProfile.cs` |
## Internal
The emulator sets these variables for its own processes. Do not set them manually.
| Variable | Value | Function | Code that reads it |
| --- | --- | --- | --- |
| `SHARPEMU_MITIGATED_CHILD` | `1` | The Windows launcher sets this variable to 1 when it starts the child process with CFG and CET mitigations off. The child accepts the `--sharpemu-mitigated-child` argument only when the value is 1. Do not set it manually. | `Program.cs`, `EmulatorProcess.cs` |
## Tests and tools
Only the tests, the scripts or the build tools read these variables.
| Variable | Value | Function | Code that reads it |
| --- | --- | --- | --- |
| `SHARPEMU_BACKING_VIEW_FAULT_WORKER` | `1` | The backing view fault test sets this for its child process. The value `1` tells the child to do the fault sequence. Do not set it manually. | `BackingViewFaultTests.cs`, `GuestFaultWorker.cs` |
| `SHARPEMU_BUFFER_FAULT_WORKER` | `1` | The guest buffer fault test sets this for its child process. The value `1` tells the child to do the fault sequence. Do not set it manually. | `GuestBufferFaultTests.cs`, `GuestFaultWorker.cs` |
| `SHARPEMU_FAULT_WORKER_REPORT` | path | The fault test parent sets this to a temporary file path for its child process. The child writes its result (`completed` or `skipped`) to this file. When unset, the child writes the result to the error stream. | `GuestFaultWorker.cs` |
| `SHARPEMU_IMAGE_FAULT_WORKER` | `1` | The guest image fault test sets this for its child process. The value `1` tells the child to do the fault sequence. Do not set it manually. | `GuestImageFaultTests.cs`, `GuestFaultWorker.cs` |
| `SHARPEMU_NATIVE_RETURN_SMOKE_WORKER` | `1` | The native return smoke test sets this for its child process. The value `1` tells the child to run the synthetic guest entry. Do not set it manually. | `Gen5NativeReturnSmokeTests.cs` |
| `SHARPEMU_SOCKET_CONNECTION_TEST_WORKER` | `1` | The kernel socket connection test sets this for its child process. The value `1` tells the child to do the connect sequence. Do not set it manually. | `KernelSocketConnectionTests.cs` |
| `SHARPEMU_TEST_REFERENCE_SPIRV_DIR` | path | Sets the directory that contains the reference compiled shader files for the GPU image tests. The tests make sure that each file has the recorded SHA-256 hash. When unset, these tests skip the reference comparison. | `ImageTestHarness.cs` |
| `SHARPEMU_TEST_REQUIRE_DEVICE` | `1` | Makes a GPU test fail when a Vulkan or Metal device or a device feature is missing. Default is to skip the test. | `ImageTestHarness.cs`, `MetalRuntimeTests.cs` |
| `SHARPEMU_TEST_REQUIRE_REFERENCE_SPIRV` | `1` | Makes a test fail when a reference shader file, its directory, or a necessary device is missing. Default is to skip the test. | `ImageTestHarness.cs`, `GuestFaultWorker.cs` |
| `SHARPEMU_TEST_VK_VALIDATION` | `1` | Loads the Vulkan validation layer in the headless test device and prints the validation messages. Default is off. | `HeadlessVulkan.cs` |
| `SHARPEMU_THREAD_CONTEXT_TEST_WORKER` | `1` | The Windows thread context capture test sets this for its child process. The value `1` tells the child to do the capture sequence. Do not set it manually. | `WindowsThreadContextCaptureTests.cs`, `GuestFaultWorker.cs` |
| `SHARPEMU_UPDATE_GOLDENS` | `1` | Makes the Metal golden tests write the generated shader text to the golden files in the source tree. Default is to compare the generated text with the golden files. | `MslGoldenTests.cs` |
## Variables that the code reads but does not use
The code reads these variables into a field or a filter. No other code uses that field or filter.
Thus they have no effect, or only a part of their function operates. The rows above give the details.
- `SHARPEMU_DUMP_FIXED_SOLID_FRAGMENT`
- `SHARPEMU_ENABLE_CHUNKED_DRAWS`
- `SHARPEMU_FORCE_ATTRIBUTE_FRAGMENT`
- `SHARPEMU_FORCE_DEFAULT_RASTER_STATE`
- `SHARPEMU_FORCE_FULLSCREEN_PIPELINE`
- `SHARPEMU_FORCE_FULLSCREEN_VERTEX`
- `SHARPEMU_FORCE_SOLID_FRAGMENT`
- `SHARPEMU_FORCE_TITLE_DEFAULT_RASTER_STATE`
- `SHARPEMU_FORCE_TITLE_FULLSCREEN_VERTEX`
- `SHARPEMU_FORCE_TITLE_SOLID_FRAGMENT`
- `SHARPEMU_SKIP_TALL_COMPUTE_Z`
- `SHARPEMU_TRACE_GUEST_IMAGE_FORMAT`
- `SHARPEMU_TRACE_GUEST_IMAGE_HEIGHT`
- `SHARPEMU_TRACE_GUEST_IMAGE_WIDTH`
- `SHARPEMU_TRACE_GUEST_WRITES`

View File

@ -1,48 +0,0 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
-->
# Windows crash capture
In the launcher, open **Options > Logging** and enable **Crash dumps** before
you start a game. The same toggle is available in each game's Logging settings.
It sets `SHARPEMU_CRASH_CAPTURE` and is off by default.
For a diagnostic run on Windows x64, you can also set it from PowerShell:
```powershell
$env:SHARPEMU_CRASH_CAPTURE = '1'
.\SharpEmu.exe
```
Start a new launcher from that PowerShell window. The game process starts a
hidden helper before runtime initialization. No SDK or debugger install is
required. Look for `[CRASH][INFO] Crash capture ready` in the game log.
The helper writes a full dump beside the run log. Without a log path, it uses
`user/logs` beside the executable. Names include the game process ID:
- `<run>.crash-<pid>.dmp`: the memory dump.
- `<run>.crash-<pid>.dmp.capture.log`: capture status and errors.
Full dumps can use many GB of disk space and contain private process data.
Keep them local until you choose to share them. There is no automatic upload.
The helper uses Windows debugger events. It passes first-chance exceptions to
the application and captures only second-chance, unhandled exceptions. Normal
handled page faults do not create dumps. A normal exit or a forced process
termination does not create a dump either. The original crash is not suppressed.
This option changes debugger presence and can change timing. Do not use it for
FPS comparisons. Do not attach WinDbg, ProcDump, or another native debugger at
the same time. Capture failures are recorded when possible; no capture method
can cover every process termination. A failed write can leave an incomplete dump.
This is separate from the `DOTNET_Dbg*` settings. It does not change them.
To disable a GUI selection, turn off **Crash dumps** before the next game launch.
If you set the option in PowerShell, close the launcher and run:
```powershell
Remove-Item Env:SHARPEMU_CRASH_CAPTURE -ErrorAction SilentlyContinue
```

View File

@ -41,36 +41,21 @@ def write_pair(nid: str, export_name: str) -> None:
def lookup(args: argparse.Namespace) -> int:
values = [value.strip() for value in args.value.split(",") if value.strip()]
names = read_names(args.names)
name_set = set(names)
value = args.value.strip()
if NID_PATTERN.fullmatch(value):
for export_name in read_names(args.names):
if compute_nid(export_name) == value:
write_pair(value, export_name)
return 0
result = 0
print(f"NID not found in catalog: {value}", file=sys.stderr)
return 1
for value in values:
if NID_PATTERN.fullmatch(value):
found = False
for export_name in names:
if compute_nid(export_name) == value:
write_pair(value, export_name)
found = True
break
if not found:
print(f"NID not found in catalog: {value}", file=sys.stderr)
result = 1
continue
write_pair(compute_nid(value), value)
if value not in name_set:
print(
f"Warning: export name is not present in the catalog: {value}",
file=sys.stderr,
)
return result
names = set(read_names(args.names))
write_pair(compute_nid(value), value)
if value not in names:
print("Warning: export name is not present in the catalog.", file=sys.stderr)
return 0
def search(args: argparse.Namespace) -> int:
@ -147,9 +132,7 @@ def create_parser() -> argparse.ArgumentParser:
lookup_parser = subparsers.add_parser(
"lookup", help="resolve a NID or calculate the NID for an export name"
)
lookup_parser.add_argument(
"value", help="11-character NID or exact export name; comma-separated values are supported"
)
lookup_parser.add_argument("value", help="11-character NID or exact export name")
lookup_parser.set_defaults(handler=lookup)
search_parser = subparsers.add_parser(

View File

@ -133845,7 +133845,6 @@ sceKernelWriteRemapIntoPrtCommand
sceKernelWriteRemapWithGpuMaskIdCommand
sceKernelWriteSdkEventLog
sceKernelWriteSdkEventLogV
sceKernelWriteThrottlingStatus
sceKernelWriteUnmapCommand
sceKernelWriteUnmapToPrtCommand
sceKernelWriteWaitOnAddressCommand
@ -153134,7 +153133,6 @@ scePsmlMfsrGetContextBufferRequirement800M3_2
scePsmlMfsrGetDispatchMfsrPacket1000
scePsmlMfsrGetDispatchMfsrPacket1100
scePsmlMfsrGetDispatchMfsrPacketSizeInDwords
scePsmlMfsrGetDispatchMfsrPacket900
scePsmlMfsrGetMipmapBias
scePsmlMfsrGetSharedResourcesInitRequirement
scePsmlMfsrInit
@ -154457,6 +154455,3 @@ sceNpEAAccessInitialize
sceNpEAAccessTerminate
sceNpHasEAAccessSubscription
sceNpHasEAAccessSubscriptionAbortRequest
sceAgcAddPrimStateRegisters
sceVoiceQoSSetMode
sceVoiceQoSTerminate

View File

@ -157,62 +157,6 @@ def ensure_tag_does_not_exist(
raise ReleaseError(f"Tag {tag} already exists on {remote}.")
def get_previous_tag(repository_root: Path) -> str:
try:
return run_git(
"describe",
"--tags",
"--abbrev=0",
"--match",
"v*",
"HEAD",
cwd=repository_root,
capture_output=True,
)
except ReleaseError:
return ""
def get_release_commits(
repository_root: Path,
previous_tag: str,
) -> list[str]:
revision_range = f"{previous_tag}..HEAD" if previous_tag else "HEAD"
output = run_git(
"log",
"--no-merges",
"--reverse",
"--pretty=tformat:%h %s",
revision_range,
cwd=repository_root,
capture_output=True,
)
return output.splitlines()
def print_release_notes_preview(repository_root: Path) -> None:
previous_tag = get_previous_tag(repository_root)
commits = get_release_commits(repository_root, previous_tag)
print()
if previous_tag:
print(f"Commits since {previous_tag} ({len(commits)}):")
else:
print(f"Commits in this release ({len(commits)}):")
if not commits:
print(" (none)")
for commit in commits:
print(f" {commit}")
print()
print("These commits go into the generated release notes.")
def read_version(props_path: Path) -> str:
if not props_path.exists():
raise ReleaseError(f"Version file not found: {props_path}")
@ -379,8 +323,6 @@ def create_release_tag(
remote,
)
print_release_notes_preview(repository_root)
run_git(
"tag",
"-a",

View File

@ -8,7 +8,6 @@ using SharpEmu.HLE;
using SharpEmu.Libs.VideoOut;
using SharpEmu.Logging;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Text;
using System.Text.Json;
@ -32,6 +31,7 @@ internal static partial class Program
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;
@ -45,14 +45,6 @@ internal static partial class Program
[STAThread]
private static int Main(string[] args)
{
ConfigureManagedPluginResolution();
if (args.Length > 0 && args[0] == SharpEmu.Core.Diagnostics.WindowsCrashCapture.HelperArgument)
return SharpEmu.Core.Diagnostics.WindowsCrashCapture.RunHelper(args);
RenderDocCapture.ApplyVulkanLoaderEnvironment();
SharpEmu.Libs.VideoOut.RenderDocCapture.Initialize();
try
{
return Run(args);
@ -64,25 +56,6 @@ internal static partial class Program
}
}
private static void ConfigureManagedPluginResolution()
{
AssemblyLoadContext.Default.Resolving += static (loadContext, assemblyName) =>
{
if (string.IsNullOrWhiteSpace(assemblyName.Name))
{
return null;
}
var assemblyPath = Path.Combine(
AppContext.BaseDirectory,
"plugins",
assemblyName.Name + ".dll");
return File.Exists(assemblyPath)
? loadContext.LoadFromAssemblyPath(assemblyPath)
: null;
};
}
private static int Run(string[] args)
{
if (Updater.TryApply(args, out var updateExitCode))
@ -91,6 +64,7 @@ internal static partial class Program
}
args = NormalizeInternalArguments(args, out var isMitigatedChild);
PreloadGlfw();
if (args.Length == 0)
{
@ -119,9 +93,14 @@ internal static partial class Program
PreloadMacVulkanLoader();
}
// SDL/AppKit window work belongs on the process main thread on
// macOS. Linux uses the same model for consistent X11/Wayland
// event ownership. Emulation remains on a worker thread.
// 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(() =>
@ -152,9 +131,10 @@ internal static partial class Program
/// 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). Failing up front on
/// any other process architecture distinguishes that from MoltenVK,
/// signal-handler, or guest-memory startup problems.
/// 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()
{
@ -198,11 +178,11 @@ internal static partial class Program
}
/// <summary>
/// Makes a Vulkan loader visible before SDL creates its Vulkan surface.
/// 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 can then resolve the loader for SDL and Silk.NET.
/// dyld then resolves GLFW's bare-name dlopen to the loaded image.
/// </summary>
private static void PreloadMacVulkanLoader()
{
@ -234,6 +214,27 @@ internal static partial class Program
"as libvulkan.1.dylib.");
}
/// <summary>
/// SharpEmu.CLI.csproj publishes glfw into a "plugins" subfolder rather
/// than flat next to the executable, which falls outside the default OS
/// DLL/dlopen search path. Preloading it here by full path first means
/// any later bare-name lookup (however Silk.NET/GLFW itself resolves the
/// library) finds it already loaded in the process and reuses it -- the
/// same technique <see cref="PreloadMacVulkanLoader"/> already relies on
/// for the Vulkan loader.
/// </summary>
private static void PreloadGlfw()
{
var fileName = OperatingSystem.IsWindows() ? "glfw3.dll"
: OperatingSystem.IsMacOS() ? "libglfw.3.dylib"
: "libglfw.so.3";
var candidate = Path.Combine(AppContext.BaseDirectory, "plugins", fileName);
if (File.Exists(candidate))
{
NativeLibrary.TryLoad(candidate, out _);
}
}
private static int RunEmulator(string[] args, bool isMitigatedChild)
{
Console.Error.WriteLine($"[DEBUG] SharpEmu starting with {args.Length} args");
@ -243,13 +244,17 @@ internal static partial class Program
return childExitCode;
}
if (!TryParseArguments(
args,
out var ebootPath,
out var runtimeOptions,
out var videoOptions,
out var logLevel,
out var logFilePath))
if (!TryExtractHostSurfaceArgument(args, out var emulatorArgs, out var hostSurface, out var hostSurfaceError))
{
Console.Error.WriteLine($"[LOADER][ERROR] {hostSurfaceError}");
return 1;
}
HostSessionControl.SetEmbeddedHostSurface(
hostSurface?.WindowHandle ?? 0,
hostSurface?.DisplayHandle ?? 0);
if (!TryParseArguments(emulatorArgs, out var ebootPath, out var runtimeOptions, out var logLevel, out var logFilePath))
{
PrintUsage();
return 1;
@ -261,11 +266,6 @@ internal static partial class Program
}
SharpEmuLog.MinimumLevel = logLevel;
if (!HostVideoHost.TryConfigureVideo(videoOptions))
{
Console.Error.WriteLine("[LOADER][ERROR] Video options cannot change while a presenter is active.");
return 3;
}
Log.Info(BuildInfo.Banner);
Log.Info(HostSystemInfo.Summary);
@ -307,10 +307,14 @@ internal static partial class Program
Console.Error.WriteLine("[DEBUG] Creating runtime...");
SharpEmu.Core.Diagnostics.WindowsCrashCapture.StartIfEnabled(logFilePath);
try
{
if (hostSurface is not null && !VulkanVideoHost.TryAttachSurface(hostSurface))
{
Console.Error.WriteLine("[LOADER][ERROR] The requested GUI host surface is already active.");
return 3;
}
using var runtime = SharpEmuRuntime.CreateDefault(runtimeOptions);
OrbisGen2Result result;
@ -323,16 +327,6 @@ internal static partial class Program
VideoOutExports.NotifyHostInterrupt();
};
Console.CancelKeyPress += cancelHandler;
// SIGTERM (launchd, process managers, `kill`) takes the same cooperative shutdown: the
// runtime's default exits with GPU work in flight, which leaves the host driver to reclaim
// resources the device still owns.
using var terminateRegistration = OperatingSystem.IsWindows()
? null
: PosixSignalRegistration.Create(PosixSignal.SIGTERM, context =>
{
context.Cancel = true;
VideoOutExports.NotifyHostInterrupt();
});
Console.Error.WriteLine($"[DEBUG] Running: {ebootPath}");
result = runtime.Run(ebootPath);
@ -390,9 +384,53 @@ internal static partial class Program
debugHost.DisposeAsync().AsTask().GetAwaiter().GetResult();
}
HostSessionControl.SetEmbeddedHostSurface(0);
if (hostSurface is not null)
{
VulkanVideoHost.RequestClose();
VulkanVideoHost.DetachSurface(hostSurface);
hostSurface.Dispose();
}
}
}
private static bool TryExtractHostSurfaceArgument(
IReadOnlyList<string> args,
out string[] emulatorArgs,
out VulkanHostSurface? hostSurface,
out string? error)
{
const string hostSurfacePrefix = "--host-surface=";
var remaining = new List<string>(args.Count);
hostSurface = null;
error = null;
foreach (var argument in args)
{
if (!argument.StartsWith(hostSurfacePrefix, StringComparison.OrdinalIgnoreCase))
{
remaining.Add(argument);
continue;
}
if (hostSurface is not null)
{
emulatorArgs = [];
error = "more than one GUI host surface was specified";
return false;
}
var descriptor = argument[hostSurfacePrefix.Length..];
if (!VulkanHostSurface.TryCreateChildProcessSurface(descriptor, out hostSurface, out error))
{
emulatorArgs = [];
return false;
}
}
emulatorArgs = remaining.ToArray();
return true;
}
private static void EnsureCliConsole()
{
if (!OperatingSystem.IsWindows())
@ -535,15 +573,9 @@ internal static partial class Program
return false;
}
var commandLineArguments = Environment.GetCommandLineArgs();
var entryAssemblyPath = commandLineArguments.Length > 0 ? commandLineArguments[0] : null;
string[] childArguments =
Path.GetFileNameWithoutExtension(processPath).Equals("dotnet", StringComparison.OrdinalIgnoreCase) &&
!string.IsNullOrWhiteSpace(entryAssemblyPath)
? [entryAssemblyPath, MitigatedChildFlag, .. args]
: [MitigatedChildFlag, .. args];
string[] childArgs = [MitigatedChildFlag, .. args];
var commandLine = BuildCommandLine(processPath, childArguments);
var commandLine = BuildCommandLine(processPath, childArgs);
var startupInfoEx = new STARTUPINFOEX();
startupInfoEx.StartupInfo.cb = Marshal.SizeOf<STARTUPINFOEX>();
ConfigureInheritedStdHandles(ref startupInfoEx.StartupInfo);
@ -1010,7 +1042,7 @@ internal static partial class Program
private static void PrintUsage()
{
Log.Info("Usage: SharpEmu.CLI [--strict] [--trace-imports[=N]] [--cpu-engine=<native>] [--console=<ps5>] [--console-language=<language>] [--log-level=<level>] [--log-file[=<path>]] [--window-mode=<windowed|borderless|exclusive>] [--resolution=<WIDTHxHEIGHT>] [--display=<N>] [--refresh-rate=<HZ>] [--scaling=<fit|cover|stretch|integer>] [--vsync=<on|off>] [--hdr=<auto|on|off>] [--overlay=<on|off>] [--overlay-mode=<full|minimal|titlebar>] [--overlay-corner=<topleft|topright|bottomright|bottomleft>] [--debug-server[=host:port]] <path-to-eboot.bin>");
Log.Info("Usage: SharpEmu.CLI [--strict] [--trace-imports[=N]] [--cpu-engine=<native>] [--log-level=<level>] [--log-file[=<path>]] [--debug-server[=host:port]] <path-to-eboot.bin>");
Log.Info(@"Example: SharpEmu.CLI --cpu-engine=native --trace-imports=64 --log-level=debug --log-file ""E:\Games\...\eboot.bin""");
Log.Info("Debug server: --debug-server starts a live debug listener (default 127.0.0.1:5714); connect with SharpEmu.DebugClient.");
}
@ -1055,7 +1087,6 @@ internal static partial class Program
string[] args,
out string ebootPath,
out SharpEmuRuntimeOptions runtimeOptions,
out HostVideoOptions videoOptions,
out LogLevel logLevel,
out string? logFilePath)
{
@ -1063,7 +1094,6 @@ internal static partial class Program
{
ebootPath = string.Empty;
runtimeOptions = default;
videoOptions = HostVideoOptions.Default;
logLevel = SharpEmuLog.MinimumLevel;
logFilePath = null;
return false;
@ -1072,158 +1102,12 @@ internal static partial class Program
var strictDynlibResolution = false;
var importTraceLimit = 0;
var cpuEngine = CpuExecutionEngine.NativeOnly;
var systemLanguage = 1;
HostWindowMode? windowModeOverride = null;
HostScalingMode? scalingModeOverride = null;
int? windowWidthOverride = null;
int? windowHeightOverride = null;
int? displayIndexOverride = null;
int? refreshRateOverride = null;
bool? vsyncOverride = null;
HostHdrMode? hdrModeOverride = null;
bool? overlayEnabledOverride = null;
PerformanceOverlayMode? overlayModeOverride = null;
PerformanceOverlayCorner? overlayCornerOverride = null;
videoOptions = HostVideoOptions.Default;
logFilePath = null;
logLevel = SharpEmuLog.MinimumLevel;
var pathTokens = new List<string>(args.Length);
for (var i = 0; i < args.Length; i++)
{
var argument = args[i];
if (TrySplitOption(argument, "--console", out var consoleText))
{
if (!string.Equals(consoleText, "ps5", StringComparison.OrdinalIgnoreCase))
{
ebootPath = string.Empty;
runtimeOptions = default;
return false;
}
continue;
}
if (TrySplitOption(argument, "--console-language", out var consoleLanguageText))
{
if (!TryParseSystemLanguage(consoleLanguageText, out systemLanguage))
{
ebootPath = string.Empty;
runtimeOptions = default;
return false;
}
continue;
}
if (TrySplitOption(argument, "--window-mode", out var windowModeText))
{
if (!TryParseWindowMode(windowModeText, out var windowMode))
{
ebootPath = string.Empty;
runtimeOptions = default;
return false;
}
windowModeOverride = windowMode;
continue;
}
if (TrySplitOption(argument, "--resolution", out var resolutionText))
{
if (!TryParseResolution(resolutionText, out var windowWidth, out var windowHeight))
{
ebootPath = string.Empty;
runtimeOptions = default;
return false;
}
windowWidthOverride = windowWidth;
windowHeightOverride = windowHeight;
continue;
}
if (TrySplitOption(argument, "--display", out var displayText))
{
if (!int.TryParse(displayText, out var displayIndex) || displayIndex < 0)
{
ebootPath = string.Empty;
runtimeOptions = default;
return false;
}
displayIndexOverride = displayIndex;
continue;
}
if (TrySplitOption(argument, "--refresh-rate", out var refreshText))
{
if (!int.TryParse(refreshText, out var refreshRate) || refreshRate < 0)
{
ebootPath = string.Empty;
runtimeOptions = default;
return false;
}
refreshRateOverride = refreshRate;
continue;
}
if (TrySplitOption(argument, "--scaling", out var scalingText))
{
if (!TryParseScalingMode(scalingText, out var scalingMode))
{
ebootPath = string.Empty;
runtimeOptions = default;
return false;
}
scalingModeOverride = scalingMode;
continue;
}
if (TrySplitOption(argument, "--vsync", out var vsyncText))
{
if (!TryParseSwitch(vsyncText, out var vsync))
{
ebootPath = string.Empty;
runtimeOptions = default;
return false;
}
vsyncOverride = vsync;
continue;
}
if (TrySplitOption(argument, "--overlay", out var overlayText))
{
if (!TryParseSwitch(overlayText, out var overlayEnabled))
{
ebootPath = string.Empty;
runtimeOptions = default;
return false;
}
overlayEnabledOverride = overlayEnabled;
continue;
}
if (TrySplitOption(argument, "--overlay-mode", out var overlayModeText))
{
if (!Enum.TryParse<PerformanceOverlayMode>(overlayModeText, true, out var overlayMode) ||
!Enum.IsDefined(overlayMode))
{
ebootPath = string.Empty;
runtimeOptions = default;
return false;
}
overlayModeOverride = overlayMode;
continue;
}
if (TrySplitOption(argument, "--overlay-corner", out var overlayCornerText))
{
if (!Enum.TryParse<PerformanceOverlayCorner>(overlayCornerText, true, out var overlayCorner) ||
!Enum.IsDefined(overlayCorner))
{
ebootPath = string.Empty;
runtimeOptions = default;
return false;
}
overlayCornerOverride = overlayCorner;
continue;
}
if (TrySplitOption(argument, "--hdr", out var hdrText))
{
if (!TryParseHdrMode(hdrText, out var hdrMode))
{
ebootPath = string.Empty;
runtimeOptions = default;
return false;
}
hdrModeOverride = hdrMode;
continue;
}
if (string.Equals(argument, "--strict", StringComparison.OrdinalIgnoreCase))
{
strictDynlibResolution = true;
@ -1382,199 +1266,12 @@ internal static partial class Program
runtimeOptions = new SharpEmuRuntimeOptions
{
CpuEngine = cpuEngine,
SystemLanguage = systemLanguage,
StrictDynlibResolution = strictDynlibResolution,
ImportTraceLimit = importTraceLimit,
};
var configuredVideoOptions = LoadConfiguredVideoOptions(ebootPath);
videoOptions = (configuredVideoOptions with
{
WindowMode = windowModeOverride ?? configuredVideoOptions.WindowMode,
ScalingMode = scalingModeOverride ?? configuredVideoOptions.ScalingMode,
Width = windowWidthOverride ?? configuredVideoOptions.Width,
Height = windowHeightOverride ?? configuredVideoOptions.Height,
DisplayIndex = displayIndexOverride ?? configuredVideoOptions.DisplayIndex,
RefreshRate = refreshRateOverride ?? configuredVideoOptions.RefreshRate,
VSync = vsyncOverride ?? configuredVideoOptions.VSync,
HdrMode = hdrModeOverride ?? configuredVideoOptions.HdrMode,
OverlayEnabled = overlayEnabledOverride ?? configuredVideoOptions.OverlayEnabled,
OverlayMode = overlayModeOverride ?? configuredVideoOptions.OverlayMode,
OverlayCorner = overlayCornerOverride ?? configuredVideoOptions.OverlayCorner,
}).Normalize();
return true;
}
private static HostVideoOptions LoadConfiguredVideoOptions(string ebootPath)
{
var defaults = HostVideoOptions.Default;
try
{
var effective = EffectiveLaunchSettings.Resolve(
GuiSettings.Load(),
PerGameSettings.Load(TryReadTitleId(ebootPath)));
var windowMode = TryParseWindowMode(effective.WindowMode, out var parsedWindowMode)
? parsedWindowMode
: defaults.WindowMode;
var scalingMode = TryParseScalingMode(effective.ScalingMode, out var parsedScalingMode)
? parsedScalingMode
: defaults.ScalingMode;
var hasResolution = TryParseResolution(
effective.Resolution,
out var configuredWidth,
out var configuredHeight);
var hdrMode = TryParseHdrMode(effective.HdrMode, out var parsedHdrMode)
? parsedHdrMode
: defaults.HdrMode;
return new HostVideoOptions
{
WindowMode = windowMode,
ScalingMode = scalingMode,
Width = hasResolution ? configuredWidth : defaults.Width,
Height = hasResolution ? configuredHeight : defaults.Height,
DisplayIndex = effective.DisplayIndex,
RefreshRate = effective.RefreshRate,
VSync = effective.VSync,
HdrMode = hdrMode,
OverlayEnabled = effective.OverlayEnabled,
OverlayCorner = Enum.TryParse<PerformanceOverlayCorner>(effective.OverlayCorner, true, out var corner)
? corner : defaults.OverlayCorner,
OverlayMode = Enum.TryParse<PerformanceOverlayMode>(effective.OverlayMode, true, out var mode)
? mode : defaults.OverlayMode,
}.Normalize();
}
catch (Exception exception)
{
Console.Error.WriteLine(
$"[LOADER][WARN] GUI video settings could not be loaded; using defaults: {exception.Message}");
return defaults;
}
}
private static bool TrySplitOption(string argument, string name, out string value)
{
var prefix = name + "=";
if (argument.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
value = argument[prefix.Length..];
return true;
}
value = string.Empty;
return false;
}
private static bool TryParseWindowMode(string value, out HostWindowMode mode)
{
mode = value.ToLowerInvariant() switch
{
"windowed" => HostWindowMode.Windowed,
"borderless" => HostWindowMode.Borderless,
"exclusive" or "fullscreen" => HostWindowMode.ExclusiveFullscreen,
_ => (HostWindowMode)(-1),
};
return Enum.IsDefined(mode);
}
private static bool TryParseSystemLanguage(string value, out int language)
{
language = value.ToLowerInvariant() switch
{
"japanese" => 0,
"englishus" => 1,
"french" => 2,
"spanishspain" => 3,
"german" => 4,
"italian" => 5,
"dutch" => 6,
"portugueseportugal" => 7,
"russian" => 8,
"korean" => 9,
"chinesetraditional" => 10,
"chinesesimplified" => 11,
"finnish" => 12,
"swedish" => 13,
"danish" => 14,
"norwegian" => 15,
"polish" => 16,
"portuguesebrazil" => 17,
"englishuk" => 18,
"turkish" => 19,
"spanishlatinamerica" => 20,
"arabic" => 21,
"frenchcanada" => 22,
"czech" => 23,
"hungarian" => 24,
"greek" => 25,
"romanian" => 26,
"thai" => 27,
"vietnamese" => 28,
"indonesian" => 29,
"ukrainian" => 30,
_ => -1,
};
return language >= 0;
}
private static bool TryParseScalingMode(string value, out HostScalingMode mode)
{
mode = value.ToLowerInvariant() switch
{
"fit" => HostScalingMode.Fit,
"cover" => HostScalingMode.Cover,
"stretch" => HostScalingMode.Stretch,
"integer" => HostScalingMode.Integer,
_ => (HostScalingMode)(-1),
};
return Enum.IsDefined(mode);
}
private static bool TryParseHdrMode(string value, out HostHdrMode mode)
{
mode = value.ToLowerInvariant() switch
{
"auto" => HostHdrMode.Auto,
"on" or "true" or "1" => HostHdrMode.On,
"off" or "false" or "0" => HostHdrMode.Off,
_ => (HostHdrMode)(-1),
};
return Enum.IsDefined(mode);
}
private static bool TryParseResolution(string value, out int width, out int height)
{
var parts = value.Split('x', 'X');
if (parts.Length == 2 && int.TryParse(parts[0], out width) && int.TryParse(parts[1], out height) &&
width >= 640 && height >= 360)
{
return true;
}
width = 0;
height = 0;
return false;
}
private static bool TryParseSwitch(string value, out bool enabled)
{
if (value is "1" || value.Equals("on", StringComparison.OrdinalIgnoreCase) ||
value.Equals("true", StringComparison.OrdinalIgnoreCase))
{
enabled = true;
return true;
}
if (value is "0" || value.Equals("off", StringComparison.OrdinalIgnoreCase) ||
value.Equals("false", StringComparison.OrdinalIgnoreCase))
{
enabled = false;
return true;
}
enabled = false;
return false;
}
private static bool TryParseCpuEngine(string valueText, out CpuExecutionEngine engine)
{
if (string.Equals(valueText, "native", StringComparison.OrdinalIgnoreCase) ||

View File

@ -77,48 +77,37 @@ SPDX-License-Identifier: GPL-2.0-or-later
<TargetPath>Languages\%(Filename)%(Extension)</TargetPath>
<Visible>False</Visible>
</Content>
<Content Include="..\SharpEmu.LibAtrac9\LICENSE.txt">
<CopyToPublishDirectory>Always</CopyToPublishDirectory>
<TargetPath>licenses\LibAtrac9.txt</TargetPath>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<Visible>False</Visible>
</Content>
</ItemGroup>
<Target Name="KeepLibAtrac9External" BeforeTargets="_ComputeFilesToBundle">
<ItemGroup>
<ResolvedFileToPublish Update="@(ResolvedFileToPublish)"
Condition="'%(Filename)%(Extension)' == 'SharpEmu.LibAtrac9.dll'">
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<RelativePath>plugins\SharpEmu.LibAtrac9.dll</RelativePath>
</ResolvedFileToPublish>
</ItemGroup>
</Target>
<!-- These are native debug symbols emitted by Skia/HarfBuzz, not managed
symbols that single-file publish can bundle. They are not needed at
runtime and would otherwise add more than 100 MB to every release. -->
<Target Name="RemoveNativeDebugSymbols" AfterTargets="Publish">
<ItemGroup>
<_NativeDebugSymbols Include="$(PublishDir)**\*.pdb" />
</ItemGroup>
<Delete Files="@(_NativeDebugSymbols)" />
</Target>
<!-- Native FFmpeg libraries publish into a subfolder next to the
<!-- Native libraries (glfw, FFmpeg) publish into a subfolder next to the
executable instead of sitting loose beside it, so the publish
directory stays uncluttered as more native deps get added. The folder
name is a fixed constant, not derived from the RID/architecture: each
publish output only ever holds one architecture's binaries anyway, so
varying the name added a class of bugs (RID resolution timing, host-OS
vs. target-RID mixups) for no benefit. Runtime code (FfmpegRuntime)
uses the same literal "plugins" folder name. -->
vs. target-RID mixups) for no benefit. Runtime code (Program.cs's
PreloadGlfw, FfmpegNativeBinkFrameSource's RootPath) uses the same
literal "plugins" folder name. -->
<PropertyGroup>
<NativeLibraryFolderName>plugins</NativeLibraryFolderName>
</PropertyGroup>
<!-- Keep glfw as a loose file in the native subfolder; every other native
library is embedded into the single-file bundle. -->
<Target Name="KeepGlfwOutsideSingleFile" AfterTargets="ComputeResolvedFilesToPublishList">
<ItemGroup>
<_GlfwPublishFiles Include="@(ResolvedFileToPublish)"
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>
<RelativePath>$(NativeLibraryFolderName)/%(Filename)%(Extension)</RelativePath>
</ResolvedFileToPublish>
</ItemGroup>
</Target>
<PropertyGroup>
<FfmpegRuntimeTag>3b502d4</FfmpegRuntimeTag>
<FfmpegRuntimeTag>2c92585</FfmpegRuntimeTag>
<FfmpegRuntimeDir>
$(BaseIntermediateOutputPath)ffmpeg-runtime/$(FfmpegRuntimeTag)/$(RuntimeIdentifier)</FfmpegRuntimeDir>
<FfmpegRuntimePackage Condition="'$(RuntimeIdentifier)' == 'win-x64'">ffmpeg-windows-x64.zip</FfmpegRuntimePackage>
@ -130,7 +119,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
</PropertyGroup>
<Target Name="FetchFfmpegRuntime"
BeforeTargets="Publish;Build"
BeforeTargets="Publish"
Condition="'$(RuntimeIdentifier)' != '' And '$(FfmpegRuntimePackage)' != ''">
<DownloadFile
SourceUrl="https://github.com/sharpemu/ffmpeg-core/releases/download/$(FfmpegRuntimeTag)/$(FfmpegRuntimePackage)"
@ -161,23 +150,4 @@ SPDX-License-Identifier: GPL-2.0-or-later
SkipUnchangedFiles="true" />
</Target>
<!-- Mirrors PublishFfmpegRuntime for plain `dotnet build`: devs running
straight out of the build output directory (no publish step) still
need the FFmpeg plugins present, otherwise AvPlayer/Bink video probing
throws NotSupportedException the first time a guest opens a movie. -->
<Target Name="BuildFfmpegRuntime"
AfterTargets="Build"
DependsOnTargets="FetchFfmpegRuntime"
Condition="'$(RuntimeIdentifier)' != '' And '$(FfmpegRuntimePackage)' != ''">
<ItemGroup>
<_FfmpegRuntimeFiles Condition="$(RuntimeIdentifier.StartsWith('win'))"
Include="$(FfmpegRuntimeExtractDir)/bin/*.dll" />
<_FfmpegRuntimeFiles Condition="!$(RuntimeIdentifier.StartsWith('win'))"
Include="$(FfmpegRuntimeExtractDir)/lib/*.so;$(FfmpegRuntimeExtractDir)/lib/*.so.*;$(FfmpegRuntimeExtractDir)/lib/*.dylib" />
</ItemGroup>
<Copy SourceFiles="@(_FfmpegRuntimeFiles)"
DestinationFolder="$(OutDir)$(NativeLibraryFolderName)"
SkipUnchangedFiles="true" />
</Target>
</Project>

View File

@ -133,20 +133,6 @@ public sealed class CpuDispatcher : ICpuDispatcher, IDisposable
}
}
public bool TryInstallAdditionalModule(
IReadOnlyDictionary<ulong, string> importStubs,
IReadOnlyDictionary<string, ulong> runtimeSymbols,
out string? error)
{
if (_nativeCpuBackend is not DirectExecutionBackend backend)
{
error = "the active CPU backend does not support runtime modules";
return false;
}
return backend.TryInstallAdditionalModule(importStubs, runtimeSymbols, out error);
}
private OrbisGen2Result DispatchEntryCore(
ulong entryPoint,
Generation generation,

View File

@ -1,149 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Numerics;
namespace SharpEmu.Core.Cpu.Emulation;
/// <summary>
/// Calculates the results of the SHA extension instructions for instruction recovery.
/// Dword 0 of a value is bits 31:0 and dword 3 is bits 127:96, as in the Intel SDM.
/// </summary>
public static class ShaInstructionEmulator
{
public static UInt128 Sha1Rnds4(UInt128 source1, UInt128 source2, int function)
{
var a = Dword(source1, 3);
var b = Dword(source1, 2);
var c = Dword(source1, 1);
var d = Dword(source1, 0);
var e = 0u;
var k = (function & 3) switch
{
0 => 0x5A827999u,
1 => 0x6ED9EBA1u,
2 => 0x8F1BBCDCu,
_ => 0xCA62C1D6u,
};
// The first message dword already carries E (SHA1NEXTE adds it).
for (var round = 0; round < 4; round++)
{
var next = Sha1Function(function, b, c, d) + BitOperations.RotateLeft(a, 5) + Dword(source2, 3 - round) + e + k;
e = d;
d = c;
c = BitOperations.RotateLeft(b, 30);
b = a;
a = next;
}
return FromDwords(d, c, b, a);
}
public static UInt128 Sha1Nexte(UInt128 source1, UInt128 source2)
{
var e = BitOperations.RotateLeft(Dword(source1, 3), 30);
return FromDwords(Dword(source2, 0), Dword(source2, 1), Dword(source2, 2), Dword(source2, 3) + e);
}
public static UInt128 Sha1Msg1(UInt128 source1, UInt128 source2)
{
var w0 = Dword(source1, 3);
var w1 = Dword(source1, 2);
var w2 = Dword(source1, 1);
var w3 = Dword(source1, 0);
var w4 = Dword(source2, 3);
var w5 = Dword(source2, 2);
return FromDwords(w5 ^ w3, w4 ^ w2, w3 ^ w1, w2 ^ w0);
}
public static UInt128 Sha1Msg2(UInt128 source1, UInt128 source2)
{
var w13 = Dword(source2, 2);
var w14 = Dword(source2, 1);
var w15 = Dword(source2, 0);
var w16 = BitOperations.RotateLeft(Dword(source1, 3) ^ w13, 1);
var w17 = BitOperations.RotateLeft(Dword(source1, 2) ^ w14, 1);
var w18 = BitOperations.RotateLeft(Dword(source1, 1) ^ w15, 1);
var w19 = BitOperations.RotateLeft(Dword(source1, 0) ^ w16, 1);
return FromDwords(w19, w18, w17, w16);
}
// SHA256RNDS2 takes its two round-constant-plus-message dwords from XMM0[63:0].
public static UInt128 Sha256Rnds2(UInt128 source1, UInt128 source2, UInt128 xmm0)
{
var a = Dword(source2, 3);
var b = Dword(source2, 2);
var c = Dword(source1, 3);
var d = Dword(source1, 2);
var e = Dword(source2, 1);
var f = Dword(source2, 0);
var g = Dword(source1, 1);
var h = Dword(source1, 0);
for (var round = 0; round < 2; round++)
{
var t1 = Ch(e, f, g) + BigSigma1(e) + Dword(xmm0, round) + h;
var t2 = Maj(a, b, c) + BigSigma0(a);
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
return FromDwords(f, e, b, a);
}
public static UInt128 Sha256Msg1(UInt128 source1, UInt128 source2)
{
var w4 = Dword(source2, 0);
var w3 = Dword(source1, 3);
var w2 = Dword(source1, 2);
var w1 = Dword(source1, 1);
var w0 = Dword(source1, 0);
return FromDwords(w0 + SmallSigma0(w1), w1 + SmallSigma0(w2), w2 + SmallSigma0(w3), w3 + SmallSigma0(w4));
}
public static UInt128 Sha256Msg2(UInt128 source1, UInt128 source2)
{
var w14 = Dword(source2, 2);
var w15 = Dword(source2, 3);
var w16 = Dword(source1, 0) + SmallSigma1(w14);
var w17 = Dword(source1, 1) + SmallSigma1(w15);
var w18 = Dword(source1, 2) + SmallSigma1(w16);
var w19 = Dword(source1, 3) + SmallSigma1(w17);
return FromDwords(w16, w17, w18, w19);
}
public static uint Dword(UInt128 value, int index) => (uint)(value >> (32 * index));
public static UInt128 FromDwords(uint dword0, uint dword1, uint dword2, uint dword3) =>
((UInt128)dword3 << 96) | ((UInt128)dword2 << 64) | ((UInt128)dword1 << 32) | dword0;
private static uint Sha1Function(int function, uint b, uint c, uint d) => (function & 3) switch
{
0 => (b & c) ^ (~b & d),
2 => (b & c) ^ (b & d) ^ (c & d),
_ => b ^ c ^ d,
};
private static uint Ch(uint e, uint f, uint g) => (e & f) ^ (~e & g);
private static uint Maj(uint a, uint b, uint c) => (a & b) ^ (a & c) ^ (b & c);
private static uint BigSigma0(uint x) =>
BitOperations.RotateRight(x, 2) ^ BitOperations.RotateRight(x, 13) ^ BitOperations.RotateRight(x, 22);
private static uint BigSigma1(uint x) =>
BitOperations.RotateRight(x, 6) ^ BitOperations.RotateRight(x, 11) ^ BitOperations.RotateRight(x, 25);
private static uint SmallSigma0(uint x) =>
BitOperations.RotateRight(x, 7) ^ BitOperations.RotateRight(x, 18) ^ (x >> 3);
private static uint SmallSigma1(uint x) =>
BitOperations.RotateRight(x, 17) ^ BitOperations.RotateRight(x, 19) ^ (x >> 10);
}

View File

@ -4,7 +4,23 @@
namespace SharpEmu.Core.Cpu.Emulation;
/// <summary>
/// Calculates the bit-field results for SSE4a instruction recovery.
/// Pure software implementation of the bit-field math behind AMD's SSE4a EXTRQ/INSERTQ
/// (immediate-form) instructions.
///
/// The direct-execution backend runs guest PS5 code natively on the host CPU. The PS5's Zen 2
/// cores implement AMD-only SSE4a (EXTRQ/INSERTQ), but Intel hosts - and Rosetta 2 on Apple
/// Silicon - do not, so they raise #UD (STATUS_ILLEGAL_INSTRUCTION) instead of executing the
/// opcode. SharpEmu already rewrites one specific compiled EXTRQ+VPBLENDD idiom at load time
/// (see <see cref="Native.Sse4aExtrqBlendPatch"/>), but any other occurrence of EXTRQ/INSERTQ -
/// a different register allocation, a title built with a different compiler version, and so on
/// - still aborts the title. This class ported from Kyty's
/// <c>Loader::X64InstructionEmulator::TryEmulateSse4a</c> provides the general bit-field
/// extract/insert so the illegal-instruction handler can finish *any* immediate-form
/// EXTRQ/INSERTQ in software and resume, instead of relying on a single hard-coded byte pattern.
///
/// The methods operate on plain 64-bit integers rather than the OS CONTEXT record so the bit
/// math can be unit-tested in isolation; the unsafe CONTEXT/XMM plumbing lives in the backend
/// adapter (<see cref="Native.DirectExecutionBackend"/>).
/// </summary>
public static class Sse4aBitFieldEmulator
{
@ -19,13 +35,16 @@ public static class Sse4aBitFieldEmulator
{
var len = length & 0x3F;
var idx = index & 0x3F;
if (len == 0)
if (!IsValidBitField(length, index))
{
len = 64;
return 0;
}
if (len == 0)
{
return value;
}
// Results past bit 63 are undefined; limit the field to the remaining bits.
len = Math.Min(len, 64 - idx);
var mask = len == 64 ? ulong.MaxValue : (1UL << len) - 1;
return (value >> idx) & mask;
}
@ -34,12 +53,16 @@ public static class Sse4aBitFieldEmulator
{
var len = length & 0x3F;
var idx = index & 0x3F;
if (len == 0)
if (!IsValidBitField(length, index))
{
len = 64;
return destination;
}
if (len == 0)
{
return source;
}
len = Math.Min(len, 64 - idx);
var fieldMask = len == 64 ? ulong.MaxValue : (1UL << len) - 1;
var destinationClearMask = fieldMask << idx;
var sourceField = (source & fieldMask) << idx;

View File

@ -26,21 +26,22 @@ public sealed unsafe class CpuPatcher : IDisposable
internal unsafe class UnsafeCodeReader : Iced.Intel.CodeReader
{
private readonly byte* _start;
private readonly ulong _length;
public ulong Position { get; private set; }
private byte* _start;
private byte* _current;
private int _length;
public UnsafeCodeReader(byte* start, ulong length)
public UnsafeCodeReader(byte* start, int length)
{
_start = start;
_current = start;
_length = length;
}
public override int ReadByte()
{
if (Position >= _length)
if (_current >= _start + _length)
return -1;
return _start[Position++];
return *_current++;
}
}
}

View File

@ -7,8 +7,23 @@ using SharpEmu.Core.Cpu.Emulation;
namespace SharpEmu.Core.Cpu.Native;
// Recover supported instructions only after an illegal-instruction fault.
// Leave native instructions and unrelated register values unchanged.
// General software fallback for the AMD-only instructions PS5 titles occasionally emit that a
// Zen 2-only host implements but Intel hosts (and Rosetta 2 on Apple Silicon) do not:
// - SSE4a EXTRQ/INSERTQ, immediate form
// - MONITORX/MWAITX
//
// This is a direct port of Kyty's Loader::X64InstructionEmulator (TryEmulateSse4a /
// TryEmulateMonitorxMwaitx). SharpEmu already special-cases exactly one compiled EXTRQ+VPBLENDD
// byte sequence at load time (Sse4aExtrqBlendPatch), which only helps the one idiom it was
// reverse-engineered from. This file is a general, fault-time fallback that engages for any
// immediate-form EXTRQ/INSERTQ or MONITORX/MWAITX the narrower patch (or a title using a
// different compiler/register allocation) does not cover, complementing rather than replacing
// it: the load-time patch still avoids paying the fault-and-recover cost on the hot path it was
// built for, while this method is the safety net for everything else.
//
// This is deliberately additive: DirectExecutionBackend.IllegalInstruction.cs (the BMI1/BMI2/ABM
// fallback) is untouched, and this method is only reached from VectoredHandler after that one
// has already declined to handle the fault.
public sealed partial class DirectExecutionBackend
{
// Byte offset of Xmm0 within the Win64 CONTEXT record: FltSave (the XMM_SAVE_AREA32/FXSAVE
@ -31,8 +46,16 @@ public sealed partial class DirectExecutionBackend
return true;
}
// EXTRQ and INSERTQ need the current vector register values.
// Use recovery only when the signal context contains these values.
// MONITORX/MWAITX above only ever reads guest code memory and rewrites RIP, both of
// which the POSIX signal bridge (DirectExecutionBackend.PosixSignals.cs) faithfully
// round-trips through the real ucontext, so it works on every supported OS. EXTRQ/
// INSERTQ additionally read and write an XMM register: on Windows contextRecord is the
// live CONTEXT the OS resumes the thread from, so touching the Xmm0.. slots is visible
// to the guest, and on Linux the bridge copies the mcontext's FXSAVE image into the
// Xmm0.. slots and writes them back through sigreturn (_posixXmmContextBridged). On
// Darwin the XMM area is still a zeroed scratch buffer - running this there would
// silently compute a result from stale bytes and then discard whatever it "wrote", so
// the recovery declines until that bridge exists.
return (OperatingSystem.IsWindows() || _posixXmmContextBridged) &&
TryRecoverSse4aExtractInsert(contextRecord, rip);
}
@ -42,7 +65,7 @@ public sealed partial class DirectExecutionBackend
// MONITORX (0F 01 FA) and MWAITX (0F 01 FB) are fixed 3-byte encodings with no
// ModRM/SIB/displacement/immediate, so a raw byte compare is sufficient and unambiguous.
var opcode = new byte[3];
if (!TryReadExecutableBytes(rip, opcode) ||
if (!TryReadHostBytes(rip, opcode) ||
opcode[0] != 0x0F || opcode[1] != 0x01 || (opcode[2] != 0xFA && opcode[2] != 0xFB))
{
return false;
@ -88,10 +111,7 @@ public sealed partial class DirectExecutionBackend
return false;
}
var isImmediateExtrq = isExtrq && instruction.OpCount == 3;
var isRegisterExtrq = isExtrq && instruction.OpCount == 2;
var isImmediateInsertq = isInsertq && instruction.OpCount == 4;
if (!isImmediateExtrq && !isRegisterExtrq && !isImmediateInsertq)
if (isExtrq && instruction.OpCount != 3 || isInsertq && instruction.OpCount != 4)
{
return false;
}
@ -105,26 +125,11 @@ public sealed partial class DirectExecutionBackend
var destLow = ReadCtxU64(contextRecord, destOffset);
if (isExtrq)
{
int length;
int index;
if (isRegisterExtrq)
var length = (int)instruction.GetImmediate(1);
var index = (int)instruction.GetImmediate(2);
if (!Sse4aBitFieldEmulator.IsValidBitField(length, index))
{
if (instruction.GetOpKind(1) != OpKind.Register ||
!TryGetXmmOffset(instruction.GetOpRegister(1), out var controlOffset))
{
return false;
}
// AMD defines the register form's field length in xmm2[5:0] and its start
// index in xmm2[13:8]. Other control bits do not affect the instruction.
var control = ReadCtxU64(contextRecord, controlOffset);
length = (int)(control & 0x3F);
index = (int)((control >> 8) & 0x3F);
}
else
{
length = (int)instruction.GetImmediate(1);
index = (int)instruction.GetImmediate(2);
return false;
}
WriteCtxU64(contextRecord, destOffset, Sse4aBitFieldEmulator.ExtractBitField(destLow, length, index));
@ -140,6 +145,11 @@ public sealed partial class DirectExecutionBackend
var length = (int)instruction.GetImmediate(2);
var index = (int)instruction.GetImmediate(3);
if (!Sse4aBitFieldEmulator.IsValidBitField(length, index))
{
return false;
}
WriteCtxU64(contextRecord, destOffset, Sse4aBitFieldEmulator.InsertBitField(
destLow, ReadCtxU64(contextRecord, srcOffset), length, index));
WriteCtxU64(contextRecord, destOffset + 8, 0);

View File

@ -23,79 +23,14 @@ public sealed partial class DirectExecutionBackend
private static long _perfHleTotal;
private static long _perfHleDispatchTicks;
private sealed class PerfHleExportCost
{
public long Calls;
public long Ticks;
}
private static readonly System.Collections.Concurrent.ConcurrentDictionary<string, PerfHleExportCost> _perfHleCosts = new();
/// <summary>
/// Name of the export currently being dispatched on this thread, so the
/// gateway can attribute its elapsed time once the call returns. Answering
/// "which export is worth optimising" needs cost per export, not just call
/// counts — a rare expensive call and a hot cheap one look identical in a
/// frequency histogram.
/// </summary>
[System.ThreadStatic]
private static string? _perfHleCurrentExport;
private static long _perfHleFirstTimestamp;
private static void RecordPerfHleDispatchTime(long ticks)
{
var total = System.Threading.Interlocked.Add(ref _perfHleDispatchTicks, ticks);
var calls = System.Threading.Interlocked.Read(ref _perfHleTotal);
var name = _perfHleCurrentExport;
if (name is not null)
{
var cost = _perfHleCosts.GetOrAdd(name, static _ => new PerfHleExportCost());
System.Threading.Interlocked.Increment(ref cost.Calls);
System.Threading.Interlocked.Add(ref cost.Ticks, ticks);
}
if (calls > 0 && calls % 500000 == 0)
{
var frequency = (double)System.Diagnostics.Stopwatch.Frequency;
var avgUs = (double)total / frequency * 1_000_000.0 / calls;
var first = System.Threading.Interlocked.CompareExchange(ref _perfHleFirstTimestamp, 0, 0);
var wallSeconds = first == 0
? 0
: (double)(System.Diagnostics.Stopwatch.GetTimestamp() - first) / frequency;
System.Console.Error.WriteLine(
$"[PERF][HLE] managed_dispatch_avg={avgUs:F3}us " +
$"total_managed_s={(double)total / frequency:F2} " +
$"wall_s={wallSeconds:F2} " +
$"cores={(wallSeconds > 0 ? total / frequency / wallSeconds : 0):F2}");
var snapshot = new System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string, PerfHleExportCost>>(_perfHleCosts.Count + 16);
foreach (var kvp in _perfHleCosts)
{
snapshot.Add(kvp);
}
var top = snapshot
.OrderByDescending(kvp => System.Threading.Interlocked.Read(ref kvp.Value.Ticks))
.Take(12)
.Select(kvp =>
{
var seconds = System.Threading.Interlocked.Read(ref kvp.Value.Ticks) / frequency;
var callCount = System.Threading.Interlocked.Read(ref kvp.Value.Calls);
var cores = wallSeconds > 0 ? seconds / wallSeconds : 0;
var perCallUs = callCount > 0 ? seconds * 1_000_000.0 / callCount : 0;
return $"{kvp.Key}: {cores:F2}cores {seconds:F1}s n={callCount} {perCallUs:F2}us/call";
});
System.Console.Error.WriteLine($"[PERF][HLE] cost: {string.Join(" | ", top)}");
if (SharpEmu.HLE.GuestFastPath.Enabled)
{
var fastPath = SharpEmu.HLE.GuestFastPath.SnapshotCounters();
System.Console.Error.WriteLine(
$"[PERF][HLE] fast_path: self_hits={fastPath.SelfHits} " +
$"getspecific_hits={fastPath.GetspecificHits} blocks={fastPath.Blocks}");
}
var avgUs = (double)total / System.Diagnostics.Stopwatch.Frequency * 1_000_000.0 / calls;
System.Console.Error.WriteLine($"[PERF][HLE] managed_dispatch_avg={avgUs:F3}us total_managed_s={(double)total / System.Diagnostics.Stopwatch.Frequency:F2}");
}
}
@ -104,16 +39,7 @@ public sealed partial class DirectExecutionBackend
private static void RecordPerfHleCall(string name)
{
_perfHleCurrentExport = name;
var total = System.Threading.Interlocked.Increment(ref _perfHleTotal);
if (total == 1)
{
System.Threading.Interlocked.CompareExchange(
ref _perfHleFirstTimestamp,
System.Diagnostics.Stopwatch.GetTimestamp(),
0);
}
if (!_perfHleNoDict)
{
_perfHleCounts.AddOrUpdate(name, 1, static (_, v) => v + 1);
@ -471,29 +397,6 @@ public sealed partial class DirectExecutionBackend
return false;
}
// The committed readable run of host pages that contains address.
private unsafe static bool TryQueryReadableRange(ulong address, out ulong start, out ulong end)
{
start = 0;
end = 0;
if (address <= 65536 || address >= 140737488355328L ||
VirtualQuery((void*)address, out var info, (nuint)sizeof(MEMORY_BASIC_INFORMATION64)) == 0)
{
return false;
}
var regionEnd = info.BaseAddress + info.RegionSize;
if (regionEnd < info.BaseAddress || address > regionEnd - 8 ||
info.State != 4096 || !IsReadableProtection(info.Protect))
{
return false;
}
start = info.BaseAddress;
end = regionEnd;
return true;
}
private unsafe static bool TryReadStackU64(ulong address, out ulong value)
{
value = 0uL;

View File

@ -10,7 +10,6 @@ using System.Runtime.InteropServices;
using System.Threading;
using SharpEmu.Core.Cpu.Disasm;
using SharpEmu.HLE;
using SharpEmu.HLE.GpuMemory;
namespace SharpEmu.Core.Cpu.Native;
@ -20,9 +19,6 @@ public sealed partial class DirectExecutionBackend
private static int _lazyCommitTraceCount;
private static int _guestAllocatorHoleRecoveries;
private static int _auxiliaryThreadExecuteFaultRecoveries;
private static int _auxiliaryThreadExecuteFaultSkips;
private nint _workerAbortStack;
private const uint WorkerAbortStackSize = 0x10000u;
private unsafe void SetupExceptionHandler()
{
@ -114,19 +110,15 @@ public sealed partial class DirectExecutionBackend
ulong rip = ReadCtxU64(contextRecord, 248);
ulong rsp = ReadCtxU64(contextRecord, 152);
if (MayBeGuestInt41(exceptionRecord) && TryRecoverGuestInt41(exceptionCode, contextRecord, rip))
if (TryRecoverGuestInt41(exceptionCode, contextRecord, rip))
{
return -1;
}
if (!OperatingSystem.IsWindows() &&
exceptionCode == 3221225477u &&
exceptionRecord->NumberParameters >= 2 &&
exceptionRecord->ExceptionInformation[0] == 1uL &&
SharpEmu.HLE.GuestImageWriteTracker.TryHandleWriteFault(
exceptionRecord->ExceptionInformation[1]))
if (TryRecoverAuxiliaryThreadExecuteFault(exceptionRecord, contextRecord, rip))
{
return -1;
}
if (exceptionCode == 3221225477u && TryHandleLazyCommittedPage(exceptionRecord, rip, rsp))
{
return -1;
@ -136,17 +128,6 @@ public sealed partial class DirectExecutionBackend
{
return -1;
}
if (exceptionCode == 3221225477u && TryResolveGpuFault(exceptionRecord))
{
return -1;
}
// Only a fault none of the handlers above resolves aborts a TBB worker: a write
// to a lazily committed or GPU-tracked page is routine, and aborting the worker
// there strands the guest allocator lock it may hold.
if (TryRecoverAuxiliaryThreadExecuteFault(exceptionRecord, contextRecord, rip))
{
return -1;
}
if (exceptionCode == StatusIllegalInstruction &&
TryRecoverIllegalInstruction(contextRecord, rip))
{
@ -157,11 +138,6 @@ public sealed partial class DirectExecutionBackend
{
return -1;
}
if (exceptionCode == StatusIllegalInstruction &&
TryRecoverShaInstruction(contextRecord, rip))
{
return -1;
}
if (IsBenignHostDebugException(exceptionCode))
{
return -1;
@ -284,7 +260,7 @@ public sealed partial class DirectExecutionBackend
for (int i = 0; i < 16; i++)
{
ulong stackAddr = rsp + (ulong)(i * 8);
if (!TryReadDiagnosticHostQword(stackAddr, out ulong value))
if (!TryReadHostQword(stackAddr, out ulong value))
{
Console.Error.WriteLine("[LOADER][WARNING] Could not read stack qwords.");
break;
@ -301,7 +277,7 @@ public sealed partial class DirectExecutionBackend
var windowStart = rsp >= 0x300 ? rsp - 0x300 : 0;
for (var stackAddr = windowStart; stackAddr < rsp + 0x100; stackAddr += 8)
{
if (!TryReadDiagnosticHostQword(stackAddr, out var value))
if (!TryReadHostQword(stackAddr, out var value))
{
continue;
}
@ -321,7 +297,6 @@ public sealed partial class DirectExecutionBackend
DumpPointerWindow("fault-register-rbx", rbx, 0x60);
DumpPointerWindow("fault-register-rsi", rsi, 0x60);
DumpPointerWindow("fault-register-rcx", rcx, 0x80);
DumpPointerWindow("fault-register-rdi", rdi, 0x60);
DumpPointerWindow("fault-register-r13", r13, 0x60);
DumpPointerWindow("fault-register-r14", r14, 0x60);
@ -332,12 +307,11 @@ public sealed partial class DirectExecutionBackend
ulong frame = rbp;
for (int i = 0; i < 12; i++)
{
if (!IsCanonicalUserAddress(frame) || (frame & 7) != 0)
if (frame < 0x10000)
{
break;
}
if (!TryReadDiagnosticHostQword(frame, out ulong next) ||
!TryReadDiagnosticHostQword(frame + 8, out ulong ret))
if (!TryReadHostQword(frame, out ulong next) || !TryReadHostQword(frame + 8, out ulong ret))
{
Console.Error.WriteLine("[LOADER][WARNING] Could not walk RBP frame chain.");
break;
@ -365,13 +339,7 @@ public sealed partial class DirectExecutionBackend
Console.Error.WriteLine("[LOADER][ERROR] - Guest code accessed unmapped memory");
Console.Error.WriteLine("[LOADER][ERROR] - Need to implement HLE for this NID");
byte[] code = new byte[16];
DumpHostRegion("RIP", rip);
// Guest code can be mapped execute-only, which makes every
// host-side read of it fail. The guest memory view still
// resolves those pages, so prefer it here: otherwise the
// whole call-site report below is silently skipped on
// exactly the faults that need it.
if (TryReadGuestOrHostBytes(rip, code))
if (TryReadHostBytes(rip, code))
{
Console.Error.WriteLine("[LOADER][INFO] Code at RIP: " + BitConverter.ToString(code).Replace("-", " "));
if (code[0] == 100)
@ -389,12 +357,12 @@ public sealed partial class DirectExecutionBackend
Console.Error.WriteLine($"[LOADER][INFO] RSP: 0x{rsp:X16} (mod 16 = {rsp % 16})");
}
byte[] before = new byte[16];
if (rip > 16 && TryReadGuestOrHostBytes(rip - 16, before))
if (rip > 16 && TryReadHostBytes(rip - 16, before))
{
Console.Error.WriteLine("[LOADER][INFO] Code before RIP: " + BitConverter.ToString(before).Replace("-", " "));
}
byte[] window = new byte[64];
if (rip > 32 && TryReadGuestOrHostBytes(rip - 32, window))
if (rip > 32 && TryReadHostBytes(rip - 32, window))
{
Console.Error.WriteLine("[LOADER][INFO] Code window [RIP-0x20..]: " + BitConverter.ToString(window).Replace("-", " "));
}
@ -411,7 +379,7 @@ public sealed partial class DirectExecutionBackend
continue;
}
byte[] callSiteWindow = new byte[48];
if (TryReadGuestOrHostBytes(candidate - 24, callSiteWindow))
if (TryReadHostBytes(candidate - 24, callSiteWindow))
{
Console.Error.WriteLine(
$"[LOADER][INFO] Stack guest-code candidate [rsp+0x{stackIndex * 8:X2}]=0x{candidate:X16}, bytes [-0x18..]: " +
@ -423,11 +391,6 @@ public sealed partial class DirectExecutionBackend
{
Console.Error.WriteLine("[LOADER][ERROR] Could not read code at RIP");
}
// The faulting instruction is the first thing an access
// violation report has to answer, so decode it through guest
// memory as well: that path still works when the host code
// page refuses a plain read.
DumpGuestInstructionStream("fault", rip, 4);
DumpRecentImportTrace();
DumpGuestDisasmDiagnostics(rip, rbp, rsp);
DumpGuestRegisterWindowDiagnostics(
@ -472,91 +435,18 @@ public sealed partial class DirectExecutionBackend
void* contextRecord,
ulong rip)
{
if (exceptionRecord->ExceptionCode != 3221225477u)
if (exceptionRecord->ExceptionCode != 3221225477u ||
rip >= 0x0000000800000000UL ||
_activeGuestThreadState is not { Name: "tbb_thead" } activeThread)
{
return false;
}
// Prefer ThreadStatic active state; fall back to host-thread name when
// concurrent TBB AVs race logging (tLT61: recover skipped, then Fatal).
GuestThreadState? activeThread = _activeGuestThreadState;
if (activeThread is null || activeThread.Name != "tbb_thead")
{
var hostName = Thread.CurrentThread.Name;
if (hostName is null ||
!hostName.StartsWith("SharpEmu-tbb_thead", StringComparison.Ordinal))
{
return false;
}
activeThread = FindGuestThreadStateByHostThreadId(unchecked((int)GetCurrentThreadId()));
if (activeThread is null || activeThread.Name != "tbb_thead")
{
var skip = Interlocked.Increment(ref _auxiliaryThreadExecuteFaultSkips);
if (skip <= 8 || skip % 64 == 0)
{
Console.Error.WriteLine(
$"[LOADER][WARN] tbb_recover skip #{skip}: rip=0x{rip:X16} " +
$"host='{hostName}' active={(activeThread?.Name ?? "null")}");
Console.Error.Flush();
}
return false;
}
}
var hostExit = ActiveEntryReturnSentinelRip;
if (hostExit < 0x10000)
{
hostExit = unchecked((ulong)_guestReturnStub);
}
// Prefer worker-abort (SetEvent + ExitThread) over host_exit→RunEpilogue:
// the latter FailFasts the process after TBB recover (tLT28/30 silent die).
// Do NOT abandon mutexes here — managed HLE from inside VEH can re-enter
// and Fatal (tLT73). NativeGuestExecutor.Run abandons after detecting abort.
var abortRip = unchecked((ulong)_workerAbortStub);
if (abortRip >= 0x10000)
{
// Do NOT SetEvent from managed VEH: that wakes the renter which may
// TerminateThread while this thread is still inside VEH return
// (tLTA2: recover logged, no respawning, process die). Abort stub
// SetEvent's only after CONTINUE_EXECUTION resumes at park.
// Prefer the entry-stub-saved host RSP (real CreateThread stack).
// Do not treat mid-range host stacks as guest — Astro worker stacks
// often sit in 0x02xxxxxx_xxxx and were wrongly replaced with a
// shared VirtualAlloc abort stack (concurrent TBB AV → die).
var hostRspSlot = TlsGetValue(_hostRspSlotTlsIndex);
ulong hostRsp = 0;
if (hostRspSlot != 0)
{
hostRsp = *(ulong*)hostRspSlot;
}
if (hostRsp < 0x10000)
{
hostRsp = EnsureWorkerAbortStackRsp();
}
if (hostRsp >= 0x10000)
{
WriteCtxU64(contextRecord, 152, hostRsp & ~0xFUL);
}
WriteCtxU64(contextRecord, 120, 0);
WriteCtxU64(contextRecord, 248, abortRip);
var recovery = Interlocked.Increment(ref _auxiliaryThreadExecuteFaultRecoveries);
Console.Error.WriteLine(
$"[LOADER][WARN] Recovered auxiliary TBB execute fault #{recovery}: " +
$"thread=0x{activeThread.ThreadHandle:X16} target=0x{rip:X16} " +
$"host_rsp=0x{hostRsp:X16} -> worker_abort=0x{abortRip:X16}");
Console.Error.WriteLine(
"[LOADER][INFO] tbb_recover: parking native worker (SetEvent+park); " +
"renter will TerminateThread+respawn — avoids ExitThread after VEH");
Console.Error.Flush();
return true;
}
if (hostExit < 0x10000)
{
Console.Error.WriteLine(
@ -568,67 +458,13 @@ public sealed partial class DirectExecutionBackend
_ = TryPatchActiveGuestReturnSlot(hostExit);
WriteCtxU64(contextRecord, 120, 0);
WriteCtxU64(contextRecord, 248, hostExit);
var recoveryFallback = Interlocked.Increment(ref _auxiliaryThreadExecuteFaultRecoveries);
var recovery = Interlocked.Increment(ref _auxiliaryThreadExecuteFaultRecoveries);
Console.Error.WriteLine(
$"[LOADER][WARN] Recovered auxiliary TBB execute fault #{recoveryFallback}: " +
$"[LOADER][WARN] Recovered auxiliary TBB execute fault #{recovery}: " +
$"thread=0x{activeThread.ThreadHandle:X16} target=0x{rip:X16} -> host_exit=0x{hostExit:X16}");
Console.Error.WriteLine(
"[LOADER][INFO] tbb_recover: resumed at host_exit (abort stub unavailable); " +
"subsequent FastFail/CLR must not re-enter managed VEH " +
"(live trampoline pre-filters 0xC0000409 / 0xE0434352)");
Console.Error.Flush();
return true;
}
private GuestThreadState? FindGuestThreadStateByHostThreadId(int hostThreadId)
{
if (hostThreadId == 0)
{
return null;
}
try
{
foreach (var thread in SnapshotGuestThreads())
{
if (Volatile.Read(ref thread.HostThreadId) == hostThreadId)
{
return thread;
}
}
}
catch
{
}
return null;
}
private unsafe ulong EnsureWorkerAbortStackRsp()
{
if (_workerAbortStack == 0)
{
_workerAbortStack = (nint)VirtualAlloc(null, WorkerAbortStackSize, 12288u, 4u);
if (_workerAbortStack == 0)
{
return 0;
}
}
// Grow-down stack: hand out near the top with alignment headroom.
return (ulong)(_workerAbortStack + (nint)WorkerAbortStackSize - 0x100) & ~0xFUL;
}
// On Windows an INT n the guest may not execute raises a general-protection fault,
// reported as an access violation whose fault address is all ones; a page fault
// carries the data address instead. GPU-tracked and lazily committed pages fault
// thousands of times per frame, so skip the opcode probe (a VirtualQuery and a
// read of the faulting instruction) for them.
private static unsafe bool MayBeGuestInt41(EXCEPTION_RECORD* exceptionRecord) =>
!OperatingSystem.IsWindows() ||
exceptionRecord->NumberParameters < 2 ||
exceptionRecord->ExceptionInformation[1] == ulong.MaxValue;
private unsafe bool TryRecoverGuestInt41(uint exceptionCode, void* contextRecord, ulong rip)
{
if (!_ignoreGuestInt41 || exceptionCode != 3221225477u || rip < 0x10000)
@ -637,7 +473,7 @@ public sealed partial class DirectExecutionBackend
}
byte[] opcode = new byte[2];
if (!TryReadExecutableBytes(rip, opcode) || opcode[0] != 0xCD || opcode[1] != 0x41)
if (!TryReadHostBytes(rip, opcode) || opcode[0] != 0xCD || opcode[1] != 0x41)
{
return false;
}
@ -653,25 +489,6 @@ public sealed partial class DirectExecutionBackend
return true;
}
// Runs after the lazy-commit branch. That branch commits the page first.
private unsafe static bool TryResolveGpuFault(EXCEPTION_RECORD* exceptionRecord)
{
if (exceptionRecord->NumberParameters < 2)
{
return false;
}
var kind = exceptionRecord->ExceptionInformation[0] switch
{
0 => FaultKind.Read,
1 => FaultKind.Write,
8 => FaultKind.Execute,
_ => FaultKind.Unknown,
};
return kind != FaultKind.Unknown
&& GuestGpuMemoryHook.TryResolveFault(kind, exceptionRecord->ExceptionInformation[1]);
}
private unsafe static bool TryRecoverGuestAllocatorHole(
EXCEPTION_RECORD* exceptionRecord,
void* contextRecord,
@ -809,7 +626,7 @@ public sealed partial class DirectExecutionBackend
// Optimized guest code frequently omits frame pointers. The return
// address at RSP is then more useful than an RBP walk and identifies the
// exact call site that supplied the faulting arguments.
if (TryReadDiagnosticHostQword(rsp, out var stackReturn) && stackReturn >= 0x60)
if (TryReadHostQword(rsp, out var stackReturn) && stackReturn >= 0x60)
{
DumpGuestInstructionStream("stack-return-prelude", stackReturn - 0x60, 40);
}
@ -1238,7 +1055,7 @@ public sealed partial class DirectExecutionBackend
for (int offset = 0; offset < size; offset += 8)
{
ulong slotAddress = baseAddress + (ulong)offset;
if (slotAddress < baseAddress || !TryReadDiagnosticHostQword(slotAddress, out var value))
if (!TryReadQword(slotAddress, out var value))
{
Console.Error.WriteLine($"[LOADER][INFO] +0x{offset:X2}: <unreadable>");
break;
@ -1281,11 +1098,6 @@ public sealed partial class DirectExecutionBackend
private static bool TryReadHostQword(ulong address, out ulong value)
{
value = 0;
if (address < 0x10000)
{
return false;
}
if (!OperatingSystem.IsWindows())
{
// A stray read inside the signal handler would raise a nested
@ -1294,6 +1106,7 @@ public sealed partial class DirectExecutionBackend
return TryReadStackU64(address, out value);
}
value = 0;
try
{
value = (ulong)Marshal.ReadInt64((nint)address);
@ -1305,90 +1118,25 @@ public sealed partial class DirectExecutionBackend
}
}
private unsafe static bool TryReadDiagnosticHostQword(ulong address, out ulong value)
private unsafe static bool TryReadHostBytes(ulong address, byte[] buffer)
{
if (OperatingSystem.IsLinux())
if (address < 65536)
{
ulong result = 0;
bool success = TryReadLinuxMemory(address, (byte*)&result, sizeof(ulong));
value = success ? result : 0;
return success;
}
if (OperatingSystem.IsMacOS())
{
ulong result = 0;
bool success = TryReadMacOsMemory(address, (byte*)&result, sizeof(ulong));
value = success ? result : 0;
return success;
return false;
}
if (!OperatingSystem.IsWindows())
{
return TryReadStackU64(address, out value);
}
value = 0;
if (!IsReadableHostRange(address, sizeof(ulong)))
{
return false;
}
ulong readValue = 0;
if (ReadProcessMemory(
(nint)(-1),
(nint)address,
&readValue,
sizeof(ulong),
out var bytesRead) == 0 ||
bytesRead != sizeof(ulong))
{
return false;
}
value = readValue;
return true;
}
private unsafe static bool TryReadHostBytes(ulong address, byte[] buffer)
{
if (OperatingSystem.IsLinux())
{
fixed (byte* destination = buffer)
// See TryReadHostQword: probe every touched page before reading.
ulong end = address + (ulong)buffer.Length;
for (ulong page = address & 0xFFFFFFFFFFFFF000uL; page < end; page += 4096)
{
return TryReadLinuxMemory(address, destination, buffer.Length);
}
}
if (OperatingSystem.IsMacOS())
{
fixed (byte* destination = buffer)
{
return TryReadMacOsMemory(address, destination, buffer.Length);
}
}
if (!IsReadableHostRange(address, buffer.Length))
{
return false;
}
if (buffer.Length == 0)
{
return true;
}
if (OperatingSystem.IsWindows())
{
fixed (byte* destination = buffer)
{
return ReadProcessMemory(
(nint)(-1),
(nint)address,
destination,
(nuint)buffer.Length,
out var bytesRead) != 0 &&
bytesRead == (nuint)buffer.Length;
if (VirtualQuery((void*)page, out var mbi, (nuint)sizeof(MEMORY_BASIC_INFORMATION64)) == 0 ||
mbi.State != MEM_COMMIT ||
!IsReadableProtection(mbi.Protect))
{
return false;
}
}
}
@ -1403,176 +1151,6 @@ public sealed partial class DirectExecutionBackend
}
}
private unsafe static bool TryReadLinuxMemory(ulong address, byte* destination, int byteCount)
{
if (byteCount < 0 || !IsCanonicalUserAddress(address) ||
address > 0x0000_8000_0000_0000UL - (ulong)byteCount)
{
return false;
}
if (byteCount == 0) return true;
// Read through the kernel so untracked or inaccessible pages cannot fault the reader.
var local = new DiagnosticMemoryVector { Address = (nint)destination, Length = (nuint)byteCount };
var remote = new DiagnosticMemoryVector { Address = (nint)address, Length = (nuint)byteCount };
return ReadLinuxProcessMemory(Environment.ProcessId, &local, 1, &remote, 1, 0) == byteCount;
}
[StructLayout(LayoutKind.Sequential)]
private struct DiagnosticMemoryVector
{
public nint Address;
public nuint Length;
}
[DllImport("libc", EntryPoint = "process_vm_readv")]
private unsafe static extern nint ReadLinuxProcessMemory(
int processId, DiagnosticMemoryVector* local, nuint localCount,
DiagnosticMemoryVector* remote, nuint remoteCount, nuint flags);
private unsafe static bool TryReadMacOsMemory(ulong address, byte* destination, int byteCount)
{
if (byteCount < 0 || !IsCanonicalUserAddress(address) ||
address > 0x0000_8000_0000_0000UL - (ulong)byteCount)
{
return false;
}
if (byteCount == 0)
{
return true;
}
// The host memory table does not contain all guest code mappings.
// Use Mach to read the memory and report access errors without another fault.
return ReadMachVirtualMemory(GetCurrentMachTask(), address, (ulong)byteCount,
(ulong)destination, out var bytesRead) == 0 && bytesRead == (ulong)byteCount;
}
[DllImport("libSystem.B.dylib", EntryPoint = "mach_task_self")]
private static extern uint GetCurrentMachTask();
[DllImport("libSystem.B.dylib", EntryPoint = "mach_vm_read_overwrite")]
private static extern int ReadMachVirtualMemory(
uint taskHandle, ulong sourceAddress, ulong byteCount, ulong destinationAddress, out ulong bytesRead);
private unsafe static bool TryReadExecutableBytes(ulong address, byte[] buffer)
{
if (!OperatingSystem.IsWindows())
{
return TryReadHostBytes(address, buffer);
}
// Faulting x64 code can have execute-only protection. Data probes still require read access.
if (!IsReadableHostRange(address, buffer.Length, allowExecuteOnly: true))
{
return false;
}
if (buffer.Length == 0)
{
return true;
}
// RIP identifies code that Windows was already executing when the
// exception occurred. These mappings are stable for the duration of
// dispatch, so read them directly. Arbitrary diagnostic and operand
// addresses continue to use ReadProcessMemory above because they can
// become invalid while an exception is being reported.
new ReadOnlySpan<byte>((void*)address, buffer.Length).CopyTo(buffer);
return true;
}
/// <summary>
/// Reads guest bytes for a crash report, preferring the guest memory view
/// over a raw host read. Guest code pages are commonly committed
/// PAGE_EXECUTE, which no host read can satisfy.
/// </summary>
private bool TryReadGuestOrHostBytes(ulong address, byte[] buffer)
{
if (_cpuContext is { } context)
{
try
{
if (context.Memory.TryRead(address, buffer))
{
return true;
}
}
catch
{
// Fall through to the host reader.
}
}
return TryReadHostBytes(address, buffer);
}
private unsafe static void DumpHostRegion(string name, ulong address)
{
if (VirtualQuery((void*)address, out var mbi, (nuint)sizeof(MEMORY_BASIC_INFORMATION64)) == 0)
{
Console.Error.WriteLine($"[LOADER][INFO] {name} region: <VirtualQuery failed> address=0x{address:X16}");
return;
}
Console.Error.WriteLine(
$"[LOADER][INFO] {name} region: base=0x{mbi.BaseAddress:X16} size=0x{mbi.RegionSize:X16} " +
$"state=0x{mbi.State:X08} protect=0x{mbi.Protect:X08} type=0x{mbi.Type:X08}");
}
private unsafe static bool IsReadableHostRange(ulong address, int byteCount, bool allowExecuteOnly = false)
{
if (byteCount < 0 || !IsCanonicalUserAddress(address))
{
return false;
}
var length = (ulong)byteCount;
if (address > 0x0000_8000_0000_0000UL - length)
{
return false;
}
var end = address + length;
var cursor = address;
while (cursor < end)
{
if (VirtualQuery(
(void*)cursor,
out var mbi,
(nuint)sizeof(MEMORY_BASIC_INFORMATION64)) == 0 ||
mbi.State != MEM_COMMIT ||
(!IsReadableProtection(mbi.Protect) &&
!(allowExecuteOnly && mbi.Protect == 0x10)))
{
return false;
}
var regionEnd = mbi.BaseAddress + mbi.RegionSize;
if (regionEnd < mbi.BaseAddress || regionEnd <= cursor)
{
return false;
}
cursor = Math.Min(regionEnd, end);
}
return true;
}
private static bool IsCanonicalUserAddress(ulong address) =>
address >= 0x10000 && address < 0x0000_8000_0000_0000UL;
[DllImport("kernel32.dll", SetLastError = false)]
private unsafe static extern int ReadProcessMemory(
nint process,
nint baseAddress,
void* buffer,
nuint byteCount,
out nuint bytesRead);
private string FormatPointerWithNearestSymbol(ulong value)
{
string text = $"0x{value:X16}";
@ -1586,10 +1164,9 @@ public sealed partial class DirectExecutionBackend
private void InitializeRuntimeSymbolIndex(IReadOnlyDictionary<string, ulong> runtimeSymbols)
{
var symbolsByName = new Dictionary<string, ulong>(StringComparer.Ordinal);
_runtimeSymbolsByName.Clear();
if (runtimeSymbols.Count == 0)
{
Volatile.Write(ref _runtimeSymbolsByName, symbolsByName);
_runtimeSymbolsByAddress = Array.Empty<KeyValuePair<string, ulong>>();
return;
}
@ -1600,12 +1177,11 @@ public sealed partial class DirectExecutionBackend
if (runtimeSymbol.Value != 0L && !string.IsNullOrWhiteSpace(runtimeSymbol.Key))
{
list.Add(runtimeSymbol);
symbolsByName[runtimeSymbol.Key] = runtimeSymbol.Value;
_runtimeSymbolsByName[runtimeSymbol.Key] = runtimeSymbol.Value;
}
}
list.Sort((a, b) => a.Value.CompareTo(b.Value));
Volatile.Write(ref _runtimeSymbolsByName, symbolsByName);
_runtimeSymbolsByAddress = list.ToArray();
}
@ -1740,7 +1316,6 @@ public sealed partial class DirectExecutionBackend
}
TryCommitRange(pageBase + 4096, 4096uL, commitProtect);
RescanTlsPatternsIfExecutable(committedBase, committedSize + 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}");
@ -1800,7 +1375,6 @@ public sealed partial class DirectExecutionBackend
}
TryCommitRange(pageBase + 4096, 4096uL, commitProtect);
RescanTlsPatternsIfExecutable(committedBase, committedSize + 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}");
@ -1902,25 +1476,6 @@ public sealed partial class DirectExecutionBackend
}
}
// Re-scans a just-committed window for FS:[0] TLS loads; skips non-executable commits.
private unsafe void RescanTlsPatternsIfExecutable(ulong committedBase, ulong committedSize, uint commitProtect)
{
const uint executableProtectionMask = PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
if ((commitProtect & executableProtectionMask) == 0 || committedSize == 0)
{
return;
}
var counts = PatchTlsPatternsInRange(committedBase, committedBase + committedSize);
if (counts.Total != 0)
{
Console.Error.WriteLine(
$"[LOADER][INFO] Patched {counts.Loads} TLS loads, {counts.Stores} TLS stores, " +
$"{counts.StackCanaries} stack-canary accesses " +
$"(lazy-commit rescan 0x{committedBase:X16}-0x{committedBase + committedSize:X16})");
}
}
private static bool ShouldTraceLazyCommit(int traceIndex)
{
if (string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_LAZY_COMMIT"), "1", StringComparison.Ordinal))

View File

@ -1,286 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using SharpEmu.HLE;
namespace SharpEmu.Core.Cpu.Native;
/// <summary>
/// Native fast-path stubs for the trivial per-thread imports that dominate the
/// HLE call count. Each stub answers from <see cref="GuestFastPath"/>'s
/// per-host-thread block and jumps to the normal import trampoline whenever it
/// cannot, so the managed implementation stays the single source of truth for
/// every case the stub does not handle.
/// </summary>
public sealed unsafe partial class DirectExecutionBackend
{
internal enum GuestFastPathStub
{
None,
PthreadSelf,
PthreadGetspecific,
MemoryCopy,
}
// scePthreadSelf / pthread_self.
private const string PthreadSelfNid = "aI+OeCz8xrQ";
private const string PosixPthreadSelfNid = "EotR8a3ASf4";
// scePthreadGetspecific / pthread_getspecific.
private const string PthreadGetspecificNid = "eoht7mQOCmo";
private const string PosixPthreadGetspecificNid = "0-KXaS70xy4";
// memcpy / memmove.
private const string MemcpyNid = "Q3VBxCXhUHs";
private const string MemmoveNid = "+P6FRGH4LfA";
// Guest memory is identity-mapped and every fault the copy can take (write tracking, lazy
// commit) is resolved from the fault address alone, so the copy may run as guest-side code.
// SHARPEMU_HLE_FAST_MEMCPY=0 keeps it on the managed export.
private static readonly bool GuestMemoryCopyStubEnabled =
!string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_HLE_FAST_MEMCPY"), "0", StringComparison.Ordinal);
private uint _fastPathBlockTlsIndex = uint.MaxValue;
private bool _guestFastPathEnabled;
private int _guestFastPathStubCount;
/// <summary>
/// Decides whether native fast-path stubs may be installed for this run and
/// arms <see cref="GuestFastPath"/> if so. Any diagnostic mode that must
/// observe every import call keeps the fast path off, because a stub answers
/// without ever reaching the managed gateway that does the tracing.
/// </summary>
private void ConfigureGuestFastPath()
{
_guestFastPathEnabled = false;
_guestFastPathStubCount = 0;
// Emission uses the macOS pthread gs-indexed key array. Windows and
// Linux keep the managed gateway until their TLS read is emitted too.
if (!OperatingSystem.IsMacOS() ||
RuntimeInformation.ProcessArchitecture != Architecture.X64)
{
return;
}
if (string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_HLE_FAST_PATH"), "0", StringComparison.Ordinal))
{
Console.Error.WriteLine("[LOADER][INFO] HLE native fast path disabled by SHARPEMU_HLE_FAST_PATH=0.");
return;
}
if (_logAllImports ||
!string.IsNullOrEmpty(_importFilter) ||
string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_PTHREADS"), "1", StringComparison.Ordinal))
{
Console.Error.WriteLine(
"[LOADER][INFO] HLE native fast path disabled: import/pthread tracing needs every call in the gateway.");
return;
}
if (_fastPathBlockTlsIndex == uint.MaxValue)
{
_fastPathBlockTlsIndex = TlsAlloc();
if (_fastPathBlockTlsIndex == uint.MaxValue)
{
return;
}
}
var tlsIndex = _fastPathBlockTlsIndex;
GuestFastPath.Enable(block => TlsSetValue(tlsIndex, block));
_guestFastPathEnabled = true;
}
private static GuestFastPathStub ClassifyGuestFastPathStub(string nid) => nid switch
{
PthreadSelfNid or PosixPthreadSelfNid => GuestFastPathStub.PthreadSelf,
PthreadGetspecificNid or PosixPthreadGetspecificNid => GuestFastPathStub.PthreadGetspecific,
MemcpyNid or MemmoveNid => GuestFastPathStub.MemoryCopy,
_ => GuestFastPathStub.None,
};
/// <summary>
/// Builds the native stub for <paramref name="nid"/>, falling back to
/// <paramref name="fallbackTrampoline"/> (the import's managed gateway
/// trampoline) for every case the stub declines.
/// </summary>
private unsafe bool TryCreateGuestFastPathStub(string nid, nint fallbackTrampoline, out nint address)
{
address = 0;
if (!_guestFastPathEnabled || fallbackTrampoline == 0)
{
return false;
}
var kind = ClassifyGuestFastPathStub(nid);
if (kind == GuestFastPathStub.None ||
// The write watch inspects every managed guest write, which a native copy never reaches.
(kind == GuestFastPathStub.MemoryCopy && (!GuestMemoryCopyStubEnabled || GuestWriteWatch.Armed)))
{
return false;
}
var code = EmitGuestFastPathStub(kind, _fastPathBlockTlsIndex, fallbackTrampoline);
const uint stubAllocationSize = 128u;
if (code.Count > stubAllocationSize)
{
return false;
}
void* memory = VirtualAlloc(null, stubAllocationSize, 12288u, 64u);
if (memory == null)
{
return false;
}
for (var i = 0; i < code.Count; i++)
{
((byte*)memory)[i] = code[i];
}
uint oldProtect = 0;
if (!VirtualProtect(memory, stubAllocationSize, 32u, &oldProtect))
{
VirtualFree(memory, 0u, 32768u);
return false;
}
FlushInstructionCache(GetCurrentProcess(), memory, (nuint)code.Count);
address = (nint)memory;
_importHandlerTrampolines.Add(address);
_guestFastPathStubCount++;
return true;
}
/// <summary>
/// Emits one fast-path stub. The stubs obey the SysV ABI the guest calls
/// them with: the answer goes in RAX, only RAX and the arithmetic flags are
/// clobbered (both caller-saved across a call), and on the slow path every
/// register - including the incoming RAX that carries the variadic vector
/// count - is restored before jumping to the trampoline.
/// </summary>
internal static List<byte> EmitGuestFastPathStub(
GuestFastPathStub kind,
uint blockTlsIndex,
nint fallbackTrampoline)
{
if (kind == GuestFastPathStub.MemoryCopy)
{
return EmitGuestMemoryCopyStub(fallbackTrampoline);
}
var code = new List<byte>(48);
var slowPathFixups = new List<int>();
void Emit(params byte[] bytes) => code.AddRange(bytes);
// Emits a short conditional branch to the slow path; 0x74 is JE, 0x73 is JAE.
void EmitBranchToSlowPath(byte opcode)
{
Emit(opcode, 0x00); // rel8, patched once the slow-path offset is known
slowPathFixups.Add(code.Count - 1);
}
void EmitJumpToSlowPath() => EmitBranchToSlowPath(0x74);
// push rax: the guest's incoming RAX/AL must survive a slow-path bail.
Emit(0x50);
// mov rax, gs:[blockTlsIndex * 8] - the macOS pthread key array is the
// gs-based thread specific data array, so a key read is a single load.
Emit(0x65, 0x48, 0x8B, 0x04, 0x25);
code.AddRange(BitConverter.GetBytes(checked(blockTlsIndex * 8u)));
// test rax, rax / je slow: no block published on this host thread.
Emit(0x48, 0x85, 0xC0);
EmitJumpToSlowPath();
switch (kind)
{
case GuestFastPathStub.PthreadSelf:
// cmp qword [rax + SelfHandleOffset], 0 / je slow: no guest
// thread bound here, and a host thread's pthread_self has to
// reach the managed export for its scheduler registration.
Emit(0x48, 0x83, 0x78, checked((byte)GuestFastPath.BlockSelfHandleOffset), 0x00);
EmitJumpToSlowPath();
// inc qword [rax + SelfHitsOffset]
Emit(0x48, 0xFF, 0x40, checked((byte)GuestFastPath.BlockSelfHitsOffset));
// mov rax, [rax + SelfHandleOffset]
Emit(0x48, 0x8B, 0x40, checked((byte)GuestFastPath.BlockSelfHandleOffset));
break;
case GuestFastPathStub.PthreadGetspecific:
// cmp qword [rax + TlsValuesOffset], 0 / je slow: this thread
// has no value table published.
Emit(0x48, 0x83, 0x78, checked((byte)GuestFastPath.BlockTlsValuesOffset), 0x00);
EmitJumpToSlowPath();
// cmp rdi, TlsSlotCount / jae slow. An out-of-range or
// sign-extended negative key is answered by the managed path,
// which truncates it to int and consults the key registry.
Emit(0x48, 0x81, 0xFF);
code.AddRange(BitConverter.GetBytes(GuestFastPath.TlsSlotCount));
EmitBranchToSlowPath(0x73);
// inc qword [rax + GetspecificHitsOffset]
Emit(0x48, 0xFF, 0x40, checked((byte)GuestFastPath.BlockGetspecificHitsOffset));
// mov rax, [rax + TlsValuesOffset] / mov rax, [rax + rdi*8]
Emit(0x48, 0x8B, 0x40, checked((byte)GuestFastPath.BlockTlsValuesOffset));
Emit(0x48, 0x8B, 0x04, 0xF8);
break;
default:
throw new ArgumentOutOfRangeException(nameof(kind), kind, "Unknown fast-path stub kind.");
}
// add rsp, 8 (drop the saved RAX - the result replaces it) / ret
Emit(0x48, 0x83, 0xC4, 0x08);
Emit(0xC3);
var slowPathOffset = code.Count;
// pop rax / jmp qword [rip+0] - the absolute target follows the
// instruction, so nothing else is clobbered on the way out.
Emit(0x58);
Emit(0xFF, 0x25, 0x00, 0x00, 0x00, 0x00);
code.AddRange(BitConverter.GetBytes((long)fallbackTrampoline));
foreach (var fixup in slowPathFixups)
{
var delta = slowPathOffset - (fixup + 1);
if (delta is < 0 or > 127)
{
throw new InvalidOperationException("Fast-path stub slow-path branch is out of rel8 range.");
}
code[fixup] = (byte)delta;
}
return code;
}
/// <summary>
/// memcpy/memmove(dst, src, n) as a forward <c>rep movsb</c>, returning dst. The libc
/// export copies with memmove semantics, so a destination that starts inside the source
/// (where a forward copy would read bytes it already overwrote) takes the managed path.
/// Only RAX, RCX, RSI, RDI and the flags change - all caller-saved - and the direction
/// flag is clear on entry per the SysV ABI.
/// </summary>
internal static List<byte> EmitGuestMemoryCopyStub(nint fallbackTrampoline)
{
var code = new List<byte>(40);
// mov rcx, rdi / sub rcx, rsi / cmp rcx, rdx / jb slow: dst - src < n (unsigned) is
// exactly a destination in (src, src + n) or equal to src with a non-empty copy.
code.AddRange([0x48, 0x89, 0xF9, 0x48, 0x29, 0xF1, 0x48, 0x39, 0xD1, 0x72, 0x00]);
var slowPathFixup = code.Count - 1;
// mov rax, rdi / mov rcx, rdx / rep movsb / ret
code.AddRange([0x48, 0x89, 0xF8, 0x48, 0x89, 0xD1, 0xF3, 0xA4, 0xC3]);
code[slowPathFixup] = checked((byte)(code.Count - (slowPathFixup + 1)));
// jmp qword [rip+0] with the absolute trampoline address after it.
code.AddRange([0xFF, 0x25, 0x00, 0x00, 0x00, 0x00]);
code.AddRange(BitConverter.GetBytes((long)fallbackTrampoline));
return code;
}
}

View File

@ -1,387 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using SharpEmu.HLE;
namespace SharpEmu.Core.Cpu.Native;
/// <summary>
/// Sampling profiler for guest code. Managed profilers only see the emulator's
/// own frames — once a guest thread is running translated code it is opaque to
/// them, so a title that burns its cores inside its own spin loops looks like
/// unattributed native time. This walks the guest thread registry and samples
/// each thread's host RIP, which lands directly on the guest instruction being
/// executed.
/// </summary>
public sealed partial class DirectExecutionBackend
{
private static readonly bool _profileGuestRip =
string.Equals(
Environment.GetEnvironmentVariable("SHARPEMU_PROFILE_GUEST_RIP"),
"1",
StringComparison.Ordinal);
private static readonly int _profileGuestRipIntervalMs =
int.TryParse(
Environment.GetEnvironmentVariable("SHARPEMU_PROFILE_GUEST_RIP_INTERVAL_MS"),
out var interval) && interval > 0
? interval
: 2;
private static readonly int _profileGuestRipReportSeconds =
int.TryParse(
Environment.GetEnvironmentVariable("SHARPEMU_PROFILE_GUEST_RIP_REPORT_S"),
out var report) && report > 0
? report
: 15;
private static readonly string? _profileGuestRipThreadFilter =
Environment.GetEnvironmentVariable("SHARPEMU_PROFILE_GUEST_RIP_THREAD");
private const ulong GuestImageBase = 0x0000_0008_0000_0000UL;
private const ulong GuestImageLimit = 0x0000_0009_0000_0000UL;
private int _guestRipSamplerStarted;
private readonly ConcurrentDictionary<ulong, long> _guestRipSamples = new();
private readonly ConcurrentDictionary<string, long> _guestRipThreadSamples = new();
private readonly ConcurrentDictionary<string, long> _guestWaitSamples = new();
private readonly ConcurrentDictionary<string, long> _guestThreadWaitSamples = new();
private readonly ConcurrentDictionary<string, long> _guestThreadWaitReasonSamples = new();
private long _guestRipTotalSamples;
private long _guestWaitTotalSamples;
private long _guestRipCaptureFailures;
private long _guestRipSamplerErrors;
private readonly record struct GuestRipSampleTarget(
string Name,
CpuContext Context,
int HostThreadId,
string? BlockReason);
/// <summary>
/// Names the HLE call a thread is parked in, using the guest RIP the import
/// dispatcher left on its context.
/// </summary>
private string ResolveWaitLabel(CpuContext context, string? blockReason)
{
var importIndex = context.ActiveImportIndex;
if ((uint)importIndex >= (uint)_importEntries.Length)
{
// Host code with no import in flight: the thread is parked by the
// emulator's own scheduler. The cooperative block records why, which
// is the part that actually identifies what the frame is waiting on.
return string.IsNullOrEmpty(blockReason)
? "<idle-or-scheduler>"
: $"blocked:{blockReason}";
}
var entry = _importEntries[importIndex];
return entry.Export?.Name ?? entry.Nid;
}
internal void ClearActiveImportIndex()
{
if (!_profileGuestRip)
{
return;
}
var context = ActiveCpuContext;
if (context is not null)
{
context.ActiveImportIndex = -1;
}
}
private void EnsureGuestRipSampler()
{
if (!_profileGuestRip ||
!OperatingSystem.IsWindows() ||
Interlocked.Exchange(ref _guestRipSamplerStarted, 1) != 0)
{
return;
}
var sampler = new Thread(GuestRipSampleLoop)
{
IsBackground = true,
Name = "SharpEmu guest RIP sampler",
// Sampling suspends guest threads briefly. Keep this diagnostic below
// the title workers so it observes them without becoming the bottleneck.
Priority = ThreadPriority.BelowNormal,
};
sampler.Start();
Console.Error.WriteLine(
$"[PERF][GUEST] RIP sampler started: interval={_profileGuestRipIntervalMs}ms " +
$"report={_profileGuestRipReportSeconds}s " +
$"thread={_profileGuestRipThreadFilter ?? "<all>"}");
}
private void GuestRipSampleLoop()
{
var clock = Stopwatch.StartNew();
var lastReportMs = 0L;
var lastReportSamples = 0L;
while (true)
{
try
{
var guestThreads = SnapshotGuestRipTargets();
if (!string.IsNullOrWhiteSpace(_profileGuestRipThreadFilter))
{
guestThreads = guestThreads
.Where(thread => thread.Name.Contains(
_profileGuestRipThreadFilter,
StringComparison.OrdinalIgnoreCase))
.ToArray();
}
var sampledHostThreads = new HashSet<int>();
foreach (var thread in guestThreads)
{
var hostThreadId = thread.HostThreadId;
if (hostThreadId == 0 || !sampledHostThreads.Add(hostThreadId))
{
continue;
}
if (!TryCaptureHostThreadContext(hostThreadId, out var snapshot) ||
!snapshot.IsValid)
{
Interlocked.Increment(ref _guestRipCaptureFailures);
continue;
}
_guestRipSamples.AddOrUpdate(snapshot.Rip, 1, static (_, value) => value + 1);
_guestRipThreadSamples.AddOrUpdate(
string.IsNullOrEmpty(thread.Name) ? "<unnamed>" : thread.Name,
1,
static (_, value) => value + 1);
Interlocked.Increment(ref _guestRipTotalSamples);
// A host RIP means the thread is inside the emulator rather
// than running translated code. DispatchImport parks the
// guest RIP on the import stub for the call being serviced,
// so the stub address names what the thread is waiting on —
// no hot-path bookkeeping needed to find out.
if (snapshot.Rip >= GuestImageBase && snapshot.Rip < GuestImageLimit)
{
continue;
}
var threadName = string.IsNullOrEmpty(thread.Name) ? "<unnamed>" : thread.Name;
var waitLabel = ResolveWaitLabel(thread.Context, thread.BlockReason);
_guestWaitSamples.AddOrUpdate(
waitLabel,
1,
static (_, value) => value + 1);
_guestThreadWaitSamples.AddOrUpdate(
threadName,
1,
static (_, value) => value + 1);
_guestThreadWaitReasonSamples.AddOrUpdate(
$"{threadName}\u001F{waitLabel}",
1,
static (_, value) => value + 1);
Interlocked.Increment(ref _guestWaitTotalSamples);
}
Thread.Sleep(_profileGuestRipIntervalMs);
var elapsedMs = clock.ElapsedMilliseconds;
if (elapsedMs - lastReportMs < _profileGuestRipReportSeconds * 1000L)
{
continue;
}
var samples = Interlocked.Read(ref _guestRipTotalSamples);
ReportGuestRipSamples(samples - lastReportSamples, (elapsedMs - lastReportMs) / 1000.0);
lastReportMs = elapsedMs;
lastReportSamples = samples;
}
catch (Exception exception)
{
// A title can tear down a thread or its context during a capture.
// The profiler must never silently die or affect guest execution.
if (Interlocked.Increment(ref _guestRipSamplerErrors) == 1)
{
Console.Error.WriteLine($"[PERF][GUEST] sampler recovery: {exception.GetType().Name}: {exception.Message}");
}
}
}
}
private GuestRipSampleTarget[] SnapshotGuestRipTargets()
{
using (LockGate("SnapshotGuestRipTargets"))
{
var targets = new GuestRipSampleTarget[_guestThreads.Count + _externalGuestThreads.Count];
var index = 0;
foreach (var thread in _guestThreads.Values)
{
targets[index++] = new GuestRipSampleTarget(
thread.Name,
thread.Context,
Volatile.Read(ref thread.HostThreadId),
thread.BlockReason);
}
foreach (var pair in _externalGuestThreads)
{
var thread = pair.Value;
targets[index++] = new GuestRipSampleTarget(
thread.Name,
thread.Context,
Volatile.Read(ref thread.HostThreadId),
null);
}
return targets;
}
}
private void ReportGuestRipSamples(long windowSamples, double windowSeconds)
{
if (windowSamples == 0)
{
return;
}
var byRip = new List<KeyValuePair<ulong, long>>(_guestRipSamples.Count + 16);
foreach (var pair in _guestRipSamples)
{
byRip.Add(pair);
}
// A tight spin lands on a handful of instructions; grouping by 4 KB page
// as well shows which routine those instructions belong to.
var byPage = new Dictionary<ulong, long>();
foreach (var pair in byRip)
{
var page = pair.Key & ~0xFFFUL;
byPage[page] = byPage.TryGetValue(page, out var existing)
? existing + pair.Value
: pair.Value;
}
var byThread = new List<KeyValuePair<string, long>>(_guestRipThreadSamples.Count + 16);
foreach (var pair in _guestRipThreadSamples)
{
byThread.Add(pair);
}
Console.Error.WriteLine(
$"[PERF][GUEST] window={windowSamples} in {windowSeconds:F1}s " +
$"capture_failures={Interlocked.Read(ref _guestRipCaptureFailures)}");
Console.Error.WriteLine(
"[PERF][GUEST] top_rip: " +
string.Join(
" | ",
byRip.OrderByDescending(pair => pair.Value)
.Take(12)
.Select(pair =>
$"0x{pair.Key:X}{DescribeGuestAddress(pair.Key)}={pair.Value * 100.0 / windowSamples:F1}%")));
Console.Error.WriteLine(
"[PERF][GUEST] top_page: " +
string.Join(
" | ",
byPage.OrderByDescending(pair => pair.Value)
.Take(8)
.Select(pair =>
$"0x{pair.Key:X}{DescribeGuestAddress(pair.Key)}={pair.Value * 100.0 / windowSamples:F1}%")));
var byWait = new List<KeyValuePair<string, long>>(_guestWaitSamples.Count + 16);
foreach (var pair in _guestWaitSamples)
{
byWait.Add(pair);
}
var waitTotal = Interlocked.Read(ref _guestWaitTotalSamples);
Console.Error.WriteLine(
$"[PERF][GUEST] waiting={waitTotal * 100.0 / windowSamples:F1}% of guest thread-time; top_wait: " +
string.Join(
" | ",
byWait.OrderByDescending(pair => pair.Value)
.Take(12)
.Select(pair => $"{pair.Key}={pair.Value * 100.0 / windowSamples:F1}%")));
Console.Error.WriteLine(
"[PERF][GUEST] thread_wait: " +
string.Join(
" | ",
_guestThreadWaitReasonSamples.OrderByDescending(pair => pair.Value)
.Take(16)
.Select(pair =>
{
var separator = pair.Key.IndexOf('\u001F');
var threadName = separator >= 0 ? pair.Key[..separator] : pair.Key;
var waitLabel = separator >= 0 ? pair.Key[(separator + 1)..] : "<unknown>";
return $"{threadName}->{waitLabel}={pair.Value * 100.0 / windowSamples:F1}%";
})));
// Per-thread spin/park split. The global wait share mixes the job pool in
// with a dozen dormant threads, which hides the number that matters:
// how much of a core each worker actually burns.
Console.Error.WriteLine(
"[PERF][GUEST] thread_split (running/parked): " +
string.Join(
" | ",
byThread.OrderByDescending(pair => pair.Value)
.Take(10)
.Select(pair =>
{
var parked = _guestThreadWaitSamples.TryGetValue(pair.Key, out var wait) ? wait : 0;
var running = pair.Value - parked;
return $"{pair.Key}={running * 100.0 / pair.Value:F0}%/{parked * 100.0 / pair.Value:F0}%";
})));
Console.Error.WriteLine(
"[PERF][GUEST] top_thread: " +
string.Join(
" | ",
byThread.OrderByDescending(pair => pair.Value)
.Take(10)
.Select(pair => $"{pair.Key}={pair.Value * 100.0 / windowSamples:F1}%")));
_guestRipSamples.Clear();
_guestRipThreadSamples.Clear();
_guestWaitSamples.Clear();
_guestThreadWaitSamples.Clear();
_guestThreadWaitReasonSamples.Clear();
Interlocked.Exchange(ref _guestWaitTotalSamples, 0);
}
/// <summary>
/// Tags a sampled address with the region it belongs to. Guest module code
/// lives above the image base; anything else is emulator or system code that
/// the managed profiler already covers.
/// </summary>
private string DescribeGuestAddress(ulong address)
{
if (address >= GuestImageBase && address < GuestImageLimit)
{
return $"(app+0x{address - GuestImageBase:X})";
}
for (var index = 0; index < _importEntries.Length; index++)
{
if (_importEntries[index].Address == (address & ~0xFUL))
{
return $"(stub:{_importEntries[index].Nid})";
}
}
return "(host)";
}
}

View File

@ -1,309 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Collections.Concurrent;
using System.Diagnostics;
namespace SharpEmu.Core.Cpu.Native;
public sealed unsafe partial class DirectExecutionBackend
{
private sealed class GuestSchedulerThreadStats
{
public string Name = string.Empty;
public long ReadyTimestamp;
public long BlockTimestamp;
public long ScheduledTimestamp;
public long RunTimestamp;
public long ReadyCount;
public long ClaimCount;
public long ScheduleCount;
public long RunCount;
public long BlockCount;
public long ResumeCount;
public long ReadyTicks;
public long BlockTicks;
public long ScheduleTicks;
public long RunTicks;
public long MaxReadyTicks;
public long MaxBlockTicks;
public long MaxScheduleTicks;
public long MaxRunTicks;
public string? LastBlockReason;
public int Completed;
}
private static readonly bool _profileGuestScheduler =
string.Equals(
Environment.GetEnvironmentVariable("SHARPEMU_PROFILE_GUEST_SCHEDULER"),
"1",
StringComparison.Ordinal) ||
string.Equals(
Environment.GetEnvironmentVariable("SHARPEMU_PROFILE_PERFORMANCE"),
"1",
StringComparison.Ordinal);
private readonly ConcurrentDictionary<ulong, GuestSchedulerThreadStats> _guestSchedulerStats = new();
private readonly GuestThreadFlowProfile _guestThreadFlowProfile = new();
private readonly object _guestTraceOutputGate = new();
private long _guestSchedulerProfileWindowStart = Stopwatch.GetTimestamp();
private long _guestSchedulerProfileNextReport =
Stopwatch.GetTimestamp() + (Stopwatch.Frequency * 5L);
private int _guestSchedulerProfileReporting;
private void StartGuestFlowTraces()
{
lock (_guestTraceOutputGate)
{
_guestThreadFlowProfile.StartSession();
SharpEmu.Libs.Diagnostics.SemaphoreSignalProfile.StartSession();
SharpEmu.Libs.Diagnostics.MutexHandoffProfile.StartSession();
SharpEmu.Libs.VideoOut.SubmissionFlowProfile.StartSession();
}
}
private void WriteGuestFlowTraces(TextWriter? output = null)
{
output ??= Console.Error;
lock (_guestTraceOutputGate)
{
var signals = SharpEmu.Libs.Diagnostics.SemaphoreSignalProfile.Close();
var mutexes = SharpEmu.Libs.Diagnostics.MutexHandoffProfile.Close();
SharpEmu.Libs.VideoOut.SubmissionFlowProfile.WriteTrace(output);
try
{
_guestThreadFlowProfile.WriteTrace(output);
SharpEmu.Libs.Diagnostics.SemaphoreSignalProfile.WriteTrace(output, signals);
SharpEmu.Libs.Diagnostics.MutexHandoffProfile.WriteTrace(output, mutexes);
}
catch (Exception exception) when (exception is IOException or ObjectDisposedException)
{
// A closed trace output must not prevent native session cleanup.
}
}
}
private void RecordGuestThreadFlow(GuestThreadState thread, GuestThreadFlowProfile.EventKind kind, string? reason = null)
{
if (!GuestThreadFlowProfile.Enabled) return;
_guestThreadFlowProfile.Record(new GuestThreadFlowProfile.TraceEvent(
Stopwatch.GetTimestamp(), Environment.CurrentManagedThreadId, thread.ThreadHandle,
thread.Name, kind, reason, thread.BlockWakeKey, Volatile.Read(ref thread.LastImportNid),
Volatile.Read(ref thread.LastImportRdi), Volatile.Read(ref thread.LastImportRsi), thread.BlockDeadlineTimestamp));
}
private GuestSchedulerThreadStats GetGuestSchedulerStats(GuestThreadState thread)
{
var stats = _guestSchedulerStats.GetOrAdd(
thread.ThreadHandle,
static _ => new GuestSchedulerThreadStats());
stats.Name = thread.Name;
return stats;
}
private void ProfileGuestThreadReady(GuestThreadState thread)
{
RecordGuestThreadFlow(thread, GuestThreadFlowProfile.EventKind.Ready);
if (!_profileGuestScheduler)
{
return;
}
var stats = GetGuestSchedulerStats(thread);
var now = Stopwatch.GetTimestamp();
Volatile.Write(ref stats.ReadyTimestamp, now);
Interlocked.Increment(ref stats.ReadyCount);
var blockTimestamp = Interlocked.Exchange(ref stats.BlockTimestamp, 0);
if (blockTimestamp != 0 && now >= blockTimestamp)
{
var ticks = now - blockTimestamp;
Interlocked.Increment(ref stats.ResumeCount);
Interlocked.Add(ref stats.BlockTicks, ticks);
UpdateGuestSchedulerMaximum(ref stats.MaxBlockTicks, ticks);
}
}
private void ProfileGuestThreadClaimed(GuestThreadState thread)
{
RecordGuestThreadFlow(thread, GuestThreadFlowProfile.EventKind.Claimed);
if (!_profileGuestScheduler)
{
return;
}
var now = Stopwatch.GetTimestamp();
var stats = GetGuestSchedulerStats(thread);
var readyTimestamp = Interlocked.Exchange(ref stats.ReadyTimestamp, 0);
Interlocked.Increment(ref stats.ClaimCount);
if (readyTimestamp != 0 && now >= readyTimestamp)
{
var ticks = now - readyTimestamp;
Interlocked.Add(ref stats.ReadyTicks, ticks);
UpdateGuestSchedulerMaximum(ref stats.MaxReadyTicks, ticks);
}
}
private void ProfileGuestThreadScheduled(GuestThreadState thread)
{
RecordGuestThreadFlow(thread, GuestThreadFlowProfile.EventKind.Scheduled);
if (!_profileGuestScheduler)
{
return;
}
var stats = GetGuestSchedulerStats(thread);
Volatile.Write(ref stats.ScheduledTimestamp, Stopwatch.GetTimestamp());
Interlocked.Increment(ref stats.ScheduleCount);
}
private void ProfileGuestThreadRunStarted(GuestThreadState thread)
{
RecordGuestThreadFlow(thread, GuestThreadFlowProfile.EventKind.RunStarted);
if (!_profileGuestScheduler)
{
return;
}
var now = Stopwatch.GetTimestamp();
var stats = GetGuestSchedulerStats(thread);
var scheduledTimestamp = Interlocked.Exchange(ref stats.ScheduledTimestamp, 0);
Volatile.Write(ref stats.RunTimestamp, now);
Interlocked.Increment(ref stats.RunCount);
if (scheduledTimestamp != 0 && now >= scheduledTimestamp)
{
var ticks = now - scheduledTimestamp;
Interlocked.Add(ref stats.ScheduleTicks, ticks);
UpdateGuestSchedulerMaximum(ref stats.MaxScheduleTicks, ticks);
}
}
private void ProfileGuestThreadRunStopped(GuestThreadState thread)
{
if (!_profileGuestScheduler)
{
return;
}
var now = Stopwatch.GetTimestamp();
var stats = GetGuestSchedulerStats(thread);
var runTimestamp = Interlocked.Exchange(ref stats.RunTimestamp, 0);
if (runTimestamp != 0 && now >= runTimestamp)
{
var ticks = now - runTimestamp;
Interlocked.Add(ref stats.RunTicks, ticks);
UpdateGuestSchedulerMaximum(ref stats.MaxRunTicks, ticks);
}
if (thread.State == GuestThreadRunState.Blocked)
{
Interlocked.Increment(ref stats.BlockCount);
Volatile.Write(ref stats.BlockTimestamp, now);
Volatile.Write(ref stats.LastBlockReason, thread.BlockReason);
}
else if (thread.State is GuestThreadRunState.Exited or GuestThreadRunState.Faulted)
{
Volatile.Write(ref stats.Completed, 1);
}
TryReportGuestSchedulerProfile(now);
}
private void TryReportGuestSchedulerProfile(long now)
{
var deadline = Volatile.Read(ref _guestSchedulerProfileNextReport);
if (now < deadline ||
Interlocked.CompareExchange(ref _guestSchedulerProfileReporting, 1, 0) != 0)
{
return;
}
try
{
Volatile.Write(
ref _guestSchedulerProfileNextReport,
now + (Stopwatch.Frequency * 5L));
var windowStart = Interlocked.Exchange(ref _guestSchedulerProfileWindowStart, now);
var seconds = Math.Max(
(now - windowStart) / (double)Stopwatch.Frequency,
double.Epsilon);
var rows = new List<(long Rank, string Text)>();
foreach (var pair in _guestSchedulerStats)
{
var stats = pair.Value;
var readyCount = Interlocked.Exchange(ref stats.ReadyCount, 0);
var claimCount = Interlocked.Exchange(ref stats.ClaimCount, 0);
var scheduleCount = Interlocked.Exchange(ref stats.ScheduleCount, 0);
var runCount = Interlocked.Exchange(ref stats.RunCount, 0);
var blockCount = Interlocked.Exchange(ref stats.BlockCount, 0);
var resumeCount = Interlocked.Exchange(ref stats.ResumeCount, 0);
var readyTicks = Interlocked.Exchange(ref stats.ReadyTicks, 0);
var blockTicks = Interlocked.Exchange(ref stats.BlockTicks, 0);
var scheduleTicks = Interlocked.Exchange(ref stats.ScheduleTicks, 0);
var runTicks = Interlocked.Exchange(ref stats.RunTicks, 0);
var maxReadyTicks = Interlocked.Exchange(ref stats.MaxReadyTicks, 0);
var maxBlockTicks = Interlocked.Exchange(ref stats.MaxBlockTicks, 0);
var maxScheduleTicks = Interlocked.Exchange(ref stats.MaxScheduleTicks, 0);
var maxRunTicks = Interlocked.Exchange(ref stats.MaxRunTicks, 0);
if (readyCount == 0 && claimCount == 0 && scheduleCount == 0 && runCount == 0)
{
continue;
}
rows.Add((Math.Max(blockTicks, Math.Max(readyTicks, runTicks)),
$"name='{stats.Name}' handle=0x{pair.Key:X16} " +
$"ready={readyCount} claimed={claimCount} scheduled={scheduleCount} " +
$"runs={runCount} blocked={blockCount} resumed={resumeCount} " +
$"blocked_ms={GuestSchedulerMilliseconds(blockTicks):F2} " +
$"blocked_avg_ms={(resumeCount == 0 ? 0.0 : GuestSchedulerMilliseconds(blockTicks) / resumeCount):F3} " +
$"blocked_max_ms={GuestSchedulerMilliseconds(maxBlockTicks):F3} " +
$"ready_ms={GuestSchedulerMilliseconds(readyTicks):F2} " +
$"ready_avg_ms={(claimCount == 0 ? 0.0 : GuestSchedulerMilliseconds(readyTicks) / claimCount):F3} " +
$"ready_max_ms={GuestSchedulerMilliseconds(maxReadyTicks):F3} " +
$"dispatch_ms={GuestSchedulerMilliseconds(scheduleTicks):F2} " +
$"dispatch_avg_ms={(runCount == 0 ? 0.0 : GuestSchedulerMilliseconds(scheduleTicks) / runCount):F3} " +
$"dispatch_max_ms={GuestSchedulerMilliseconds(maxScheduleTicks):F3} " +
$"run_ms={GuestSchedulerMilliseconds(runTicks):F2} " +
$"run_avg_ms={(runCount == 0 ? 0.0 : GuestSchedulerMilliseconds(runTicks) / runCount):F3} " +
$"run_max_ms={GuestSchedulerMilliseconds(maxRunTicks):F3} " +
$"last_block={Volatile.Read(ref stats.LastBlockReason) ?? "none"}"));
if (Volatile.Read(ref stats.Completed) != 0)
{
_guestSchedulerStats.TryRemove(pair.Key, out _);
}
}
Console.Error.WriteLine(
$"[PERF][GUEST_SCHED] window={seconds:F1}s active_threads={rows.Count}");
foreach (var row in rows
.OrderByDescending(static item => item.Rank)
.Take(32))
{
Console.Error.WriteLine($"[PERF][GUEST_SCHED] {row.Text}");
}
}
finally
{
Volatile.Write(ref _guestSchedulerProfileReporting, 0);
}
}
private static double GuestSchedulerMilliseconds(long ticks) =>
ticks * 1000.0 / Stopwatch.Frequency;
private static void UpdateGuestSchedulerMaximum(ref long target, long candidate)
{
var current = Volatile.Read(ref target);
while (candidate > current)
{
var observed = Interlocked.CompareExchange(ref target, candidate, current);
if (observed == current)
{
return;
}
current = observed;
}
}
}

View File

@ -201,7 +201,7 @@ public sealed partial class DirectExecutionBackend
foreach (var attempt in DecodeWindowSizes)
{
var buffer = new byte[attempt];
if (!TryReadExecutableBytes(rip, buffer))
if (!TryReadHostBytes(rip, buffer))
{
continue;
}

View File

@ -54,13 +54,10 @@ public sealed partial class DirectExecutionBackend
var startTicks = System.Diagnostics.Stopwatch.GetTimestamp();
var r = directExecutionBackend.DispatchImport(importIndex, argPackPtr);
RecordPerfHleDispatchTime(System.Diagnostics.Stopwatch.GetTimestamp() - startTicks);
directExecutionBackend.ClearActiveImportIndex();
return r;
}
var result = directExecutionBackend.DispatchImport(importIndex, argPackPtr);
directExecutionBackend.ClearActiveImportIndex();
return result;
return directExecutionBackend.DispatchImport(importIndex, argPackPtr);
}
catch (Exception ex)
{
@ -164,32 +161,16 @@ public sealed partial class DirectExecutionBackend
return 18446744071562199042uL;
}
ImportStubEntry importStubEntry = _importEntries[importIndex];
using var registerPacketImport = SharpEmu.Libs.Diagnostics.AgcRegisterPacketProfile.MeasureImport(importStubEntry.Nid);
if (_perfHleHistogram)
{
RecordPerfHleCall(importStubEntry.Export?.Name ?? importStubEntry.Nid);
}
if (_profileGuestRip)
{
EnsureGuestRipSampler();
}
int num2 = Volatile.Read(in _rawSentinelRecoveries);
if (num2 != _lastReportedRawSentinelRecoveries)
{
Console.Error.WriteLine($"[LOADER][TRACE] Raw sentinel recoveries: {num2} (last import index={importIndex})");
_lastReportedRawSentinelRecoveries = num2;
}
if (importStubEntry.IsLeaf &&
TryDispatchHotMemoryLeaf(cpuContext, importStubEntry, argPackPtr, out var hotMemoryResult))
{
return hotMemoryResult;
}
if (importStubEntry.IsTrivialLeaf && !_disableTrivialLeafDispatch)
{
return DispatchTrivialLeaf(cpuContext, in importStubEntry, argPackPtr, num);
}
if (importStubEntry.IsLeaf &&
TryDispatchLeafImport(cpuContext, importStubEntry, argPackPtr, num, out var leafResult))
{
@ -197,10 +178,6 @@ public sealed partial class DirectExecutionBackend
}
cpuContext.Rip = importStubEntry.Address;
if (_profileGuestRip)
{
cpuContext.ActiveImportIndex = importIndex;
}
LoadImportVolatileArguments(cpuContext, argPackPtr);
cpuContext[CpuRegister.Rdi] = *(ulong*)argPackPtr;
cpuContext[CpuRegister.Rsi] = *(ulong*)(argPackPtr + 8);
@ -215,13 +192,6 @@ public sealed partial class DirectExecutionBackend
cpuContext[CpuRegister.R14] = *(ulong*)(argPackPtr + 80);
cpuContext[CpuRegister.R15] = *(ulong*)(argPackPtr + 88);
cpuContext[CpuRegister.Rsp] = (ulong)argPackPtr + 96uL;
cpuContext.SetImportStackArguments(
ReadImportStackArgument(argPackPtr, 0),
ReadImportStackArgument(argPackPtr, 1),
ReadImportStackArgument(argPackPtr, 2),
ReadImportStackArgument(argPackPtr, 3),
ReadImportStackArgument(argPackPtr, 4),
ReadImportStackArgument(argPackPtr, 5));
ulong value = cpuContext[CpuRegister.Rdi];
ulong value2 = cpuContext[CpuRegister.Rsi];
ulong num3 = cpuContext[CpuRegister.Rdx];
@ -243,8 +213,8 @@ public sealed partial class DirectExecutionBackend
if (probeTarget &&
Interlocked.Increment(ref _probeImportReturnAddressCount) <= 2048)
{
var frameValue = TryReadImportStackU64(value4, out var savedRbp) ? savedRbp : 0;
var frameReturn = TryReadImportStackU64(value4 + sizeof(ulong), out var savedReturn)
var frameValue = TryReadStackU64(value4, out var savedRbp) ? savedRbp : 0;
var frameReturn = TryReadStackU64(value4 + sizeof(ulong), out var savedReturn)
? savedReturn
: 0;
Console.Error.WriteLine(
@ -345,14 +315,6 @@ public sealed partial class DirectExecutionBackend
Console.Error.WriteLine(
$"[LOADER][TRACE] bootstrap_call#{num}: op=0x{value:X16} sym_ptr=0x{value2:X16} sym='{symbolText}' out_ptr=0x{num3:X16} ret=0x{num7:X16}");
}
// Once the host is shutting down, a guest thread still running reaches no more HLE: the
// services behind the imports are being torn down, and a title that sees them fail (a null
// command buffer from the GPU library, say) crashes the process on its way out.
if (_forcedGuestExit && !ActiveForcedGuestExit && TryEndGuestSliceForShutdown(argPackPtr))
{
cpuContext[CpuRegister.Rax] = 1uL;
return 1uL;
}
if (!isGuestWorker &&
!ActiveForcedGuestExit &&
ShouldForceGuestExitOnImportLoop(in importStubEntry, num7, num, value, value2))
@ -372,8 +334,7 @@ public sealed partial class DirectExecutionBackend
bool flag4 = !string.IsNullOrWhiteSpace(_importFilter);
bool flag5 = false;
ExportedFunction? matchedExport = importStubEntry.Export;
bool periodicTrace = _logImportPeriodic &&
(num <= 128 ||
bool periodicTrace = num <= 128 ||
(num >= 240 && num <= 400) ||
(num >= 900 && num <= 1300) ||
num % 100000 == 0L ||
@ -381,7 +342,7 @@ public sealed partial class DirectExecutionBackend
(importStubEntry.Nid == "rTXw65xmLIA" && (num <= 256 || num % 128 == 0)) ||
flag ||
flag2 ||
flag3);
flag3;
if (matchedExport is not null)
{
if (flag4)
@ -1230,56 +1191,10 @@ public sealed partial class DirectExecutionBackend
}
}
// Every import reads its stack arguments. On POSIX a region query takes the global region lock,
// so keep the last readable range per thread until any mapping changes. The signal handlers
// use TryReadStackU64 instead: they must not touch thread-static storage.
[ThreadStatic] private static ulong _importReadableStart;
[ThreadStatic] private static ulong _importReadableEnd;
[ThreadStatic] private static long _importReadableGeneration;
private unsafe static bool TryReadImportStackU64(ulong address, out ulong value)
{
if (OperatingSystem.IsWindows())
{
return TryReadHostQword(address, out value);
}
// Stack arguments sit on the calling guest thread's own stack, which the backend mapped read-write
// for the thread's lifetime and no tracker ever protects. Reading inside it needs no query: the
// cached range below is keyed by a mapping generation that every tracker protection change bumps,
// so falling through here cost a locked host region query per argument on nearly every import.
if (_activeGuestThreadState is { StackSize: > 0 } thread &&
address >= thread.StackBase && address <= thread.StackBase + thread.StackSize - sizeof(ulong))
{
value = *(ulong*)address;
return true;
}
var generation = HostMemory.MappingGeneration;
if (generation == _importReadableGeneration &&
address >= _importReadableStart && address <= _importReadableEnd - 8)
{
value = *(ulong*)address;
return true;
}
if (!TryQueryReadableRange(address, out var start, out var end))
{
value = 0;
return false;
}
_importReadableStart = start;
_importReadableEnd = end;
_importReadableGeneration = generation;
value = *(ulong*)address;
return true;
}
private static ulong ReadImportStackArgument(nint argPackPtr, int index)
{
var address = checked((ulong)argPackPtr + 104UL + (ulong)index * sizeof(ulong));
return TryReadImportStackU64(address, out var value) ? value : 0;
return TryReadHostQword(address, out var value) ? value : 0;
}
private static GuestCpuContinuation CaptureImportBoundaryContinuation(
@ -1312,41 +1227,6 @@ public sealed partial class DirectExecutionBackend
Mxcsr: context.Mxcsr,
RestoreFullFpuState: false);
/// <summary>
/// Ultra-thin path for hot memcpy/memmove leaf imports: skip
/// CpuContext register marshalling, import-call frames, and vector return
/// stores when guest memory can satisfy the copy directly.
/// </summary>
private unsafe bool TryDispatchHotMemoryLeaf(
CpuContext cpuContext,
ImportStubEntry importStubEntry,
nint argPackPtr,
out ulong result)
{
result = 0;
var nid = importStubEntry.Nid;
if (nid is not ("Q3VBxCXhUHs" or "+P6FRGH4LfA"))
{
return false;
}
var destination = *(ulong*)argPackPtr;
var source = *(ulong*)(argPackPtr + 8);
var count = *(ulong*)(argPackPtr + 16);
if (count > (ulong)int.MaxValue)
{
return false;
}
if (count != 0 && !cpuContext.Memory.TryCopy(destination, source, count))
{
return false;
}
result = destination;
return true;
}
private unsafe bool TryDispatchLeafImport(
CpuContext cpuContext,
ImportStubEntry importStubEntry,
@ -1390,13 +1270,6 @@ public sealed partial class DirectExecutionBackend
cpuContext[CpuRegister.R14] = *(ulong*)(argPackPtr + 80);
cpuContext[CpuRegister.R15] = *(ulong*)(argPackPtr + 88);
cpuContext[CpuRegister.Rsp] = (ulong)argPackPtr + 96uL;
cpuContext.SetImportStackArguments(
ReadImportStackArgument(argPackPtr, 0),
ReadImportStackArgument(argPackPtr, 1),
ReadImportStackArgument(argPackPtr, 2),
ReadImportStackArgument(argPackPtr, 3),
ReadImportStackArgument(argPackPtr, 4),
ReadImportStackArgument(argPackPtr, 5));
if (_activeGuestThreadState is { } activeGuestThreadState)
{
@ -1417,7 +1290,7 @@ public sealed partial class DirectExecutionBackend
Volatile.Write(ref activeGuestThreadState.LastReturnRip, returnRip);
Volatile.Write(ref activeGuestThreadState.LastImportNid, importStubEntry.Nid);
}
if (_logImportPeriodic && dispatchIndex % 100000 == 0)
if (dispatchIndex % 100000 == 0)
{
Console.Error.WriteLine(
$"[LOADER][TRACE] Import#{dispatchIndex}: {export.LibraryName}:{export.Name} ({importStubEntry.Nid}) " +
@ -1518,68 +1391,6 @@ public sealed partial class DirectExecutionBackend
return true;
}
private static readonly bool _disableTrivialLeafDispatch = string.Equals(
Environment.GetEnvironmentVariable("SHARPEMU_DISABLE_TRIVIAL_LEAF"), "1", StringComparison.Ordinal);
// Tiny exports called millions of times per second, where the ~250ns of full
// import bookkeeping costs more than the export itself. Each one reads only
// argument registers (RDI..R9) and thread-local state, returns in RAX, never
// blocks, yields, calls back into the guest or reads the guest stack.
private static bool IsTrivialLeafImport(string nid) =>
nid is
"0-KXaS70xy4" or // pthread_getspecific
"eoht7mQOCmo" or // scePthreadGetspecific
"EI-5-jlq2dE" or // scePthreadGetthreadid
"3eqs37G74-s" or // pthread_getthreadid_np
"BNowx2l588E" or // sceKernelGetProcessTimeCounterFrequency
"fgxnMeTNUtY" or // sceKernelGetProcessTimeCounter
"4J2sUJmuHZQ" or // sceKernelGetProcessTime
"-2IRUCO--PM" or // sceKernelReadTsc
"1j3S3n-tTW4" or // sceKernelGetTscFrequency
"ob5xAW4ln-0" or // strchr
"9yDWMxEFdJU" or // strrchr
"V++UgBtQhn0"; // sceAgcGetDataPacketPayloadAddress
private unsafe ulong DispatchTrivialLeaf(
CpuContext cpuContext,
in ImportStubEntry importStubEntry,
nint argPackPtr,
long dispatchIndex)
{
// Polling loops on the host main thread use the time queries as loop-guard
// boundaries; keep resetting the pattern so skipping the guard here cannot
// turn a legitimate time-polling loop into a forced exit.
if (importStubEntry.IsLoopGuardBoundary && !GuestThreadExecution.IsGuestThread)
{
ResetImportLoopPattern();
}
cpuContext.Rip = importStubEntry.Address;
cpuContext[CpuRegister.Rdi] = *(ulong*)argPackPtr;
cpuContext[CpuRegister.Rsi] = *(ulong*)(argPackPtr + 8);
cpuContext[CpuRegister.Rdx] = *(ulong*)(argPackPtr + 16);
cpuContext[CpuRegister.Rcx] = *(ulong*)(argPackPtr + 24);
cpuContext[CpuRegister.R8] = *(ulong*)(argPackPtr + 32);
cpuContext[CpuRegister.R9] = *(ulong*)(argPackPtr + 40);
cpuContext.ClearRaxWriteFlag();
var returnValue = importStubEntry.Export!.Function(cpuContext);
if (!cpuContext.WasRaxWritten)
{
cpuContext[CpuRegister.Rax] = unchecked((ulong)returnValue);
}
if (returnValue != (int)OrbisGen2Result.ORBIS_GEN2_OK &&
ShouldLogImportResult(importStubEntry.Nid, (OrbisGen2Result)returnValue))
{
Console.Error.WriteLine(
$"[LOADER][WARN] Import#{dispatchIndex} result: {(OrbisGen2Result)returnValue} ({importStubEntry.Nid}) " +
$"rdi=0x{cpuContext[CpuRegister.Rdi]:X16} rsi=0x{cpuContext[CpuRegister.Rsi]:X16} " +
$"ret=0x{*(ulong*)(argPackPtr + 96):X16}");
}
return cpuContext[CpuRegister.Rax];
}
private static bool IsNoBlockLeafImport(string nid) =>
nid is
"8aI7R7WaOlc" or // sceAmprCommandBufferConstructor
@ -1613,12 +1424,7 @@ public sealed partial class DirectExecutionBackend
"xk0AcarP3V4" or // scePadOpen
"yH17Q6NWtVg" or // sceUserServiceGetEvent
"D-CzAxQL0XI" or // sceUserServiceGetPlatformPrivacySetting
"K-jXhbt2gn4" or // scePthreadMutexTrylock
// Hot memory leaves: skip non-NoBlock call-frame bookkeeping on top of TryCopy.
"Q3VBxCXhUHs" or // memcpy
"+P6FRGH4LfA" or // memmove
"DfivPArhucg" or // memcmp
"8zTFvBIAIN8"; // memset
"K-jXhbt2gn4"; // scePthreadMutexTrylock
private bool ShouldLogImportResult(string nid, OrbisGen2Result result)
{
@ -1637,28 +1443,12 @@ public sealed partial class DirectExecutionBackend
var expectedEqueueTimeout =
string.Equals(nid, "fzyMKs9kim0", StringComparison.Ordinal) &&
result == OrbisGen2Result.ORBIS_GEN2_ERROR_TIMED_OUT;
// scePthreadCondTimedwait and sceKernelWaitEventFlag report an elapsed timeout.
var expectedWaitTimeout =
(nid is "BmMjYxmew1w" or "JTvBflhYazQ") &&
result == OrbisGen2Result.ORBIS_GEN2_ERROR_TIMED_OUT;
// scePthreadMutexLock on an error-checking mutex the caller already owns; titles use it
// to build their own recursive locks.
var expectedErrorCheckRelock =
string.Equals(nid, "9UK1vLZQft4", StringComparison.Ordinal) &&
result == OrbisGen2Result.ORBIS_GEN2_ERROR_DEADLOCK;
// scePadReadState on a handle that is not open; titles poll every pad slot.
var expectedPadNotOpen =
string.Equals(nid, "YndgXqQVV7c", StringComparison.Ordinal) &&
resultValue == unchecked((int)0x80920003);
var expectedMutexTrylockBusy =
(nid is "K-jXhbt2gn4" or "upoVrzMHFeE") &&
string.Equals(nid, "K-jXhbt2gn4", StringComparison.Ordinal) &&
result == OrbisGen2Result.ORBIS_GEN2_ERROR_BUSY;
var expectedSemaphoreTrywaitAgain =
string.Equals(nid, "H2a+IN9TP0E", StringComparison.Ordinal) &&
result == OrbisGen2Result.ORBIS_GEN2_ERROR_TRY_AGAIN;
var expectedPollSemaBusy =
string.Equals(nid, "12wOHk8ywb0", StringComparison.Ordinal) &&
result == OrbisGen2Result.ORBIS_GEN2_ERROR_BUSY;
var expectedNetAcceptWouldBlock =
string.Equals(nid, "PIWqhn9oSxc", StringComparison.Ordinal) &&
resultValue == unchecked((int)0x80410123);
@ -1668,22 +1458,14 @@ public sealed partial class DirectExecutionBackend
var expectedPrivacyInvalidParameter =
string.Equals(nid, "D-CzAxQL0XI", StringComparison.Ordinal) &&
resultValue == unchecked((int)0x80960009);
var expectedPlayGoChunkEnumerationEnd =
string.Equals(nid, "uWIYLFkkwqk", StringComparison.Ordinal) &&
resultValue == unchecked((int)0x80B2000C);
if (!expectedFileProbeMiss &&
!expectedTimedWaitTimeout &&
!expectedEqueueTimeout &&
!expectedWaitTimeout &&
!expectedErrorCheckRelock &&
!expectedPadNotOpen &&
!expectedMutexTrylockBusy &&
!expectedSemaphoreTrywaitAgain &&
!expectedPollSemaBusy &&
!expectedNetAcceptWouldBlock &&
!expectedUserServiceNoEvent &&
!expectedPrivacyInvalidParameter &&
!expectedPlayGoChunkEnumerationEnd)
!expectedPrivacyInvalidParameter)
{
return true;
}
@ -1735,7 +1517,7 @@ public sealed partial class DirectExecutionBackend
"8aI7R7WaOlc" or // sceAmprCommandBufferConstructor
"zgXifHT9ErY" or // sceVideoOutIsFlipPending
"V++UgBtQhn0" or // sceAgcGetDataPacketPayloadAddress
"qj7QZpgr9Uw" or // Graphics context-state operation
"qj7QZpgr9Uw" or // Gen5 graphics type-2 packet
"LtTouSCZjHM" or // sceAgcCbNop
"k3GhuSNmBLU" or // sceAgcCbDispatch
"UZbQjYAwwXM" or // sceAgcCbSetShRegistersDirect
@ -1869,20 +1651,6 @@ public sealed partial class DirectExecutionBackend
}
}
// Returns the import straight to the host entry stub, which ends this guest slice.
private unsafe bool TryEndGuestSliceForShutdown(nint argPackPtr)
{
ulong sentinel = ActiveEntryReturnSentinelRip;
if (sentinel < 65536 || !TryPatchActiveGuestReturnSlot(sentinel))
{
return false;
}
*(ulong*)(argPackPtr + 96) = sentinel;
ActiveForcedGuestExit = true;
return true;
}
private unsafe bool TryForceGuestExitToHostStub(nint argPackPtr, long dispatchIndex, ulong returnRip, string nid)
{
ulong num = ActiveEntryReturnSentinelRip;
@ -2013,18 +1781,10 @@ public sealed partial class DirectExecutionBackend
private static bool IsImportLoopGuardBoundary(string nid) =>
nid is
"1jfXLRVzisc" or // sceKernelUsleep
"1j3S3n-tTW4" or // sceKernelGetTscFrequency (polling/time base query)
"WKAXJ4XBPQ4" or // scePthreadCondWait
"BmMjYxmew1w" or // scePthreadCondTimedwait
"Op8TBGY5KHg" or // pthread_cond_wait
"27bAgiJmOh0" or // pthread_cond_timedwait
"Zxa0VhQVTsk" or // sceKernelWaitSema
"n88vx3C5nW8" or // gettimeofday
"lLMT9vJAck0" or // clock_gettime
"-2IRUCO--PM" or // sceKernelReadTsc
"4J2sUJmuHZQ" or // sceKernelGetProcessTime
"fgxnMeTNUtY" or // sceKernelGetProcessTimeCounter
"yH17Q6NWtVg"; // sceUserServiceGetEvent (non-blocking event poll)
"27bAgiJmOh0"; // pthread_cond_timedwait
private void ResetImportLoopPattern()
{
@ -2423,18 +2183,17 @@ public sealed partial class DirectExecutionBackend
{
return false;
}
var runtimeSymbolsByName = Volatile.Read(ref _runtimeSymbolsByName);
if (runtimeSymbolsByName.TryGetValue(symbolName, out var value) && IsRuntimeSymbolAddressUsable(value))
if (_runtimeSymbolsByName.TryGetValue(symbolName, out var value) && IsRuntimeSymbolAddressUsable(value))
{
address = value;
return true;
}
if (symbolName.StartsWith("_", StringComparison.Ordinal) && runtimeSymbolsByName.TryGetValue(symbolName[1..], out value) && IsRuntimeSymbolAddressUsable(value))
if (symbolName.StartsWith("_", StringComparison.Ordinal) && _runtimeSymbolsByName.TryGetValue(symbolName[1..], out value) && IsRuntimeSymbolAddressUsable(value))
{
address = value;
return true;
}
if (runtimeSymbolsByName.TryGetValue("_" + symbolName, out value) && IsRuntimeSymbolAddressUsable(value))
if (_runtimeSymbolsByName.TryGetValue("_" + symbolName, out value) && IsRuntimeSymbolAddressUsable(value))
{
address = value;
return true;

View File

@ -1,51 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System;
using System.Runtime.InteropServices;
namespace SharpEmu.Core.Cpu.Native;
// On macOS the runtime receives EXC_BAD_ACCESS on each of its threads through a Mach exception
// port before the kernel raises SIGSEGV or SIGBUS. It calls any fault in the page holding RSP, or
// the page below it, a stack overflow and aborts, assuming RSP is on a stack it owns. Guest code
// runs on guest stacks, and those pages fault whenever GPU or image write tracking has protected
// them, so a thread running guest code must leave its access faults to the signal handler. The
// handler resolves guest faults and chains every other one to the runtime's own signal handler,
// the same path the runtime uses on Linux.
public sealed unsafe partial class DirectExecutionBackend
{
private const uint ExceptionMaskBadAccess = 1u << 1;
private const int ExceptionDefault = 1;
private const int ThreadStateNone = 13;
[ThreadStatic]
private static bool _guestFaultsUseSignals;
private static int _machExceptionPortWarning;
[DllImport("libSystem.dylib", EntryPoint = "mach_thread_self")]
private static extern uint MachThreadSelf();
[DllImport("libSystem.dylib", EntryPoint = "thread_set_exception_ports")]
private static extern int ThreadSetExceptionPorts(uint thread, uint exceptionMask, uint newPort, int behavior, int newFlavor);
[DllImport("libSystem.dylib", EntryPoint = "mach_port_deallocate")]
private static extern int MachPortDeallocate(uint task, uint name);
private static readonly uint _machTaskSelf = OperatingSystem.IsMacOS()
? (uint)Marshal.ReadInt32(NativeLibrary.GetExport(NativeLibrary.Load("libSystem.dylib"), "mach_task_self_"))
: 0;
private static void RouteGuestAccessFaultsToSignals()
{
if (_guestFaultsUseSignals || !OperatingSystem.IsMacOS())
return;
_guestFaultsUseSignals = true;
var thread = MachThreadSelf();
var result = ThreadSetExceptionPorts(thread, ExceptionMaskBadAccess, 0, ExceptionDefault, ThreadStateNone);
_ = MachPortDeallocate(_machTaskSelf, thread);
if (result != 0 && System.Threading.Interlocked.Exchange(ref _machExceptionPortWarning, 1) == 0)
Console.Error.WriteLine($"[LOADER][WARN] Cannot hand guest access faults to the signal handler: thread_set_exception_ports={result}.");
}
}

View File

@ -29,29 +29,9 @@ public sealed partial class DirectExecutionBackend
private static readonly bool NativeGuestWorkersDisabled =
string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_DISABLE_NATIVE_GUEST_WORKERS"), "1", StringComparison.Ordinal);
// Cap concurrent native-worker Runs. Astro's tbb_thead burst overlaps many
// UnmanagedCallersOnly prologues; a large prewarm + unbounded concurrency
// FailFasts (0xC0000409) mid-storm with no VEH breadcrumb. Pool size and
// in-flight Runs are separate knobs.
private static readonly int NativeWorkerMaxConcurrent = ReadNativeWorkerMaxConcurrent();
private static int ReadNativeWorkerMaxConcurrent()
{
if (int.TryParse(
Environment.GetEnvironmentVariable("SHARPEMU_NATIVE_WORKER_MAX_CONCURRENT"),
out var parsed) &&
parsed > 0)
{
return Math.Clamp(parsed, 1, 64);
}
return 2;
}
private readonly object _nativeWorkerGate = new();
private readonly List<NativeGuestExecutor> _allNativeWorkers = new();
private readonly Stack<NativeGuestExecutor> _idleNativeWorkers = new();
private readonly SemaphoreSlim _nativeWorkerRunLimiter = new(NativeWorkerMaxConcurrent);
private bool _nativeWorkersDisposed;
private int _nativeWorkerCreationFailedLogged;
@ -69,9 +49,6 @@ public sealed partial class DirectExecutionBackend
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint WaitForSingleObject(nint hHandle, uint dwMilliseconds);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool TerminateThread(nint hThread, uint dwExitCode);
// 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.
@ -79,148 +56,40 @@ public sealed partial class DirectExecutionBackend
// Callers set the Active* thread-statics before emitting the stub and read the
// yield/forced-exit flags right after this returns, so the worker outcome is
// copied back into this thread's statics before returning.
private unsafe ulong RunGuestEntryStub(void* entryStub, ulong hostRspSlot, bool requireNativeWorker = false)
private unsafe int RunGuestEntryStub(void* entryStub, ulong hostRspSlot)
{
// Limit in-flight native Runs before renting so the idle pool is not
// drained by threads blocked on the concurrency gate.
_nativeWorkerRunLimiter.Wait();
NativeGuestExecutor? worker = null;
var worker = RentNativeGuestExecutor();
if (worker is null)
{
TlsSetValue(_hostRspSlotTlsIndex, (nint)hostRspSlot);
return CallNativeEntry(entryStub);
}
try
{
// Astro can spawn a burst of tbb_thead while workers are still in
// TerminateThread+respawn. Wait for a native worker — never fall back
// to managed inline (FailFast) and never throw (uncaught throw mid-
// storm was a silent process die).
var maxAttempts = requireNativeWorker ? 500 : 48;
for (var attempt = 0; attempt < maxAttempts; attempt++)
{
worker = RentNativeGuestExecutor();
if (worker is not null)
{
break;
}
if (!requireNativeWorker)
{
break;
}
Thread.Sleep(attempt < 32 ? 1 : 4);
}
if (worker is null)
{
if (requireNativeWorker)
{
var n = Interlocked.Increment(ref _tbbNativeWorkerRefuseCount);
if (n <= 8 || n % 32 == 0)
{
Console.Error.WriteLine(
$"[LOADER][ERROR] tbb_native_worker unavailable #{n} after {maxAttempts} attempts; " +
"skipping run (no managed inline, no throw)");
Console.Error.Flush();
}
_activeGuestThreadYieldRequested = true;
_activeGuestThreadYieldReason = "tbb_native_worker_unavailable";
_activeForcedGuestExit = true;
return 0x80020012UL;
}
TlsSetValue(_hostRspSlotTlsIndex, (nint)hostRspSlot);
return CallNativeEntry(entryStub);
}
try
{
var state = _activeGuestThreadState;
if (LogThreadMode && state is { Name: "tbb_thead" })
{
var n = Interlocked.Increment(ref _tbbNativeRunEnterCount);
if (n <= 12 || n % 64 == 0)
{
Console.Error.WriteLine(
$"[LOADER][INFO] tbb_run_enter #{n} native_tid_pending handle=0x{state.ThreadHandle:X16} " +
$"max_concurrent={NativeWorkerMaxConcurrent}");
Console.Error.Flush();
}
}
var nativeReturn = worker.Run(
_activeCpuContext!,
state,
GuestThreadExecution.CurrentGuestThreadHandle,
_activeEntryReturnSentinelRip,
_activeGuestReturnSlotAddress,
(nint)hostRspSlot,
(nint)entryStub,
state?.AffinityMask ?? 0,
out var yieldRequested,
out var yieldReason,
out var forcedExit);
_activeGuestThreadYieldRequested = yieldRequested;
_activeGuestThreadYieldReason = yieldReason;
_activeForcedGuestExit = forcedExit;
return nativeReturn;
}
finally
{
ReturnNativeGuestExecutor(worker);
}
var state = _activeGuestThreadState;
var nativeReturn = worker.Run(
_activeCpuContext!,
state,
GuestThreadExecution.CurrentGuestThreadHandle,
_activeEntryReturnSentinelRip,
_activeGuestReturnSlotAddress,
(nint)hostRspSlot,
(nint)entryStub,
state?.AffinityMask ?? 0,
out var yieldRequested,
out var yieldReason,
out var forcedExit);
_activeGuestThreadYieldRequested = yieldRequested;
_activeGuestThreadYieldReason = yieldReason;
_activeForcedGuestExit = forcedExit;
return nativeReturn;
}
finally
{
_nativeWorkerRunLimiter.Release();
ReturnNativeGuestExecutor(worker);
}
}
private static int _tbbNativeRunEnterCount;
private static int _tbbNativeWorkerRefuseCount;
internal static int _tbbWorkerPrologueFaultCount;
private void PrewarmNativeGuestWorkers(int count)
{
if (!OperatingSystem.IsWindows() || NativeGuestWorkersDisabled || count <= 0)
{
return;
}
var warmed = new List<NativeGuestExecutor>(count);
for (var i = 0; i < count; i++)
{
var worker = NativeGuestExecutor.TryCreate(this);
if (worker is null)
{
break;
}
warmed.Add(worker);
}
lock (_nativeWorkerGate)
{
if (_nativeWorkersDisposed)
{
foreach (var worker in warmed)
{
worker.Dispose();
}
return;
}
foreach (var worker in warmed)
{
_allNativeWorkers.Add(worker);
_idleNativeWorkers.Push(worker);
}
}
Console.Error.WriteLine(
$"[LOADER][INFO] Native guest workers prewarmed: {warmed.Count}/{count} " +
$"max_concurrent={NativeWorkerMaxConcurrent}");
Console.Error.Flush();
}
private NativeGuestExecutor? RentNativeGuestExecutor()
{
// NativeGuestExecutor emits a Win32 wait loop and creates it with
@ -302,8 +171,8 @@ public sealed partial class DirectExecutionBackend
// loop: WaitForSingleObject(work);
// if (*stopFlag) { SetEvent(done); ExitThread(0); }
// rax = RunPrologue(self); // managed: binds per-run ambient, returns stub
// if (rax != 0) rax = rax(); // guest entry stub — zero managed frames below
// RunEpilogue(self, rax); // managed: captures outcome, restores ambient
// if (rax != 0) eax = rax(); // guest entry stub — zero managed frames below
// RunEpilogue(self, eax); // managed: captures outcome, restores ambient
// SetEvent(done); goto loop;
//
// Workers carry no per-guest identity of their own: the prologue rebinds guest TLS,
@ -348,7 +217,7 @@ public sealed partial class DirectExecutionBackend
private nint _runHostRspSlot;
private nint _runEntryStub;
private ulong _runAffinityMask;
private ulong _runNativeResult;
private int _runNativeResult;
private bool _runYieldRequested;
private string? _runYieldReason;
private bool _runForcedExit;
@ -425,7 +294,7 @@ public sealed partial class DirectExecutionBackend
}
var prologuePtr = (nint)(delegate* unmanaged<nint, nint>)&RunPrologue;
var epiloguePtr = (nint)(delegate* unmanaged<nint, ulong, void>)&RunEpilogue;
var epiloguePtr = (nint)(delegate* unmanaged<nint, int, void>)&RunEpilogue;
var executorHandle = GCHandle.ToIntPtr(_selfHandle);
nint workHandle;
nint doneHandle;
@ -504,9 +373,9 @@ public sealed partial class DirectExecutionBackend
Emit(0x0F); Emit(0x84); // je skipEntry
int skipJump = offset;
offset += sizeof(int);
EmitCallRax(); // guest entry stub -> rax
EmitCallRax(); // guest entry stub -> eax
int skipEntryOffset = offset;
Emit(0x48); Emit(0x89); Emit(0xC2); // mov rdx, rax
Emit(0x89); Emit(0xC2); // mov edx, eax
EmitMovRcxImm64((ulong)executorHandle);
EmitMovRaxImm64((ulong)epiloguePtr);
EmitCallRax();
@ -531,22 +400,6 @@ public sealed partial class DirectExecutionBackend
return false;
}
FlushInstructionCache(GetCurrentProcess(), _loopStub, LoopStubSize);
return StartWorkerThread();
}
private bool RestartWorkerThread()
{
if (_loopStub == null || _controlBlock == null)
{
return false;
}
*(int*)_controlBlock = 0;
return StartWorkerThread();
}
private bool StartWorkerThread()
{
_threadHandle = CreateThread(
0,
WorkerStackReservation,
@ -565,7 +418,7 @@ public sealed partial class DirectExecutionBackend
return true;
}
public ulong Run(
public int Run(
CpuContext context,
GuestThreadState? state,
ulong guestThreadHandle,
@ -592,49 +445,6 @@ public sealed partial class DirectExecutionBackend
_runForcedExit = false;
SignalWorkAvailable();
WaitWorkCompleted();
// Normal path: RunEpilogue/ExitRun clears _entered before SetEvent(done).
// TBB abort stub SetEvent's without ExitRun — _entered stays true.
if (_entered)
{
var waitRc = WaitForSingleObject(_threadHandle, 500u);
Console.Error.WriteLine(
$"[LOADER][WARN] Native guest worker tid={_nativeThreadId} aborted during run; " +
$"wait_rc=0x{waitRc:X8} respawning");
Console.Error.Flush();
if (_runState is { } abortedState)
{
_ = GuestThreadExecution.NotifyGuestThreadAbandoned(
abortedState.ThreadHandle,
"tbb_worker_abort");
Volatile.Write(ref abortedState.HostThreadId, _prevHostThreadId);
}
_entered = false;
if (_threadHandle != 0)
{
// Abort stub parks (no ExitThread). Force-kill the parked OS
// thread so we can recreate the loop without process teardown.
if (waitRc != 0u)
{
_ = TerminateThread(_threadHandle, unchecked((uint)(-1)));
_ = WaitForSingleObject(_threadHandle, 1000u);
}
CloseHandle(_threadHandle);
_threadHandle = 0;
_nativeThreadId = 0;
}
if (!RestartWorkerThread())
{
_runPrologueFailed = true;
}
else
{
_runPrologueFailed = false;
_runForcedExit = true;
_runNativeResult = 0;
}
}
_runContext = null;
_runState = null;
yieldRequested = _runYieldRequested;
@ -642,22 +452,7 @@ public sealed partial class DirectExecutionBackend
forcedExit = _runForcedExit;
if (_runPrologueFailed)
{
// Never throw out of the native-worker rent path: an uncaught
// exception mid-TBB storm kills the process with no FailFast
// breadcrumb.
var n = Interlocked.Increment(ref _tbbWorkerPrologueFaultCount);
if (n <= 8 || n % 32 == 0)
{
Console.Error.WriteLine(
$"[LOADER][ERROR] tbb_worker prologue fault #{n}; soft-fail run " +
$"(tid={_nativeThreadId})");
Console.Error.Flush();
}
yieldRequested = true;
yieldReason = "tbb_worker_prologue_fault";
forcedExit = true;
return 0x80020012UL;
throw new InvalidOperationException("Native guest worker failed to bind the run ambient (prologue fault)");
}
return _runNativeResult;
}
@ -707,7 +502,7 @@ public sealed partial class DirectExecutionBackend
}
[UnmanagedCallersOnly]
private static void RunEpilogue(nint executorHandle, ulong nativeResult)
private static void RunEpilogue(nint executorHandle, int nativeResult)
{
try
{
@ -750,20 +545,7 @@ public sealed partial class DirectExecutionBackend
_activeGuestThreadYieldReason = null;
_activeGuestThreadState = _runState;
backend.BindTlsBase(_runContext!);
RouteGuestAccessFaultsToSignals();
TlsSetValue(backend._hostRspSlotTlsIndex, _runHostRspSlot);
if (backend._workerDoneEventTlsIndex != uint.MaxValue)
{
nint doneHandle = OperatingSystem.IsWindows()
? _workCompleted!.SafeWaitHandle.DangerousGetHandle()
: _doneSemaphore;
TlsSetValue(backend._workerDoneEventTlsIndex, doneHandle);
}
if (backend._tbbAbortEligibleTlsIndex != uint.MaxValue)
{
nint eligible = _runState is { Name: "tbb_thead" } ? 1 : 0;
TlsSetValue(backend._tbbAbortEligibleTlsIndex, eligible);
}
if (_runState is { } state)
{
_prevHostThreadId = Volatile.Read(ref state.HostThreadId);
@ -782,7 +564,7 @@ public sealed partial class DirectExecutionBackend
return _runEntryStub;
}
private void ExitRun(ulong nativeResult)
private void ExitRun(int nativeResult)
{
_runNativeResult = nativeResult;
_runYieldRequested = _activeGuestThreadYieldRequested;
@ -798,14 +580,6 @@ public sealed partial class DirectExecutionBackend
Volatile.Write(ref state.HostThreadId, _prevHostThreadId);
}
TlsSetValue(_backend._hostRspSlotTlsIndex, _prevHostRspSlot);
if (_backend._workerDoneEventTlsIndex != uint.MaxValue)
{
TlsSetValue(_backend._workerDoneEventTlsIndex, 0);
}
if (_backend._tbbAbortEligibleTlsIndex != uint.MaxValue)
{
TlsSetValue(_backend._tbbAbortEligibleTlsIndex, 0);
}
GuestThreadExecution.RestoreGuestThread(_prevGuestThreadHandle);
_activeExecutionBackend = _prevBackend;
_activeCpuContext = _prevContext;
@ -822,7 +596,7 @@ public sealed partial class DirectExecutionBackend
if (LogThreadMode)
{
TraceThreadMode(
$"worker_exit guest=0x{_runGuestThreadHandle:X16} result=0x{nativeResult:X16} yield={_runYieldRequested}");
$"worker_exit guest=0x{_runGuestThreadHandle:X16} result=0x{nativeResult:X8} yield={_runYieldRequested}");
}
}

View File

@ -1,140 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System;
using System.Runtime.InteropServices;
using Iced.Intel;
using SharpEmu.HLE;
using static Iced.Intel.AssemblerRegisters;
namespace SharpEmu.Core.Cpu.Native;
// Guest faults are delivered on the guest stack. The runtime only knows the thread's own stack,
// so managed code that runs on the guest stack can make a garbage collection misread the frames
// of that thread. Windows swaps the stack bounds in the TEB while guest code runs; POSIX cannot,
// so the signal handler moves to the host stack below the frames that entered guest code first.
public sealed unsafe partial class DirectExecutionBackend
{
// Host stack below the saved host RSP that is still treated as the host frames in use.
private const ulong HostStackSearchBytes = 0x100_0000;
private const int SignalStackGap = 0x1000;
// [0] the host RSP TLS slot (uint.MaxValue while unknown), [8] the Win64 TlsGetValue stub.
private static nint _signalStackCells;
private static unsafe nint CreatePosixSignalTrampoline()
{
_signalStackCells = (nint)NativeMemory.AllocZeroed(16);
*(uint*)_signalStackCells = uint.MaxValue;
var a = new Assembler(64);
var direct = a.CreateLabel();
var call = a.CreateLabel();
var done = a.CreateLabel();
a.push(rbx);
a.push(r12);
a.push(r13);
a.push(r14);
a.push(r15);
a.mov(r12d, edi);
a.mov(r13, rsi);
a.mov(r14, rdx);
a.mov(rbx, rsp);
// The saved host RSP of this thread, when it entered guest code.
a.mov(rax, (ulong)_signalStackCells);
a.mov(ecx, __dword_ptr[rax]);
a.cmp(ecx, -1);
a.je(direct);
a.mov(rax, __qword_ptr[rax + 8]);
a.test(rax, rax);
a.je(direct);
a.sub(rsp, 48);
a.call(rax);
a.add(rsp, 48);
a.test(rax, rax);
a.je(direct);
a.mov(r15, __qword_ptr[rax]);
a.test(r15, r15);
a.je(direct);
// Already on the host stack below the saved RSP: an import or host code faulted.
a.cmp(rbx, r15);
a.jae(call);
a.mov(rax, r15);
a.sub(rax, rbx);
a.cmp(rax, (int)HostStackSearchBytes);
a.jb(direct);
a.Label(ref call);
a.lea(rsp, __[r15 - SignalStackGap]);
a.and(rsp, -16);
a.Label(ref direct);
a.mov(edi, r12d);
a.mov(rsi, r13);
a.mov(rdx, r14);
a.mov(rax, (ulong)(nint)(delegate* unmanaged<int, nint, nint, void>)&HandlePosixSignal);
a.call(rax);
a.Label(ref done);
a.mov(rsp, rbx);
a.pop(r15);
a.pop(r14);
a.pop(r13);
a.pop(r12);
a.pop(rbx);
a.ret();
var page = (byte*)HostMemory.Alloc(null, 4096, HostMemory.MEM_COMMIT | HostMemory.MEM_RESERVE, HostMemory.PAGE_EXECUTE_READWRITE);
if (page == null)
{
throw new OutOfMemoryException("Failed to allocate the POSIX signal trampoline page");
}
var writer = new SpanCodeWriter(new Span<byte>(page, 4096));
a.Assemble(writer, (ulong)page);
if (!HostMemory.Protect(page, 4096, HostMemory.PAGE_EXECUTE_READ, out _))
{
throw new InvalidOperationException("Failed to protect the POSIX signal trampoline page");
}
return (nint)page;
}
private unsafe void PublishSignalStackState()
{
if (_signalStackCells == 0)
{
return;
}
*(nint*)(_signalStackCells + 8) = _tlsGetValueAddress;
*(uint*)_signalStackCells = _hostRspSlotTlsIndex;
}
private sealed unsafe class SpanCodeWriter : CodeWriter
{
private readonly byte* _start;
private readonly int _length;
private int _offset;
public SpanCodeWriter(Span<byte> destination)
{
fixed (byte* start = destination)
{
_start = start;
}
_length = destination.Length;
}
public override void WriteByte(byte value)
{
if (_offset >= _length)
{
throw new InvalidOperationException("The POSIX signal trampoline does not fit its page.");
}
_start[_offset++] = value;
}
}
}

View File

@ -5,7 +5,6 @@ using System;
using System.Runtime.InteropServices;
using System.Threading;
using SharpEmu.HLE;
using SharpEmu.HLE.GpuMemory;
namespace SharpEmu.Core.Cpu.Native;
@ -24,7 +23,6 @@ public sealed unsafe partial class DirectExecutionBackend
private const int PosixSigIll = 4;
private const int PosixSigTrap = 5;
private const int PosixSigAbort = 6;
private const int PosixSigFpe = 8;
private const int PosixSigSegv = 11;
private static readonly int PosixSigBus = OperatingSystem.IsMacOS() ? 10 : 7;
@ -47,10 +45,6 @@ public sealed unsafe partial class DirectExecutionBackend
// registers in gregs[23]. Rosetta 2 delivers the regular x86-64 layout
// to translated processes.
private const int DarwinUcontextMcontextOffset = 48;
private const int DarwinUserContextMachineContextSizeOffset = 40;
// Darwin stores vector registers at the same offset in both signal frame formats.
// The system headers i386/_mcontext.h and mach/i386/_structs.h define this offset.
private const int DarwinMachineContextVectorRegistersOffset = 352;
private const int DarwinMcontextErrOffset = 4;
private const int DarwinMcontextFaultAddressOffset = 8;
private const int LinuxUcontextGregsOffset = 40;
@ -79,7 +73,6 @@ public sealed unsafe partial class DirectExecutionBackend
private static DirectExecutionBackend? _posixSignalBackend;
private static bool _posixSignalHandlersInstalled;
private static nint _posixSignalTrampoline;
private static bool _posixRawRecoveryEnabled;
private static bool _posixSignalWarmup;
private static readonly nint[] _posixPreviousActions = new nint[32];
@ -91,8 +84,12 @@ public sealed unsafe partial class DirectExecutionBackend
[ThreadStatic]
private static int _posixSignalHandlerDepth;
// True when the signal context contains the current vector register values.
// Copy changes back to these registers before the guest continues.
// True while the current thread's in-flight POSIX fault carries the real
// XMM registers in the CONTEXT scratch buffer and writes to them will
// reach the mcontext on resume. Gates recovery paths (SSE4a EXTRQ/
// INSERTQ) that would otherwise compute results from a zeroed XMM area
// and silently discard what they "wrote". Darwin is not bridged yet, so
// the flag stays false there.
[ThreadStatic]
private static bool _posixXmmContextBridged;
@ -107,7 +104,6 @@ public sealed unsafe partial class DirectExecutionBackend
_posixSignalBackend = this;
if (_posixSignalHandlersInstalled)
{
PublishSignalStackState();
return;
}
@ -121,20 +117,17 @@ public sealed unsafe partial class DirectExecutionBackend
WarmUpPosixSignalPath();
SharpEmu.HLE.GuestImageWriteTracker.WarmUp();
_posixSignalTrampoline = CreatePosixSignalTrampoline();
PublishSignalStackState();
if (!InstallPosixSignalHandler(PosixSigSegv) ||
!InstallPosixSignalHandler(PosixSigBus) ||
!InstallPosixSignalHandler(PosixSigIll) ||
!InstallPosixSignalHandler(PosixSigTrap) ||
!InstallPosixSignalHandler(PosixSigAbort) ||
!InstallPosixSignalHandler(PosixSigFpe))
!InstallPosixSignalHandler(PosixSigAbort))
{
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/SIGFPE)");
Console.Error.WriteLine("[LOADER][INFO] POSIX signal exception bridge installed (SIGSEGV/SIGBUS/SIGILL)");
}
/// <summary>
@ -148,23 +141,19 @@ public sealed unsafe partial class DirectExecutionBackend
/// </summary>
private void WarmUpPosixSignalPath()
{
byte* testUserContext = stackalloc byte[512];
new Span<byte>(testUserContext, 512).Clear();
byte* testMachineContext = stackalloc byte[1024];
new Span<byte>(testMachineContext, 1024).Clear();
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**)(testUserContext + DarwinUcontextMcontextOffset) = testMachineContext;
*(ulong*)(testUserContext + DarwinUserContextMachineContextSizeOffset) = 1024;
// Load the Mach memory functions before the first signal uses them.
byte readProbe = 0;
_ = TryReadMacOsMemory((ulong)testMachineContext, &readProbe, 1);
*(byte**)(fakeUcontext + DarwinUcontextMcontextOffset) = fakeMcontext;
}
_posixSignalWarmup = true;
try
{
((delegate* unmanaged<int, nint, nint, void>)&HandlePosixSignal)(PosixSigSegv, 0, (nint)testUserContext);
((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
@ -198,7 +187,7 @@ public sealed unsafe partial class DirectExecutionBackend
{
byte* action = stackalloc byte[PosixSigactionSize];
new Span<byte>(action, PosixSigactionSize).Clear();
*(nint*)action = _posixSignalTrampoline;
*(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
@ -245,7 +234,6 @@ public sealed unsafe partial class DirectExecutionBackend
// address (safe for host and guest threads alike) and must resume
// the faulting write immediately after restoring write access.
if (signal != PosixSigIll &&
signal != PosixSigFpe &&
siginfo != 0 &&
SharpEmu.HLE.GuestImageWriteTracker.TryHandleWriteFault(
*(ulong*)((byte*)siginfo + PosixSigInfoAddressOffset)))
@ -253,17 +241,6 @@ public sealed unsafe partial class DirectExecutionBackend
return;
}
// GPU-tracked pages fault on every first CPU access after the GPU or an upload used them,
// thousands of times a second in a frame. Resolving them needs only the address and the
// access kind, so they skip the Win64 context conversion and the other handlers.
if (PosixGpuFaultFastPath && !_posixSignalWarmup &&
(signal == PosixSigSegv || signal == PosixSigBus) &&
siginfo != 0 &&
TryResolvePosixGpuFault(siginfo, ucontext))
{
return;
}
if (TryHandlePosixFault(signal, siginfo, ucontext))
{
return;
@ -281,28 +258,6 @@ public sealed unsafe partial class DirectExecutionBackend
ChainPreviousPosixAction(signal, siginfo, ucontext);
}
private static readonly bool PosixGpuFaultFastPath =
Environment.GetEnvironmentVariable("SHARPEMU_POSIX_GPU_FAULT_FAST_PATH") != "0";
private static bool TryResolvePosixGpuFault(nint siginfo, nint ucontext)
{
byte* registers = GetPosixRegisterBase(ucontext);
if (registers == null)
{
return false;
}
ulong faultAddress = GetPosixFaultAddress(siginfo, registers);
ulong rip = *(ulong*)(registers + PosixRegisterOffsets[16]);
var kind = GetPosixAccessType(registers, faultAddress, rip) switch
{
0 => FaultKind.Read,
1 => FaultKind.Write,
_ => FaultKind.Unknown,
};
return kind != FaultKind.Unknown && GuestGpuMemoryHook.TryResolveFault(kind, faultAddress);
}
private static bool TryHandlePosixFault(int signal, nint siginfo, nint ucontext)
{
byte* registers = GetPosixRegisterBase(ucontext);
@ -319,18 +274,25 @@ public sealed unsafe partial class DirectExecutionBackend
WriteCtxU64(contextRecord, CTX_RAX + i * 8, *(ulong*)(registers + offsets[i]));
}
// Copy the vector registers that instruction recovery can change.
// Keep all other floating-point state unchanged.
byte* vectorRegisters = GetSignalVectorRegisterAddress(ucontext, registers);
if (vectorRegisters != null)
// Bridge the XMM registers alongside the GPRs where the layout is
// known: on Linux the fpstate pointer and FXSAVE image are kernel
// ABI, so recovery paths that read or write XMM state (SSE4a
// EXTRQ/INSERTQ) see the live registers and their writes reach the
// guest through sigreturn.
byte* fpstate = null;
if (OperatingSystem.IsLinux())
{
Buffer.MemoryCopy(
vectorRegisters,
contextRecord + Win64ContextXmm0Offset,
XmmBlockSize,
XmmBlockSize);
fpstate = *(byte**)(registers + LinuxGregsFpstateOffset);
if (fpstate != null)
{
Buffer.MemoryCopy(
fpstate + FxsaveXmmOffset,
contextRecord + Win64ContextXmm0Offset,
XmmBlockSize,
XmmBlockSize);
}
}
_posixXmmContextBridged = vectorRegisters != null;
_posixXmmContextBridged = fpstate != null;
EXCEPTION_RECORD record = default;
record.ExceptionAddress = (void*)ReadCtxU64(contextRecord, CTX_RIP);
@ -346,11 +308,6 @@ public sealed unsafe partial class DirectExecutionBackend
{
record.ExceptionCode = 1073741845u;
}
else if (signal == PosixSigFpe)
{
// STATUS_INTEGER_DIVIDE_BY_ZERO: #DE from div/idiv (zero divisor or quotient overflow).
record.ExceptionCode = 3221225620u;
}
else
{
ulong faultAddress = GetPosixFaultAddress(siginfo, registers);
@ -402,36 +359,17 @@ public sealed unsafe partial class DirectExecutionBackend
{
*(ulong*)(registers + offsets[i]) = ReadCtxU64(contextRecord, CTX_RAX + i * 8);
}
if (vectorRegisters != null)
if (fpstate != null)
{
Buffer.MemoryCopy(
contextRecord + Win64ContextXmm0Offset,
vectorRegisters,
fpstate + FxsaveXmmOffset,
XmmBlockSize,
XmmBlockSize);
}
return true;
}
private static byte* GetSignalVectorRegisterAddress(nint userContextAddress, byte* machineContext)
{
if (OperatingSystem.IsMacOS())
{
var machineContextSize = *(ulong*)((byte*)userContextAddress + DarwinUserContextMachineContextSizeOffset);
return machineContextSize >= DarwinMachineContextVectorRegistersOffset + XmmBlockSize
? machineContext + DarwinMachineContextVectorRegistersOffset
: null;
}
if (OperatingSystem.IsLinux())
{
byte* floatingPointState = *(byte**)(machineContext + LinuxGregsFpstateOffset);
return floatingPointState != null ? floatingPointState + FxsaveXmmOffset : null;
}
return null;
}
private static byte* GetPosixRegisterBase(nint ucontext)
{
if (ucontext == 0)

View File

@ -1,107 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Buffers.Binary;
using System.Threading;
using Iced.Intel;
using SharpEmu.Core.Cpu.Emulation;
namespace SharpEmu.Core.Cpu.Native;
// The PS5 CPU has the SHA extensions and titles use them without a CPUID check.
// Rosetta 2 does not translate them, so they raise #UD on Apple Silicon hosts.
public sealed partial class DirectExecutionBackend
{
private static int _shaSoftwareFallbackAnnounced;
private static long _shaInstructionsEmulated;
private unsafe bool TryRecoverShaInstruction(void* contextRecord, ulong rip)
{
if (!OperatingSystem.IsWindows() && !_posixXmmContextBridged ||
!TryReadFaultingInstruction(rip, out var instruction))
{
return false;
}
switch (instruction.Mnemonic)
{
case Mnemonic.Sha1rnds4:
case Mnemonic.Sha1nexte:
case Mnemonic.Sha1msg1:
case Mnemonic.Sha1msg2:
case Mnemonic.Sha256rnds2:
case Mnemonic.Sha256msg1:
case Mnemonic.Sha256msg2:
break;
default:
return false;
}
if (instruction.GetOpKind(0) != OpKind.Register ||
!TryGetXmmOffset(instruction.GetOpRegister(0), out var destOffset) ||
!TryReadXmmOperand(contextRecord, in instruction, 1, out var source2))
{
return false;
}
var source1 = ReadCtxXmm(contextRecord, destOffset);
var result = instruction.Mnemonic switch
{
Mnemonic.Sha1rnds4 => ShaInstructionEmulator.Sha1Rnds4(source1, source2, instruction.Immediate8),
Mnemonic.Sha1nexte => ShaInstructionEmulator.Sha1Nexte(source1, source2),
Mnemonic.Sha1msg1 => ShaInstructionEmulator.Sha1Msg1(source1, source2),
Mnemonic.Sha1msg2 => ShaInstructionEmulator.Sha1Msg2(source1, source2),
Mnemonic.Sha256rnds2 => ShaInstructionEmulator.Sha256Rnds2(
source1, source2, ReadCtxXmm(contextRecord, Win64ContextXmm0Offset)),
Mnemonic.Sha256msg1 => ShaInstructionEmulator.Sha256Msg1(source1, source2),
_ => ShaInstructionEmulator.Sha256Msg2(source1, source2),
};
WriteCtxU64(contextRecord, destOffset, (ulong)result);
WriteCtxU64(contextRecord, destOffset + 8, (ulong)(result >> 64));
WriteCtxU64(contextRecord, CTX_RIP, rip + (ulong)instruction.Length);
Interlocked.Increment(ref _shaInstructionsEmulated);
if (Interlocked.Exchange(ref _shaSoftwareFallbackAnnounced, 1) == 0)
{
Console.Error.WriteLine(
"[LOADER][INFO] Host lacks the SHA extensions used by the guest; " +
"emulating those instructions in software.");
}
return true;
}
private unsafe bool TryReadXmmOperand(void* contextRecord, in Instruction instruction, int operandIndex, out UInt128 value)
{
value = 0;
switch (instruction.GetOpKind(operandIndex))
{
case OpKind.Register:
if (!TryGetXmmOffset(instruction.GetOpRegister(operandIndex), out var offset))
{
return false;
}
value = ReadCtxXmm(contextRecord, offset);
return true;
case OpKind.Memory:
var buffer = new byte[16];
if (!TryComputeMemoryAddress(contextRecord, in instruction, out var address) ||
!TryReadHostBytes(address, buffer))
{
return false;
}
value = BinaryPrimitives.ReadUInt128LittleEndian(buffer);
return true;
default:
return false;
}
}
private static unsafe UInt128 ReadCtxXmm(void* contextRecord, int offset) =>
new(ReadCtxU64(contextRecord, offset + 8), ReadCtxU64(contextRecord, offset));
}

View File

@ -1,206 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Runtime.InteropServices;
namespace SharpEmu.Core.Cpu.Native;
public sealed partial class DirectExecutionBackend
{
private const int HostStackStateBytes = 3 * sizeof(ulong);
internal static unsafe bool TryGetGuestStackBounds(ulong stackPointer, out ulong bottom, out ulong top)
{
if (OperatingSystem.IsWindows() &&
QueryVirtualMemoryInformation(-1, (void*)stackPointer, 0, out var allocation,
(nuint)sizeof(StackMemoryRegionInformation), null) != 0 &&
((allocation.Flags & 1) == 0 || allocation.CommitSize == allocation.RegionSize) &&
allocation.RegionSize != 0 && allocation.RegionSize <= ulong.MaxValue - allocation.AllocationBase &&
stackPointer >= allocation.AllocationBase && stackPointer - allocation.AllocationBase < allocation.RegionSize)
{
bottom = allocation.AllocationBase;
top = bottom + allocation.RegionSize;
return true;
}
bottom = top = 0;
var queried = VirtualQuery((void*)stackPointer, out var region, (nuint)sizeof(MEMORY_BASIC_INFORMATION64));
if (queried == 0 ||
region.State != 0x1000 || region.RegionSize == 0 || region.RegionSize > ulong.MaxValue - region.BaseAddress)
{
return false;
}
bottom = region.BaseAddress;
top = region.BaseAddress + region.RegionSize;
return stackPointer >= bottom && stackPointer < top;
}
private static unsafe void EmitStackBound(byte* code, ref int offset, byte register, uint field, bool store)
{
EmitByte(code, ref offset, 0x65);
EmitByte(code, ref offset, (byte)(0x48 | (register >= 8 ? 4 : 0)));
EmitByte(code, ref offset, store ? (byte)0x89 : (byte)0x8B);
EmitByte(code, ref offset, (byte)(0x04 | ((register & 7) << 3)));
EmitByte(code, ref offset, 0x25);
EmitUInt32(code, ref offset, field);
}
// Fiber switches replace the guest stack without passing through a guest-entry stub, so the
// context-transfer stub keeps the Windows TEB bounds in sync from the target state in R11
// (stack top at +160, bottom at +168). Only Windows keeps stack bounds at gs:[8]/gs:[16]: on
// macOS gs addresses the pthread TSD, where those slots hold errno's address and another key.
// Writing a fiber's bounds there nulled errno, and the next failed libc call on the thread
// crashed reading it (Demon's Souls, about 10 s into boot).
private static unsafe void EmitFiberStackBounds(byte* code, ref int offset)
{
if (!OperatingSystem.IsWindows()) return;
ReadOnlySpan<byte> loadTop = [0x4D, 0x8B, 0x93, 160, 0, 0, 0]; // mov r10, [r11+160]
foreach (var value in loadTop) EmitByte(code, ref offset, value);
EmitStackBound(code, ref offset, 10, 8, store: true);
ReadOnlySpan<byte> loadBottom = [0x4D, 0x8B, 0x93, 168, 0, 0, 0]; // mov r10, [r11+168]
foreach (var value in loadBottom) EmitByte(code, ref offset, value);
EmitStackBound(code, ref offset, 10, 16, store: true);
}
// Test hook: the bytes the fiber stack-bounds sync emits on this host.
internal static unsafe byte[] EmitFiberStackBoundsForTest()
{
var buffer = new byte[64];
var offset = 0;
fixed (byte* code = buffer)
{
EmitFiberStackBounds(code, ref offset);
}
return buffer[..offset];
}
// R10 points to the entry state. R11 is scratch; RAX remains unchanged.
private static unsafe void EmitHostStackBounds(byte* code, ref int offset, bool save)
{
if (!OperatingSystem.IsWindows()) return;
for (byte field = 8; field <= 16; field += 8)
{
if (save) EmitStackBound(code, ref offset, 11, field, store: false);
EmitByte(code, ref offset, 0x4D);
EmitByte(code, ref offset, save ? (byte)0x89 : (byte)0x8B);
EmitByte(code, ref offset, 0x5A);
EmitByte(code, ref offset, field);
if (!save) EmitStackBound(code, ref offset, 11, field, store: true);
}
}
private static unsafe void EmitGuestStackBounds(byte* code, ref int offset, ulong stackPointer)
{
if (!OperatingSystem.IsWindows()) return;
if (!TryGetGuestStackBounds(stackPointer, out var bottom, out var top))
{
throw new InvalidOperationException("Guest stack has no committed host mapping.");
}
EmitHostStackBounds(code, ref offset, save: true);
for (uint field = 8; field <= 16; field += 8)
{
EmitByte(code, ref offset, 0x49);
EmitByte(code, ref offset, 0xBB);
*(ulong*)(code + offset) = field == 8 ? top : bottom;
offset += sizeof(ulong);
EmitStackBound(code, ref offset, 11, field, store: true);
}
}
private static unsafe void EmitSavedStackBounds(byte* code, ref int offset, bool restore)
{
if (!OperatingSystem.IsWindows()) return;
EmitStackBound(code, ref offset, 14, 8, restore);
EmitStackBound(code, ref offset, 15, 16, restore);
}
private unsafe void EmitExceptionHostStackBounds(byte* code, ref int offset)
{
EmitSavedStackBounds(code, ref offset, restore: false);
ReadOnlySpan<byte> reserve = [0x48, 0x83, 0xEC, 0x28, 0xB9];
foreach (var value in reserve) EmitByte(code, ref offset, value);
EmitUInt32(code, ref offset, _hostRspSlotTlsIndex);
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0xB8);
*(nint*)(code + offset) = _tlsGetValueAddress;
offset += sizeof(nint);
ReadOnlySpan<byte> lookup = [0xFF, 0xD0, 0x48, 0x83, 0xC4, 0x28, 0x48, 0x85, 0xC0, 0x0F, 0x84];
foreach (var value in lookup) EmitByte(code, ref offset, value);
var missingState = offset;
EmitUInt32(code, ref offset, 0);
// The state is zeroed at allocation; bounds the entry stub has not saved yet stay untouched.
ReadOnlySpan<byte> unsaved = [0x48, 0x83, 0x78, 0x08, 0x00, 0x0F, 0x84];
foreach (var value in unsaved) EmitByte(code, ref offset, value);
var missingBounds = offset;
EmitUInt32(code, ref offset, 0);
EmitByte(code, ref offset, 0x49); EmitByte(code, ref offset, 0x89); EmitByte(code, ref offset, 0xC2);
// A host fault already has live bounds. Do not replace a grown limit with an old one.
ReadOnlySpan<byte> sameStack = [0x4C, 0x3B, 0x70, 0x08, 0x0F, 0x85];
foreach (var value in sameStack) EmitByte(code, ref offset, value);
var guestStack = offset;
EmitUInt32(code, ref offset, 0);
EmitHostStackBounds(code, ref offset, save: true);
EmitByte(code, ref offset, 0xE9);
var hostStack = offset;
EmitUInt32(code, ref offset, 0);
*(int*)(code + guestStack) = offset - guestStack - sizeof(int);
EmitHostStackBounds(code, ref offset, save: false);
*(int*)(code + hostStack) = offset - hostStack - sizeof(int);
*(int*)(code + missingState) = offset - missingState - sizeof(int);
*(int*)(code + missingBounds) = offset - missingBounds - sizeof(int);
}
[UnmanagedCallersOnly]
private static unsafe int SelectExceptionStackBounds(void* exceptionInfo, int disposition, ulong* bounds)
{
if (disposition != -1) return disposition;
var context = ((EXCEPTION_POINTERS*)exceptionInfo)->ContextRecord;
if (context == null) return 0;
var stackPointer = ReadCtxU64(context, 152);
if (stackPointer >= bounds[1] && stackPointer < bounds[0]) return disposition;
GetCurrentThreadStackLimits(out var nativeBottom, out var nativeTop);
if (stackPointer >= nativeBottom && stackPointer < nativeTop)
{
bounds[0] = nativeTop;
bounds[1] = nativeBottom;
return disposition;
}
if (!TryGetGuestStackBounds(stackPointer, out var bottom, out var top)) return 0;
bounds[0] = top;
bounds[1] = bottom;
return disposition;
}
private static unsafe void EmitExceptionStackSelection(byte* code, ref int offset)
{
// The caller reserves 72 bytes: ABI home space and two stack bounds.
ReadOnlySpan<byte> arguments = [0x4C, 0x89, 0x74, 0x24, 0x28, 0x4C, 0x89, 0x7C, 0x24, 0x30,
0x89, 0xC2, 0x4C, 0x89, 0xE9, 0x4C, 0x8D, 0x44, 0x24, 0x28, 0x48, 0xB8];
foreach (var value in arguments) EmitByte(code, ref offset, value);
*(nint*)(code + offset) = (nint)(delegate* unmanaged<void*, int, ulong*, int>)&SelectExceptionStackBounds;
offset += sizeof(nint);
ReadOnlySpan<byte> result = [0xFF, 0xD0, 0x4C, 0x8B, 0x74, 0x24, 0x28, 0x4C, 0x8B, 0x7C, 0x24, 0x30];
foreach (var value in result) EmitByte(code, ref offset, value);
}
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern void GetCurrentThreadStackLimits(out ulong lowLimit, out ulong highLimit);
[StructLayout(LayoutKind.Sequential)]
private struct StackMemoryRegionInformation
{
public ulong AllocationBase;
public uint AllocationProtect;
public uint Flags;
public ulong RegionSize;
public ulong CommitSize;
}
[DllImport("api-ms-win-core-memory-l1-1-4.dll", ExactSpelling = true)]
private static extern unsafe int QueryVirtualMemoryInformation(nint process, void* address, int informationClass,
out StackMemoryRegionInformation information, nuint informationSize, nuint* returnSize);
}

View File

@ -1,182 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace SharpEmu.Core.Cpu.Native;
public sealed unsafe partial class DirectExecutionBackend
{
private SafeWaitHandle? _mainExecutionThreadHandle;
// One immutable code page serves all diagnostic samples for the process lifetime.
private static readonly Lazy<ThreadContextCaptureCode> ThreadCaptureCode = new(() => new());
private sealed class ThreadContextCaptureCode : SafeHandle
{
public override bool IsInvalid => handle == 0;
public ThreadContextCaptureCode() : base(0, ownsHandle: true)
{
var kernelModule = GetModuleHandle("kernel32.dll");
var suspendAddress = GetProcAddress(kernelModule, "SuspendThread");
var contextAddress = GetProcAddress(kernelModule, "GetThreadContext");
var resumeAddress = GetProcAddress(kernelModule, "ResumeThread");
if (suspendAddress == 0 || contextAddress == 0 || resumeAddress == 0) return;
var instructions = BuildThreadContextCaptureCode(suspendAddress, contextAddress, resumeAddress);
SetHandle((nint)VirtualAlloc(null, (nuint)instructions.Length, 0x3000, 0x04));
if (IsInvalid) return;
instructions.CopyTo(new Span<byte>((void*)handle, instructions.Length));
uint previousProtection = 0;
if (!VirtualProtect((void*)handle, (nuint)instructions.Length, 0x20, &previousProtection))
{
Dispose();
return;
}
FlushInstructionCache(GetCurrentProcess(), (void*)handle, (nuint)instructions.Length);
}
protected override bool ReleaseHandle() => VirtualFree((void*)handle, 0, 0x8000);
}
private static SafeWaitHandle? OpenThreadForContext(uint threadId)
{
if (!OperatingSystem.IsWindows() || RuntimeInformation.ProcessArchitecture != Architecture.X64 || threadId == 0)
return null;
const uint queryLimitedInformation = 0x0800;
var threadHandle = OpenThread(ThreadGetContext | ThreadSuspendResume | queryLimitedInformation, false, threadId);
return threadHandle == 0 ? null : new SafeWaitHandle(threadHandle, ownsHandle: true);
}
private static bool TryCaptureHostThreadContext(int threadId, out HostThreadContextSnapshot snapshot)
{
using var threadHandle = OpenThreadForContext(unchecked((uint)threadId));
return TryCaptureThreadContext(threadHandle, out snapshot);
}
private static bool TryCaptureThreadContext(SafeWaitHandle? threadHandle, out HostThreadContextSnapshot snapshot)
{
snapshot = default;
if (threadHandle is null || !OperatingSystem.IsWindows() || RuntimeInformation.ProcessArchitecture != Architecture.X64)
return false;
var handleReferenced = false;
try
{
threadHandle.DangerousAddRef(ref handleReferenced);
var nativeHandle = threadHandle.DangerousGetHandle();
var threadId = GetThreadId(nativeHandle);
if (threadId == 0 || threadId == GetCurrentThreadId()) return false;
var captureCode = ThreadCaptureCode.Value;
if (captureCode.IsInvalid || captureCode.IsClosed) return false;
byte* contextStorage = stackalloc byte[Win64ContextSize + 15];
var contextRecord = (void*)(((nuint)contextStorage + 15) & ~(nuint)15);
new Span<byte>(contextRecord, Win64ContextSize).Clear();
WriteCtxU32(contextRecord, Win64ContextFlagsOffset, ContextAmd64ControlInteger);
// One native transition keeps managed work outside the suspended interval.
var captured = ((delegate* unmanaged<nint, void*, int>)captureCode.DangerousGetHandle())(nativeHandle, contextRecord);
if (captured == 0) return false;
snapshot = DecodeHostThreadContext(threadId, contextRecord);
return true;
}
catch (ObjectDisposedException)
{
return false;
}
finally
{
if (handleReferenced) threadHandle!.DangerousRelease();
}
}
private static HostThreadContextSnapshot DecodeHostThreadContext(uint threadId, void* contextRecord) => new(
threadId,
ReadCtxU64(contextRecord, 248), ReadCtxU64(contextRecord, 152), ReadCtxU64(contextRecord, 160),
ReadCtxU64(contextRecord, 120), ReadCtxU64(contextRecord, 144), ReadCtxU64(contextRecord, 128),
ReadCtxU64(contextRecord, 136), ReadCtxU64(contextRecord, 168), ReadCtxU64(contextRecord, 176),
ReadCtxU64(contextRecord, 184), ReadCtxU64(contextRecord, 192), ReadCtxU64(contextRecord, 200),
ReadCtxU64(contextRecord, 208), ReadCtxU64(contextRecord, 216), ReadCtxU64(contextRecord, 224),
ReadCtxU64(contextRecord, 232), ReadCtxU64(contextRecord, 240));
internal static byte[] BuildThreadContextCaptureCode(nint suspendAddress, nint contextAddress, nint resumeAddress)
{
var instructions = new List<byte>();
void CallAddress(nint address)
{
instructions.AddRange([0x48, 0xB8]);
instructions.AddRange(BitConverter.GetBytes((long)address));
instructions.AddRange([0xFF, 0xD0]);
}
// Preserve nonvolatile registers and reserve aligned argument space.
instructions.AddRange([0x53, 0x56, 0x57, 0x48, 0x83, 0xEC, 0x20,
0x48, 0x89, 0xCB, 0x48, 0x89, 0xD6, 0x31, 0xFF]);
CallAddress(suspendAddress);
instructions.AddRange([0x83, 0xF8, 0xFF, 0x74, 0]);
var failedSuspendJump = instructions.Count - 1;
instructions.AddRange([0x48, 0x89, 0xD9, 0x48, 0x89, 0xF2]);
CallAddress(contextAddress);
instructions.AddRange([0x89, 0xC7, 0x48, 0x89, 0xD9]);
CallAddress(resumeAddress);
instructions.AddRange([0x83, 0xF8, 0xFF, 0x75, 0x02, 0x31, 0xFF]);
var returnOffset = instructions.Count;
instructions.AddRange([0x89, 0xF8, 0x48, 0x83, 0xC4, 0x20, 0x5F, 0x5E, 0x5B, 0xC3]);
instructions[failedSuspendJump] = checked((byte)(returnOffset - failedSuspendJump - 1));
return instructions.ToArray();
}
private void LogMainThreadStallContext()
{
if (!TryCaptureThreadContext(Volatile.Read(ref _mainExecutionThreadHandle), out var context)) return;
Console.Error.WriteLine($"[LOADER][ERROR] Live hardware context (main thread {context.ThreadId}):");
Console.Error.WriteLine($"[LOADER][ERROR] RIP=0x{context.Rip:X16} RSP=0x{context.Rsp:X16} RBP=0x{context.Rbp:X16}");
Console.Error.WriteLine($"[LOADER][ERROR] RAX=0x{context.Rax:X16} RBX=0x{context.Rbx:X16} RCX=0x{context.Rcx:X16} RDX=0x{context.Rdx:X16}");
Console.Error.WriteLine($"[LOADER][ERROR] RSI=0x{context.Rsi:X16} RDI=0x{context.Rdi:X16} R8=0x{context.R8:X16} R9=0x{context.R9:X16}");
Console.Error.WriteLine($"[LOADER][ERROR] R10=0x{context.R10:X16} R11=0x{context.R11:X16} R12=0x{context.R12:X16} R13=0x{context.R13:X16} R14=0x{context.R14:X16} R15=0x{context.R15:X16}");
var modules = Array.Empty<(ulong Start, ulong Size, string Name)>();
try
{
using var process = Process.GetCurrentProcess();
modules = process.Modules.Cast<ProcessModule>().Select(module =>
(Start: unchecked((ulong)module.BaseAddress), Size: (ulong)module.ModuleMemorySize, Name: module.ModuleName)).ToArray();
}
catch (Win32Exception) { }
catch (InvalidOperationException) { }
string DescribeAddress(ulong address)
{
foreach (var module in modules)
if (address >= module.Start && address - module.Start < module.Size)
return $"{module.Name}+0x{address - module.Start:X}";
return $"0x{address:X16}";
}
Console.Error.WriteLine($"[LOADER][ERROR] RIP location: {DescribeAddress(context.Rip)}");
// The thread has resumed. These bytes are best-effort observations, not an atomic snapshot.
var instructionBytes = new byte[48];
if (context.Rip >= 32 && TryReadHostBytes(context.Rip - 32, instructionBytes))
Console.Error.WriteLine($"[LOADER][ERROR] Live bytes @[RIP-32..RIP+16]: {Convert.ToHexString(instructionBytes)}");
var currentInstruction = new byte[16];
if (TryReadHostBytes(context.Rip, currentInstruction))
Console.Error.WriteLine($"[LOADER][ERROR] Live bytes @RIP: {Convert.ToHexString(currentInstruction)}");
Console.Error.WriteLine("[LOADER][ERROR] Live stack pointer candidates:");
for (var offset = 0; offset < 256; offset += sizeof(ulong))
{
var address = context.Rsp + (ulong)offset;
if (address < context.Rsp || !TryReadDiagnosticHostQword(address, out var value)) break;
if (value != 0)
Console.Error.WriteLine($"[LOADER][ERROR] [rsp+0x{offset:X2}] = 0x{value:X16} ({DescribeAddress(value)})");
}
}
[DllImport("kernel32.dll")]
private static extern uint GetThreadId(nint threadHandle);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,100 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Diagnostics;
namespace SharpEmu.Core.Cpu.Native;
internal sealed class GuestThreadFlowProfile(int capacity = 131072)
{
internal static readonly bool Enabled =
(Environment.GetEnvironmentVariable("SHARPEMU_PROFILE_PERFORMANCE") == "1" ||
Environment.GetEnvironmentVariable("SHARPEMU_PROFILE_GUEST_SCHEDULER") == "1") &&
Environment.GetEnvironmentVariable("SHARPEMU_PROFILE_PERFORMANCE_FRAME_TRACE") == "1";
internal enum EventKind
{
Blocked, Ready, Claimed, Scheduled, RunStarted, RunStopped, CallbackResumed,
ExecutorReleased, ClaimDeferred
}
internal readonly record struct TraceEvent(long Timestamp, int HostThreadId, ulong GuestThreadHandle,
string Name, EventKind Kind, string? Reason, string? WakeKey, string? ImportNid,
ulong Argument0, ulong Argument1, long DeadlineTimestamp);
internal readonly record struct Snapshot(TraceEvent[] Events, long TotalEvents);
private readonly int _capacity = capacity > 0 ? capacity : throw new ArgumentOutOfRangeException(nameof(capacity));
private readonly object _gate = new();
private readonly object _writeGate = new();
private TraceEvent[]? _events;
private long _eventCount;
private bool _closed;
internal void StartSession()
{
lock (_writeGate)
{
lock (_gate)
{
_events = null;
_eventCount = 0;
_closed = false;
}
}
}
internal void Record(in TraceEvent traceEvent)
{
lock (_gate)
{
if (_closed) return;
_events ??= new TraceEvent[_capacity];
_events[(int)(_eventCount % _capacity)] = traceEvent;
_eventCount++;
}
}
internal Snapshot Close()
{
lock (_gate)
{
_closed = true;
var retained = (int)Math.Min(_eventCount, _capacity);
var records = new TraceEvent[retained];
var first = _eventCount - retained;
for (var index = 0; index < retained; index++)
records[index] = _events![(int)((first + index) % _capacity)];
var snapshot = new Snapshot(records, _eventCount);
_events = null;
_eventCount = 0;
return snapshot;
}
}
internal void WriteTrace(TextWriter output)
{
// A concurrent shutdown caller must wait for the first writer to finish.
lock (_writeGate)
{
WriteRetainedEvents(output);
}
}
private void WriteRetainedEvents(TextWriter output)
{
var snapshot = Close();
if (snapshot.TotalEvents == 0) return;
output.WriteLine($"[PERF][GUEST_FLOW_TRACE] frequency={Stopwatch.Frequency} retained={snapshot.Events.Length} overwritten={snapshot.TotalEvents - snapshot.Events.Length}");
for (var index = 0; index < snapshot.Events.Length; index++)
{
var item = snapshot.Events[index];
output.WriteLine($"[PERF][GUEST_FLOW] sequence={snapshot.TotalEvents - snapshot.Events.Length + index} timestamp={item.Timestamp} thread={item.HostThreadId} guest=0x{item.GuestThreadHandle:X} name='{Quote(item.Name)}' event={item.Kind} reason='{Quote(item.Reason)}' wake='{Quote(item.WakeKey)}' nid='{Quote(item.ImportNid)}' arg0=0x{item.Argument0:X} arg1=0x{item.Argument1:X} deadline={item.DeadlineTimestamp}");
}
output.Flush();
}
// Guest names must not split one trace event across multiple output lines.
private static string Quote(string? value) => (value ?? "none")
.Replace("\\", "\\\\").Replace("'", "\\'").Replace("\r", "\\r").Replace("\n", "\\n");
}

View File

@ -274,7 +274,7 @@ internal static unsafe class PosixHostStubs
// Linux: call pthread_getspecific, preserving the registers that are
// volatile in SysV but non-volatile in Win64 (rsi, rdi).
var pthreadGetSpecific = NativeLibrary.GetExport(NativeLibrary.Load("libpthread.so.0"), "pthread_getspecific");
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
@ -366,25 +366,25 @@ internal static unsafe class PosixHostStubs
[DllImport("libc", EntryPoint = "pthread_key_create", SetLastError = true)]
private static extern int pthread_key_create_mac(nuint* key, nint destructor);
[DllImport("libpthread.so.0", EntryPoint = "pthread_key_create", SetLastError = true)]
[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("libpthread.so.0", EntryPoint = "pthread_key_delete")]
[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("libpthread.so.0", EntryPoint = "pthread_setspecific")]
[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("libpthread.so.0", EntryPoint = "pthread_getspecific")]
[DllImport("libc", EntryPoint = "pthread_getspecific")]
private static extern nint pthread_getspecific_linux(uint key);
[DllImport("libc")]

View File

@ -0,0 +1,115 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System;
namespace SharpEmu.Core.Cpu.Native;
/// <summary>
/// Recognizes Sony's AMD-only SSE4a EXTRQ+blend idiom and rewrites it into an
/// equivalent SSE4.1 sequence. SharpEmu executes guest x86-64 natively, but
/// Rosetta 2 and Intel hosts do not implement SSE4a, so the original opcode
/// raises #UD -> SIGILL. The compiler emits the idiom against whichever XMM
/// register it happens to allocate (Dead Cells uses xmm1, others xmm2), so the
/// source register is read from the ModRM r/m field rather than hard-coded.
///
/// The match/encode logic is deliberately free of native page-patching so it
/// can be unit-tested against handcrafted byte sequences.
/// </summary>
public static class Sse4aExtrqBlendPatch
{
/// <summary>Length in bytes of both the matched idiom and its replacement.</summary>
public const int SequenceLength = 12;
/// <summary>
/// Matches the 12-byte idiom, extracting the destination register D and the
/// source (scratch) register N:
/// <code>
/// EXTRQ xmmN, 0x28, 0x00 ; 66 0F 78 /0 28 00 mask xmmN to low 40 bits
/// VPBLENDD xmmD, xmmD, xmmN, 2 ; C4 E3 vvvv 02 /r 02 copy dword 1 into xmmD
/// </code>
/// N lives in the ModRM r/m field of both instructions; D (the blend
/// destination and src1) lives in the VPBLENDD ModRM reg field and VEX.vvvv.
/// Both are xmm0-xmm7 (the VEX byte1 0xE3 pins R/X/B, so no xmm8-15 extension).
/// The compiler allocates whichever registers it likes — Dead Cells builds use
/// D=xmm0 and D=xmm3, others differ — so both are read from the encoding.
/// </summary>
public static bool TryMatch(ReadOnlySpan<byte> source, out int destRegister, out int srcRegister)
{
destRegister = -1;
srcRegister = -1;
if (source.Length < SequenceLength)
{
return false;
}
// EXTRQ xmmN, 0x28, 0x00 : 66 0F 78, ModRM (mod=11 reg=000 rm=N), 28, 00.
if (source[0] != 0x66 || source[1] != 0x0F || source[2] != 0x78 ||
(source[3] & 0xF8) != 0xC0 || source[4] != 0x28 || source[5] != 0x00)
{
return false;
}
var n = source[3] & 0x07;
// VPBLENDD xmmD, xmmD, xmmN, 2 : C4 E3 <W=0 vvvv=~D L=0 pp=01> 02 ModRM 02.
// VEX.byte2 fixed bits (W, L, pp) must read 0b*0000*01; vvvv encodes ~D.
if (source[6] != 0xC4 || source[7] != 0xE3 || (source[8] & 0x87) != 0x01 ||
source[9] != 0x02 || source[11] != 0x02)
{
return false;
}
var d = (~(source[8] >> 3)) & 0x0F;
if (d > 7)
{
return false;
}
// ModRM: mod=11, reg=D (dest = src1), rm=N (src2 = the masked register).
if (source[10] != (0xC0 | (d << 3) | n))
{
return false;
}
destRegister = d;
srcRegister = n;
return true;
}
/// <summary>
/// Writes the SSE4.1 equivalent into <paramref name="destination"/>:
/// <code>
/// PEXTRB eax, xmmN, 4 ; 66 0F 3A 14 /r 04 extract byte 4 (zero-extended)
/// PINSRD xmmD, eax, 1 ; 66 0F 3A 22 /r 01 insert into xmmD dword lane 1
/// </code>
/// After EXTRQ masks xmmN to its low 40 bits, dword 1 is just byte 4
/// zero-extended, so the two-instruction extract/insert reproduces the exact
/// observable result the AMD idiom left in xmmD. eax is a caller-dead scratch
/// at every site the compiler emits this idiom.
/// </summary>
public static bool TryEncode(int destRegister, int srcRegister, Span<byte> destination)
{
if ((uint)destRegister > 7 || (uint)srcRegister > 7 || destination.Length < SequenceLength)
{
return false;
}
// PEXTRB eax, xmmN, 4 : ModRM (mod=11 reg=N rm=000 -> eax), imm8 = byte index 4.
destination[0] = 0x66;
destination[1] = 0x0F;
destination[2] = 0x3A;
destination[3] = 0x14;
destination[4] = (byte)(0xC0 | (srcRegister << 3));
destination[5] = 0x04;
// PINSRD xmmD, eax, 1 : ModRM (mod=11 reg=D -> xmmD, rm=000 -> eax), lane 1.
destination[6] = 0x66;
destination[7] = 0x0F;
destination[8] = 0x3A;
destination[9] = 0x22;
destination[10] = (byte)(0xC0 | (destRegister << 3));
destination[11] = 0x01;
return true;
}
}

View File

@ -16,8 +16,6 @@ internal static class WindowsFaultCodes
public const uint FastFail = 0xC0000409u; // 3221226505
public const uint StackOverflow = 0xC00000FDu;
public const uint ClrManagedException = 0xE0434352u;
public const uint DebugOutputAnsi = 0x40010006u;
public const uint DebugOutputUnicode = 0x4001000Au;
// EXCEPTION_RECORD.ExceptionInformation[0] for access violations.
public const ulong AccessRead = 0;

View File

@ -24,7 +24,7 @@ internal sealed unsafe partial class WindowsFaultHandling : IHostFaultHandling
public nint CreateHandlerThunk(nint managedCallback, uint hostRspSwitchTlsSlot, nint tlsGetValueAddress)
{
const uint stubSize = 1024u;
const uint stubSize = 256u;
void* ptr = (void*)_memory.Allocate(0, stubSize, HostPageProtection.ReadWriteExecute);
if (ptr == null)
{
@ -43,16 +43,11 @@ internal sealed unsafe partial class WindowsFaultHandling : IHostFaultHandling
// 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.
//
// FastFail (0xC0000409) is logged from this native path only: managed VEH never
// sees it (tLT18–21 silent exits after TBB AV recovery).
ReadOnlySpan<uint> nonManagedExceptionCodes =
[WindowsFaultCodes.ClrManagedException, 0xE06D7363u, WindowsFaultCodes.FastFail, WindowsFaultCodes.StackOverflow,
WindowsFaultCodes.DebugOutputAnsi, WindowsFaultCodes.DebugOutputUnicode];
[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];
int fastFailJumpSlot = -1;
for (int i = 0; i < nonManagedExceptionCodes.Length; i++)
{
EmitByte(code, ref offset, 0x3D); // cmp eax, imm32
@ -60,162 +55,13 @@ internal sealed unsafe partial class WindowsFaultHandling : IHostFaultHandling
EmitByte(code, ref offset, 0x74); // je pass
passJumpOffsets[i] = offset;
EmitByte(code, ref offset, 0x00);
if (nonManagedExceptionCodes[i] == WindowsFaultCodes.FastFail)
{
fastFailJumpSlot = i;
}
}
EmitByte(code, ref offset, 0xE9); // jmp mainBody rel32 (FastFail breadcrumb sits between)
var mainBodyJumpSlot = offset;
EmitUInt32(code, ref offset, 0u);
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
// FastFail: native stderr breadcrumb with Context.Rip (no managed entry), then CONTINUE_SEARCH.
// Keep in sync with DirectExecutionBackend.CreateExceptionHandlerTrampoline.
int fastFailPassOffset = offset;
var fastFailLogInstalled = false;
if (fastFailJumpSlot >= 0 &&
NativeLibrary.TryLoad("kernel32.dll", out var kernel32) &&
NativeLibrary.TryGetExport(kernel32, "GetStdHandle", out var getStdHandle) &&
NativeLibrary.TryGetExport(kernel32, "WriteFile", out var writeFile))
{
ReadOnlySpan<byte> msg =
"[LOADER][FATAL] VEH_PASS FastFail 0xC0000409 (native; no managed VEH) rip=0x"u8;
ReadOnlySpan<byte> hexDigits = "0123456789ABCDEF"u8;
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0x8B); EmitByte(code, ref offset, 0x41);
EmitByte(code, ref offset, 0x08); // mov rax, [rcx+8]
EmitByte(code, ref offset, 0x4C); EmitByte(code, ref offset, 0x8B); EmitByte(code, ref offset, 0x90);
EmitUInt32(code, ref offset, 0xF8u); // mov r10, [rax+0xF8]
EmitByte(code, ref offset, 0x50); // push rax
EmitByte(code, ref offset, 0x51); // push rcx
EmitByte(code, ref offset, 0x52); // push rdx
EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0x50); // push r8
EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0x51); // push r9
EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0x52); // push r10
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0x83);
EmitByte(code, ref offset, 0xEC); EmitByte(code, ref offset, 0x40); // sub rsp, 0x40
EmitByte(code, ref offset, 0xB9); EmitUInt32(code, ref offset, unchecked((uint)-12));
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0xB8);
*(nint*)(code + offset) = getStdHandle;
offset += sizeof(nint);
EmitByte(code, ref offset, 0xFF); EmitByte(code, ref offset, 0xD0);
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0x89);
EmitByte(code, ref offset, 0x44); EmitByte(code, ref offset, 0x24);
EmitByte(code, ref offset, 0x28); // mov [rsp+0x28], rax
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0x89); EmitByte(code, ref offset, 0xC1);
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0xB8);
var msgAbsSlot = offset;
*(nint*)(code + offset) = 0;
offset += sizeof(nint);
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0x89); EmitByte(code, ref offset, 0xC2);
EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0xB8);
EmitUInt32(code, ref offset, (uint)msg.Length);
EmitByte(code, ref offset, 0x4C); EmitByte(code, ref offset, 0x8D);
EmitByte(code, ref offset, 0x4C); EmitByte(code, ref offset, 0x24);
EmitByte(code, ref offset, 0x20);
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0xC7);
EmitByte(code, ref offset, 0x44); EmitByte(code, ref offset, 0x24);
EmitByte(code, ref offset, 0x20); EmitUInt32(code, ref offset, 0);
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0xC7);
EmitByte(code, ref offset, 0x44); EmitByte(code, ref offset, 0x24);
EmitByte(code, ref offset, 0x38); EmitUInt32(code, ref offset, 0);
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0xB8);
*(nint*)(code + offset) = writeFile;
offset += sizeof(nint);
EmitByte(code, ref offset, 0xFF); EmitByte(code, ref offset, 0xD0);
EmitByte(code, ref offset, 0x4C); EmitByte(code, ref offset, 0x8B);
EmitByte(code, ref offset, 0x54); EmitByte(code, ref offset, 0x24);
EmitByte(code, ref offset, 0x40); // mov r10, [rsp+0x40]
EmitByte(code, ref offset, 0x49); EmitByte(code, ref offset, 0xB8);
var hexDigitsAbsSlot = offset;
*(nint*)(code + offset) = 0;
offset += sizeof(nint);
EmitByte(code, ref offset, 0x4C); EmitByte(code, ref offset, 0x8D);
EmitByte(code, ref offset, 0x5C); EmitByte(code, ref offset, 0x24);
EmitByte(code, ref offset, 0x30); // lea r11, [rsp+0x30]
EmitByte(code, ref offset, 0xB9); EmitUInt32(code, ref offset, 16u);
EmitByte(code, ref offset, 0x4C); EmitByte(code, ref offset, 0x89); EmitByte(code, ref offset, 0xD0);
int hexLoopOffset = offset;
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0xC1); EmitByte(code, ref offset, 0xC0);
EmitByte(code, ref offset, 0x04);
EmitByte(code, ref offset, 0x89); EmitByte(code, ref offset, 0xC2);
EmitByte(code, ref offset, 0x83); EmitByte(code, ref offset, 0xE2); EmitByte(code, ref offset, 0x0F);
EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0x0F); EmitByte(code, ref offset, 0xB6);
EmitByte(code, ref offset, 0x14); EmitByte(code, ref offset, 0x10);
EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0x88); EmitByte(code, ref offset, 0x13);
EmitByte(code, ref offset, 0x49); EmitByte(code, ref offset, 0xFF); EmitByte(code, ref offset, 0xC3);
EmitByte(code, ref offset, 0xFF); EmitByte(code, ref offset, 0xC9);
EmitByte(code, ref offset, 0x75);
EmitByte(code, ref offset, unchecked((byte)(hexLoopOffset - (offset + 1)))); // jnz rel8
EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0xC6); EmitByte(code, ref offset, 0x03);
EmitByte(code, ref offset, 0x0A);
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0x8B);
EmitByte(code, ref offset, 0x4C); EmitByte(code, ref offset, 0x24);
EmitByte(code, ref offset, 0x28);
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0x8D);
EmitByte(code, ref offset, 0x54); EmitByte(code, ref offset, 0x24);
EmitByte(code, ref offset, 0x30);
EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0xB8);
EmitUInt32(code, ref offset, 17u);
EmitByte(code, ref offset, 0x4C); EmitByte(code, ref offset, 0x8D);
EmitByte(code, ref offset, 0x4C); EmitByte(code, ref offset, 0x24);
EmitByte(code, ref offset, 0x20);
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0xC7);
EmitByte(code, ref offset, 0x44); EmitByte(code, ref offset, 0x24);
EmitByte(code, ref offset, 0x20); EmitUInt32(code, ref offset, 0);
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0xC7);
EmitByte(code, ref offset, 0x44); EmitByte(code, ref offset, 0x24);
EmitByte(code, ref offset, 0x38); EmitUInt32(code, ref offset, 0);
EmitByte(code, ref offset, 0x48); EmitByte(code, ref offset, 0xB8);
*(nint*)(code + offset) = writeFile;
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, 0x40);
EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0x5A);
EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0x59);
EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0x58);
EmitByte(code, ref offset, 0x5A);
EmitByte(code, ref offset, 0x59);
EmitByte(code, ref offset, 0x58);
EmitByte(code, ref offset, 0x31); EmitByte(code, ref offset, 0xC0);
EmitByte(code, ref offset, 0xC3);
var msgOffset = offset;
for (int i = 0; i < msg.Length; i++)
{
EmitByte(code, ref offset, msg[i]);
}
var hexDigitsOffset = offset;
for (int i = 0; i < hexDigits.Length; i++)
{
EmitByte(code, ref offset, hexDigits[i]);
}
*(nint*)(code + msgAbsSlot) = (nint)ptr + msgOffset;
*(nint*)(code + hexDigitsAbsSlot) = (nint)ptr + hexDigitsOffset;
code[passJumpOffsets[fastFailJumpSlot]] =
checked((byte)(fastFailPassOffset - (passJumpOffsets[fastFailJumpSlot] + 1)));
fastFailLogInstalled = true;
}
int mainBodyOffset = offset;
*(int*)(code + mainBodyJumpSlot) = mainBodyOffset - (mainBodyJumpSlot + sizeof(int));
for (int i = 0; i < nonManagedExceptionCodes.Length; i++)
{
if (i == fastFailJumpSlot && fastFailLogInstalled)
{
continue;
}
code[passJumpOffsets[i]] = checked((byte)(passOffset - (passJumpOffsets[i] + 1)));
}
EmitByte(code, ref offset, 0x41); EmitByte(code, ref offset, 0x54); // push r12

View File

@ -18,8 +18,6 @@ public sealed class TrackedCpuMemory : ICpuMemory, ITrackedCpuMemory, IGuestMemo
public ICpuMemory Inner => _inner;
public string DescribeReadRange(ulong address, ulong size) => _inner.DescribeReadRange(address, size);
public bool TryRead(ulong virtualAddress, Span<byte> destination)
{
var result = _inner.TryRead(virtualAddress, destination);
@ -42,20 +40,9 @@ public sealed class TrackedCpuMemory : ICpuMemory, ITrackedCpuMemory, IGuestMemo
return result;
}
public bool TryCompare(
ulong virtualAddress,
ReadOnlySpan<byte> expected,
out bool equal) =>
_inner.TryCompare(virtualAddress, expected, out equal);
public bool TryCopy(ulong destinationAddress, ulong sourceAddress, ulong length) =>
_inner.TryCopy(destinationAddress, sourceAddress, length);
public bool CanRead(ulong address, ulong size) => _inner.CanRead(address, size);
public bool TryScanCString(ulong address, byte needle, bool findLast, ulong maxLength, out ulong match) =>
_inner.TryScanCString(address, needle, findLast, maxLength, out match);
public bool TryAllocateGuestMemory(ulong size, ulong alignment, out ulong address)
{
if (_inner is IGuestMemoryAllocator allocator)

View File

@ -1,122 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Reflection.PortableExecutable;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace SharpEmu.Core.Diagnostics;
public static partial class WindowsCrashCapture
{
internal sealed class DebuggerBreakTracker
{
private readonly Dictionary<uint, nint> _threadStarts = new();
private nint _libraryBase;
private nint _breakThreadEntry;
private nint _breakpointAddress;
internal void Observe(DebugEvent debugEvent)
{
switch (debugEvent.Kind)
{
case CreateProcessEvent:
_threadStarts[debugEvent.ThreadId] = debugEvent.ProcessThreadStartAddress;
break;
case CreateThreadEvent:
_threadStarts[debugEvent.ThreadId] = debugEvent.ThreadStartAddress;
break;
case ExitThreadEvent:
_threadStarts.Remove(debugEvent.ThreadId);
break;
case LoadLibraryEvent:
if (TryReadDebuggerExports(debugEvent.FileHandle, out var threadOffset, out var breakpointOffset))
{
_libraryBase = debugEvent.LoadedLibraryBase;
_breakThreadEntry = checked(_libraryBase + threadOffset);
_breakpointAddress = checked(_libraryBase + breakpointOffset);
}
break;
case UnloadLibraryEvent when debugEvent.UnloadedLibraryBase == _libraryBase:
_libraryBase = _breakThreadEntry = _breakpointAddress = 0;
break;
}
}
internal bool IsDebuggerBreak(DebugEvent debugEvent) =>
debugEvent.Kind == ExceptionEvent && debugEvent.FirstChance != 0 &&
debugEvent.Exception.Code == BreakpointException && _libraryBase != 0 &&
debugEvent.Exception.Address == _breakpointAddress &&
_threadStarts.TryGetValue(debugEvent.ThreadId, out var startAddress) && startAddress == _breakThreadEntry;
}
private static unsafe bool TryReadDebuggerExports(nint fileHandle, out int threadOffset, out int breakpointOffset)
{
threadOffset = breakpointOffset = 0;
if (fileHandle == 0 || fileHandle == -1)
return false;
const int pathCapacity = 512;
var pathBuffer = stackalloc char[pathCapacity];
var pathLength = GetFinalPathNameByHandle(fileHandle, pathBuffer, pathCapacity, 0);
if (pathLength == 0 || pathLength >= pathCapacity)
return false;
var path = new string(pathBuffer, 0, (int)pathLength);
var systemLibrary = @"\\?\" + Path.Combine(Environment.SystemDirectory, "ntdll.dll");
if (!string.Equals(path, systemLibrary, StringComparison.OrdinalIgnoreCase))
return false;
try
{
// Read the file supplied by the debug event, then use the target's load address.
using var handle = new SafeFileHandle(fileHandle, ownsHandle: false);
using var stream = new FileStream(handle, FileAccess.Read);
using var image = new PEReader(stream);
if (image.PEHeaders.PEHeader is not { Magic: PEMagic.PE32Plus } header)
return false;
var directory = header.ExportTableDirectory;
if (directory.Size < 40)
return false;
var exports = image.GetSectionData(directory.RelativeVirtualAddress).GetReader(0, 40);
exports.Offset = 20;
var functionCount = exports.ReadInt32();
var nameCount = exports.ReadInt32();
var functionsAddress = exports.ReadInt32();
var namesAddress = exports.ReadInt32();
var ordinalsAddress = exports.ReadInt32();
var functions = image.GetSectionData(functionsAddress).GetReader(0, checked(functionCount * 4));
var names = image.GetSectionData(namesAddress).GetReader(0, checked(nameCount * 4));
var ordinals = image.GetSectionData(ordinalsAddress).GetReader(0, checked(nameCount * 2));
for (var nameIndex = 0; nameIndex < nameCount; nameIndex++)
{
var nameBlock = image.GetSectionData(names.ReadInt32());
var nameBytes = nameBlock.GetContent(0, Math.Min(nameBlock.Length, "DbgUiRemoteBreakin".Length + 1)).AsSpan();
var terminator = nameBytes.IndexOf((byte)0);
var ordinal = ordinals.ReadUInt16();
if (ordinal >= functionCount)
return false;
if (terminator < 0)
continue;
var name = Encoding.ASCII.GetString(nameBytes[..terminator]);
if (name is not ("DbgUiRemoteBreakin" or "DbgBreakPoint"))
continue;
functions.Offset = ordinal * 4;
var functionOffset = functions.ReadInt32();
// A forwarded export is not executable code in this image.
if (functionOffset <= 0 || functionOffset >= header.SizeOfImage ||
(functionOffset >= directory.RelativeVirtualAddress &&
functionOffset - directory.RelativeVirtualAddress < directory.Size))
return false;
if (name == "DbgUiRemoteBreakin")
threadOffset = functionOffset;
else
breakpointOffset = functionOffset;
}
return threadOffset != 0 && breakpointOffset != 0;
}
catch (Exception exception) when (exception is IOException or BadImageFormatException or ArgumentException or OverflowException)
{
threadOffset = breakpointOffset = 0;
return false;
}
}
}

View File

@ -1,161 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace SharpEmu.Core.Diagnostics;
public static partial class WindowsCrashCapture
{
private const uint ExceptionEvent = 1;
private const uint CreateThreadEvent = 2;
private const uint CreateProcessEvent = 3;
private const uint ExitThreadEvent = 4;
private const uint ExitProcessEvent = 5;
private const uint LoadLibraryEvent = 6;
private const uint UnloadLibraryEvent = 7;
private const uint BreakpointException = 0x80000003;
private const uint DebugContinue = 0x00010002;
private const uint DebugExceptionNotHandled = 0x80010001;
private const uint ProcessReadAccess = 0x0450;
private const uint ThreadContextAccess = 0x0008;
private const uint DumpFullMemory = 0x00000002;
private const uint DumpHandleData = 0x00000004;
private const uint DumpUnloadedModules = 0x00000020;
private const uint DumpMemoryInformation = 0x00000800;
private const uint DumpThreadInformation = 0x00001000;
private const uint DumpIgnoreInaccessibleMemory = 0x00020000;
private const uint FullDumpFlags = DumpFullMemory | DumpHandleData | DumpUnloadedModules |
DumpMemoryInformation | DumpThreadInformation | DumpIgnoreInaccessibleMemory;
private const uint AllX64ContextFlags = 0x0010001F;
private static unsafe void WriteDump(uint processId, DebugEvent debugEvent, string dumpPath)
{
using var process = OpenProcess(ProcessReadAccess, false, processId);
if (process.IsInvalid)
throw NativeFailure("Open the crashed process");
using var thread = OpenThread(ThreadContextAccess, false, debugEvent.ThreadId);
if (thread.IsInvalid)
throw NativeFailure("Open the faulting thread");
var context = (ThreadContext*)NativeMemory.AlignedAlloc((nuint)sizeof(ThreadContext), 16);
if (context == null)
throw new OutOfMemoryException();
try
{
NativeMemory.Clear(context, (nuint)sizeof(ThreadContext));
context->Flags = AllX64ContextFlags;
if (!GetThreadContext(thread, context))
throw NativeFailure("Read the faulting thread context");
// The exception pointers refer to this helper, not to the crashed process.
var record = debugEvent.Exception;
record.NestedRecord = 0;
var pointers = new ExceptionPointers { Record = &record, Context = context };
var exception = new DumpExceptionInformation
{
ThreadId = debugEvent.ThreadId,
Pointers = &pointers,
ClientPointers = 0,
};
using var output = new FileStream(dumpPath, FileMode.CreateNew, FileAccess.Write, FileShare.Read);
if (!MiniDumpWriteDump(process, processId, output.SafeFileHandle, FullDumpFlags, &exception, 0, 0))
throw NativeFailure("Write the crash dump");
output.Flush(flushToDisk: true);
}
finally
{
NativeMemory.AlignedFree(context);
}
}
[StructLayout(LayoutKind.Explicit, Size = 176)]
internal struct DebugEvent
{
[FieldOffset(0)] public uint Kind;
[FieldOffset(4)] public uint ProcessId;
[FieldOffset(8)] public uint ThreadId;
[FieldOffset(16)] public ExceptionRecord Exception;
[FieldOffset(168)] public uint FirstChance;
[FieldOffset(16)] public nint FileHandle;
[FieldOffset(16)] public uint ExitCode;
[FieldOffset(24)] public nint LoadedLibraryBase;
[FieldOffset(16)] public nint UnloadedLibraryBase;
[FieldOffset(32)] public nint ThreadStartAddress;
[FieldOffset(64)] public nint ProcessThreadStartAddress;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct ExceptionRecord
{
public uint Code;
public uint Flags;
public nint NestedRecord;
public nint Address;
public uint ParameterCount;
public fixed ulong Parameters[15];
}
[StructLayout(LayoutKind.Explicit, Size = 1232)]
internal struct ThreadContext
{
[FieldOffset(48)] public uint Flags;
}
[StructLayout(LayoutKind.Sequential)]
private unsafe struct ExceptionPointers
{
public ExceptionRecord* Record;
public ThreadContext* Context;
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal unsafe struct DumpExceptionInformation
{
public uint ThreadId;
public void* Pointers;
public int ClientPointers;
}
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool DebugActiveProcess(uint processId);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool DebugActiveProcessStop(uint processId);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool DebugSetProcessKillOnExit([MarshalAs(UnmanagedType.Bool)] bool killOnExit);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool WaitForDebugEventEx(out DebugEvent debugEvent, uint milliseconds);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool ContinueDebugEvent(uint processId, uint threadId, uint status);
[LibraryImport("kernel32.dll", SetLastError = true)]
private static partial SafeProcessHandle OpenProcess(uint access, [MarshalAs(UnmanagedType.Bool)] bool inherit, uint processId);
[LibraryImport("kernel32.dll", SetLastError = true)]
private static partial SafeWaitHandle OpenThread(uint access, [MarshalAs(UnmanagedType.Bool)] bool inherit, uint threadId);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static unsafe partial bool GetThreadContext(SafeWaitHandle thread, ThreadContext* context);
[LibraryImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool CloseHandle(nint handle);
[LibraryImport("kernel32.dll", EntryPoint = "GetFinalPathNameByHandleW", SetLastError = true)]
private static unsafe partial uint GetFinalPathNameByHandle(nint file, char* path, uint length, uint flags);
[LibraryImport("dbghelp.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static unsafe partial bool MiniDumpWriteDump(SafeProcessHandle process, uint processId,
SafeFileHandle file, uint dumpType, DumpExceptionInformation* exception, nint userStream, nint callback);
}

View File

@ -1,182 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace SharpEmu.Core.Diagnostics;
public static partial class WindowsCrashCapture
{
public const string HelperArgument = "--sharpemu-crash-helper";
private const string CaptureVariable = "SHARPEMU_CRASH_CAPTURE";
public static void StartIfEnabled(string? logFilePath)
{
if (!string.Equals(Environment.GetEnvironmentVariable(CaptureVariable), "1", StringComparison.Ordinal))
return;
if (!OperatingSystem.IsWindows() || RuntimeInformation.ProcessArchitecture != Architecture.X64)
{
Console.Error.WriteLine("[CRASH][WARN] Crash capture requires a Windows x64 process.");
return;
}
try
{
var logPath = string.IsNullOrWhiteSpace(logFilePath)
? Path.Combine(AppContext.BaseDirectory, "user", "logs", $"run-{DateTime.UtcNow:yyyyMMdd-HHmmss}.log")
: Path.GetFullPath(logFilePath);
var dumpPath = Path.ChangeExtension(logPath, $"crash-{Environment.ProcessId}.dmp");
Directory.CreateDirectory(Path.GetDirectoryName(dumpPath)!);
var readyEventName = $"Local\\SharpEmu-Crash-{Guid.NewGuid():N}";
using var readyEvent = new EventWaitHandle(false, EventResetMode.ManualReset, readyEventName);
var executable = Environment.ProcessPath ?? throw new InvalidOperationException("The executable path is not available.");
var startInfo = new ProcessStartInfo(executable) { UseShellExecute = false, CreateNoWindow = true };
if (string.Equals(Path.GetFileNameWithoutExtension(executable), "dotnet", StringComparison.OrdinalIgnoreCase))
startInfo.ArgumentList.Add(Assembly.GetEntryAssembly()!.Location);
startInfo.ArgumentList.Add(HelperArgument);
startInfo.ArgumentList.Add(Environment.ProcessId.ToString(CultureInfo.InvariantCulture));
startInfo.ArgumentList.Add(readyEventName);
startInfo.ArgumentList.Add(dumpPath);
startInfo.Environment.Remove(CaptureVariable);
// The helper stays attached until this process exits, including runtime teardown.
using var helper = Process.Start(startInfo) ?? throw new InvalidOperationException("The crash helper did not start.");
using var exited = new ProcessExitWaitHandle(helper);
WaitForHelper(readyEvent, exited);
Console.Error.WriteLine($"[CRASH][INFO] Crash capture ready. Dump: {dumpPath}");
Console.Error.WriteLine($"[CRASH][INFO] Capture report: {dumpPath}.capture.log");
Console.Error.WriteLine($"[CRASH][INFO] Runtime: {RuntimeInformation.FrameworkDescription}. Debugging can change timing.");
}
catch (Exception exception)
{
Console.Error.WriteLine($"[CRASH][ERROR] Crash capture is not active: {exception.Message}");
}
}
internal static void WaitForHelper(WaitHandle ready, WaitHandle exited)
{
if (WaitHandle.WaitAny([ready, exited]) != 0)
throw new InvalidOperationException("The crash helper exited before capture was ready. Check the capture report.");
}
private sealed class ProcessExitWaitHandle : WaitHandle
{
public ProcessExitWaitHandle(Process process) =>
SafeWaitHandle = new SafeWaitHandle(process.Handle, ownsHandle: false);
}
public static int RunHelper(string[] arguments)
{
if (!OperatingSystem.IsWindows() || RuntimeInformation.ProcessArchitecture != Architecture.X64 ||
arguments.Length != 4 || arguments[0] != HelperArgument ||
!uint.TryParse(arguments[1], NumberStyles.None, CultureInfo.InvariantCulture, out var processId) || processId == 0)
return 1;
var attached = false;
StreamWriter? report = null;
try
{
report = new StreamWriter(arguments[3] + ".capture.log", append: true) { AutoFlush = true };
report.WriteLine($"Capture helper started. Process: {processId}. Dump: {arguments[3]}");
report.WriteLine($"Runtime: {RuntimeInformation.FrameworkDescription}. OS: {Environment.OSVersion}.");
using var readyEvent = EventWaitHandle.OpenExisting(arguments[2]);
if (!DebugActiveProcess(processId))
throw NativeFailure("Attach to the game process");
attached = true;
if (!DebugSetProcessKillOnExit(false))
throw NativeFailure("Keep the game alive if the helper exits");
return ProcessDebugEvents(processId, arguments[3], readyEvent, report);
}
catch (Exception exception)
{
report?.WriteLine($"Capture failed: {exception.Message}");
Console.Error.WriteLine($"[CRASH][ERROR] Capture failed: {exception.Message}");
return 1;
}
finally
{
if (attached)
_ = DebugActiveProcessStop(processId);
report?.Dispose();
}
}
private static int ProcessDebugEvents(uint processId, string dumpPath, EventWaitHandle readyEvent, TextWriter report)
{
var initialBreakpoint = true;
var captured = false;
var debuggerBreaks = new DebuggerBreakTracker();
while (true)
{
if (!WaitForDebugEventEx(out var debugEvent, uint.MaxValue))
throw NativeFailure("Wait for a debug event");
var continuation = DebugContinue;
var ready = false;
try
{
try
{
debuggerBreaks.Observe(debugEvent);
}
finally
{
if (debugEvent.Kind is CreateProcessEvent or LoadLibraryEvent && debugEvent.FileHandle != 0)
_ = CloseHandle(debugEvent.FileHandle);
}
if (debugEvent.Kind == ExceptionEvent)
{
continuation = DebugExceptionNotHandled;
if (initialBreakpoint && debugEvent.FirstChance != 0 && debugEvent.Exception.Code == BreakpointException)
{
initialBreakpoint = false;
continuation = DebugContinue;
ready = true;
}
else if (debuggerBreaks.IsDebuggerBreak(debugEvent))
{
continuation = DebugContinue;
report.WriteLine($"Debugger break continued. Thread: {debugEvent.ThreadId}.");
}
else if (debugEvent.FirstChance == 0 && !captured)
{
captured = true;
report.WriteLine($"Unhandled exception: 0x{debugEvent.Exception.Code:X8}. " +
$"Address: 0x{debugEvent.Exception.Address:X16}. Thread: {debugEvent.ThreadId}.");
WriteDump(processId, debugEvent, dumpPath);
report.WriteLine("Dump complete.");
}
}
}
finally
{
// Even a failed dump must leave the original exception unhandled.
if (!ContinueDebugEvent(debugEvent.ProcessId, debugEvent.ThreadId, continuation))
throw NativeFailure("Continue a debug event");
}
if (ready)
{
report.WriteLine("Capture ready. Application exceptions remain unhandled by the helper.");
readyEvent.Set();
}
if (debugEvent.Kind == ExitProcessEvent)
{
report.WriteLine($"Process exited: 0x{debugEvent.ExitCode:X8}. Dump captured: {captured}.");
return 0;
}
}
}
private static Win32Exception NativeFailure(string operation)
{
var error = Marshal.GetLastPInvokeError();
return new Win32Exception(error, $"{operation} failed (Windows error {error}).");
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,66 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Runtime.InteropServices;
using Iced.Intel;
namespace SharpEmu.Core.Loader;
// Use two 128-bit stores to let Rosetta report a memory fault.
// Keep the source register, general registers, and flags unchanged.
internal static class RosettaVectorStorePatch
{
internal static bool IsRequired { get; } = IsRosettaProcess();
private static unsafe bool IsRosettaProcess()
{
if (!OperatingSystem.IsMacOS() || RuntimeInformation.ProcessArchitecture != Architecture.X64)
{
return false;
}
int translationStatus = 0;
nuint valueByteCount = sizeof(int);
return ReadSystemControlValue("sysctl.proc_translated", &translationStatus, &valueByteCount, null, 0) == 0 && translationStatus == 1;
}
[DllImport("libSystem.B.dylib", EntryPoint = "sysctlbyname")]
private static extern unsafe int ReadSystemControlValue(string controlName, void* valueBuffer, nuint* valueByteCount, void* newValueBuffer, nuint newValueByteCount);
internal static bool RequiresStoreSplit(in Instruction instruction) =>
instruction.Code is Code.VEX_Vmovups_ymmm256_ymm or Code.VEX_Vmovupd_ymmm256_ymm or Code.VEX_Vmovdqu_ymmm256_ymm &&
instruction.Op0Kind == OpKind.Memory && instruction.Op1Register is >= Register.YMM0 and <= Register.YMM15;
internal static IList<Instruction> SplitVectorStores(IList<Instruction> instructions)
{
var splitInstructions = new List<Instruction>(instructions.Count * 2);
foreach (var instruction in instructions)
{
if (!RequiresStoreSplit(instruction))
{
splitInstructions.Add(instruction);
continue;
}
var lowerStore = instruction;
lowerStore.Code = Code.VEX_Vmovups_xmmm128_xmm;
lowerStore.Op1Register = Register.XMM0 + (instruction.Op1Register - Register.YMM0);
splitInstructions.Add(lowerStore);
var upperStore = instruction;
upperStore.Code = Code.VEX_Vextractf128_xmmm128_ymm_imm8;
upperStore.Op2Kind = OpKind.Immediate8;
upperStore.Immediate8 = 1;
upperStore.MemoryDisplacement64 = unchecked(instruction.MemoryDisplacement64 + 16);
// Use the address size for the displacement size that Iced requires.
upperStore.MemoryDisplSize = instruction.MemoryBase is >= Register.EAX and <= Register.R15D ||
instruction.MemoryIndex is >= Register.EAX and <= Register.R15D ? 4 : 8;
// Give the added instruction a separate address for the block encoder.
// Keep branch targets at the first store.
upperStore.IP = instruction.IP + 1;
splitInstructions.Add(upperStore);
}
return splitInstructions;
}
}

View File

@ -27,8 +27,7 @@ public sealed class SelfImage
string? version = null,
uint tlsModuleId = 0,
ulong tlsMemorySize = 0,
ulong tlsStaticOffset = 0,
IReadOnlyList<string>? importedModuleNames = null)
ulong tlsStaticOffset = 0)
{
ArgumentNullException.ThrowIfNull(programHeaders);
ArgumentNullException.ThrowIfNull(mappedRegions);
@ -51,7 +50,6 @@ public sealed class SelfImage
TlsModuleId = tlsModuleId;
TlsMemorySize = tlsMemorySize;
TlsStaticOffset = tlsStaticOffset;
ImportedModuleNames = importedModuleNames ?? Array.Empty<string>();
}
public bool IsSelf { get; }
@ -90,6 +88,4 @@ public sealed class SelfImage
/// <summary>Variant II distance from the thread pointer to this module's static TLS base.</summary>
public ulong TlsStaticOffset { get; }
public IReadOnlyList<string> ImportedModuleNames { get; }
}

View File

@ -56,8 +56,6 @@ public sealed class SelfLoader : ISelfLoader
private const long DtSceStrSize = 0x61000037;
private const long DtSceSymTab = 0x61000039;
private const long DtSceSymTabSize = 0x6100003F;
private const long DtSceNeededModule = 0x6100000F;
private const long DtSceNeededModuleNext = 0x61000045;
private const uint RelocationTypeNone = 0;
private const uint RelocationTypeAbsolute64 = 1;
@ -171,7 +169,6 @@ public sealed class SelfLoader : ISelfLoader
if (clearVirtualMemory)
{
SharpEmu.Libs.Kernel.KernelMemoryCompatExports.ResetBackingMappings(virtualMemory as IGuestBackedSpace);
virtualMemory.Clear();
_nextTlsModuleId = 1;
GuestTlsTemplate.Reset();
@ -262,14 +259,7 @@ public sealed class SelfLoader : ISelfLoader
imageBase,
_moduleManager,
tlsModuleId,
out var importedRelocations,
out var importedModuleNames);
if (tlsModuleId != 0)
{
// Thread copies must include pointers written by relocation.
GuestTlsTemplate.UpdateInitializationImage(
tlsModuleId, ReadTlsInitializationImage(processTlsHeader, virtualMemory, imageBase));
}
out var importedRelocations);
var effectiveImportStubs = importStubs.Count == 0
? new Dictionary<ulong, string>()
: new Dictionary<ulong, string>(importStubs);
@ -300,16 +290,6 @@ public sealed class SelfLoader : ISelfLoader
out var initializerFunctions);
var procParamAddress = ResolveProcParamAddress(programHeaders, imageBase);
if (virtualMemory is PhysicalVirtualMemory patchableMemory)
{
_ = GuestRedZonePatcher.Patch(
virtualMemory,
patchableMemory,
programHeaders,
imageBase,
totalImageSize);
}
Console.WriteLine($"[LOADER] ELF e_entry: 0x{elfHeader.EntryPoint:X16}");
Console.WriteLine($"[LOADER] Generation: {(isNextGen ? "Gen5 (PS5)" : "Gen4 (PS4)")}");
Console.WriteLine($"[LOADER] Using image base: 0x{imageBase:X16}");
@ -351,8 +331,7 @@ public sealed class SelfLoader : ISelfLoader
applicationInfo.Version,
tlsModuleId,
tlsInfo.MemorySize,
tlsInfo.StaticOffset,
importedModuleNames);
tlsInfo.StaticOffset);
}
private static (string? Title, string? TitleId, string? Version) TryLoadParamJson(
@ -560,7 +539,18 @@ public sealed class SelfLoader : ISelfLoader
return default;
}
var initImage = ReadTlsInitializationImage(tlsHeader, virtualMemory, imageBase);
// tdata (initialized) bytes come from the mapped segment; tbss is the
// implicitly-zero remainder up to MemorySize.
var fileSize = (int)Math.Min(tlsHeader.FileSize, tlsHeader.MemorySize);
var initImage = fileSize > 0 ? new byte[fileSize] : [];
if (fileSize > 0 &&
!virtualMemory.TryRead(imageBase + tlsHeader.VirtualAddress, initImage))
{
Console.Error.WriteLine(
$"[LOADER][TLS] Failed to read TLS init image at 0x{imageBase + tlsHeader.VirtualAddress:X}; seeding zeros.");
initImage = [];
}
var staticOffset = GuestTlsTemplate.RegisterModule(
tlsModuleId,
initImage,
@ -574,19 +564,6 @@ public sealed class SelfLoader : ISelfLoader
return new ModuleTlsInfo(tlsHeader.MemorySize, staticOffset);
}
private static byte[] ReadTlsInitializationImage(
ProgramHeader header, IVirtualMemory virtualMemory, ulong imageBase)
{
if (header.FileSize > header.MemorySize || header.FileSize > int.MaxValue)
throw new InvalidDataException("PT_TLS initialization size is invalid.");
var initializationImage = new byte[(int)header.FileSize];
var address = checked(imageBase + header.VirtualAddress);
if (initializationImage.Length != 0 && !virtualMemory.TryRead(address, initializationImage))
throw new InvalidDataException($"Cannot read TLS initialization bytes at 0x{address:X}.");
return initializationImage;
}
private static IReadOnlyDictionary<ulong, string> ResolveAndPatchImportStubs(
ReadOnlySpan<byte> imageData,
LoadContext loadContext,
@ -596,11 +573,9 @@ public sealed class SelfLoader : ISelfLoader
ulong imageBase,
IModuleManager? moduleManager,
uint tlsModuleId,
out IReadOnlyList<ImportedSymbolRelocation> importedRelocations,
out IReadOnlyList<string> importedModuleNames)
out IReadOnlyList<ImportedSymbolRelocation> importedRelocations)
{
importedRelocations = Array.Empty<ImportedSymbolRelocation>();
importedModuleNames = Array.Empty<string>();
if (!TryGetProgramHeader(programHeaders, ProgramHeaderType.Dynamic, out var dynamicHeader, out var dynamicHeaderIndex))
{
return EmptyImportStubs;
@ -691,21 +666,15 @@ public sealed class SelfLoader : ISelfLoader
byte[] stringTable = Array.Empty<byte>();
byte[] symbolTable = Array.Empty<byte>();
if (dynamicInfo.StrTabOffset != 0 && dynamicInfo.StrTabSize != 0 &&
!TryLoadTableBytes(
elfData,
virtualMemory,
imageBase,
dynamicInfo.StrTabOffset,
dynamicInfo.StrTabSize,
out stringTable))
{
return EmptyImportStubs;
}
if (maxSymbolIndex != 0)
{
if (stringTable.Length == 0)
if (!TryLoadTableBytes(
elfData,
virtualMemory,
imageBase,
dynamicInfo.StrTabOffset,
dynamicInfo.StrTabSize,
out stringTable))
{
return EmptyImportStubs;
}
@ -725,8 +694,6 @@ public sealed class SelfLoader : ISelfLoader
}
}
importedModuleNames = ReadImportedModuleNames(dynamicTable, stringTable);
var descriptors = new List<RelocationDescriptor>(256);
var orderedImportNids = new List<string>(128);
var seenImportNids = new HashSet<string>(StringComparer.Ordinal);
@ -2018,39 +1985,6 @@ public sealed class SelfLoader : ISelfLoader
preInitArraySize);
}
private static IReadOnlyList<string> ReadImportedModuleNames(
ReadOnlySpan<byte> dynamicTable,
ReadOnlySpan<byte> stringTable)
{
if (stringTable.IsEmpty)
{
return Array.Empty<string>();
}
var names = new List<string>();
for (var offset = 0; offset + DynamicEntrySize <= dynamicTable.Length; offset += DynamicEntrySize)
{
var tag = BinaryPrimitives.ReadInt64LittleEndian(dynamicTable.Slice(offset, sizeof(long)));
var value = BinaryPrimitives.ReadUInt64LittleEndian(dynamicTable.Slice(offset + sizeof(long), sizeof(ulong)));
if (tag == DtNull)
{
break;
}
if (tag is not (DtSceNeededModule or DtSceNeededModuleNext) ||
!TryReadNullTerminatedAscii(stringTable, (uint)value, out var name) ||
string.IsNullOrWhiteSpace(name) ||
names.Contains(name, StringComparer.OrdinalIgnoreCase))
{
continue;
}
names.Add(name);
}
return names.Count == 0 ? Array.Empty<string>() : names;
}
private static bool IsSupportedRelocationType(uint relocationType)
{
return relocationType is

View File

@ -1,405 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Runtime.Intrinsics.X86;
using Iced.Intel;
using static Iced.Intel.AssemblerRegisters;
namespace SharpEmu.Core.Loader;
// Rewrite SHA extension instructions into general-register code when the host CPU lacks them.
// Rosetta 2 and some x86 hosts raise #UD for them, and a signal per instruction is far too slow
// for titles that hash whole files. The expansion keeps every register except the destination
// XMM register and keeps the flags. It runs inside the trampoline, after the red zone is skipped.
internal static class ShaInstructionRewrite
{
// pushfq plus the saved general registers.
private const int SavedBytes = 8 * 13;
// Scratch layout: source 1 (and result), source 2, XMM0 (SHA256RNDS2 round inputs).
private const int Source1 = 0;
private const int Source2 = 16;
private const int Xmm0Copy = 32;
private const int ScratchBytes = 48;
private static readonly Register[] SavedRegisters =
{
Register.RAX, Register.RCX, Register.RDX, Register.RBX, Register.RSI, Register.RDI,
Register.R8, Register.R9, Register.R10, Register.R11, Register.R12, Register.R13,
};
internal static bool IsRequired { get; } = HostLacksSha() &&
!string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_DISABLE_SHA_REWRITE"), "1", StringComparison.Ordinal);
// Bytes the expansion of one instruction needs at most in the trampoline.
internal const int MaximumExpansionBytes = 1024;
private static bool HostLacksSha()
{
if (!X86Base.IsSupported)
{
return false;
}
var (_, ebx, _, _) = X86Base.CpuId(7, 0);
return (ebx & (1 << 29)) == 0;
}
internal static bool IsShaInstruction(in Instruction instruction) => instruction.Mnemonic is
Mnemonic.Sha1rnds4 or Mnemonic.Sha1nexte or Mnemonic.Sha1msg1 or Mnemonic.Sha1msg2 or
Mnemonic.Sha256rnds2 or Mnemonic.Sha256msg1 or Mnemonic.Sha256msg2;
// A memory source with a segment prefix or an RIP-relative address cannot be rebuilt here.
internal static bool CanRewrite(in Instruction instruction)
{
if (!IsShaInstruction(instruction) || instruction.Op0Kind != OpKind.Register)
{
return false;
}
return instruction.Op1Kind == OpKind.Register ||
(instruction.Op1Kind == OpKind.Memory &&
instruction.SegmentPrefix == Register.None &&
!instruction.IsIPRelativeMemoryOperand);
}
internal static IList<Instruction> Expand(IList<Instruction> instructions)
{
var expanded = new List<Instruction>(instructions.Count);
foreach (var instruction in instructions)
{
if (!CanRewrite(instruction))
{
expanded.Add(instruction);
continue;
}
var assembler = new Assembler(64);
EmitExpansion(assembler, instruction);
var first = true;
ulong generatedIp = 0xFFFF_0000_0000_0000UL + ((instruction.IP & 0xFFFF_FFFF) << 12);
foreach (var generated in assembler.Instructions)
{
var copy = generated;
// Keep branch targets at the first generated instruction.
copy.IP = first ? instruction.IP : generatedIp++;
first = false;
expanded.Add(copy);
}
}
return expanded;
}
internal static void EmitExpansion(Assembler a, in Instruction instruction)
{
var destination = ToXmm(instruction.Op0Register);
a.pushfq();
foreach (var register in SavedRegisters)
{
a.push(ToGpr64(register));
}
a.sub(rsp, ScratchBytes);
if (instruction.Op1Kind == OpKind.Memory)
{
// LEA reads the guest registers before any of them change.
a.lea(rax, RebaseMemory(instruction));
a.mov(rcx, __qword_ptr[rax]);
a.mov(__qword_ptr[rsp + Source2], rcx);
a.mov(rcx, __qword_ptr[rax + 8]);
a.mov(__qword_ptr[rsp + Source2 + 8], rcx);
}
else
{
a.movdqu(__xmmword_ptr[rsp + Source2], ToXmm(instruction.Op1Register));
}
a.movdqu(__xmmword_ptr[rsp + Source1], destination);
if (instruction.Mnemonic == Mnemonic.Sha256rnds2)
{
a.movdqu(__xmmword_ptr[rsp + Xmm0Copy], xmm0);
}
switch (instruction.Mnemonic)
{
case Mnemonic.Sha1rnds4: EmitSha1Rnds4(a, instruction.Immediate8 & 3); break;
case Mnemonic.Sha1nexte: EmitSha1Nexte(a); break;
case Mnemonic.Sha1msg1: EmitSha1Msg1(a); break;
case Mnemonic.Sha1msg2: EmitSha1Msg2(a); break;
case Mnemonic.Sha256rnds2: EmitSha256Rnds2(a); break;
case Mnemonic.Sha256msg1: EmitSha256Msg1(a); break;
default: EmitSha256Msg2(a); break;
}
a.movdqu(destination, __xmmword_ptr[rsp + Source1]);
a.add(rsp, ScratchBytes);
for (var index = SavedRegisters.Length - 1; index >= 0; index--)
{
a.pop(ToGpr64(SavedRegisters[index]));
}
a.popfq();
}
// The guest stack pointer is above the scratch area, the saved registers and the red zone.
private static AssemblerMemoryOperand RebaseMemory(in Instruction instruction)
{
var displacement = unchecked((long)instruction.MemoryDisplacement64);
if (instruction.MemoryBase == Register.RSP)
{
displacement += ScratchBytes + SavedBytes + 128;
}
var baseRegister = instruction.MemoryBase == Register.None ? default : ToGpr64(instruction.MemoryBase);
var memory = instruction.MemoryBase == Register.None ? __[displacement] : __[baseRegister + displacement];
if (instruction.MemoryIndex != Register.None)
{
memory = instruction.MemoryBase == Register.None
? __[ToGpr64(instruction.MemoryIndex) * instruction.MemoryIndexScale + displacement]
: __[baseRegister + ToGpr64(instruction.MemoryIndex) * instruction.MemoryIndexScale + displacement];
}
return memory;
}
private static AssemblerMemoryOperand Dword(int slot, int index) => __dword_ptr[rsp + slot + 4 * index];
private static void EmitSha1Rnds4(Assembler a, int function)
{
var k = function switch
{
0 => 0x5A827999,
1 => 0x6ED9EBA1,
2 => unchecked((int)0x8F1BBCDC),
_ => unchecked((int)0xCA62C1D6),
};
a.mov(eax, Dword(Source1, 3));
a.mov(ebx, Dword(Source1, 2));
a.mov(ecx, Dword(Source1, 1));
a.mov(edx, Dword(Source1, 0));
a.xor(esi, esi);
for (var round = 0; round < 4; round++)
{
switch (function)
{
case 0:
// (b & c) ^ (~b & d) == d ^ (b & (c ^ d))
a.mov(edi, ecx);
a.xor(edi, edx);
a.and(edi, ebx);
a.xor(edi, edx);
break;
case 2:
// (b & c) | (d & (b | c)) is the majority of b, c and d.
a.mov(edi, ebx);
a.or(edi, ecx);
a.and(edi, edx);
a.mov(r8d, ebx);
a.and(r8d, ecx);
a.or(edi, r8d);
break;
default:
a.mov(edi, ebx);
a.xor(edi, ecx);
a.xor(edi, edx);
break;
}
a.add(edi, Dword(Source2, 3 - round));
a.add(edi, esi);
a.add(edi, k);
a.mov(r8d, eax);
a.rol(r8d, (byte)5);
a.add(edi, r8d);
a.mov(esi, edx);
a.mov(edx, ecx);
a.mov(ecx, ebx);
a.rol(ecx, (byte)30);
a.mov(ebx, eax);
a.mov(eax, edi);
}
a.mov(Dword(Source1, 3), eax);
a.mov(Dword(Source1, 2), ebx);
a.mov(Dword(Source1, 1), ecx);
a.mov(Dword(Source1, 0), edx);
}
private static void EmitSha1Nexte(Assembler a)
{
a.mov(eax, Dword(Source1, 3));
a.rol(eax, (byte)30);
a.add(eax, Dword(Source2, 3));
a.mov(Dword(Source1, 3), eax);
for (var index = 0; index < 3; index++)
{
a.mov(ecx, Dword(Source2, index));
a.mov(Dword(Source1, index), ecx);
}
}
private static void EmitSha1Msg1(Assembler a)
{
// w0..w3 from source 1 (w0 in dword 3), w4 and w5 from source 2.
a.mov(eax, Dword(Source1, 3));
a.mov(ebx, Dword(Source1, 2));
a.mov(ecx, Dword(Source1, 1));
a.mov(edx, Dword(Source1, 0));
a.mov(esi, Dword(Source2, 3));
a.mov(edi, Dword(Source2, 2));
a.xor(eax, ecx);
a.xor(ebx, edx);
a.xor(ecx, esi);
a.xor(edx, edi);
a.mov(Dword(Source1, 3), eax);
a.mov(Dword(Source1, 2), ebx);
a.mov(Dword(Source1, 1), ecx);
a.mov(Dword(Source1, 0), edx);
}
private static void EmitSha1Msg2(Assembler a)
{
a.mov(eax, Dword(Source1, 3));
a.xor(eax, Dword(Source2, 2));
a.rol(eax, (byte)1);
a.mov(ebx, Dword(Source1, 2));
a.xor(ebx, Dword(Source2, 1));
a.rol(ebx, (byte)1);
a.mov(ecx, Dword(Source1, 1));
a.xor(ecx, Dword(Source2, 0));
a.rol(ecx, (byte)1);
a.mov(edx, Dword(Source1, 0));
a.xor(edx, eax);
a.rol(edx, (byte)1);
a.mov(Dword(Source1, 3), eax);
a.mov(Dword(Source1, 2), ebx);
a.mov(Dword(Source1, 1), ecx);
a.mov(Dword(Source1, 0), edx);
}
private static void EmitSha256Rnds2(Assembler a)
{
// a..h in eax, ebx, ecx, edx, esi, edi, r8d, r9d.
a.mov(eax, Dword(Source2, 3));
a.mov(ebx, Dword(Source2, 2));
a.mov(ecx, Dword(Source1, 3));
a.mov(edx, Dword(Source1, 2));
a.mov(esi, Dword(Source2, 1));
a.mov(edi, Dword(Source2, 0));
a.mov(r8d, Dword(Source1, 1));
a.mov(r9d, Dword(Source1, 0));
for (var round = 0; round < 2; round++)
{
// r10d = h + Sigma1(e) + Ch(e, f, g) + wk
EmitRotateXor(a, r10d, esi, r11d, 6, 11, 25);
a.add(r10d, r9d);
a.add(r10d, Dword(Xmm0Copy, round));
a.mov(r11d, edi);
a.xor(r11d, r8d);
a.and(r11d, esi);
a.xor(r11d, r8d);
a.add(r10d, r11d);
// r11d = Sigma0(a) + Maj(a, b, c)
EmitRotateXor(a, r11d, eax, r12d, 2, 13, 22);
a.mov(r12d, eax);
a.or(r12d, ebx);
a.and(r12d, ecx);
a.mov(r13d, eax);
a.and(r13d, ebx);
a.or(r12d, r13d);
a.add(r11d, r12d);
a.mov(r9d, r8d);
a.mov(r8d, edi);
a.mov(edi, esi);
a.mov(esi, edx);
a.add(esi, r10d);
a.mov(edx, ecx);
a.mov(ecx, ebx);
a.mov(ebx, eax);
a.mov(eax, r10d);
a.add(eax, r11d);
}
a.mov(Dword(Source1, 3), eax);
a.mov(Dword(Source1, 2), ebx);
a.mov(Dword(Source1, 1), esi);
a.mov(Dword(Source1, 0), edi);
}
private static void EmitSha256Msg1(Assembler a)
{
// w0..w3 in edx, ecx, ebx, eax; w4 in esi. Results go to r9d..r12d.
a.mov(eax, Dword(Source1, 3));
a.mov(ebx, Dword(Source1, 2));
a.mov(ecx, Dword(Source1, 1));
a.mov(edx, Dword(Source1, 0));
a.mov(esi, Dword(Source2, 0));
EmitSmallSigma(a, r9d, esi, r8d, 7, 18, 3);
a.add(r9d, eax);
EmitSmallSigma(a, r10d, eax, r8d, 7, 18, 3);
a.add(r10d, ebx);
EmitSmallSigma(a, r11d, ebx, r8d, 7, 18, 3);
a.add(r11d, ecx);
EmitSmallSigma(a, r12d, ecx, r8d, 7, 18, 3);
a.add(r12d, edx);
a.mov(Dword(Source1, 3), r9d);
a.mov(Dword(Source1, 2), r10d);
a.mov(Dword(Source1, 1), r11d);
a.mov(Dword(Source1, 0), r12d);
}
private static void EmitSha256Msg2(Assembler a)
{
// w16 = s1[0] + sigma1(w14); w17 = s1[1] + sigma1(w15); w18 and w19 use w16 and w17.
a.mov(esi, Dword(Source2, 2));
EmitSmallSigma(a, eax, esi, r8d, 17, 19, 10);
a.add(eax, Dword(Source1, 0));
a.mov(esi, Dword(Source2, 3));
EmitSmallSigma(a, ebx, esi, r8d, 17, 19, 10);
a.add(ebx, Dword(Source1, 1));
EmitSmallSigma(a, ecx, eax, r8d, 17, 19, 10);
a.add(ecx, Dword(Source1, 2));
EmitSmallSigma(a, edx, ebx, r8d, 17, 19, 10);
a.add(edx, Dword(Source1, 3));
a.mov(Dword(Source1, 0), eax);
a.mov(Dword(Source1, 1), ebx);
a.mov(Dword(Source1, 2), ecx);
a.mov(Dword(Source1, 3), edx);
}
// result = ror(x, r1) ^ ror(x, r2) ^ ror(x, r3)
private static void EmitRotateXor(
Assembler a, AssemblerRegister32 result, AssemblerRegister32 x, AssemblerRegister32 temp, int r1, int r2, int r3)
{
a.mov(result, x);
a.ror(result, (byte)r1);
a.mov(temp, x);
a.ror(temp, (byte)r2);
a.xor(result, temp);
a.mov(temp, x);
a.ror(temp, (byte)r3);
a.xor(result, temp);
}
// result = ror(x, r1) ^ ror(x, r2) ^ (x >> shift)
private static void EmitSmallSigma(
Assembler a, AssemblerRegister32 result, AssemblerRegister32 x, AssemblerRegister32 temp, int r1, int r2, int shift)
{
a.mov(result, x);
a.ror(result, (byte)r1);
a.mov(temp, x);
a.ror(temp, (byte)r2);
a.xor(result, temp);
a.mov(temp, x);
a.shr(temp, (byte)shift);
a.xor(result, temp);
}
private static AssemblerRegisterXMM ToXmm(Register register) => new(register);
private static AssemblerRegister64 ToGpr64(Register register) => new(register.GetFullRegister());
}

View File

@ -10,8 +10,6 @@ public interface IVirtualMemory : ICpuMemory
{
void Clear();
bool IsBackedView(ulong address);
void Map(ulong virtualAddress, ulong memorySize, ulong fileOffset, ReadOnlySpan<byte> fileData, ProgramHeaderFlags protection);
IReadOnlyList<VirtualMemoryRegion> SnapshotRegions();

File diff suppressed because it is too large Load Diff

View File

@ -11,8 +11,6 @@ public sealed class VirtualMemory : IVirtualMemory
private readonly object _gate = new();
private readonly List<MappedRegion> _regions = new();
public bool IsBackedView(ulong address) => false;
public void Clear()
{
lock (_gate)

View File

@ -7,16 +7,12 @@ using SharpEmu.Core.Cpu.Disasm;
using SharpEmu.Core.Loader;
using SharpEmu.Core.Memory;
using SharpEmu.HLE;
using SharpEmu.HLE.Host;
using SharpEmu.HLE.GpuMemory;
using SharpEmu.Libs.VideoOut;
using SharpEmu.Libs.Kernel;
using SharpEmu.Libs.AppContent;
using SharpEmu.Libs.SaveData;
using SharpEmu.Libs.Fiber;
using SharpEmu.Libs.SystemService;
using SharpEmu.Libs.Network;
using SharpEmu.Libs.Np;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Linq;
@ -41,9 +37,6 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
private readonly ISymbolCatalog _symbolCatalog;
private readonly CpuExecutionOptions _cpuExecutionOptions;
private readonly IFileSystem _fileSystem;
private readonly GuestGpuMemory? _gpuMemory;
private readonly int _systemLanguage;
private readonly object _dynamicModuleGate = new();
private bool _disposed;
public string? LastExecutionDiagnostics { get; private set; }
@ -63,11 +56,8 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
IModuleManager moduleManager,
ISymbolCatalog? symbolCatalog = null,
CpuExecutionOptions cpuExecutionOptions = default,
IFileSystem? fileSystem = null,
GuestGpuMemory? gpuMemory = null,
int systemLanguage = 1)
IFileSystem? fileSystem = null)
{
_gpuMemory = gpuMemory;
_selfLoader = selfLoader ?? throw new ArgumentNullException(nameof(selfLoader));
_virtualMemory = virtualMemory ?? throw new ArgumentNullException(nameof(virtualMemory));
_cpuDispatcher = cpuDispatcher ?? throw new ArgumentNullException(nameof(cpuDispatcher));
@ -81,7 +71,6 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
DebugHook = cpuExecutionOptions.DebugHook,
};
_fileSystem = fileSystem ?? new PhysicalFileSystem();
_systemLanguage = systemLanguage;
}
public static ISharpEmuRuntime CreateDefault(SharpEmuRuntimeOptions options = default)
@ -93,17 +82,13 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
ImportTraceLimit = Math.Max(0, options.ImportTraceLimit),
DebugHook = options.DebugHook,
};
var virtualMemory = new PhysicalVirtualMemory(
viewHost: HostViewMemory.Create(),
preReserveGuestAddressSpace: true);
var moduleManager = new ModuleManager();
// The compile-time generated registry (SharpEmu.SourceGenerators) is the sole
// registration source; content tests in SharpEmu.Libs.Tests pin its invariants.
moduleManager.RegisterExports(SharpEmu.Generated.SysAbiExportRegistry.CreateExports(Generation.Gen4 | Generation.Gen5));
moduleManager.Freeze();
var gpuMemory = new GuestGpuMemory(virtualMemory);
GuestGpuMemoryHook.Attach(gpuMemory);
var virtualMemory = new PhysicalVirtualMemory();
var fileSystem = new PhysicalFileSystem();
@ -114,9 +99,7 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
moduleManager,
Aerolib.Instance,
cpuExecutionOptions,
fileSystem,
gpuMemory,
options.SystemLanguage ?? 1);
fileSystem);
}
public SelfImage LoadImage(string ebootPath)
@ -157,15 +140,11 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
LastBasicBlockTrace = null;
LastMilestoneLog = null;
FiberExports.ResetRuntimeState();
Http2Exports.ResetRuntimeState();
NpAuthExports.ResetRuntimeState();
NpUniversalDataSystemExports.ResetRuntimeState();
KernelModuleRegistry.Reset();
var image = LoadImage(normalizedEbootPath);
VideoOutExports.ConfigureApplicationInfo(image.Title, image.TitleId, image.Version);
KernelMemoryCompatExports.ConfigureApplicationInfo(image.TitleId);
SaveDataExports.ConfigureApplicationInfo(image.TitleId);
SystemServiceExports.ConfigureApplicationInfo(image.TitleId, _systemLanguage);
SystemServiceExports.ConfigureApplicationInfo(image.TitleId);
_ = RegisterLoadedModule(normalizedEbootPath, image, isMain: true, isSystemModule: false);
KernelRuntimeCompatExports.ConfigureProcessProcParamAddress(image.ProcParamAddress);
Console.Error.WriteLine($"[RUNTIME] Entry: 0x{image.EntryPoint:X16}");
@ -180,16 +159,8 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
HleDataSymbols.ConfigureProcessImageName(processImageName);
MergeKnownHleDataSymbols(activeRuntimeSymbols);
var loadedModuleImages = LoadAdjacentSceModules(ebootPath, image, activeImportStubs, activeRuntimeSymbols);
var loadedModuleImages = LoadAdjacentSceModules(ebootPath, activeImportStubs, activeRuntimeSymbols);
RebindImportedDataSymbols(image, loadedModuleImages, activeRuntimeSymbols);
var app0Root = Path.GetDirectoryName(normalizedEbootPath) ?? string.Empty;
KernelModuleRegistry.ConfigureModuleLoader(modulePath => LoadRequestedAppModule(
modulePath,
app0Root,
image,
loadedModuleImages,
activeImportStubs,
activeRuntimeSymbols));
var initializerResult = RunAllInitializers(
image,
loadedModuleImages,
@ -429,9 +400,6 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
}
Environment.SetEnvironmentVariable(app0VariableName, app0Root);
// Overlap the cooked-id APR walk with module load so the first ReadFile
// miss mid-boot does not stall on a cold USB index.
SharpEmu.Libs.Ampr.AmprFileRegistry.BeginApp0IndexPreload(app0Root);
return new App0BindingScope(app0VariableName);
}
@ -655,7 +623,6 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
private List<LoadedModuleImage> LoadAdjacentSceModules(
string ebootPath,
SelfImage mainImage,
IDictionary<ulong, string> importStubs,
IDictionary<string, ulong> runtimeSymbols)
{
@ -668,20 +635,16 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
var moduleDirectories = new[]
{
(Path: Path.Combine(ebootDirectory, "sce_module"), StartAtBoot: true, LinkedOnly: false, SearchOption: SearchOption.TopDirectoryOnly),
(Path: Path.Combine(ebootDirectory, "sce_modules"), StartAtBoot: true, LinkedOnly: false, SearchOption: SearchOption.TopDirectoryOnly),
(Path: Path.Combine(ebootDirectory, "Media", "Modules"), StartAtBoot: true, LinkedOnly: false, SearchOption: SearchOption.TopDirectoryOnly),
// A linked PRX can be beside eboot.bin. Load only the app-root modules
// named by the main image at boot, after the normal module directories
// they may depend on. Map the other app-root modules so
// sceKernelLoadStartModule can start them later.
(Path: ebootDirectory, StartAtBoot: true, LinkedOnly: true, SearchOption: SearchOption.TopDirectoryOnly),
(Path: ebootDirectory, StartAtBoot: false, LinkedOnly: false, SearchOption: SearchOption.TopDirectoryOnly),
(Path: Path.Combine(ebootDirectory, "sce_module"), StartAtBoot: true),
(Path: Path.Combine(ebootDirectory, "sce_modules"), StartAtBoot: true),
(Path: Path.Combine(ebootDirectory, "Media", "Modules"), StartAtBoot: true),
// Unity native plugins are loaded later through sceKernelLoadStartModule. Map
// them up front so the HLE loader can return a real module handle and dlsym
// can resolve their exports, but defer DT_INIT until the guest requests them.
(Path: Path.Combine(ebootDirectory, "Media", "Plugins"), StartAtBoot: false, LinkedOnly: false, SearchOption: SearchOption.TopDirectoryOnly),
(Path: Path.Combine(ebootDirectory, "Media", "Plugins"), StartAtBoot: false),
}
.GroupBy(entry => entry.Path, StringComparer.OrdinalIgnoreCase)
.Select(group => group.First())
.Where(entry => Directory.Exists(entry.Path))
.ToArray();
@ -692,9 +655,8 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
var allModulePaths = moduleDirectories
.SelectMany(directory => Directory
.EnumerateFiles(directory.Path, "*", directory.SearchOption)
.EnumerateFiles(directory.Path)
.OrderBy(path => path, StringComparer.OrdinalIgnoreCase)
.Where(path => !directory.LinkedOnly || IsMainImageLinkedModule(path, mainImage.ImportedModuleNames))
.Select(path => (Path: path, directory.StartAtBoot)))
.Where(entry =>
{
@ -781,176 +743,6 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
return loadedImages;
}
private KernelModuleRegistry.ModuleLoadResult LoadRequestedAppModule(
string guestModulePath,
string app0Root,
SelfImage mainImage,
List<LoadedModuleImage> loadedModuleImages,
Dictionary<ulong, string> activeImportStubs,
Dictionary<string, ulong> activeRuntimeSymbols)
{
lock (_dynamicModuleGate)
{
if (!TryResolveApp0ModulePath(app0Root, guestModulePath, out var modulePath))
{
Console.Error.WriteLine(
$"[RUNTIME] Runtime module path rejected: '{guestModulePath}'");
return KernelModuleRegistry.ModuleLoadResult.Failure(
(int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND);
}
if (KernelModuleRegistry.TryFindByExactPath(modulePath, out var existingModule))
{
return KernelModuleRegistry.ModuleLoadResult.Success(existingModule.Handle);
}
try
{
var fileInfo = new FileInfo(modulePath);
if (!fileInfo.Exists || fileInfo.Length <= 0 || fileInfo.Length > int.MaxValue)
{
return KernelModuleRegistry.ModuleLoadResult.Failure(
(int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND);
}
var moduleBytes = GC.AllocateUninitializedArray<byte>((int)fileInfo.Length);
using (var stream = File.OpenRead(modulePath))
{
stream.ReadExactly(moduleBytes);
}
var moduleImage = _selfLoader.LoadAdditional(
moduleBytes.AsSpan(),
_virtualMemory,
_moduleManager,
_fileSystem,
Path.GetDirectoryName(modulePath));
var candidateImportStubs = new Dictionary<ulong, string>(activeImportStubs);
var candidateRuntimeSymbols = new Dictionary<string, ulong>(activeRuntimeSymbols, StringComparer.Ordinal);
_ = MergeImportStubs(candidateImportStubs, moduleImage.ImportStubs, modulePath);
_ = MergeRuntimeSymbols(candidateRuntimeSymbols, moduleImage.RuntimeSymbols);
InstallNativePluginCompatibilityHooks(candidateImportStubs, moduleImage, modulePath);
string? installError = null;
if (_cpuDispatcher is not CpuDispatcher dispatcher ||
!dispatcher.TryInstallAdditionalModule(
candidateImportStubs,
candidateRuntimeSymbols,
out installError))
{
Console.Error.WriteLine(
$"[RUNTIME] Runtime module import installation failed: {modulePath} " +
$"({installError ?? "unsupported CPU backend"})");
return KernelModuleRegistry.ModuleLoadResult.Failure(
(int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_IMPLEMENTED);
}
ReplaceDictionary(activeImportStubs, candidateImportStubs);
ReplaceDictionary(activeRuntimeSymbols, candidateRuntimeSymbols);
var handle = RegisterLoadedModule(
modulePath,
moduleImage,
isMain: false,
isSystemModule: false);
loadedModuleImages.Add(new LoadedModuleImage(modulePath, moduleImage, handle, StartAtBoot: false));
RebindImportedDataSymbols(mainImage, loadedModuleImages, activeRuntimeSymbols);
Console.Error.WriteLine(
$"[RUNTIME] Loaded requested module '{guestModulePath}' as {Path.GetFileName(modulePath)}: " +
$"handle={handle}, imports={moduleImage.ImportStubs.Count}, symbols={moduleImage.RuntimeSymbols.Count}");
return KernelModuleRegistry.ModuleLoadResult.Success(handle);
}
catch (Exception ex)
{
Console.Error.WriteLine(
$"[RUNTIME] Runtime module load failed: {modulePath} " +
$"({ex.GetType().Name}: {ex.Message})");
return KernelModuleRegistry.ModuleLoadResult.Failure(
(int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND);
}
}
}
private static bool TryResolveApp0ModulePath(
string app0Root,
string guestModulePath,
out string modulePath)
{
modulePath = string.Empty;
if (string.IsNullOrWhiteSpace(app0Root) || string.IsNullOrWhiteSpace(guestModulePath))
{
return false;
}
var normalizedGuestPath = guestModulePath.Replace('\\', '/');
string relativePath;
if (normalizedGuestPath.StartsWith("/app0/", StringComparison.OrdinalIgnoreCase))
{
relativePath = normalizedGuestPath[6..];
}
else if (normalizedGuestPath.StartsWith("app0/", StringComparison.OrdinalIgnoreCase))
{
relativePath = normalizedGuestPath[5..];
}
else if (!normalizedGuestPath.StartsWith("/", StringComparison.Ordinal))
{
relativePath = normalizedGuestPath;
}
else
{
return false;
}
var root = Path.GetFullPath(app0Root);
var candidate = Path.GetFullPath(
Path.Combine(root, relativePath.Replace('/', Path.DirectorySeparatorChar)));
var rootPrefix = Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar;
if (!candidate.StartsWith(rootPrefix, HostPathComparison))
{
return false;
}
modulePath = candidate;
return true;
}
private static StringComparison HostPathComparison => OperatingSystem.IsWindows()
? StringComparison.OrdinalIgnoreCase
: StringComparison.Ordinal;
private static void ReplaceDictionary<TKey, TValue>(
IDictionary<TKey, TValue> destination,
IReadOnlyDictionary<TKey, TValue> source)
where TKey : notnull
{
destination.Clear();
foreach (var entry in source)
{
destination.Add(entry);
}
}
private static bool IsMainImageLinkedModule(string modulePath, IReadOnlyList<string> importedModuleNames)
{
var fileName = Path.GetFileName(modulePath);
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(modulePath);
if (string.IsNullOrWhiteSpace(fileName) || string.IsNullOrWhiteSpace(fileNameWithoutExtension))
{
return false;
}
for (var i = 0; i < importedModuleNames.Count; i++)
{
var importedName = importedModuleNames[i];
if (string.Equals(importedName, fileName, StringComparison.OrdinalIgnoreCase) ||
string.Equals(importedName, fileNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
private static void InstallNativePluginCompatibilityHooks(
IDictionary<ulong, string> importStubs,
SelfImage moduleImage,
@ -1009,7 +801,6 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
Environment.GetEnvironmentVariable("SHARPEMU_LOG_DATA_REBIND"),
"1",
StringComparison.Ordinal);
Span<byte> relocationValueBytes = stackalloc byte[sizeof(ulong)];
for (var i = 0; i < image.ImportedRelocations.Count; i++)
{
var relocation = image.ImportedRelocations[i];
@ -1036,19 +827,8 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
{
if (logRebind)
{
var readable = _virtualMemory.TryRead(relocation.TargetAddress, relocationValueBytes);
var currentValue = readable ? BinaryPrimitives.ReadUInt64LittleEndian(relocationValueBytes) : 0;
Console.Error.WriteLine(
$"[RUNTIME] Imported data write-failed: nid={relocation.Nid} target=0x{relocation.TargetAddress:X16} value=0x{reboundValue:X16} readable={readable} current=0x{currentValue:X16}");
foreach (var region in _virtualMemory.SnapshotRegions())
{
if (relocation.TargetAddress >= region.VirtualAddress &&
relocation.TargetAddress - region.VirtualAddress < region.MemorySize)
{
Console.Error.WriteLine(
$"[RUNTIME] Imported data target-region: start=0x{region.VirtualAddress:X16} size=0x{region.MemorySize:X} protection={region.Protection}");
}
}
$"[RUNTIME] Imported data write-failed: nid={relocation.Nid} target=0x{relocation.TargetAddress:X16} value=0x{reboundValue:X16}");
}
unresolved++;
@ -1378,7 +1158,6 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
}
_disposed = true;
KernelModuleRegistry.ConfigureModuleLoader(null);
if (_cpuDispatcher is IDisposable disposableDispatcher)
{
@ -1395,17 +1174,6 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
return;
}
if (_gpuMemory != null)
{
if (GuestGpuMemoryHook.TryTakeShutdownSummary(out var gpuSummary))
{
Console.Error.WriteLine("[LOADER][INFO] " + gpuSummary);
}
GuestGpuMemoryHook.Attach(null);
_gpuMemory.Dispose();
}
KernelMemoryCompatExports.ResetBackingMappings(_virtualMemory as IGuestBackedSpace);
if (_virtualMemory is IDisposable disposableMemory)
{
disposableMemory.Dispose();

View File

@ -10,8 +10,6 @@ public readonly struct SharpEmuRuntimeOptions
{
public CpuExecutionEngine CpuEngine { get; init; }
public int? SystemLanguage { get; init; }
public bool StrictDynlibResolution { get; init; }
public int ImportTraceLimit { get; init; }

View File

@ -1,16 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.GUI;
/// <summary>
/// Stateless trailing action that opens the library folder picker.
/// </summary>
public sealed class AddFolderTile : LibraryTile
{
public static AddFolderTile Instance { get; } = new();
private AddFolderTile()
{
}
}

View File

@ -1,38 +1,267 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
Application composition root. Shared resources and styles are included in
cascade order so individual launcher views do not redefine global visuals.
-->
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SharpEmu.GUI"
x:Class="SharpEmu.GUI.App"
RequestedThemeVariant="Dark">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceInclude Source="avares://SharpEmu.GUI/Themes/Tokens.axaml" />
<ResourceInclude Source="avares://SharpEmu.GUI/Themes/Templates/SettingRow.axaml" />
<ResourceInclude Source="avares://SharpEmu.GUI/Themes/Templates/OptionsControls.axaml" />
<ResourceInclude Source="avares://SharpEmu.GUI/Themes/Templates/SplitNumericUpDown.axaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
<Color x:Key="SystemAccentColor">#7C5CFC</Color>
<LinearGradientBrush x:Key="BgBrush" StartPoint="0%,0%" EndPoint="100%,100%">
<GradientStop Offset="0" Color="#12151F" />
<GradientStop Offset="0.55" Color="#0D1017" />
<GradientStop Offset="1" Color="#0B0D14" />
</LinearGradientBrush>
<SolidColorBrush x:Key="ChromeBrush" Color="#090C12" />
<SolidColorBrush x:Key="CardBrush" Color="#141924" />
<SolidColorBrush x:Key="CardBorderBrush" Color="#232B3A" />
<SolidColorBrush x:Key="ElevatedBrush" Color="#1B2230" />
<SolidColorBrush x:Key="TextBrush" Color="#E8ECF4" />
<SolidColorBrush x:Key="MutedBrush" Color="#8B94A7" />
<SolidColorBrush x:Key="FaintBrush" Color="#5A6478" />
<SolidColorBrush x:Key="AccentBrush" Color="#7C5CFC" />
<SolidColorBrush x:Key="AccentHoverBrush" Color="#8F73FF" />
<SolidColorBrush x:Key="DangerBrush" Color="#E5484D" />
<SolidColorBrush x:Key="DangerHoverBrush" Color="#F2555A" />
<SolidColorBrush x:Key="SuccessBrush" Color="#46C46B" />
<SolidColorBrush x:Key="InfoBrush" Color="#58A6FF" />
<SolidColorBrush x:Key="TileHoverBrush" Color="#1A2130" />
<SolidColorBrush x:Key="TileSelectedBrush" Color="#212A3F" />
<ControlTheme x:Key="{x:Type local:SettingRow}" TargetType="local:SettingRow">
<Setter Property="Template">
<ControlTemplate>
<Grid ColumnDefinitions="*,Auto">
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
<TextBlock x:Name="PART_Label" Text="{TemplateBinding Label}" FontSize="13" />
<TextBlock Text="{TemplateBinding Description}" FontSize="11"
Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap"
IsVisible="{Binding Description, RelativeSource={RelativeSource TemplatedParent},
Converter={x:Static StringConverters.IsNotNullOrEmpty}}" />
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="10" VerticalAlignment="Center">
<ToggleSwitch OnContent="Override" OffContent="Override" MinWidth="0"
VerticalAlignment="Center"
IsVisible="{TemplateBinding ShowOverride}"
IsChecked="{Binding IsOverridden, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}" />
<ContentPresenter x:Name="PART_Slot" Content="{TemplateBinding Content}" VerticalAlignment="Center" />
</StackPanel>
</Grid>
</ControlTemplate>
</Setter>
</ControlTheme>
</Application.Resources>
<Application.Styles>
<FluentTheme />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Base.axaml" />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Surfaces.axaml" />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Buttons.axaml" />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Chrome.axaml" />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Inputs.axaml" />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Console.axaml" />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Library.axaml" />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/OptionsNav.axaml" />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/Options.axaml" />
<StyleInclude Source="avares://SharpEmu.GUI/Themes/Styles/GameOptions.axaml" />
<Style Selector="Window">
<Setter Property="FontFamily" Value="Inter, Segoe UI, sans-serif" />
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
</Style>
<Style Selector="Border.card">
<Setter Property="Background" Value="{StaticResource CardBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource CardBorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="12" />
<Setter Property="Padding" Value="16" />
</Style>
<Style Selector="Border.pill">
<Setter Property="Background" Value="{StaticResource ElevatedBrush}" />
<Setter Property="CornerRadius" Value="999" />
<Setter Property="Padding" Value="10,3" />
</Style>
<!-- Session status/hotkey badges: the title-id pill geometry with a
tinted fill so state (RUNNING) and keys (F11) read at a glance. -->
<Style Selector="Border.badge">
<Setter Property="CornerRadius" Value="999" />
<Setter Property="Padding" Value="8,2" />
<Setter Property="BorderThickness" Value="1" />
</Style>
<Style Selector="Border.badge.running">
<Setter Property="Background" Value="#1E46C46B" />
<Setter Property="BorderBrush" Value="#5546C46B" />
</Style>
<Style Selector="Border.badge.key">
<Setter Property="Background" Value="#1E58A6FF" />
<Setter Property="BorderBrush" Value="#5558A6FF" />
</Style>
<Style Selector="TextBlock.sectionTitle">
<Setter Property="FontSize" Value="11" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="LetterSpacing" Value="1.5" />
<Setter Property="Foreground" Value="{StaticResource MutedBrush}" />
</Style>
<Style Selector="TextBlock.fieldLabel">
<Setter Property="FontSize" Value="12" />
<Setter Property="Foreground" Value="{StaticResource MutedBrush}" />
<Setter Property="Margin" Value="0,0,0,6" />
</Style>
<Style Selector="TextBox">
<Setter Property="CornerRadius" Value="8" />
</Style>
<Style Selector="Button.accent">
<Setter Property="Background" Value="{StaticResource AccentBrush}" />
<Setter Property="Foreground" Value="White" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Padding" Value="22,10" />
<Setter Property="CornerRadius" Value="8" />
</Style>
<Style Selector="Button.accent:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{StaticResource AccentHoverBrush}" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="Button.danger">
<Setter Property="Background" Value="{StaticResource DangerBrush}" />
<Setter Property="Foreground" Value="White" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Padding" Value="22,10" />
<Setter Property="CornerRadius" Value="8" />
</Style>
<Style Selector="Button.danger:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{StaticResource DangerHoverBrush}" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="Button.ghost">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="{StaticResource CardBorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
<Setter Property="Padding" Value="12,7" />
<Setter Property="CornerRadius" Value="8" />
</Style>
<Style Selector="Button.ghost:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{StaticResource ElevatedBrush}" />
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
</Style>
<Style Selector="ToggleButton.ghost">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="{StaticResource CardBorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
<Setter Property="Padding" Value="12,7" />
<Setter Property="CornerRadius" Value="8" />
</Style>
<Style Selector="ToggleButton.ghost:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{StaticResource ElevatedBrush}" />
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
</Style>
<Style Selector="ToggleButton.ghost:checked /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{StaticResource ElevatedBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource AccentBrush}" />
<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}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="10" />
<Setter Property="Padding" Value="6" />
</Style>
<Style Selector="ContextMenu MenuItem">
<Setter Property="Padding" Value="10,7" />
<Setter Property="CornerRadius" Value="7" />
</Style>
<Style Selector="ContextMenu Separator">
<Setter Property="Background" Value="{StaticResource CardBorderBrush}" />
<Setter Property="Height" Value="1" />
<Setter Property="Margin" Value="8,4" />
</Style>
<Style Selector="ListBox.console">
<Setter Property="Background" Value="#0B0E14" />
<Setter Property="FontFamily" Value="Cascadia Mono, Consolas, Courier New, monospace" />
<Setter Property="FontSize" Value="12" />
</Style>
<Style Selector="ListBox.console ListBoxItem">
<Setter Property="Padding" Value="10,1" />
<Setter Property="MinHeight" Value="0" />
</Style>
<!-- Cover-art library grid -->
<Style Selector="ListBox.tileGrid ListBoxItem">
<Setter Property="Padding" Value="10" />
<Setter Property="Margin" Value="5" />
<Setter Property="CornerRadius" Value="14" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="RenderTransform" Value="translateY(0px)" />
<Setter Property="Transitions">
<Transitions>
<TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.12" />
</Transitions>
</Setter>
</Style>
<Style Selector="ListBox.tileGrid ListBoxItem:pointerover">
<Setter Property="RenderTransform" Value="translateY(-3px)" />
</Style>
<Style Selector="ListBox.tileGrid ListBoxItem:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{StaticResource TileHoverBrush}" />
</Style>
<Style Selector="ListBox.tileGrid ListBoxItem:selected /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{StaticResource TileSelectedBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource AccentBrush}" />
</Style>
<Style Selector="ListBox.tileGrid ListBoxItem:selected:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{StaticResource TileSelectedBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource AccentHoverBrush}" />
</Style>
<Style Selector="Border.coverShadow">
<Setter Property="CornerRadius" Value="10" />
<Setter Property="BoxShadow" Value="0 6 14 0 #55000000" />
</Style>
<Style Selector="Border.coverClip">
<Setter Property="CornerRadius" Value="10" />
<Setter Property="ClipToBounds" Value="True" />
<Setter Property="Background" Value="{StaticResource ElevatedBrush}" />
</Style>
</Application.Styles>
</Application>

View File

@ -18,7 +18,6 @@ public partial class App : Application
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
desktop.ShutdownMode = Avalonia.Controls.ShutdownMode.OnMainWindowClose;
desktop.MainWindow = new MainWindow();
}

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
using System.IO;
using LibAtrac9.Utilities;
@ -21,7 +20,6 @@ namespace LibAtrac9
public int SampleRateIndex { get; }
/// <summary>
/// A 3-bit value specifying one of 6 substream channel mappings.
/// Always 0 for streams with independent mono channels.
/// </summary>
public int ChannelConfigIndex { get; }
/// <summary>
@ -71,12 +69,6 @@ namespace LibAtrac9
/// The number of samples in one superframe.
/// </summary>
public int SuperframeSamples { get; }
/// <summary>
/// Non-zero for streams whose config header is 0x30: every channel is
/// an independent mono stream with this many bytes per superframe,
/// and the channels are interleaved frame by frame.
/// </summary>
public int IndependentBlockSuperframeBytes { get; }
/// <summary>
/// Reads ATRAC9 configuration data and calculates the stream parameters from it.
@ -89,33 +81,16 @@ namespace LibAtrac9
throw new InvalidDataException("Config data must be 4 bytes long");
}
ReadConfigData(configData, out int a, out int b, out int c, out int d, out int independentChannels);
ReadConfigData(configData, out int a, out int b, out int c, out int d);
SampleRateIndex = a;
ChannelConfigIndex = b;
FrameBytes = c;
SuperframeIndex = d;
ConfigData = configData;
if (independentChannels > 0)
{
// The frame size field holds one channel's share; the frame as
// a whole carries one mono block per channel.
ChannelConfig = ChannelConfig.CreateIndependentMono(independentChannels);
IndependentBlockSuperframeBytes = c << SuperframeIndex;
FrameBytes = c * independentChannels;
}
else
{
if (ChannelConfigIndex >= Tables.ChannelConfig.Length)
{
throw new InvalidDataException("ATRAC9 Config Data is invalid");
}
ChannelConfig = Tables.ChannelConfig[ChannelConfigIndex];
FrameBytes = c;
}
FramesPerSuperframe = 1 << SuperframeIndex;
SuperframeBytes = FrameBytes << SuperframeIndex;
ChannelConfig = Tables.ChannelConfig[ChannelConfigIndex];
ChannelCount = ChannelConfig.ChannelCount;
SampleRate = Tables.SampleRates[SampleRateIndex];
@ -125,36 +100,21 @@ namespace LibAtrac9
SuperframeSamples = FrameSamples * FramesPerSuperframe;
}
private static void ReadConfigData(byte[] configData, out int sampleRateIndex, out int channelConfigIndex, out int frameBytes, out int superframeIndex, out int independentChannels)
private static void ReadConfigData(byte[] configData, out int sampleRateIndex, out int channelConfigIndex, out int frameBytes, out int superframeIndex)
{
var reader = new BitReader(configData);
int header = reader.ReadInt(8);
sampleRateIndex = reader.ReadInt(4);
channelConfigIndex = 0;
independentChannels = 0;
if (header == IndependentMonoHeader)
{
// PS5 multichannel streams (ambisonics: 4, 9 or 16 channels)
// replace the 3-bit channel mapping with a 6-bit channel count.
independentChannels = reader.ReadInt(6) + 1;
}
else
{
channelConfigIndex = reader.ReadInt(3);
}
channelConfigIndex = reader.ReadInt(3);
int validationBit = reader.ReadInt(1);
frameBytes = reader.ReadInt(11) + 1;
superframeIndex = reader.ReadInt(2);
if ((header != StandardHeader && header != IndependentMonoHeader) || validationBit != 0)
if (header != 0xFE || validationBit != 0)
{
throw new InvalidDataException("ATRAC9 Config Data is invalid");
}
}
private const int StandardHeader = 0xFE;
private const int IndependentMonoHeader = 0x30;
}
}

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
using System;
using LibAtrac9.Utilities;

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
namespace LibAtrac9
{

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
using System;

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
using System;

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
namespace LibAtrac9
{
@ -14,7 +13,6 @@ namespace LibAtrac9
public bool FirstInSuperframe { get; set; }
public bool ReuseBandParams { get; set; }
public int SuperframeBytesUsed { get; set; }
public int BandCount { get; set; }
public int StereoBand { get; set; }

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
using LibAtrac9.Utilities;

View File

@ -1,7 +1,4 @@
// SPDX-License-Identifier: MIT
#nullable disable
using System;
namespace LibAtrac9
{
/// <summary>
@ -19,13 +16,6 @@ namespace LibAtrac9
}
}
internal static ChannelConfig CreateIndependentMono(int channelCount)
{
var blockTypes = new BlockType[channelCount];
Array.Fill(blockTypes, BlockType.Mono);
return new ChannelConfig(blockTypes);
}
/// <summary>
/// The number of blocks or substreams in the ATRAC9 stream
/// </summary>

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
namespace LibAtrac9
{

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
using System;
using LibAtrac9.Utilities;

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
namespace LibAtrac9
{
@ -1351,4 +1350,4 @@ namespace LibAtrac9
new byte[] {0, 0, 0, 0}
};
}
}
}

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
using System;

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
using System;
using System.IO;

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
namespace LibAtrac9
{

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
using System;
using static LibAtrac9.HuffmanCodebooks;

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
using System;
using System.IO;
@ -10,57 +9,12 @@ namespace LibAtrac9
{
public static void UnpackFrame(BitReader reader, Frame frame)
{
if (frame.Config.IndependentBlockSuperframeBytes != 0)
{
UnpackIndependentMonoFrame(reader, frame);
return;
}
foreach (Block block in frame.Blocks)
{
UnpackBlock(reader, block);
}
}
// Each channel is a standalone mono superframe with a fixed byte budget,
// interleaved frame by frame. Blocks of the earlier frames are packed
// back to back; in the last frame every block gets whatever is left of
// its channel's budget, so those slots end in padding.
private static void UnpackIndependentMonoFrame(BitReader reader, Frame frame)
{
int budget = frame.Config.IndependentBlockSuperframeBytes;
bool lastFrame = frame.FrameIndex == frame.Config.FramesPerSuperframe - 1;
int slotStart = reader.Position / 8;
foreach (Block block in frame.Blocks)
{
if (frame.FrameIndex == 0)
{
block.SuperframeBytesUsed = 0;
}
int usedBefore = block.SuperframeBytesUsed;
if (lastFrame)
{
reader.Position = slotStart * 8;
}
int start = reader.Position;
UnpackBlock(reader, block);
block.SuperframeBytesUsed += (reader.Position - start) / 8;
if (block.SuperframeBytesUsed > budget)
{
throw new InvalidDataException();
}
if (lastFrame)
{
slotStart += budget - usedBefore;
reader.Position = slotStart * 8;
}
}
}
private static void UnpackBlock(BitReader reader, Block block)
{
ReadBlockHeader(reader, block);

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
namespace LibAtrac9.Utilities
{

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
using System;
using System.Diagnostics;

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
using System.Runtime.CompilerServices;

View File

@ -1,4 +1,3 @@
// SPDX-License-Identifier: MIT
#nullable disable
using System;
using System.Collections.Generic;

View File

@ -6,7 +6,6 @@ using Avalonia.Collections;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input.Platform;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Platform;
@ -22,22 +21,18 @@ public sealed class ConsoleWindow : Window
private readonly ListBox _list;
private readonly TextBox _searchBox;
private readonly CheckBox _autoScrollCheck;
private readonly GuiSettings _settings;
private bool _placementRestored;
public ConsoleWindow(
AvaloniaList<LogLine> lines,
Action clear,
bool autoScroll,
GuiSettings settings)
bool autoScroll)
{
var loc = Localization.Instance;
_sourceLines = lines;
_settings = settings;
Title = loc.Get("Console.WindowTitle");
Width = settings.ConsoleWindowWidth;
Height = settings.ConsoleWindowHeight;
Width = 980;
Height = 620;
MinWidth = 520;
MinHeight = 320;
Background = new SolidColorBrush(Color.Parse("#0D1017"));
@ -45,7 +40,7 @@ public sealed class ConsoleWindow : Window
_searchBox = new TextBox
{
PlaceholderText = loc.Get("Console.SearchWatermark"),
Watermark = loc.Get("Console.SearchWatermark"),
Width = 320,
Margin = new Thickness(0, 0, 12, 0),
};
@ -119,66 +114,9 @@ public sealed class ConsoleWindow : Window
lines.CollectionChanged += OnLinesChanged;
Closed += (_, _) => lines.CollectionChanged -= OnLinesChanged;
Opened += (_, _) => RestorePlacement();
PositionChanged += (_, _) => RememberNormalBounds();
SizeChanged += (_, _) => RememberNormalBounds();
PropertyChanged += (_, change) =>
{
if (_placementRestored && change.Property == WindowStateProperty && WindowState != WindowState.Minimized)
_settings.ConsoleWindowMaximized = WindowState == WindowState.Maximized;
};
Closing += (_, _) =>
{
RememberNormalBounds();
if (WindowState != WindowState.Minimized)
_settings.ConsoleWindowMaximized = WindowState == WindowState.Maximized;
_settings.Save();
};
RefreshVisibleLines();
}
private void RestorePlacement()
{
if (_settings.ConsoleWindowLeft is { } left && _settings.ConsoleWindowTop is { } top)
{
var savedPosition = new PixelPoint(left, top);
var screen = Screens.ScreenFromPoint(savedPosition) ?? Screens.ScreenFromWindow(Owner ?? this) ?? Screens.Primary;
if (screen is not null)
{
Width = Math.Min(Width, Math.Max(MinWidth, screen.WorkingArea.Width / screen.Scaling));
Height = Math.Min(Height, Math.Max(MinHeight, screen.WorkingArea.Height / screen.Scaling));
Position = ConstrainPosition(savedPosition, screen.WorkingArea, new Size(Width, Height), screen.Scaling);
}
}
_placementRestored = true;
RememberNormalBounds();
if (_settings.ConsoleWindowMaximized)
WindowState = WindowState.Maximized;
}
private void RememberNormalBounds()
{
if (!_placementRestored || !IsVisible || WindowState != WindowState.Normal)
return;
_settings.ConsoleWindowLeft = Position.X;
_settings.ConsoleWindowTop = Position.Y;
if (ClientSize.Width >= MinWidth && ClientSize.Height >= MinHeight)
{
_settings.ConsoleWindowWidth = ClientSize.Width;
_settings.ConsoleWindowHeight = ClientSize.Height;
}
}
internal static PixelPoint ConstrainPosition(PixelPoint position, PixelRect workingArea, Size size, double scaling)
{
var maximumLeft = workingArea.Right - (int)Math.Ceiling(size.Width * scaling);
var maximumTop = workingArea.Bottom - (int)Math.Ceiling(size.Height * scaling);
return new PixelPoint(
Math.Clamp(position.X, workingArea.X, Math.Max(workingArea.X, maximumLeft)),
Math.Clamp(position.Y, workingArea.Y, Math.Max(workingArea.Y, maximumTop)));
}
private void OnLinesChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
RefreshVisibleLines();

Some files were not shown because too many files have changed in this diff Show More