diff --git a/README.md b/README.md
index 4a15571419..021fed17b3 100644
--- a/README.md
+++ b/README.md
@@ -68,6 +68,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
+- Anti-cheat support under FEX is the work of [StonkGuy](https://github.com/StonkGuy): the x86-64 ptrace, seccomp and `/proc` emulation from his [FEX fork](https://github.com/StonkGuy/FEX) (`eac-2611` branch, MIT) is carried as build patch 0021 with his authorship, patches 0022 to 0029 build on it, and his `eac-tests` regression suite verifies them.
- x86-64 programs on Wayland reach the GPU through FEX's Wayland client, wayland-egl and EGL thunks. The guest `wl_list` and `wl_array` helpers follow [libwayland](https://gitlab.freedesktop.org/wayland/wayland)'s `src/wayland-util.c` (MIT). The EGL extension table comes from the [Khronos EGL registry](https://github.com/KhronosGroup/EGL-Registry) (Apache-2.0) and Mesa's `egl_other.xml` (MIT).
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
- DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence.
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 5db5b11509..4211f6bbc5 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -40,6 +40,8 @@
+
+
diff --git a/app/src/main/cpp/fakeinput_steam.cpp b/app/src/main/cpp/fakeinput_steam.cpp
index 856501cb3c..4c592ded09 100644
--- a/app/src/main/cpp/fakeinput_steam.cpp
+++ b/app/src/main/cpp/fakeinput_steam.cpp
@@ -329,16 +329,28 @@ static constexpr int kWatchedFds = 1 << 16;
static constexpr int kWatchedBits = sizeof(unsigned long) * 8;
static std::atomic watched_fds[kWatchedFds / kWatchedBits];
static std::atomic watched_beyond{false};
+static std::atomic watched_count{0};
static void watch_fd(int fd) {
if (fd < 0) return;
- if (fd >= kWatchedFds) watched_beyond.store(true, std::memory_order_release);
- else watched_fds[fd / kWatchedBits].fetch_or(1UL << (fd % kWatchedBits), std::memory_order_release);
+ if (fd >= kWatchedFds) {
+ watched_beyond.store(true, std::memory_order_release);
+ return;
+ }
+ const unsigned long bit = 1UL << (fd % kWatchedBits);
+ if (!(watched_fds[fd / kWatchedBits].fetch_or(bit, std::memory_order_acq_rel) & bit))
+ watched_count.fetch_add(1, std::memory_order_acq_rel);
}
static void unwatch_fd(int fd) {
- if (fd >= 0 && fd < kWatchedFds)
- watched_fds[fd / kWatchedBits].fetch_and(~(1UL << (fd % kWatchedBits)), std::memory_order_release);
+ if (fd < 0 || fd >= kWatchedFds) return;
+ const unsigned long bit = 1UL << (fd % kWatchedBits);
+ if (watched_fds[fd / kWatchedBits].fetch_and(~bit, std::memory_order_acq_rel) & bit)
+ watched_count.fetch_sub(1, std::memory_order_acq_rel);
+}
+
+static bool any_watched() {
+ return watched_count.load(std::memory_order_acquire) > 0 || watched_beyond.load(std::memory_order_acquire);
}
static bool watched(int fd) {
@@ -4269,7 +4281,7 @@ static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout,
const auto my_poll = next_symbol(Next::poll);
const auto my_ppoll = next_symbol(Next::ppoll);
- nfds_t first = 0;
+ nfds_t first = any_watched() ? 0 : nfds;
while (first < nfds && !watched(fds[first].fd)) first++;
bool has_fake_fds = false;
std::vector real_fds;
@@ -4372,12 +4384,12 @@ EXPORT int poll(struct pollfd *fds, nfds_t nfds, int timeout) {
EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
const struct timespec *timeout, const sigset_t *sigmask) {
const auto my_ppoll = next_symbol(Next::ppoll);
- if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
- errno = EINVAL;
- return -1;
- }
- for (nfds_t i = 0; i < nfds; ++i) {
+ for (nfds_t i = 0; any_watched() && i < nfds; ++i) {
if (!is_fake_input_fd(fds[i].fd)) continue;
+ if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
+ errno = EINVAL;
+ return -1;
+ }
if (!sigmask)
return poll_fake(fds, nfds, static_cast(timespec_to_ms(timeout)), nullptr);
sigset_t all_signals, original_mask;
@@ -4410,6 +4422,8 @@ EXPORT int __ppoll_chk(struct pollfd *fds, nfds_t nfds, const struct timespec *t
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout) {
const auto my_select = next_symbol(Next::select);
+ if (!any_watched())
+ return my_select ? my_select(nfds, readfds, writefds, exceptfds, timeout) : -1;
fd_set original_readfds;
fd_set original_writefds;
diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c
index 112f731f5a..f17591cb16 100644
--- a/app/src/main/cpp/waylandcomp/src/compositor.c
+++ b/app/src/main/cpp/waylandcomp/src/compositor.c
@@ -343,6 +343,7 @@ volatile int g_hide_shell;
volatile int g_zero_copy;
static int g_zero_copy_paused;
+static int g_mirror_capture;
extern volatile int g_display_buffer_driver;
extern void droiddeck_on_overlay_planes(int planes);
static int g_overlay_planes_told = -1;
@@ -2961,7 +2962,7 @@ static void hdr_note_route(int route, const struct hdr_scene *hs) {
static int said = -1, said_tm = -1;
static const char *said_why;
const int tm = route != 0 && !droiddeck_color_output();
- if (route == said && tm == said_tm && (route != 1 || hs->why == said_why)) return;
+ if (route == said && tm == said_tm && (route < 1 || route > 2 || hs->why == said_why)) return;
int was = said;
said = route; said_why = hs->why; said_tm = tm;
char name[160] = "the HDR game";
@@ -2978,6 +2979,10 @@ static void hdr_note_route(int route, const struct hdr_scene *hs) {
"BT2020_PQ", name, hs->why ? hs->why : "?", droiddeck_color_sdr_white());
break;
case 2:
+ if (g_mirror_capture) {
+ droiddeck_log("color", "Mirror: %s is composed through the screen swapchain", name);
+ break;
+ }
if (tm)
droiddeck_log("color", "HDR with frame generation for %s, HDR output switched off: the scene is tone-mapped to "
"SDR and presented through an SDR screen swapchain", name);
@@ -3198,6 +3203,11 @@ static void render_scene(void) {
const int cardboard = vkp_cardboard_active();
struct hdr_scene hs;
int hdr_route = hdr_plan(&dl, w, h, fx_on, framegen, &hs);
+ /* Mirror's PixelCopy cannot see the separate game layer. Keep unimportable frames visible on top. */
+ if (g_mirror_capture && hdr_route != 3 && hs.n_hdr > 0) {
+ hdr_route = 2;
+ hs.why = "Mirror needs the screen swapchain";
+ }
const char *hdr_copy = NULL;
if (droiddeck_color_hdr_open()) {
hdr_note_route(hdr_route, &hs);
@@ -3263,16 +3273,16 @@ static void render_scene(void) {
else if (rendered && how == 2) droiddeck_color_frame_shown(hs.color, DROIDDECK_HDR_TONEMAPPED, 0);
else if (rendered) hdr_copy = "the HDR composition pass is unavailable on this driver";
}
- if (hdr_route == 0 && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on &&
+ if (hdr_route == 0 && !g_mirror_capture && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on &&
!ahb_only) {
settle_unwaited();
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
} else if (hdr_route == 0 || hdr_route == 3) {
const int pass_on = fx_on || framegen;
tell_overlay_planes();
- const int fg_layer = framegen && hdr_route == 0 && framegen_fits_layer();
+ const int fg_layer = framegen && !g_mirror_capture && hdr_route == 0 && framegen_fits_layer();
g_framegen_layer = fg_layer;
- int li = (g_zero_copy && (!framegen || fg_layer) && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1;
+ int li = (g_zero_copy && !g_mirror_capture && (!framegen || fg_layer) && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1;
int over = li >= 0 ? dl.n - 1 - li : 0;
const int fx_blocks = (li >= 0 && fx_on && over > 0);
if (fx_blocks) { li = -1; over = 0; }
@@ -5002,6 +5012,12 @@ const char *droiddeck_client_name(struct wl_client *client) { return client_name
struct wl_display *droiddeck_get_display(void) { return g_display; }
void droiddeck_request_redraw(void) { schedule_render(); }
+void droiddeck_set_mirror_capture(int on) {
+ if (g_mirror_capture == on) return;
+ g_mirror_capture = on;
+ schedule_render();
+}
+
struct wl_resource *droiddeck_ime_target(void) {
struct surface *s;
if (g_ime_click && g_ime_click->mapped) return g_ime_click->resource;
diff --git a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c
index 041f9c6c2b..e4ce7e201d 100644
--- a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c
+++ b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c
@@ -11,7 +11,7 @@
#include "ahb_swapchain.h"
#include "droiddeck_color.h"
-enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT, HOST_KEY, HOST_SELECT_GAME_FIELD };
+enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT, HOST_KEY, HOST_SELECT_GAME_FIELD, HOST_MIRROR_CAPTURE };
struct host_msg {
enum host_kind kind;
@@ -91,6 +91,9 @@ void droiddeck_host_text_delete(int before, int after) {
void droiddeck_host_zero_copy(int on, int live) {
host_post(HOST_ZERO_COPY, NULL, 0, on, live);
}
+void droiddeck_host_mirror_capture(int on) {
+ host_post(HOST_MIRROR_CAPTURE, NULL, 0, on, 0);
+}
void droiddeck_host_hdr_output(int on) {
host_post(HOST_HDR_OUTPUT, NULL, 0, on, 0);
}
@@ -271,6 +274,9 @@ static int on_wake(int fd, uint32_t mask, void *data) {
case HOST_ZERO_COPY:
ahb_swapchain_set_mode(m->a, m->b);
break;
+ case HOST_MIRROR_CAPTURE:
+ droiddeck_set_mirror_capture(m->a);
+ break;
case HOST_HDR_OUTPUT:
droiddeck_color_set_output(m->a);
break;
diff --git a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h
index d7813eb7eb..bc67469eff 100644
--- a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h
+++ b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h
@@ -29,6 +29,8 @@ void droiddeck_host_text_commit_and_submit(const char *utf8, int len);
void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end);
void droiddeck_host_text_delete(int before, int after);
void droiddeck_host_zero_copy(int on, int live);
+void droiddeck_host_mirror_capture(int on);
+void droiddeck_set_mirror_capture(int on);
void droiddeck_host_hdr_output(int on);
void droiddeck_host_key(int evdev, int state);
void droiddeck_host_select_game_field(int copy);
diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c
index 6d8754e4e5..f22865c110 100644
--- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c
+++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c
@@ -461,6 +461,11 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetZeroCopy(JNIEnv *
__android_log_print(ANDROID_LOG_INFO, TAG, "zero-copy layer mode %s%s", on ? "on" : "off", live ? " (live)" : "");
}
+JNIEXPORT void JNICALL
+Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetMirrorCapture(JNIEnv *env, jclass clazz, jboolean on) {
+ droiddeck_host_mirror_capture(on ? 1 : 0);
+}
+
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetDisplayBufferDriver(JNIEnv *env, jclass clazz, jboolean on) {
g_display_buffer_driver = on ? 1 : 0;
diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
index d371dd5491..2fc1b15edc 100644
--- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
@@ -661,6 +661,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var effects by mutableStateOf(ScreenEffects.OFF)
private var observedScreenEffectsProfileId by mutableStateOf(null)
private var screenEffectsTarget by mutableStateOf(SCREEN_EFFECTS_TARGET_AUTO)
+ private var screenEffectsProfileRevision by mutableIntStateOf(0)
private var cardboard by mutableStateOf(Cardboard.OFF)
private var headTracker: HeadTracker? = null
private var steamVrStatus by mutableStateOf(null)
@@ -1641,8 +1642,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
effects = effects,
screenEffectsTarget = screenEffectsTarget,
screenEffectsTargets = screenEffectsTargetOptions(),
- screenEffectsCanDelete = screenEffectsProfileIdForTarget(screenEffectsTarget)?.let {
- SessionPrefs.hasScreenEffectsOverride(this@SessionActivity, it)
+ screenEffectsCanDelete = screenEffectsProfileRevision.let {
+ screenEffectsProfileIdForTarget(screenEffectsTarget)?.let {
+ SessionPrefs.hasScreenEffectsOverride(this@SessionActivity, it) ||
+ SessionPrefs.hasScreenEffectsUpscalerOverride(this@SessionActivity, it)
+ }
} == true,
cardboard = cardboard,
cardboardSensor = hasRotationSensor,
@@ -1748,6 +1752,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} else {
val profileId = screenEffectsProfileIdForTarget(target)
SessionPrefs.setScreenEffectsUpscaler(this@SessionActivity, profileId, m)
+ screenEffectsProfileRevision++
if (target == screenEffectsTarget) {
upscaler = m
@@ -1783,6 +1788,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} else {
val profileId = screenEffectsProfileIdForTarget(target)
SessionPrefs.setScreenEffectsUpscaler(this@SessionActivity, profileId, m)
+ screenEffectsProfileRevision++
if (target == screenEffectsTarget) {
upscaler = m
if (screenEffectsUpscalerTargetAppliesToLiveOutput(target)) {
@@ -1829,7 +1835,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val profileId = screenEffectsProfileIdForTarget(editorTarget)
SessionPrefs.setScreenEffects(this@SessionActivity, profileId, e)
effects = e
- if (screenEffectsTargetAppliesToLiveOutput(editorTarget)) e.push(upscaler)
+ if (screenEffectsTargetAppliesToLiveOutput(editorTarget)) {
+ val upscalerAppliesToLiveOutput =
+ screenEffectsUpscalerTargetAppliesToLiveOutput(editorTarget)
+ val liveUpscaler = if (upscalerAppliesToLiveOutput) {
+ SessionPrefs.screenEffectsUpscaler(
+ this@SessionActivity,
+ screenEffectsProfileIdForTarget(editorTarget)
+ )
+ } else {
+ SessionPrefs.screenEffectsUpscaler(
+ this@SessionActivity,
+ currentScreenEffectsProfileId()
+ )
+ }
+ e.push(liveUpscaler)
+ }
}
}
},
@@ -2648,10 +2669,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val targetUpscaler = SessionPrefs.screenEffectsUpscaler(this, profileId)
effects = targetEffects
upscaler = targetUpscaler
+ val upscalerAppliesToLiveOutput = screenEffectsUpscalerTargetAppliesToLiveOutput(target)
+ val liveUpscaler = if (upscalerAppliesToLiveOutput) {
+ targetUpscaler
+ } else {
+ SessionPrefs.screenEffectsUpscaler(this, currentScreenEffectsProfileId())
+ }
+ if (upscalerAppliesToLiveOutput) {
+ WaylandCompositor.nativeSetUpscaler(liveUpscaler)
+ }
if (screenEffectsTargetAppliesToLiveOutput(target)) {
- WaylandCompositor.nativeSetUpscaler(targetUpscaler)
- WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(targetEffects, targetUpscaler)?.name)
- targetEffects.push(targetUpscaler)
+ WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(targetEffects, liveUpscaler)?.name)
+ targetEffects.push(liveUpscaler)
+ } else if (upscalerAppliesToLiveOutput) {
+ val liveEffects = SessionPrefs.screenEffects(this, currentScreenEffectsProfileId())
+ WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(liveEffects, liveUpscaler)?.name)
}
}
@@ -2664,6 +2696,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun resetScreenEffectsTarget(target: String) {
if (target != screenEffectsTarget) return
SessionPrefs.resetScreenEffectsProfile(this, screenEffectsProfileIdForTarget(target))
+ screenEffectsProfileRevision++
syncScreenEffectsTarget(target)
}
@@ -2671,6 +2704,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (target != screenEffectsTarget) return
val profileId = screenEffectsProfileIdForTarget(target) ?: return
SessionPrefs.deleteScreenEffectsProfile(this, profileId)
+ screenEffectsProfileRevision++
syncScreenEffectsTarget(target)
}
@@ -6348,7 +6382,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun holdComposedOutput(hold: Boolean) {
+ val wasHeld = composedHolds > 0
composedHolds = (composedHolds + if (hold) 1 else -1).coerceAtLeast(0)
+ val held = composedHolds > 0
+ if (held == wasHeld) return
+ WaylandCompositor.nativeSetMirrorCapture(held)
+ // Importable HDR is redirected by the compositor hold. Keep its layer-only fallback available.
if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy(composedOutputFree())
}
diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentAttachments.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentAttachments.kt
index 96ddf0057a..9c9dd5c150 100644
--- a/app/src/main/java/com/droiddeck/launcher/agent/AgentAttachments.kt
+++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentAttachments.kt
@@ -22,6 +22,12 @@ object AgentAttachments {
/** True while the file picker is open over a session: it answers the drawer's agent page, so the drawer must stay. */
@Volatile var picking = false
+ /** Launches a system screen that answers the agent page, keeping the drawer for it; the result callback clears [picking]. */
+ fun pick(launch: () -> Unit) {
+ picking = true
+ if (runCatching(launch).isFailure) picking = false
+ }
+
private const val NEW = "new"
private const val GUEST_DIR = "/root/.cache/droiddeck/attachments"
private val IMAGE = setOf("png", "jpg", "jpeg", "webp", "gif", "bmp")
@@ -38,14 +44,17 @@ object AgentAttachments {
val folder = chat ?: NEW
val dir = File(hostDir(app), folder).apply { mkdirs() }
return uris.mapNotNull { uri ->
+ var target: File? = null
runCatching {
val name = displayName(app, uri).replace(Regex("[^A-Za-z0-9._-]"), "_").ifEmpty { "file" }
- var target = File(dir, name)
+ var candidate = File(dir, name)
var n = 1
- while (target.exists()) target = File(dir, "${name.substringBeforeLast('.')}-${n++}${name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }}")
- app.contentResolver.openInputStream(uri)!!.use { input -> target.outputStream().use { input.copyTo(it) } }
- "$GUEST_DIR/$folder/${target.name}"
- }.getOrNull()
+ // Created atomically, so copies running side by side never pick the same name.
+ while (!candidate.createNewFile()) candidate = File(dir, "${name.substringBeforeLast('.')}-${n++}${name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }}")
+ target = candidate
+ app.contentResolver.openInputStream(uri)!!.use { input -> candidate.outputStream().use { input.copyTo(it) } }
+ "$GUEST_DIR/$folder/${candidate.name}"
+ }.onFailure { target?.delete() }.getOrNull()
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt
index 412fc79627..fa66513e3a 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt
@@ -66,11 +66,14 @@ object ProtonExtras {
internal fun installedIn(dir: File, tool: Tool): List =
dir.listFiles()
- ?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && usable(it) }
+ ?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && !x86_64Build(it) && usable(it) }
?.map { it.name }
?.sortedWith { a, b -> compareVersions(a, b) }
?: emptyList()
+ internal fun x86_64Build(dir: File): Boolean =
+ File(dir, "files/lib/wine/x86_64-unix").isDirectory && !File(dir, "files/bin-arm64").isDirectory
+
private fun usable(dir: File): Boolean {
val manifest = runCatching { File(dir, "toolmanifest.vdf").readText() }.getOrNull() ?: return false
val command = Regex("\\\"commandline\\\"\\s+\\\"/?([^\\\" ]+)").find(manifest)?.groupValues?.getOrNull(1) ?: return false
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
index 5f48f05683..e7d0b1bb5d 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
@@ -2014,24 +2014,84 @@ object SessionPrefs {
sessionPrefs.edit().putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString()).apply()
}
+ private const val GAME_UPSCALER_OVERRIDES_KEY = "upscaler.gameOverrides"
+
+ private fun gameUpscalerOverrides(context: Context): JSONObject = runCatching {
+ JSONObject(prefs(context).getString(GAME_UPSCALER_OVERRIDES_KEY, null) ?: "{}")
+ }.getOrDefault(JSONObject())
+
+ private fun legacyScreenEffectsUpscaler(context: Context, profileId: String): Int? =
+ runCatching {
+ val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
+ val profile = profiles.optJSONObject(profileId)
+ if (profile?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true) {
+ profile.optInt(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY, -1).takeIf { it >= 0 }
+ } else null
+ }.getOrNull()?.let(::canonicalUpscaler)
+
+ private fun clearLegacyScreenEffectsUpscaler(context: Context, profileId: String) {
+ val sessionPrefs = prefs(context)
+ val profiles = runCatching {
+ JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
+ }.getOrNull() ?: return
+ val profile = profiles.optJSONObject(profileId) ?: return
+ if (!profile.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY)) return
+ profile.remove(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY)
+ if (profile.length() == 0) profiles.remove(profileId)
+ sessionPrefs.edit().apply {
+ if (profiles.length() == 0) remove(SCREEN_EFFECTS_PROFILES_KEY)
+ else putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString())
+ }.apply()
+ }
+
+ fun hasGameUpscalerOverride(context: Context, gameId: String): Boolean {
+ if (gameId.isBlank()) return false
+ val stored = gameUpscalerOverrides(context)
+ return (stored.has(gameId) && stored.optInt(gameId, -1) >= 0) ||
+ legacyScreenEffectsUpscaler(context, "game:$gameId") != null
+ }
+
+ fun setGameUpscaler(context: Context, gameId: String, mode: Int) {
+ if (gameId.isBlank()) return
+ val overrides = gameUpscalerOverrides(context)
+ overrides.put(gameId, canonicalUpscaler(mode))
+ prefs(context).edit().putString(GAME_UPSCALER_OVERRIDES_KEY, overrides.toString()).apply()
+ clearLegacyScreenEffectsUpscaler(context, "game:$gameId")
+ }
+
+ fun clearGameUpscaler(context: Context, gameId: String) {
+ if (gameId.isBlank()) return
+ val sessionPrefs = prefs(context)
+ val overrides = gameUpscalerOverrides(context)
+ if (overrides.has(gameId)) {
+ overrides.remove(gameId)
+ sessionPrefs.edit().apply {
+ if (overrides.length() == 0) remove(GAME_UPSCALER_OVERRIDES_KEY)
+ else putString(GAME_UPSCALER_OVERRIDES_KEY, overrides.toString())
+ }.apply()
+ }
+ clearLegacyScreenEffectsUpscaler(context, "game:$gameId")
+ }
+
fun hasScreenEffectsUpscalerOverride(context: Context, profileId: String?): Boolean {
if (profileId.isNullOrBlank()) return false
- return runCatching {
- val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
- profiles.optJSONObject(profileId)?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true
- }.getOrDefault(false)
+ if (profileId.startsWith("game:")) {
+ return hasGameUpscalerOverride(context, profileId.removePrefix("game:"))
+ }
+ return legacyScreenEffectsUpscaler(context, profileId) != null
}
fun screenEffectsUpscaler(context: Context, profileId: String?): Int {
if (profileId.isNullOrBlank()) return upscaler(context)
- val stored = runCatching {
- val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
- val profile = profiles.optJSONObject(profileId)
- if (profile?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true) {
- profile.optInt(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY, -1)
- } else -1
- }.getOrDefault(-1)
- return if (stored >= 0) canonicalUpscaler(stored) else upscaler(context)
+ if (profileId.startsWith("game:")) {
+ val gameId = profileId.removePrefix("game:")
+ val overrides = gameUpscalerOverrides(context)
+ if (overrides.has(gameId)) {
+ val stored = overrides.optInt(gameId, -1)
+ if (stored >= 0) return canonicalUpscaler(stored)
+ }
+ }
+ return legacyScreenEffectsUpscaler(context, profileId) ?: upscaler(context)
}
fun setScreenEffectsUpscaler(context: Context, profileId: String?, mode: Int) {
@@ -2039,6 +2099,10 @@ object SessionPrefs {
setUpscaler(context, mode)
return
}
+ if (profileId.startsWith("game:")) {
+ setGameUpscaler(context, profileId.removePrefix("game:"), mode)
+ return
+ }
val sessionPrefs = prefs(context)
val profiles = runCatching {
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
@@ -2075,6 +2139,7 @@ object SessionPrefs {
val profiles = runCatching {
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
}.getOrElse { JSONObject() }
+ if (profileId.startsWith("game:")) clearGameUpscaler(context, profileId.removePrefix("game:"))
if (!profiles.has(profileId)) return
profiles.remove(profileId)
sessionPrefs.edit().apply {
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt
index 44f4d4bc90..b2793e5ba1 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt
@@ -5,7 +5,9 @@ import android.content.ContextWrapper
import android.os.Build
import android.view.KeyEvent
import android.view.WindowManager
+import androidx.activity.compose.BackHandler
import androidx.activity.compose.LocalActivityResultRegistryOwner
+import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.expandVertically
@@ -50,12 +52,12 @@ import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Send
import androidx.compose.material.icons.outlined.Extension
-import androidx.compose.material.icons.outlined.PhotoCamera
import androidx.compose.material.icons.outlined.MicOff
import androidx.compose.material.icons.outlined.Mic
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.ArrowDownward
import androidx.compose.material.icons.outlined.AttachFile
+import androidx.compose.material.icons.outlined.Keyboard
import androidx.compose.material.icons.outlined.Terminal
import androidx.compose.material.icons.outlined.Build
import androidx.compose.material.icons.outlined.Close
@@ -79,6 +81,7 @@ import androidx.compose.runtime.MutableState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
@@ -108,6 +111,7 @@ import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.platform.testTag
@@ -301,7 +305,7 @@ private fun AgentPageContent(
readingBack = false
scope.launch { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) }
}
- val hidden = !composer.focused && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() &&
+ val hidden = !composer.focused && !composer.tray && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() &&
AgentHost.approvals.isEmpty()
var listHeight by remember { mutableIntStateOf(0) }
Box(
@@ -319,6 +323,7 @@ private fun AgentPageContent(
awaitEachGesture {
awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
if (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE) panel = AgentPanel.NONE
+ composer.tray = false
// Forced: the unforced path walks the focus chain and throws ("ActiveParent with no focused child") when a tap lands while focus is moving.
if (composer.focused) focusManager.clearFocus(force = true)
}
@@ -344,6 +349,12 @@ private fun AgentPageContent(
@Stable
private class ComposerState {
var focused by mutableStateOf(false)
+ /** The photo tray stands in for the keyboard, at the height the keyboard last had. */
+ var tray by mutableStateOf(false)
+ var keyboardHeight by mutableStateOf(0.dp)
+ /** Tray photos copied, or being copied, for this conversation, so reopening the tray keeps their marks and copies nothing twice. */
+ val photoCopies = mutableStateMapOf()
+ val photosCopying = mutableStateMapOf()
var focusRequests by mutableIntStateOf(0)
private set
private var consumedFocusRequests by mutableIntStateOf(0)
@@ -390,7 +401,7 @@ private fun ModelChip(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstCon
.clickable { onPanel(AgentPanel.MODEL) }.padding(horizontal = 8.dp).testTag("agent-model"),
) {
val mode = AgentHost.harness.permissions.drop(1).firstOrNull { it.id == AgentHost.permission }?.let { stringResource(it.label) }
- val parts = if (compact) listOfNotNull(mode ?: model)
+ val parts = if (compact) listOf(model)
else listOfNotNull(
AgentHost.harness.name, model, AgentHost.effort, mode,
stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans },
@@ -748,6 +759,8 @@ private fun AgentComposer(
if (text.isEmpty() && AgentAttachments.pending.isEmpty()) return@send
AgentHost.send(context, text, AgentAttachments.pending.toList())
AgentAttachments.pending.clear()
+ composer.photosCopying.clear()
+ composer.tray = false
onSent()
}
}
@@ -813,7 +826,34 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState composer.keyboardHeight) composer.keyboardHeight = height
+ }
+ LaunchedEffect(hideAttach) { if (hideAttach) composer.tray = false }
+ LaunchedEffect(AgentHost.chat) {
+ composer.photoCopies.clear()
+ composer.photosCopying.clear()
+ }
+ // BackHandler throws where the host provides no back dispatcher: the front end and the floating pet.
+ if (LocalOnBackPressedDispatcherOwner.current != null) BackHandler(composer.tray) { composer.tray = false }
+ val focusManager = LocalFocusManager.current
+ val files = if (picks) rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) {
+ AgentAttachments.picking = false
+ attachUris(context, it)
+ } else null
+ val toggleTray = {
+ if (composer.tray) {
+ composer.tray = false
+ composer.open()
+ } else {
+ focusManager.clearFocus(force = true)
+ composer.tray = true
+ }
+ }
BoxWithConstraints(
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape16).background(colors.surface)
.border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16).padding(6.dp),
@@ -841,6 +881,7 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState 0.dp) composer.keyboardHeight else 280.dp).coerceAtLeast(160.dp).coerceAtMost(most)
+ AgentPhotoTray(height, composer.photoCopies, composer.photosCopying, files?.let { { AgentAttachments.pick { it.launch(arrayOf("*/*")) } } })
+ }
}
/**
@@ -974,53 +1018,15 @@ private fun VoiceButton(voice: AgentVoice, onStart: () -> Unit, onSend: () -> Un
}
}
-/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */
+/** Opens the photo tray in place of the keyboard; while it is open, brings the keyboard back. */
@Composable
-private fun GameFrameButton() {
- val context = LocalContext.current
+private fun AttachButton(trayOpen: Boolean, onClick: () -> Unit) {
val pal = LocalPalette.current
- RoundButton(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), pal.surfaceVariant, pal.onBackground, "agent-game-frame") {
- val grab = AgentAttachments.gameFrame ?: return@RoundButton
- val chat = AgentHost.chat
- grab frame@{ frame ->
- if (frame == null) {
- android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show()
- return@frame
- }
- Thread({
- val path = AgentAttachments.saveFrame(context, chat, frame)
- frame.recycle()
- android.os.Handler(android.os.Looper.getMainLooper()).post {
- when {
- path == null -> android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show()
- AgentHost.chat == chat -> AgentAttachments.pending.add(path)
- else -> AgentAttachments.discard(context, listOf(path))
- }
- }
- }, "agent-game-frame").start()
- }
- }
-}
-
-@Composable
-private fun AttachButton() {
- val context = LocalContext.current
- val pal = LocalPalette.current
- val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
- AgentAttachments.picking = false
- if (uris.isEmpty()) return@rememberLauncherForActivityResult
- val chat = AgentHost.chat
- Thread({
- val paths = AgentAttachments.copy(context, chat, uris)
- android.os.Handler(android.os.Looper.getMainLooper()).post {
- if (AgentHost.chat == chat) AgentAttachments.pending.addAll(paths) else AgentAttachments.discard(context, paths)
- }
- }, "agent-attach").start()
- }
- RoundButton(Icons.Outlined.AttachFile, stringResource(R.string.agent_attach), pal.surfaceVariant, pal.onBackground, "agent-attach") {
- AgentAttachments.picking = true
- if (runCatching { picker.launch(arrayOf("*/*")) }.isFailure) AgentAttachments.picking = false
- }
+ RoundButton(
+ if (trayOpen) Icons.Outlined.Keyboard else Icons.Outlined.AttachFile,
+ stringResource(if (trayOpen) R.string.agent_keyboard else R.string.agent_attach),
+ if (trayOpen) pal.primary else pal.surfaceVariant, if (trayOpen) pal.onPrimary else pal.onBackground, "agent-attach", onClick = onClick,
+ )
}
@Composable
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPhotoTray.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPhotoTray.kt
new file mode 100644
index 0000000000..d6c5dabe68
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPhotoTray.kt
@@ -0,0 +1,280 @@
+package com.droiddeck.launcher.ui
+
+import android.Manifest
+import android.content.ContentUris
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.net.Uri
+import android.os.Build
+import android.os.Environment
+import android.provider.MediaStore
+import android.provider.Settings
+import android.widget.Toast
+import androidx.activity.compose.LocalActivityResultRegistryOwner
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.lazy.grid.GridCells
+import androidx.compose.foundation.lazy.grid.GridItemSpan
+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
+import androidx.compose.foundation.lazy.grid.items
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.outlined.Check
+import androidx.compose.material.icons.outlined.FolderOpen
+import androidx.compose.material.icons.outlined.PhotoCamera
+import androidx.compose.material.icons.outlined.PhotoLibrary
+import androidx.compose.material3.Icon
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.runtime.snapshots.SnapshotStateMap
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.LocalLifecycleOwner
+import androidx.compose.ui.platform.testTag
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.selected
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleEventObserver
+import coil.compose.AsyncImage
+import coil.request.ImageRequest
+import com.droiddeck.launcher.R
+import com.droiddeck.launcher.agent.AgentAttachments
+import com.droiddeck.launcher.agent.AgentHost
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+
+/** The device's photos, newest first, as MediaStore lets the app see them. */
+internal object AgentPhotos {
+ enum class Access { NONE, SELECTED, ALL }
+
+ /** Android stops showing the request after repeated denials and answers it at once, so a denied request sends later ones to Settings. */
+ var refused = false
+
+ fun permissions(sdk: Int = Build.VERSION.SDK_INT): Array = when {
+ sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE -> arrayOf(Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED)
+ sdk >= Build.VERSION_CODES.TIRAMISU -> arrayOf(Manifest.permission.READ_MEDIA_IMAGES)
+ else -> arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
+ }
+
+ fun access(context: Context): Access {
+ fun granted(permission: String) = context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
+ val all = permissions().first()
+ return when {
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && Environment.isExternalStorageManager() -> Access.ALL
+ granted(all) -> Access.ALL
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && granted(Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED) -> Access.SELECTED
+ else -> Access.NONE
+ }
+ }
+
+ class Photo(val uri: Uri, val name: String)
+
+ fun recent(context: Context, limit: Int = 300): List = runCatching {
+ val images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
+ context.contentResolver.query(
+ images, arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME), null, null, "${MediaStore.Images.Media.DATE_ADDED} DESC",
+ )?.use { c ->
+ buildList {
+ while (size < limit && c.moveToNext()) add(Photo(ContentUris.withAppendedId(images, c.getLong(0)), c.getString(1).orEmpty()))
+ }
+ }.orEmpty()
+ }.getOrDefault(emptyList())
+}
+
+/**
+ * Copies [uris] into the conversation's attachments off the main thread, then hands [onCopied] what was attached: nothing if the
+ * conversation changed meanwhile or [current] says the copy was superseded.
+ */
+internal fun attachUris(context: Context, uris: List, current: () -> Boolean = { true }, onCopied: (List>) -> Unit = {}) {
+ if (uris.isEmpty()) return
+ val chat = AgentHost.chat
+ Thread({
+ val copied = uris.mapNotNull { uri -> AgentAttachments.copy(context, chat, listOf(uri)).firstOrNull()?.let { uri to it } }
+ android.os.Handler(android.os.Looper.getMainLooper()).post {
+ val paths = copied.map { it.second }
+ if (AgentHost.chat == chat && current()) {
+ AgentAttachments.pending.addAll(paths)
+ onCopied(copied)
+ } else {
+ AgentAttachments.discard(context, paths)
+ onCopied(emptyList())
+ }
+ }
+ }, "agent-attach").start()
+}
+
+/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */
+private fun attachGameFrame(context: Context) {
+ val grab = AgentAttachments.gameFrame ?: return
+ val chat = AgentHost.chat
+ grab frame@{ frame ->
+ if (frame == null) {
+ Toast.makeText(context, R.string.agent_attach_game_failed, Toast.LENGTH_SHORT).show()
+ return@frame
+ }
+ Thread({
+ val path = AgentAttachments.saveFrame(context, chat, frame)
+ frame.recycle()
+ android.os.Handler(android.os.Looper.getMainLooper()).post {
+ when {
+ path == null -> Toast.makeText(context, R.string.agent_attach_game_failed, Toast.LENGTH_SHORT).show()
+ AgentHost.chat == chat -> AgentAttachments.pending.add(path)
+ else -> AgentAttachments.discard(context, listOf(path))
+ }
+ }
+ }, "agent-game-frame").start()
+ }
+}
+
+/** Shown in place of the keyboard: recent photos to tap onto the message, and the system picker for anything else. */
+@Composable
+internal fun AgentPhotoTray(height: Dp, copies: SnapshotStateMap, copying: SnapshotStateMap, onFiles: (() -> Unit)?) {
+ val context = LocalContext.current
+ val pal = LocalPalette.current
+ var access by remember { mutableStateOf(AgentPhotos.access(context)) }
+ var photos by remember { mutableStateOf?>(null) }
+ var reloads by remember { mutableStateOf(0) }
+ // A window no activity owns (the floating pet's chat) cannot ask for a permission, so it sends the user to the app's settings.
+ val launcher = if (LocalActivityResultRegistryOwner.current != null) {
+ rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
+ AgentAttachments.picking = false
+ access = AgentPhotos.access(context)
+ if (access == AgentPhotos.Access.NONE) AgentPhotos.refused = true
+ reloads++
+ }
+ } else null
+ val request = {
+ if (launcher != null && !AgentPhotos.refused) {
+ AgentAttachments.pick { launcher.launch(AgentPhotos.permissions()) }
+ } else {
+ val details = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + context.packageName)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ runCatching { context.startActivity(details) }
+ }
+ Unit
+ }
+ // Access can change in Settings, and new pictures arrive, while the app is in the background.
+ val lifecycle = LocalLifecycleOwner.current.lifecycle
+ DisposableEffect(lifecycle) {
+ val observer = LifecycleEventObserver { _, event ->
+ if (event == Lifecycle.Event.ON_RESUME) {
+ access = AgentPhotos.access(context)
+ reloads++
+ }
+ }
+ lifecycle.addObserver(observer)
+ onDispose { lifecycle.removeObserver(observer) }
+ }
+ LaunchedEffect(access, reloads) {
+ photos = if (access == AgentPhotos.Access.NONE) emptyList() else withContext(Dispatchers.IO) { AgentPhotos.recent(context) }
+ }
+ LazyVerticalGrid(
+ GridCells.Adaptive(96.dp),
+ Modifier.fillMaxWidth().height(height).padding(top = 8.dp).testTag("agent-photo-tray"),
+ horizontalArrangement = Arrangement.spacedBy(4.dp),
+ verticalArrangement = Arrangement.spacedBy(4.dp),
+ ) {
+ if (AgentAttachments.gameFrame != null) item {
+ TrayTile(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), "agent-game-frame") { attachGameFrame(context) }
+ }
+ if (onFiles != null) item { TrayTile(Icons.Outlined.FolderOpen, stringResource(R.string.agent_attach_files), "agent-attach-files", onFiles) }
+ if (access != AgentPhotos.Access.ALL) item {
+ TrayTile(
+ Icons.Outlined.PhotoLibrary,
+ stringResource(if (access == AgentPhotos.Access.NONE) R.string.agent_photos_allow else R.string.agent_photos_more),
+ "agent-photos-allow",
+ onClick = request,
+ )
+ }
+ val list = photos
+ if (list != null && list.isEmpty() && access != AgentPhotos.Access.NONE) item(span = { GridItemSpan(maxLineSpan) }) {
+ Text(
+ stringResource(R.string.agent_photos_empty), fontSize = 13.sp, color = pal.onSurfaceVariant, textAlign = TextAlign.Center,
+ modifier = Modifier.fillMaxWidth().padding(16.dp),
+ )
+ }
+ items(list.orEmpty(), key = { it.uri.toString() }) { photo ->
+ val uri = photo.uri
+ val path = copies[uri]
+ val selected = path != null && path in AgentAttachments.pending
+ Box(
+ Modifier.aspectRatio(1f).clip(Shape12).background(pal.surfaceVariant)
+ .then(if (selected) Modifier.border(3.dp, pal.primary, Shape12) else Modifier)
+ .clickable {
+ when {
+ selected -> AgentAttachments.pending.remove(path)
+ path != null && AgentAttachments.host(context, path).exists() -> AgentAttachments.pending.add(path)
+ uri in copying -> Unit
+ else -> {
+ // Leaving the conversation clears the markers, so a copy started before that is no longer current even back in it.
+ val copy = Any()
+ copying[uri] = copy
+ attachUris(context, listOf(uri), current = { copying[uri] === copy }) { copied ->
+ copied.forEach { (u, p) -> copies[u] = p }
+ if (copying[uri] === copy) copying.remove(uri)
+ }
+ }
+ }
+ }.semantics {
+ contentDescription = photo.name
+ this.selected = selected
+ }.testTag("agent-photo"),
+ ) {
+ AsyncImage(
+ model = ImageRequest.Builder(context).data(uri).size(320).build(), contentDescription = null,
+ contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize(),
+ )
+ if (selected) Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier.align(Alignment.TopEnd).padding(6.dp).size(22.dp).clip(CircleShape).background(pal.primary),
+ ) {
+ Icon(Icons.Outlined.Check, null, tint = pal.onPrimary, modifier = Modifier.size(16.dp))
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun TrayTile(icon: ImageVector, label: String, tag: String, onClick: () -> Unit) {
+ val pal = LocalPalette.current
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center,
+ modifier = Modifier.aspectRatio(1f).clip(Shape12).background(pal.surfaceVariant).clickable(onClick = onClick).padding(8.dp).testTag(tag),
+ ) {
+ Icon(icon, null, tint = pal.onBackground, modifier = Modifier.size(26.dp))
+ Text(
+ label, fontSize = 12.sp, color = pal.onBackground, textAlign = TextAlign.Center, maxLines = 3, overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(top = 6.dp),
+ )
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt
index 3bec0c50aa..4047781350 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt
@@ -881,6 +881,28 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
com.droiddeck.launcher.gpu.FrameGen.hasGameOverride(context, it)
} ?: false)
}
+ val scalingFilterChoices = SessionPrefs.upscalerChoices(context)
+ var gameUpscaler by remember(frameGenProfileKey) {
+ mutableStateOf(frameGenProfileKey?.let {
+ SessionPrefs.screenEffectsUpscaler(context, "game:$it")
+ } ?: SessionPrefs.upscaler(context))
+ }
+ var gameUpscalerOverride by remember(frameGenProfileKey) {
+ mutableStateOf(frameGenProfileKey?.let { SessionPrefs.hasGameUpscalerOverride(context, it) } ?: false)
+ }
+ val lifecycleOwner = LocalLifecycleOwner.current
+ DisposableEffect(lifecycleOwner, frameGenProfileKey) {
+ val observer = LifecycleEventObserver { _, event ->
+ if (event == Lifecycle.Event.ON_RESUME) {
+ frameGenProfileKey?.let { key ->
+ gameUpscaler = SessionPrefs.screenEffectsUpscaler(context, "game:$key")
+ gameUpscalerOverride = SessionPrefs.hasGameUpscalerOverride(context, key)
+ }
+ }
+ }
+ lifecycleOwner.lifecycle.addObserver(observer)
+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
+ }
var wincompOpen by remember(wincompKey) { mutableStateOf(null) }
val wincompPicks = remember(wincompKey, wincompOpen) { wincompKey?.let { com.droiddeck.launcher.session.WinComponents.picks(context, it) }.orEmpty() }
val steamScope = game?.let { com.droiddeck.launcher.session.NoSteamLaunch.scope(it) }
@@ -914,6 +936,25 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
},
)
}
+ val scalingFilterMenuContent: @Composable () -> Unit = {
+ val key = frameGenProfileKey
+ if (key != null) ScalingFilterMenu(
+ mode = gameUpscaler,
+ options = scalingFilterChoices,
+ hasGameOverride = gameUpscalerOverride,
+ onPick = { mode ->
+ SessionPrefs.setGameUpscaler(context, key, mode)
+ gameUpscaler = SessionPrefs.screenEffectsUpscaler(context, "game:$key")
+ gameUpscalerOverride = SessionPrefs.hasGameUpscalerOverride(context, key)
+ },
+ onResetGame = {
+ SessionPrefs.clearGameUpscaler(context, key)
+ gameUpscaler = SessionPrefs.upscaler(context)
+ gameUpscalerOverride = false
+ },
+ gameName = game?.name,
+ )
+ }
val cards = if (game?.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER) listOfNotNull(steamCard) else buildList<@Composable (Modifier) -> Unit> {
add { m ->
val back = stringResource(R.string.hop_from_games)
@@ -938,6 +979,17 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
}
}
+ if (frameGenProfileKey != null) add { m ->
+ Box(m) {
+ SettingCard(
+ stringResource(R.string.display_filter),
+ scalingFilterChoices.firstOrNull { it.first == gameUpscaler }?.second ?: scalingFilterChoices.first().second,
+ "card:scaling-filter", Modifier.fillMaxSize(),
+ ) {
+ host.open = if (host.open == "scaling-filter") null else "scaling-filter"
+ }
+ }
+ }
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
if (steamCard != null) add(steamCard)
val cardStore = com.droiddeck.launcher.stores.Store.byId(game?.source.orEmpty())?.takeIf { it == com.droiddeck.launcher.stores.Store.EPIC || it == com.droiddeck.launcher.stores.Store.GOG }
@@ -972,6 +1024,11 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
frameGenMenuContent()
}
}
+ if (host.open == "scaling-filter") {
+ Box(Modifier.fillMaxWidth().padding(top = 4.dp)) {
+ scalingFilterMenuContent()
+ }
+ }
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ScalingFilterMenu.kt b/app/src/main/java/com/droiddeck/launcher/ui/ScalingFilterMenu.kt
new file mode 100644
index 0000000000..b012bb1292
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/ui/ScalingFilterMenu.kt
@@ -0,0 +1,69 @@
+package com.droiddeck.launcher.ui
+
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.unit.dp
+import com.droiddeck.launcher.R
+
+@Composable
+internal fun ScalingFilterMenu(
+ mode: Int,
+ options: List>,
+ hasGameOverride: Boolean,
+ onPick: (Int) -> Unit,
+ onResetGame: () -> Unit,
+ gameName: String? = null,
+) {
+ val colors = MaterialTheme.colorScheme
+ Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, bottom = 8.dp)) {
+ val selectedLabel = options.firstOrNull { it.first == mode }?.second ?: mode.toString()
+ Text(
+ stringResource(
+ if (hasGameOverride) R.string.display_filter_game_profile else R.string.display_filter_default_profile,
+ if (hasGameOverride) gameName.orEmpty() else selectedLabel,
+ selectedLabel,
+ ),
+ color = colors.onSurfaceVariant,
+ style = MaterialTheme.typography.bodySmall,
+ modifier = Modifier.padding(bottom = 6.dp),
+ )
+ options.forEachIndexed { index, (option, label) ->
+ val selected = mode == option
+ val pick = { onPick(option) }
+ OutlinedButton(
+ onClick = pick,
+ modifier = Modifier.fillMaxWidth()
+ .padding(top = if (index == 0) 0.dp else 6.dp)
+ .controllerConfirm(onClick = pick),
+ contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
+ colors = ButtonDefaults.outlinedButtonColors(
+ containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
+ contentColor = if (selected) colors.primary else colors.onSurface,
+ ),
+ ) { Text(label) }
+ }
+ Text(
+ stringResource(R.string.display_filter_note),
+ color = colors.onSurfaceVariant,
+ style = MaterialTheme.typography.bodySmall,
+ modifier = Modifier.padding(top = 6.dp),
+ )
+ OutlinedButton(
+ onClick = onResetGame,
+ modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
+ .controllerConfirm(onClick = onResetGame),
+ contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
+ ) {
+ Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓")
+ }
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt
index 7a5510360e..f15b69287b 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt
@@ -706,7 +706,8 @@ private fun TestList(tests: List, me: AppUpdates.Installed, u: UpdatesS
val followed = u.follow.pr.takeIf { u.follow.channel == Channel.TEST }
val rowShown = followed != null && (ready.any { it.pr == followed } || (oldShown && old.any { it.pr == followed }))
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
- if (!rowShown) status(false)
+ // A followed test's row carries the status; browsing Tests while following Stable or Preview shows it only for an install running or failed.
+ if (if (followed != null) !rowShown else u.stage != null || u.error != null) status(false)
Column(Modifier.padding(start = 18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
if (tests.size > 5 || query.isNotEmpty()) AdbTextField(
value = query, onValueChange = { query = it }, label = stringResource(R.string.upd_tests_find),
diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java
index 2cc0ecd638..a2676304d9 100644
--- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java
+++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java
@@ -333,6 +333,8 @@ public final class WaylandCompositor {
public static native void nativeSetZeroCopy(boolean on);
+ public static native void nativeSetMirrorCapture(boolean on);
+
public static native void nativeSetDisplayBufferDriver(boolean on);
public static native int nativeZeroCopyFrames();
diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml
index ea85ca5c12..f2af52c651 100644
--- a/app/src/main/res/values-ar/strings.xml
+++ b/app/src/main/res/values-ar/strings.xml
@@ -1180,6 +1180,11 @@
أدوات الوكيل غير مثبتة: %1$s
لا تُرسل
إرفاق
+ الملفات
+ السماح بالوصول إلى الصور
+ اختيار المزيد من الصور
+ لا توجد صور بعد
+ لوحة المفاتيح
إزالة
الافتراضي
جهد الاستدلال
@@ -4325,4 +4330,6 @@
اختصار داخل اللعبة
إظهار اختصار النظارات الذكية
إظهار زر النظارات الذكية العائم فوق اللعبة.
+ استخدام ملف تعريف %1$s: %2$s
+ استخدام الملف التعريفي الافتراضي: %1$s
diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml
index 12254b5715..109f454cba 100644
--- a/app/src/main/res/values-b+es+419/strings.xml
+++ b/app/src/main/res/values-b+es+419/strings.xml
@@ -1198,6 +1198,11 @@
Herramientas del agente sin instalar: %1$s
No enviar
Adjuntar
+ Archivos
+ Permitir acceso a fotos
+ Elegir más fotos
+ Aún no hay fotos
+ Teclado
Quitar
Predeterminado
Esfuerzo de razonamiento
@@ -4203,4 +4208,6 @@
Acceso directo en el juego
Mostrar acceso directo de Smart Glasses
Mostrar el botón flotante de Smart Glasses sobre el juego.
+ Usando el perfil %1$s: %2$s
+ Usando el perfil predeterminado: %1$s
diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml
index bb4ff12581..12846c1ab5 100644
--- a/app/src/main/res/values-bg/strings.xml
+++ b/app/src/main/res/values-bg/strings.xml
@@ -1168,6 +1168,11 @@
Инструментите на агента не са инсталирани: %1$s
Не изпращай
Прикачи
+ Файлове
+ Разрешаване на достъп до снимки
+ Избор на още снимки
+ Все още няма снимки
+ Клавиатура
Премахни
По подразбиране
Усилие за разсъждение
@@ -4165,4 +4170,6 @@
Пряк път в играта
Показване на прекия път за Smart Glasses
Показва плаващия бутон за Smart Glasses върху играта.
+ Използва се профил %1$s: %2$s
+ Използва се профилът по подразбиране: %1$s
diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml
index 02d5c6d00d..ba390d045d 100644
--- a/app/src/main/res/values-cs/strings.xml
+++ b/app/src/main/res/values-cs/strings.xml
@@ -1174,6 +1174,11 @@
Nástroje agenta nejsou nainstalované: %1$s
Neposílat
Přiložit
+ Soubory
+ Povolit přístup k fotkám
+ Vybrat další fotky
+ Zatím žádné fotky
+ Klávesnice
Odebrat
Výchozí
Náročnost uvažování
@@ -4245,4 +4250,6 @@
Zkratka ve hře
Zobrazit zkratku Smart Glasses
Zobrazit plovoucí tlačítko Smart Glasses nad hrou.
+ Používá se profil %1$s: %2$s
+ Používá se výchozí profil: %1$s
diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml
index f3383e6768..7dde6f63c7 100644
--- a/app/src/main/res/values-da/strings.xml
+++ b/app/src/main/res/values-da/strings.xml
@@ -1168,6 +1168,11 @@
Agentens værktøjer er ikke installeret: %1$s
Send ikke
Vedhæft
+ Filer
+ Tillad adgang til billeder
+ Vælg flere billeder
+ Ingen billeder endnu
+ Tastatur
Fjern
Standard
Ræsonneringsindsats
@@ -4165,4 +4170,6 @@
Genvej i spillet
Vis Smart Glasses-genvej
Vis den flydende Smart Glasses-knap oven på spillet.
+ Bruger profilen %1$s: %2$s
+ Bruger standardprofilen: %1$s
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index ce45ef01d4..992d29d406 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -1160,6 +1160,11 @@
Agent-Werkzeuge nicht installiert: %1$s
Nicht senden
Anhängen
+ Dateien
+ Zugriff auf Fotos erlauben
+ Weitere Fotos auswählen
+ Noch keine Fotos
+ Tastatur
Entfernen
Standard
Denkaufwand
@@ -4165,4 +4170,6 @@
Ingame-Verknüpfung
Smart-Glasses-Verknüpfung anzeigen
Die schwebende Smart-Glasses-Schaltfläche über dem Spiel anzeigen.
+ Profil %1$s wird verwendet: %2$s
+ Standardprofil wird verwendet: %1$s
diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml
index 7205dd9940..a49dd4fbe4 100644
--- a/app/src/main/res/values-el/strings.xml
+++ b/app/src/main/res/values-el/strings.xml
@@ -1168,6 +1168,11 @@
Τα εργαλεία του πράκτορα δεν εγκαταστάθηκαν: %1$s
Να μην σταλεί
Επισύναψη
+ Αρχεία
+ Να επιτρέπεται η πρόσβαση στις φωτογραφίες
+ Επιλογή περισσότερων φωτογραφιών
+ Δεν υπάρχουν φωτογραφίες ακόμα
+ Πληκτρολόγιο
Αφαίρεση
Προεπιλογή
Προσπάθεια συλλογισμού
@@ -4165,4 +4170,6 @@
Συντόμευση μέσα στο παιχνίδι
Εμφάνιση συντόμευσης Smart Glasses
Εμφάνιση του αιωρούμενου κουμπιού Smart Glasses πάνω από το παιχνίδι.
+ Χρήση προφίλ %1$s: %2$s
+ Χρήση προεπιλεγμένου προφίλ: %1$s
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 71e10bdab3..c24fabe18d 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -1171,6 +1171,11 @@
Herramientas del agente sin instalar: %1$s
No enviar
Adjuntar
+ Archivos
+ Permitir acceso a las fotos
+ Elegir más fotos
+ Aún no hay fotos
+ Teclado
Quitar
Predeterminado
Esfuerzo de razonamiento
@@ -4205,4 +4210,6 @@
Acceso directo en el juego
Mostrar acceso directo de Smart Glasses
Mostrar el botón flotante de Smart Glasses sobre el juego.
+ Usando el perfil %1$s: %2$s
+ Usando el perfil predeterminado: %1$s
diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml
index 464e2576be..16713dbcb4 100644
--- a/app/src/main/res/values-fi/strings.xml
+++ b/app/src/main/res/values-fi/strings.xml
@@ -1168,6 +1168,11 @@
Agentin työkaluja ei ole asennettu: %1$s
Älä lähetä
Liitä
+ Tiedostot
+ Salli kuvien käyttö
+ Valitse lisää kuvia
+ Ei vielä kuvia
+ Näppäimistö
Poista
Oletus
Päättelyteho
@@ -4165,4 +4170,6 @@
Pelin aikainen pikakuvake
Näytä Smart Glasses -pikakuvake
Näytä pelin päällä kelluva Smart Glasses -painike.
+ Käytössä profiili %1$s: %2$s
+ Käytössä oletusprofiili: %1$s
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index 7c1c1ef44d..6238a0cc16 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -1171,6 +1171,11 @@
Outils de l’agent non installés : %1$s
Ne pas envoyer
Joindre
+ Fichiers
+ Autoriser l\'accès aux photos
+ Choisir d\'autres photos
+ Aucune photo pour l\'instant
+ Clavier
Supprimer
Par défaut
Effort de raisonnement
@@ -4204,4 +4209,6 @@
Raccourci en jeu
Afficher le raccourci Smart Glasses
Afficher le bouton flottant Smart Glasses par-dessus le jeu.
+ Profil %1$s utilisé : %2$s
+ Profil par défaut utilisé : %1$s
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index 281c5914d5..e557f76d02 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -1168,6 +1168,11 @@
एजेंट टूल इंस्टॉल नहीं हुए: %1$s
न भेजें
संलग्न करें
+ फ़ाइलें
+ फ़ोटो की अनुमति दें
+ और फ़ोटो चुनें
+ अभी कोई फ़ोटो नहीं
+ कीबोर्ड
हटाएँ
डिफ़ॉल्ट
सोचने का स्तर
@@ -4165,4 +4170,6 @@
गेम में शॉर्टकट
Smart Glasses शॉर्टकट दिखाएँ
गेम के ऊपर तैरता हुआ Smart Glasses बटन दिखाएँ।
+ %1$s प्रोफ़ाइल का उपयोग: %2$s
+ डिफ़ॉल्ट प्रोफ़ाइल का उपयोग: %1$s
diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml
index a74cef1df8..497d330460 100644
--- a/app/src/main/res/values-hu/strings.xml
+++ b/app/src/main/res/values-hu/strings.xml
@@ -1168,6 +1168,11 @@
Az ügynök eszközei nincsenek telepítve: %1$s
Ne küldd el
Csatolás
+ Fájlok
+ Fotókhoz való hozzáférés engedélyezése
+ További fotók kiválasztása
+ Még nincsenek fotók
+ Billentyűzet
Eltávolítás
Alapértelmezett
Gondolkodási erőfeszítés
@@ -4165,4 +4170,6 @@
Játékon belüli parancsikon
Smart Glasses parancsikon megjelenítése
A játék fölött lebegő Smart Glasses gomb megjelenítése.
+ Használt profil: %1$s – %2$s
+ Alapértelmezett profil használata: %1$s
diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml
index 8bd5840655..cdbb9de406 100644
--- a/app/src/main/res/values-in/strings.xml
+++ b/app/src/main/res/values-in/strings.xml
@@ -1165,6 +1165,11 @@
Alat agen tidak terpasang: %1$s
Jangan kirim
Lampirkan
+ File
+ Izinkan akses foto
+ Pilih foto lainnya
+ Belum ada foto
+ Keyboard
Hapus
Default
Upaya penalaran
@@ -4135,4 +4140,6 @@
Pintasan dalam game
Tampilkan pintasan Smart Glasses
Tampilkan tombol Smart Glasses mengambang di atas game.
+ Menggunakan profil %1$s: %2$s
+ Menggunakan profil default: %1$s
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index 0d79a90921..d37563a4d5 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -1163,6 +1163,11 @@
Strumenti dell’agente non installati: %1$s
Non inviare
Allega
+ File
+ Consenti accesso alle foto
+ Scegli altre foto
+ Ancora nessuna foto
+ Tastiera
Rimuovi
Predefinito
Livello di ragionamento
@@ -4204,4 +4209,6 @@
Scorciatoia nel gioco
Mostra scorciatoia Smart Glasses
Mostra il pulsante mobile Smart Glasses sopra il gioco.
+ Profilo %1$s in uso: %2$s
+ Profilo predefinito in uso: %1$s
diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml
index f66a14fc6e..be60a37db5 100644
--- a/app/src/main/res/values-ja/strings.xml
+++ b/app/src/main/res/values-ja/strings.xml
@@ -1165,6 +1165,11 @@
エージェントのツールが未インストール: %1$s
送信しない
添付
+ ファイル
+ 写真へのアクセスを許可
+ 写真をさらに選択
+ まだ写真がありません
+ キーボード
削除
デフォルト
推論レベル
@@ -4135,4 +4140,6 @@
ゲーム内ショートカット
Smart Glasses のショートカットを表示
ゲーム画面上に Smart Glasses のフローティングボタンを表示します。
+ %1$s プロファイルを使用中: %2$s
+ デフォルトプロファイルを使用中: %1$s
diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml
index dbcf405e3f..89c839ce22 100644
--- a/app/src/main/res/values-ko/strings.xml
+++ b/app/src/main/res/values-ko/strings.xml
@@ -1165,6 +1165,11 @@
에이전트 도구가 설치되지 않음: %1$s
보내지 않기
첨부
+ 파일
+ 사진 접근 허용
+ 사진 더 선택
+ 아직 사진이 없습니다
+ 키보드
제거
기본
추론 수준
@@ -4135,4 +4140,6 @@
게임 내 바로가기
Smart Glasses 바로가기 표시
게임 위에 떠 있는 Smart Glasses 버튼을 표시합니다.
+ %1$s 프로필 사용 중: %2$s
+ 기본 프로필 사용 중: %1$s
diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml
index 2dc5bcea1b..a13e0ba39f 100644
--- a/app/src/main/res/values-ms/strings.xml
+++ b/app/src/main/res/values-ms/strings.xml
@@ -1165,6 +1165,11 @@
Alat ejen tidak dipasang: %1$s
Jangan hantar
Lampirkan
+ Fail
+ Benarkan akses foto
+ Pilih lebih banyak foto
+ Belum ada foto
+ Papan kekunci
Alih keluar
Lalai
Usaha penaakulan
@@ -4135,4 +4140,6 @@
Pintasan dalam permainan
Tunjukkan pintasan Smart Glasses
Tunjukkan butang Smart Glasses terapung di atas permainan.
+ Menggunakan profil %1$s: %2$s
+ Menggunakan profil lalai: %1$s
diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml
index 70da47fde8..e2130d6988 100644
--- a/app/src/main/res/values-nb/strings.xml
+++ b/app/src/main/res/values-nb/strings.xml
@@ -1168,6 +1168,11 @@
Agentverktøy er ikke installert: %1$s
Ikke send
Legg ved
+ Filer
+ Tillat tilgang til bilder
+ Velg flere bilder
+ Ingen bilder ennå
+ Tastatur
Fjern
Standard
Resonneringsinnsats
@@ -4165,4 +4170,6 @@
Snarvei i spillet
Vis Smart Glasses-snarvei
Vis den flytende Smart Glasses-knappen over spillet.
+ Bruker profilen %1$s: %2$s
+ Bruker standardprofilen: %1$s
diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml
index aa95f349be..7563fbaf45 100644
--- a/app/src/main/res/values-nl/strings.xml
+++ b/app/src/main/res/values-nl/strings.xml
@@ -1168,6 +1168,11 @@
Agenttools niet geïnstalleerd: %1$s
Niet verzenden
Bijvoegen
+ Bestanden
+ Toegang tot foto\'s toestaan
+ Meer foto\'s kiezen
+ Nog geen foto\'s
+ Toetsenbord
Verwijderen
Standaard
Redeneerinspanning
@@ -4165,4 +4170,6 @@
Snelkoppeling in game
Smart Glasses-snelkoppeling tonen
Toon de zwevende Smart Glasses-knop boven het spel.
+ Profiel %1$s in gebruik: %2$s
+ Standaardprofiel in gebruik: %1$s
diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml
index 350871461b..383bc3aed3 100644
--- a/app/src/main/res/values-pl/strings.xml
+++ b/app/src/main/res/values-pl/strings.xml
@@ -1174,6 +1174,11 @@
Narzędzia agenta nie są zainstalowane: %1$s
Nie wysyłaj
Załącz
+ Pliki
+ Zezwól na dostęp do zdjęć
+ Wybierz więcej zdjęć
+ Brak zdjęć
+ Klawiatura
Usuń
Domyślny
Poziom rozumowania
@@ -4245,4 +4250,6 @@
Skrót w grze
Pokaż skrót Smart Glasses
Pokaż pływający przycisk Smart Glasses nad grą.
+ Używany profil %1$s: %2$s
+ Używany profil domyślny: %1$s
diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml
index 58c25267da..c18340904d 100644
--- a/app/src/main/res/values-pt-rPT/strings.xml
+++ b/app/src/main/res/values-pt-rPT/strings.xml
@@ -1163,6 +1163,11 @@
Ferramentas do agente não instaladas: %1$s
Não enviar
Anexar
+ Ficheiros
+ Permitir acesso às fotos
+ Escolher mais fotos
+ Ainda não há fotos
+ Teclado
Remover
Predefinido
Esforço de raciocínio
@@ -4204,4 +4209,6 @@
Atalho no jogo
Mostrar atalho do Smart Glasses
Mostrar o botão flutuante do Smart Glasses sobre o jogo.
+ Perfil %1$s em utilização: %2$s
+ Perfil predefinido em utilização: %1$s
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index 08eb2c38de..6fea986206 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -1170,6 +1170,11 @@
Ferramentas do agente não instaladas: %1$s
Não enviar
Anexar
+ Arquivos
+ Permitir acesso às fotos
+ Escolher mais fotos
+ Ainda não há fotos
+ Teclado
Remover
Padrão
Esforço de raciocínio
@@ -4212,4 +4217,6 @@
Atalho durante o jogo
Mostrar atalho do Smart Glasses
Mostrar o botão flutuante do Smart Glasses sobre o jogo.
+ Perfil %1$s em uso: %2$s
+ Perfil predefinido em uso: %1$s
diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml
index bd89893d52..fc7da00b02 100644
--- a/app/src/main/res/values-ro/strings.xml
+++ b/app/src/main/res/values-ro/strings.xml
@@ -1171,6 +1171,11 @@
Instrumentele agentului nu sunt instalate: %1$s
Nu trimite
Atașează
+ Fișiere
+ Permite accesul la fotografii
+ Alege mai multe fotografii
+ Încă nu există fotografii
+ Tastatură
Elimină
Implicit
Efort de raționament
@@ -4205,4 +4210,6 @@
Comandă rapidă în joc
Afișează comanda rapidă Smart Glasses
Afișează butonul plutitor Smart Glasses peste joc.
+ Se folosește profilul %1$s: %2$s
+ Se folosește profilul implicit: %1$s
diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml
index c75b0aa343..5117873485 100644
--- a/app/src/main/res/values-ru/strings.xml
+++ b/app/src/main/res/values-ru/strings.xml
@@ -1174,6 +1174,11 @@
Инструменты агента не установлены: %1$s
Не отправлять
Прикрепить
+ Файлы
+ Разрешить доступ к фото
+ Выбрать ещё фото
+ Пока нет фото
+ Клавиатура
Удалить
По умолчанию
Уровень рассуждений
@@ -4246,4 +4251,6 @@
Ярлык в игре
Показывать ярлык Smart Glasses
Показывать плавающую кнопку Smart Glasses поверх игры.
+ Используется профиль %1$s: %2$s
+ Используется профиль по умолчанию: %1$s
diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml
index f3819c7385..455c4d6472 100644
--- a/app/src/main/res/values-sv/strings.xml
+++ b/app/src/main/res/values-sv/strings.xml
@@ -1168,6 +1168,11 @@
Agentens verktyg är inte installerade: %1$s
Skicka inte
Bifoga
+ Filer
+ Tillåt åtkomst till bilder
+ Välj fler bilder
+ Inga bilder än
+ Tangentbord
Ta bort
Standard
Resonemangsnivå
@@ -4165,4 +4170,6 @@
Genväg i spelet
Visa Smart Glasses-genväg
Visa den flytande Smart Glasses-knappen ovanpå spelet.
+ Använder profilen %1$s: %2$s
+ Använder standardprofilen: %1$s
diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml
index 21c96ecd2a..104b5f6407 100644
--- a/app/src/main/res/values-th/strings.xml
+++ b/app/src/main/res/values-th/strings.xml
@@ -1165,6 +1165,11 @@
ยังไม่ได้ติดตั้งเครื่องมือของเอเจนต์: %1$s
ไม่ต้องส่ง
แนบ
+ ไฟล์
+ อนุญาตให้เข้าถึงรูปภาพ
+ เลือกรูปภาพเพิ่ม
+ ยังไม่มีรูปภาพ
+ แป้นพิมพ์
นำออก
ค่าเริ่มต้น
ระดับการใช้เหตุผล
@@ -4135,4 +4140,6 @@
ทางลัดในเกม
แสดงทางลัด Smart Glasses
แสดงปุ่ม Smart Glasses แบบลอยทับบนเกม
+ ใช้โปรไฟล์ %1$s: %2$s
+ ใช้โปรไฟล์เริ่มต้น: %1$s
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index acc9089167..bbe4bad308 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -1160,6 +1160,11 @@
Ajan araçları yüklenmedi: %1$s
Gönderme
Ekle
+ Dosyalar
+ Fotoğraflara erişime izin ver
+ Daha fazla fotoğraf seç
+ Henüz fotoğraf yok
+ Klavye
Kaldır
Varsayılan
Akıl yürütme çabası
@@ -4165,4 +4170,6 @@
Oyun içi kısayol
Smart Glasses kısayolunu göster
Oyun üzerinde yüzen Smart Glasses düğmesini göster.
+ %1$s profili kullanılıyor: %2$s
+ Varsayılan profil kullanılıyor: %1$s
diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml
index 6ca06df91c..36ba31f001 100644
--- a/app/src/main/res/values-uk/strings.xml
+++ b/app/src/main/res/values-uk/strings.xml
@@ -1174,6 +1174,11 @@
Інструменти агента не встановлено: %1$s
Не надсилати
Прикріпити
+ Файли
+ Дозволити доступ до фото
+ Вибрати ще фото
+ Поки немає фото
+ Клавіатура
Видалити
За замовчуванням
Рівень міркувань
@@ -4245,4 +4250,6 @@
Ярлик у грі
Показувати ярлик Smart Glasses
Показувати плаваючу кнопку Smart Glasses поверх гри.
+ Використовується профіль %1$s: %2$s
+ Використовується профіль за замовчуванням: %1$s
diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml
index 420c0c1bf5..9c9ec116bf 100644
--- a/app/src/main/res/values-vi/strings.xml
+++ b/app/src/main/res/values-vi/strings.xml
@@ -1165,6 +1165,11 @@
Chưa cài công cụ của tác tử: %1$s
Không gửi
Đính kèm
+ Tệp
+ Cho phép truy cập ảnh
+ Chọn thêm ảnh
+ Chưa có ảnh
+ Bàn phím
Xóa
Mặc định
Mức độ lập luận
@@ -4135,4 +4140,6 @@
Lối tắt trong trò chơi
Hiển thị lối tắt Smart Glasses
Hiển thị nút Smart Glasses nổi phía trên trò chơi.
+ Đang dùng hồ sơ %1$s: %2$s
+ Đang dùng hồ sơ mặc định: %1$s
diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml
index eb5407a271..d9a964ca6a 100644
--- a/app/src/main/res/values-zh-rCN/strings.xml
+++ b/app/src/main/res/values-zh-rCN/strings.xml
@@ -1248,6 +1248,11 @@
智能体工具未安装:%1$s
不发送
添加附件
+ 文件
+ 允许访问照片
+ 选择更多照片
+ 还没有照片
+ 键盘
移除
默认
推理强度
@@ -4133,4 +4138,6 @@
游戏内快捷方式
显示 Smart Glasses 快捷方式
在游戏画面上显示悬浮的 Smart Glasses 按钮。
+ 正在使用 %1$s 配置:%2$s
+ 正在使用默认配置:%1$s
diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml
index 7f4bbd0233..1e921fb63e 100644
--- a/app/src/main/res/values-zh-rHK/strings.xml
+++ b/app/src/main/res/values-zh-rHK/strings.xml
@@ -1164,6 +1164,11 @@
智能體工具未安裝:%1$s
不要傳送
附加
+ 檔案
+ 允許存取相片
+ 選擇更多相片
+ 尚未有相片
+ 鍵盤
移除
預設
推理強度
@@ -4133,4 +4138,6 @@
遊戲內捷徑
顯示 Smart Glasses 捷徑
在遊戲畫面上顯示浮動的 Smart Glasses 按鈕。
+ 正在使用 %1$s 設定檔:%2$s
+ 正在使用預設設定檔:%1$s
diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml
index e52193ca17..7ea662de72 100644
--- a/app/src/main/res/values-zh-rTW/strings.xml
+++ b/app/src/main/res/values-zh-rTW/strings.xml
@@ -1164,6 +1164,11 @@
智慧代理工具未安裝:%1$s
不要傳送
附加
+ 檔案
+ 允許存取相片
+ 選擇更多相片
+ 還沒有相片
+ 鍵盤
移除
預設
推理強度
@@ -4133,4 +4138,6 @@
遊戲內捷徑
顯示 Smart Glasses 捷徑
在遊戲畫面上顯示浮動的 Smart Glasses 按鈕。
+ 正在使用 %1$s 設定檔:%2$s
+ 正在使用預設設定檔:%1$s
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index ed8b435d3f..213b72aa62 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -1330,6 +1330,11 @@
Agent tools not installed: %1$s
Don\'t send
Attach
+ Files
+ Allow photo access
+ Choose more photos
+ No photos yet
+ Keyboard
Remove
Default
Reasoning effort
@@ -2852,6 +2857,8 @@
Shared by Steam and Desktop.
Applies live. Shared by Steam and Desktop.
FSR, GSR and NIS apply when enlarging the session image. Sharpen only also works without enlargement.
+ Using %1$s profile: %2$s
+ Using Default profile: %1$s
Filter sharpness
%1$s Sets scaling to %2$s.
Match screen (%1$d×%2$d)
diff --git a/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt
index d975b6b756..2f9f3ad5e5 100644
--- a/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt
+++ b/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt
@@ -181,6 +181,17 @@ class ProtonExtrasTest {
assertEquals(emptyList(), ProtonExtras.installedIn(File(tools, "missing"), tool("ge")))
}
+ @Test
+ fun x86_64BuildsAreNotTakenForTheArm64Tool() {
+ val tools = temp.newFolder("compatibilitytools.d")
+ for (name in listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton-11-14.2-x86_64")) installTool(tools, name)
+ File(tools, "DroidDeck-Proton-11-14.2-x86_64/files/lib/wine/x86_64-unix").mkdirs()
+ File(tools, "DroidDeck-Proton 11-7.5/files/lib/wine/x86_64-unix").mkdirs()
+ File(tools, "DroidDeck-Proton 11-7.5/files/bin-arm64").mkdirs()
+ assertEquals(listOf("DroidDeck-Proton 11-7.5"), ProtonExtras.installedIn(tools, tool("droiddeck")))
+ assertTrue(ProtonExtras.x86_64Build(File(tools, "DroidDeck-Proton-11-14.2-x86_64")))
+ }
+
@Test
fun interruptedBuildsAreNotReportedAsInstalled() {
val tools = temp.newFolder("compatibilitytools.d")
diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionPrefsUpscalerTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionPrefsUpscalerTest.kt
new file mode 100644
index 0000000000..36708bc145
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/session/SessionPrefsUpscalerTest.kt
@@ -0,0 +1,79 @@
+package com.droiddeck.launcher.session
+
+import android.content.Context
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+import org.robolectric.annotation.Config
+
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [28], manifest = Config.NONE)
+class SessionPrefsUpscalerTest {
+ private lateinit var context: Context
+
+ @Before fun setUp() {
+ context = RuntimeEnvironment.getApplication()
+ context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
+ }
+
+ @Test fun gameOverridesAreIsolatedAndFallBackToTheGlobalFilter() {
+ SessionPrefs.setUpscaler(context, 4)
+ SessionPrefs.setGameUpscaler(context, "12345", 7)
+
+ assertEquals(4, SessionPrefs.upscaler(context))
+ assertEquals(7, SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
+ assertEquals(4, SessionPrefs.screenEffectsUpscaler(context, "game:54321"))
+ assertTrue(SessionPrefs.hasGameUpscalerOverride(context, "12345"))
+ assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "54321"))
+ assertFalse(SessionPrefs.hasScreenEffectsOverride(context, "game:12345"))
+ }
+
+ @Test fun resettingGameOverrideRestoresTheGlobalFilter() {
+ SessionPrefs.setUpscaler(context, 3)
+ SessionPrefs.setGameUpscaler(context, "12345", 6)
+
+ SessionPrefs.clearGameUpscaler(context, "12345")
+
+ assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "12345"))
+ assertEquals(3, SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
+ }
+
+ @Test fun screenEffectsUpscalerApiKeepsGameFiltersSeparateFromScreenEffects() {
+ SessionPrefs.setUpscaler(context, 4)
+ SessionPrefs.setScreenEffectsUpscaler(context, "game:12345", 8)
+
+ assertEquals(8, SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
+ assertFalse(SessionPrefs.hasScreenEffectsOverride(context, "game:12345"))
+ }
+
+ @Test fun legacyGameFilterOverridesRemainReadableAndCanBeReset() {
+ val profile = JSONObject().put("upscaler", 6)
+ val profiles = JSONObject().put("game:12345", profile)
+ context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
+ .putString("screenEffects.profiles", profiles.toString()).commit()
+
+ assertTrue(SessionPrefs.hasGameUpscalerOverride(context, "12345"))
+ assertEquals(6, SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
+
+ SessionPrefs.clearGameUpscaler(context, "12345")
+
+ assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "12345"))
+ assertEquals(2, SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
+ assertFalse(SessionPrefs.hasScreenEffectsOverride(context, "game:12345"))
+ }
+
+ @Test fun deletingGameScreenEffectsProfileClearsUpscalerOverrideEvenWithoutEffectsProfile() {
+ SessionPrefs.setGameUpscaler(context, "12345", 6)
+
+ SessionPrefs.deleteScreenEffectsProfile(context, "game:12345")
+
+ assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "12345"))
+ assertEquals(SessionPrefs.upscaler(context), SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
+ }
+}
diff --git a/docs/development/anti-cheat.md b/docs/development/anti-cheat.md
new file mode 100644
index 0000000000..d287aea85e
--- /dev/null
+++ b/docs/development/anti-cheat.md
@@ -0,0 +1,54 @@
+# Easy Anti-Cheat and BattlEye
+
+On a Steam Deck, Proton loads Valve's anti-cheat runtimes (Proton EasyAntiCheat Runtime, app 1826330, and
+Proton BattlEye Runtime, app 1161040). Their bridge libraries are x86 only, so the ARM64 DroidDeck-Proton
+cannot load them. Games that need them run an x86-64 DroidDeck-Proton under FEX instead.
+
+## Routing
+
+The Proton launchers (`steam-compatibility`: the built-in DroidDeck-Proton launcher and the wrapper put around
+every tool in `compatibilitytools.d`) check each `run` and `waitforexitandrun` before any ARM64 setup:
+
+- **Condition.** The game folder (`STEAM_COMPAT_INSTALL_PATH`, three levels deep) holds one of
+ `EasyAntiCheat/Settings.json`, `easyanticheat_x64.so`, `BEClient_x64.so` or `BEService_x64.exe`. No
+ title, app ID or device list is involved.
+- **Chosen tool.** Only launches through DroidDeck's own Proton (the built-in launcher or a `DroidDeck-Proton*`
+ folder) are moved. A game set to any other tool, such as GE-Proton, Bionic or Valve's Proton, in DroidDeck or
+ in Steam's Properties, runs on that tool and the launcher logs that it was chosen.
+- **Tool.** The newest `compatibilitytools.d/DroidDeck-Proton*` whose layout is x86-64
+ (`files/lib/wine/x86_64-unix`, no `files/bin-arm64`).
+- **Runtime.** `PROTON_EAC_RUNTIME` or `PROTON_BATTLEYE_RUNTIME` when it already points at a folder with the
+ bridge libraries, otherwise the runtime's folder in any Steam library.
+- **Launch.** `droiddeck-fex proton /proton `: FEX with the Steam Linux Runtime rootfs,
+ keeping the game's own `STEAM_COMPAT_DATA_PATH` prefix.
+
+Without the x86-64 tool or the runtime files the launch stays on ARM64 and the launcher logs why.
+`DROIDDECK_ANTICHEAT=off` in the game's launch options keeps it on ARM64. Picking the x86-64 tool for a
+game in Steam always runs it under FEX.
+
+## Why the x86-64 build needs its own Wine patches
+
+Android kernels use 39-bit user address spaces. Easy Anti-Cheat's launcher maps fixed memory at
+`0x7001_0000_0000`, which FEX serves from emulated guest pages (`tools/fex/patches/0027`). Exclusive load and store pairs on that
+memory are emulated as a compare-and-swap, so hosts without LSE atomics work too. `tools/fex/probes/guest-high-memory.c`
+checks loads, stores, atomics, iovec system calls, `madvise` and code written through a high alias. The x86-64 Wine
+in DroidDeck-Proton carries `ntdll-fixed-allocations-above-host-address-limit.patch` (fixed mappings above
+the host limit go to the emulator) and `ntdll-keep-libc-in-native-syscall-dispatch-range.patch` (the
+re-armed syscall user dispatch range keeps libc native). Stock x86-64 Proton stops after "Hack native
+syscalls" on the same game.
+
+Easy Anti-Cheat's launcher attaches to the game with ptrace, stops it on a `rt_sigprocmask` call, runs its
+own loader and restores the registers it saved at the stop. The call then returns `ENOSYS` without writing
+the old mask, as it does on a desktop kernel. `ntdll-retry-blocking-signals-dropped-by-a-tracer.patch`
+retries the block once when it fails, so Wine never restores an uninitialised mask that blocks `SIGSYS`.
+
+## The container's procfs
+
+Android mounts `/proc` with `hidepid=invisible,gid=3009`, and Easy Anti-Cheat refuses that mount with
+launch error 261. Without root, user namespaces or PID namespaces, no procfs instance without those options
+can be mounted. Every program in the container runs as the app's user and already sees all of the
+container's processes, as it would in a PID-namespaced sandbox on a desktop, so FEX's emulated
+`/proc//mounts` and `/proc//mountinfo` show the proc mount without `hidepid=`, `gid=` and
+`subset=` (`tools/fex/patches/0029`). Only x86 programs under FEX see this view; every other line of the
+table is the host's. Processes of other Android users stay hidden, as host processes do from a desktop
+sandbox.
diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md
index ced25e4c70..d4d67c7687 100644
--- a/docs/development/x86-64-steam-client.md
+++ b/docs/development/x86-64-steam-client.md
@@ -216,9 +216,10 @@ alone would then read as an installed client.
NullReferenceException, internal CLR errors). A writable mapping or mprotect now write-protects the
overlapping part of any alias that is already executable, so the first write faults and invalidates.
`FEX_SMCCHECKS=full` was the only workaround; no setting is needed with the patch.
- - `0007-cmake-install-code-without-depends`: CMake 4.5 rejects the `DEPENDS` argument FEX passes to
- `install(CODE ...)` for the guest thunk libraries, so builds with host thunks stopped at configure.
- The guest libraries are external projects in the default build, which `install` already follows.
+ - `0007-cmake-install-code-without-depends` (`Fixed-upstream: FEX-2612`): CMake 4.5 rejects the
+ `DEPENDS` argument FEX passes to `install(CODE ...)` for the guest thunk libraries, so builds with
+ host thunks stopped at configure. The guest libraries are external projects in the default build,
+ which `install` already follows.
- `0008-signal-return-restores-syscall-state`: a guest `rt_sigreturn` is a system call, so FEX's
syscall stub marks every static register as spilled (`InSyscallInfo = 0xFFFF`). When the handler
left RIP alone, the return resumed the interrupted JIT code without passing the stub's reset, and
diff --git a/tools/agent/AGENTS.md b/tools/agent/AGENTS.md
index 709dcbf181..3b2ccd2c84 100644
--- a/tools/agent/AGENTS.md
+++ b/tools/agent/AGENTS.md
@@ -44,8 +44,10 @@ from what tripped agents up on real devices.
running makes Steam show "Game already running" and `launch` time out.
- Session scripts are APK assets, copied into the rootfs at every session start over any local
edit. A Lab build (`dd-lab-build`, see `docs/lab-builds.md`) carries app code and resources only:
- session scripts, native code and assets need a new APK, such as the pull request's CI test build
- (DroidDeck > Updates > Test builds).
+ session scripts, native code, assets and `AndroidManifest.xml` need a new APK, such as the pull
+ request's CI test build (DroidDeck > Updates > Test builds). `dd-lab-build` refuses changes to the
+ manifest, native code, Gradle files and a few startup classes, but builds session script and asset
+ changes without them. To try the rest of a branch, build a copy without those changes.
## Changing DroidDeck
@@ -56,7 +58,8 @@ The source is checked out at `/root/DroidDeck` once the Agent tab's build tools
- `dd-lab-build` builds the checkout as a Lab build and restarts DroidDeck on it. DroidDeck runs the
build in a process of its own and shows its progress; `dd-lab-build` follows its log. Run it in
the background and keep checking, so the user can talk to you meanwhile. The restart ends your
- process, and the conversation continues on the new build.
+ process; DroidDeck starts you again on the new build, in the same conversation, so tell the user
+ what you will check then instead of asking them to message you.
- To try a change, commit it and go straight to `dd-lab-build`: it compiles the app, so a Gradle
compile first only adds time. It refuses changes since the installed build (`apkCommit` in
`droiddeckctl state`) that need a new APK. For a branch from a newer `origin/main`, cherry-pick
diff --git a/tools/fex/build-in-arch.sh b/tools/fex/build-in-arch.sh
index dccb24f882..9adc7e93e5 100755
--- a/tools/fex/build-in-arch.sh
+++ b/tools/fex/build-in-arch.sh
@@ -63,6 +63,11 @@ cmake -S fex-src -B fex-build -G Ninja \
${FEX_EXTRA_CXXFLAGS:+-DCMAKE_CXX_FLAGS="$FEX_EXTRA_CXXFLAGS"}
ninja -C fex-build
DESTDIR="$WORK/out" ninja -C fex-build install
+mkdir -p out/usr/local/share/fex-emu
+for p in tools/fex/patches/*.patch; do
+ p=$(basename "$p" .patch)
+ echo "${p#*-}"
+done > out/usr/local/share/fex-emu/.droiddeck-patches
install -Dm755 /usr/bin/unsquashfs out/usr/local/bin/unsquashfs
install -Dm644 "$(readlink -f /usr/lib/libxxhash.so.0)" out/usr/local/lib/libxxhash.so.0
bundled=$(cd out/usr/local/lib && ls -- *.so* | sort -u)
diff --git a/tools/fex/patches/0007-cmake-install-code-without-depends.patch b/tools/fex/patches/0007-cmake-install-code-without-depends.patch
index 6752b40280..83c0e1fb82 100644
--- a/tools/fex/patches/0007-cmake-install-code-without-depends.patch
+++ b/tools/fex/patches/0007-cmake-install-code-without-depends.patch
@@ -1,3 +1,4 @@
+Fixed-upstream: FEX-2612
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8976588..3ae54f4 100644
--- a/CMakeLists.txt
diff --git a/tools/fex/patches/0008-signal-return-restores-syscall-state.patch b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch
index 6592a94550..327fe76a85 100644
--- a/tools/fex/patches/0008-signal-return-restores-syscall-state.patch
+++ b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch
@@ -1,8 +1,8 @@
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
-index b4c7b24..643185d 100644
+index 345f4d834..085ff00a2 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
-@@ -264,12 +264,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
+@@ -283,12 +283,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
auto Frame = Thread->CurrentFrame;
if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {
diff --git a/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch b/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch
index fbeec5ec96..6af2b7eb33 100644
--- a/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch
+++ b/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch
@@ -1,5 +1,5 @@
diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
-index 02bb6bf..2e72492 100644
+index 02bb6bfef..2e724929f 100644
--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
+++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
@@ -49,6 +49,11 @@ struct X86ContextBackup {
@@ -27,10 +27,10 @@ index 02bb6bf..2e72492 100644
// Arm64 doesn't have a red zone
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
-index 643185d..53179c4 100644
+index 085ff00a2..5c79d1092 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
-@@ -136,6 +136,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
+@@ -155,6 +155,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
#endif
}
@@ -62,7 +62,7 @@ index 643185d..53179c4 100644
ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore::Core::InternalThreadState* Thread, int Signal, void* ucontext) {
// We can end up getting a signal at any point in our host state
// Jump to a handler that saves all state so we can safely return
-@@ -249,6 +274,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
+@@ -268,6 +293,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
}
OldSP = *reinterpret_cast(GuestSP);
@@ -82,7 +82,7 @@ index 643185d..53179c4 100644
}
uintptr_t NewSP = OldSP;
-@@ -287,6 +325,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
+@@ -306,6 +344,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
auto ContextBackup = StoreThreadState(Thread, Signal, ucontext);
auto Frame = Thread->CurrentFrame;
@@ -90,7 +90,7 @@ index 643185d..53179c4 100644
// Ref count our faults
// We use this to track if it is safe to clear cache
-@@ -336,6 +375,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
+@@ -355,6 +394,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
uint64_t OldGuestSP = Frame->State.gregs[FEXCore::X86State::REG_RSP];
uint64_t NewGuestSP = OldGuestSP;
@@ -99,7 +99,7 @@ index 643185d..53179c4 100644
// altstack is only used if the signal handler was setup with SA_ONSTACK
if (GuestAction->sa_flags & SA_ONSTACK) {
-@@ -345,6 +386,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
+@@ -364,6 +405,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
// Then that means we are hitting recursive signals and we need to walk back the stack correctly
uint64_t AltStackBase = reinterpret_cast(GuestStack->ss_sp);
uint64_t AltStackEnd = AltStackBase + GuestStack->ss_size;
@@ -108,7 +108,7 @@ index 643185d..53179c4 100644
if (OldGuestSP >= AltStackBase && OldGuestSP <= AltStackEnd) {
// We are already in the alt stack, the rest of the code will handle adjusting this
} else {
-@@ -353,6 +396,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
+@@ -372,6 +415,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
}
}
@@ -149,7 +149,7 @@ index 643185d..53179c4 100644
// siginfo_t
siginfo_t* HostSigInfo = reinterpret_cast(info);
-@@ -491,6 +568,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre
+@@ -510,6 +587,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre
// Our ref counting doesn't matter anymore
Thread->CurrentFrame->SignalHandlerRefCounter = 0;
@@ -159,7 +159,7 @@ index 643185d..53179c4 100644
// Set the new PC
if (CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext))) {
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
-index dfcd4b0..e4a86a9 100644
+index 0f45cf68d..408cddf71 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
@@ -83,6 +83,9 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators {
diff --git a/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch b/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch
index 626c726b59..cebe184aa2 100644
--- a/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch
+++ b/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch
@@ -1,7 +1,8 @@
diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp
+index 1946dc946..9f04358c5 100644
--- a/FEXCore/Source/Interface/Core/Core.cpp
+++ b/FEXCore/Source/Interface/Core/Core.cpp
-@@ -383,7 +383,11 @@
+@@ -383,7 +383,11 @@ bool ContextImpl::InitCore() {
}
void ContextImpl::HandleCallback(FEXCore::Core::InternalThreadState* Thread, uint64_t RIP) {
@@ -15,9 +16,10 @@ diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/C
void ContextImpl::ExecuteThread(FEXCore::Core::InternalThreadState* Thread) {
diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
+index ae3ed51e4..c5e656d2c 100644
--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
+++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
-@@ -305,6 +305,9 @@
+@@ -306,6 +306,9 @@ DEF_OP(Thunk) {
PushDynamicRegs(TMP1);
@@ -27,7 +29,7 @@ diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/In
mov(ARMEmitter::Size::i64Bit, ARMEmitter::Reg::r0, GetReg(Op->ArgPtr));
InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash);
-@@ -320,6 +323,8 @@
+@@ -321,6 +324,8 @@ DEF_OP(Thunk) {
FillStaticRegs({
.NZCV = false,
});
@@ -37,9 +39,10 @@ diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/In
DEF_OP(ValidateCode) {
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
+index 5c79d1092..e8e04b056 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
-@@ -107,6 +107,10 @@
+@@ -126,6 +126,10 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
#ifdef ARCHITECTURE_arm64
Thread->CurrentFrame->State.rip = CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext));
@@ -50,7 +53,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou
for (size_t i = 0; i < Config.SRAGPRCount; i++) {
const uint8_t SRAIdxMap = Config.SRAGPRMapping[i];
if (IgnoreMask & (1U << SRAIdxMap)) {
-@@ -301,12 +305,10 @@
+@@ -320,12 +324,10 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
if (Context->UContextLocation) {
auto Frame = Thread->CurrentFrame;
@@ -67,7 +70,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou
if (Is64BitMode) {
RestoreFrame_x64(Thread, Context, Frame, ucontext);
-@@ -361,6 +363,9 @@
+@@ -380,6 +382,9 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo;
Thread->CurrentFrame->InSyscallInfo = 0;
} else {
@@ -78,9 +81,10 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou
// This is likely to cause issues but in some cases it isn't fatal
// This can also happen if we have put a signal on hold, then we just reenabled the signal
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
+index fa6260954..e5d92e7c5 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
-@@ -131,7 +131,7 @@
+@@ -131,7 +131,7 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa
if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) {
// Restore previous `InSyscallInfo` structure.
@@ -89,7 +93,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
// Hack! Go back to the top of the dispatcher top
// This is only safe inside the JIT rather than anything outside of it
-@@ -211,7 +211,7 @@
+@@ -211,7 +211,7 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre
// If the guest modified the RIP then we need to take special precautions here
if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException) {
// Restore previous `InSyscallInfo` structure.
@@ -98,7 +102,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
// Hack! Go back to the top of the dispatcher top
// This is only safe inside the JIT rather than anything outside of it
-@@ -290,7 +290,7 @@
+@@ -290,7 +290,7 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th
if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) {
// Restore previous `InSyscallInfo` structure.
diff --git a/tools/fex/patches/0012-signal-return-applies-guest-registers.patch b/tools/fex/patches/0012-signal-return-applies-guest-registers.patch
index d97a75bee3..09c8398310 100644
--- a/tools/fex/patches/0012-signal-return-applies-guest-registers.patch
+++ b/tools/fex/patches/0012-signal-return-applies-guest-registers.patch
@@ -1,7 +1,8 @@
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
+index 9e6820bf6..43898e700 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
-@@ -263,6 +263,8 @@
+@@ -266,6 +266,8 @@ private:
FEXCore::Core::CpuStateFrame* Frame, void* ucontext);
void RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context,
FEXCore::Core::CpuStateFrame* Frame, void* ucontext);
@@ -11,9 +12,10 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Sourc
///< Setup the signal frame for x64.
uint64_t SetupFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* ContextBackup,
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
+index e5d92e7c5..38dc524f1 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
-@@ -122,6 +122,32 @@
+@@ -122,6 +122,32 @@ static void SetXStateInfo(T* xstate, bool is_avx_enabled) {
}
}
@@ -46,7 +48,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context,
FEXCore::Core::CpuStateFrame* Frame, void* ucontext) {
auto* guest_uctx = reinterpret_cast(Context->UContextLocation);
-@@ -202,6 +228,27 @@
+@@ -202,6 +228,27 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa
const auto modulo_i = (i + CurrentOffset) % 8;
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], sizeof(Frame->State.mm[0]));
}
@@ -74,7 +76,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
}
}
-@@ -280,6 +327,17 @@
+@@ -280,6 +327,17 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre
const auto modulo_i = (i + CurrentOffset) % 8;
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10);
}
@@ -92,7 +94,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
}
}
-@@ -359,6 +417,17 @@
+@@ -359,6 +417,17 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th
const auto modulo_i = (i + CurrentOffset) % 8;
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10);
}
diff --git a/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch b/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch
index 2192b9b0af..9bdad1cebd 100644
--- a/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch
+++ b/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch
@@ -1,8 +1,8 @@
diff --git a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
-index 2881ad9..abc84f3 100644
+index dd2c18303..e7e88f8f2 100644
--- a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
+++ b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
-@@ -518,7 +518,7 @@ int main(int argc, char** argv, char** const envp) {
+@@ -524,7 +524,7 @@ int main(int argc, char** argv, char** const envp) {
FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, Program.ProgramName);
} else {
// Anonymous program.
@@ -12,7 +12,7 @@ index 2881ad9..abc84f3 100644
}
} else {
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
-index a7a432b..4a77d87 100644
+index a7a432bbd..4a77d8716 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
@@ -441,7 +441,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname
diff --git a/tools/fex/patches/0021-anticheat-ptrace-seccomp-and-proc-emulation.patch b/tools/fex/patches/0021-anticheat-ptrace-seccomp-and-proc-emulation.patch
new file mode 100644
index 0000000000..b070802512
--- /dev/null
+++ b/tools/fex/patches/0021-anticheat-ptrace-seccomp-and-proc-emulation.patch
@@ -0,0 +1,5015 @@
+From: StonkGuy <68372320+StonkGuy@users.noreply.github.com>
+Subject: [PATCH] x86-64 ptrace, seccomp and /proc emulation for anti-cheat launchers
+
+Author: StonkGuy (https://github.com/StonkGuy/FEX)
+Source: https://github.com/StonkGuy/FEX branch eac-2611 (tag eac-2611.1)
+Copyright (c) StonkGuy and FEX contributors, MIT licence
+
+diff --git a/FEXCore/Source/CMakeLists.txt b/FEXCore/Source/CMakeLists.txt
+index 61385d2c3..b515a4a02 100644
+--- a/FEXCore/Source/CMakeLists.txt
++++ b/FEXCore/Source/CMakeLists.txt
+@@ -4,6 +4,7 @@ set(FEXCORE_BASE_SRCS
+ Interface/Config/Config.cpp
+ Utils/Allocator.cpp
+ Utils/FileLoading.cpp
++ Utils/FaultSafeRead.cpp
+ Utils/FileUtils.cpp
+ Utils/ForcedAssert.cpp
+ Utils/LogManager.cpp
+diff --git a/FEXCore/Source/Interface/Config/Config.json.in b/FEXCore/Source/Interface/Config/Config.json.in
+index 6bd89a1e5..860bd4429 100644
+--- a/FEXCore/Source/Interface/Config/Config.json.in
++++ b/FEXCore/Source/Interface/Config/Config.json.in
+@@ -604,6 +604,62 @@
+ "\tfull: Validate code before every run (slow)"
+ ]
+ },
++ "ProfileSampleHz": {
++ "Type": "uint32",
++ "Default": "0",
++ "AffectsCodeGen": "false",
++ "Desc": [
++ "Samples the host PC of the main guest thread this many times per second into /dev/shm/fex--samples (in-process; no ptrace).",
++ "Use with LibraryJITNaming to attribute samples to guest libraries. 0 disables."
++ ]
++ },
++ "ProfileSampleMinThreads": {
++ "Type": "uint32",
++ "Default": "100",
++ "AffectsCodeGen": "false",
++ "Desc": [
++ "ProfileSampleHz starts the sampler in the process that reaches this many guest threads (default 100: the application,",
++ "not the hundreds of helper processes of a Steam/Wine session). 1 samples every process from its first thread.",
++ "0: no sampler thread; each SIGPROF sent from outside stores a snapshot record of the receiving thread (ring in fex--snap)."
++ ]
++ },
++ "ProfileSampleAllThreads": {
++ "Type": "bool",
++ "Default": "false",
++ "AffectsCodeGen": "false",
++ "Desc": [
++ "ProfileSampleHz samples every guest thread instead of only the main one."
++ ]
++ },
++ "SignalTrace": {
++ "Type": "bool",
++ "Default": "false",
++ "AffectsCodeGen": "false",
++ "Desc": [
++ "Records guest signal handling events (host signal arrival, masking decisions, delivery, rt_sigreturn, sigprocmask, kill/tgkill)",
++ "into a ring buffer in /dev/shm/fex--sigtrace. For diagnosing lost signals; decode with tools/harness/sigtrace.py."
++ ]
++ },
++ "SignalMaskFix": {
++ "Type": "bool",
++ "Default": "true",
++ "AffectsCodeGen": "false",
++ "Desc": [
++ "Run guest signal handlers with the signal mask Linux gives them (the interrupted mask plus sa_mask and the signal)",
++ "and restore the interrupted mask at rt_sigreturn. With false FEX blocks only sa_mask and the signal during the handler and keeps",
++ "a stale view of the mask afterwards, so a signal handler that restores its saved mask can unblock the signal it is running for."
++ ]
++ },
++ "SMCHotPageFaults": {
++ "Type": "uint32",
++ "Default": "32",
++ "AffectsCodeGen": "true",
++ "Desc": [
++ "Number of self-modifying-code write faults a guest page may take before FEX stops write-protecting it.",
++ "Instead the JIT verifies the code of every instruction it translates from such a page (like SMCChecks=full, but only for that page).",
++ "Only used with SMCChecks=mtrack. 0 disables the demotion (pages stay write-protected and keep faulting)."
++ ]
++ },
+ "TSOEnabled": {
+ "Type": "bool",
+ "Default": "true",
+@@ -691,6 +747,16 @@
+ "Should only be used for applications that have issues with this set."
+ ]
+ },
++ "EnableCPUIDFaulting": {
++ "Type": "bool",
++ "Default": "false",
++ "AffectsCodeGen": "false",
++ "Desc": [
++ "Honour ARCH_SET_CPUID. When a guest thread calls arch_prctl(ARCH_SET_CPUID, 0), CPUID from that",
++ "thread raises a #GP (SIGSEGV, si_code SI_KERNEL) like Linux with a CPUID-faulting CPU, instead of",
++ "executing transparently. Off by default, so a guest that never asks for it is unaffected."
++ ]
++ },
+ "StartupSleep": {
+ "Type": "uint32",
+ "Default": "0",
+diff --git a/FEXCore/Source/Interface/Context/Context.h b/FEXCore/Source/Interface/Context/Context.h
+index cce4d5113..24118405d 100644
+--- a/FEXCore/Source/Interface/Context/Context.h
++++ b/FEXCore/Source/Interface/Context/Context.h
+@@ -224,8 +224,12 @@ public:
+
+ void OnCodeBufferAllocated(const std::shared_ptr&) override;
+ void ClearCodeCache(FEXCore::Core::InternalThreadState* Thread, bool NewCodeBuffer = true) override;
+- void InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) override;
+- void InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override;
++ void InvalidateExecutableRangeCaches() override {
++ ExecutableRangeEpoch.fetch_add(1, std::memory_order_acq_rel);
++ }
++ bool InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) override;
++ std::atomic ExecutableRangeEpoch {};
++ void InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length, bool CodeMayBeCached) override;
+ FEXCore::Utils::WritePriorityMutex::Mutex& GetCodeInvalidationMutex() override {
+ return CodeInvalidationMutex;
+ }
+diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp
+index 9f04358c5..02d9a280a 100644
+--- a/FEXCore/Source/Interface/Core/Core.cpp
++++ b/FEXCore/Source/Interface/Core/Core.cpp
+@@ -31,6 +31,7 @@ $end_info$
+ #include "Utils/Allocator.h"
+ #include "Utils/Allocator/HostAllocator.h"
+ #include "Utils/crc32.h"
++#include
+ #include
+ #include "Utils/variable_length_integer.h"
+
+@@ -201,8 +202,11 @@ uint32_t ContextImpl::ReconstructCompactedEFLAGS(FEXCore::Core::InternalThreadSt
+ case X86State::RFLAG_SF_RAW_LOC:
+ case X86State::RFLAG_OF_RAW_LOC:
+ case X86State::RFLAG_DF_RAW_LOC:
++ case X86State::RFLAG_NZCV_LOC:
++ case X86State::RFLAG_NZCV_1_LOC:
++ case X86State::RFLAG_NZCV_2_LOC:
++ case X86State::RFLAG_NZCV_3_LOC:
+ // Intentionally do nothing.
+- // These contain multiple bits which can corrupt other members when compacted.
+ break;
+ default: EFLAGS |= uint32_t {Frame->State.flags[i]} << i; break;
+ }
+@@ -645,11 +649,13 @@ ContextImpl::GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t Gue
+ Thread->OpDispatcher->_GuestOpcode(InstAddress - GuestRIP);
+ }
+
+- if (Config.SMCChecks == FEXCore::Config::CONFIG_SMC_FULL || Block.ForceFullSMCDetection) {
++ if (Config.SMCChecks == FEXCore::Config::CONFIG_SMC_FULL || Block.ForceFullSMCDetection || SyscallHandler->IsSMCHotPage(InstAddress)) {
+ auto ExistingCodePtr = reinterpret_cast(Block.Entry + BlockInstructionsLength);
+ auto InstAddressReg = Thread->OpDispatcher->_EntrypointOffset(GPRSize, InstAddress - GuestRIP);
+
+- auto Value = FEXCore::Utils::crc32(ExistingCodePtr, DecodedInfo->InstSize);
++ uint8_t InstBytes[16];
++ const bool Readable = FEXCore::Utils::FaultSafeRead::Copy(InstBytes, ExistingCodePtr, DecodedInfo->InstSize);
++ auto Value = Readable ? FEXCore::Utils::crc32(InstBytes, DecodedInfo->InstSize) : ~0U;
+ auto CRC = WantsDiskCachePatching ?
+ Thread->OpDispatcher->_PatchableGuestCRC(IR::OpSize::i64Bit, Value, (int64_t)ExistingCodePtr, DecodedInfo->InstSize) :
+ Thread->OpDispatcher->Constant(Value);
+@@ -730,6 +736,8 @@ ContextImpl::GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t Gue
+ Thread->OpDispatcher->InvalidOp(DecodedInfo);
+ } else if (Block.BlockStatus == Frontend::Decoder::DecodedBlockStatus::UNIMPLEMENTED_INST) {
+ Thread->OpDispatcher->UnimplementedOp(DecodedInfo);
++ } else if (Block.BlockStatus == Frontend::Decoder::DecodedBlockStatus::TOO_LONG_INST) {
++ Thread->OpDispatcher->PermissionRestrictedOp(DecodedInfo);
+ } else {
+ Thread->OpDispatcher->NoExecOrPartialOp(DecodedInfo);
+ }
+@@ -897,9 +905,10 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_
+ auto LoadedCode = Thread->CPUBackend->LoadCachedCode(Hit->HostCode);
+ if (LoadedCode.BlockBegin) {
+ for (auto& CodePage : Hit->GuestPages) {
+- if (Thread->LookupCache->AddBlockExecutableRange(Thread, Hit->EntryPointRIPs, CodePage, FEXCore::Utils::FEX_PAGE_SIZE)) {
++ if (!Thread->LookupCache->HasBlockExecutableRange(CodePage)) {
+ SyscallHandler->MarkGuestExecutableRange(Thread, CodePage, FEXCore::Utils::FEX_PAGE_SIZE);
+ }
++ Thread->LookupCache->AddBlockExecutableRange(Thread, Hit->EntryPointRIPs, CodePage, FEXCore::Utils::FEX_PAGE_SIZE);
+ }
+
+ LOGMAN_THROW_A_FMT(Hit->EntryPointRIPs.size() == Hit->EntryPointHostOffsets.size(), "Mismatched Disk Cache entrypoint pairs!");
+@@ -993,9 +1002,10 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_
+ CodePages.reserve(BlockInfo->CodePages.size());
+ CodePages.insert(CodePages.end(), BlockInfo->CodePages.begin(), BlockInfo->CodePages.end());
+ for (auto CodePage : BlockInfo->CodePages) {
+- if (Thread->LookupCache->AddBlockExecutableRange(Thread, BlockInfo->EntryPoints, CodePage, FEXCore::Utils::FEX_PAGE_SIZE)) {
++ if (!Thread->LookupCache->HasBlockExecutableRange(CodePage)) {
+ SyscallHandler->MarkGuestExecutableRange(Thread, CodePage, FEXCore::Utils::FEX_PAGE_SIZE);
+ }
++ Thread->LookupCache->AddBlockExecutableRange(Thread, BlockInfo->EntryPoints, CodePage, FEXCore::Utils::FEX_PAGE_SIZE);
+ }
+ }
+
+@@ -1006,10 +1016,13 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_
+ if (DebugData && DebugData->Relocations) {
+ Relocations = *DebugData->Relocations;
+ }
+- std::span GuestCode = {reinterpret_cast(StartAddr), Length};
+- const Frontend::Decoder::DecodedBlockInformation* BlockInfo =
+- NeedsAddGuestCodeRanges ? Thread->FrontendDecoder->GetDecodedBlockInfo() : nullptr;
+- DiskCache.Store(Thread, Region, GuestRIP, *DiskCacheGuestCodeKey, GuestCode, CompiledCode, Relocations, BlockInfo);
++ fextl::vector GuestCodeCopy(Length);
++ if (FEXCore::Utils::FaultSafeRead::Copy(GuestCodeCopy.data(), reinterpret_cast(StartAddr), Length)) {
++ std::span GuestCode = GuestCodeCopy;
++ const Frontend::Decoder::DecodedBlockInformation* BlockInfo =
++ NeedsAddGuestCodeRanges ? Thread->FrontendDecoder->GetDecodedBlockInfo() : nullptr;
++ DiskCache.Store(Thread, Region, GuestRIP, *DiskCacheGuestCodeKey, GuestCode, CompiledCode, Relocations, BlockInfo);
++ }
+ }
+
+ if (CodeMapWriter && Region && Region->FileStartVA != 0) {
+@@ -1055,31 +1068,38 @@ uintptr_t ContextImpl::CompileSingleStep(FEXCore::Core::CpuStateFrame* Frame, ui
+ return (uintptr_t)CodePtr;
+ }
+
+-void ContextImpl::InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) {
++bool ContextImpl::InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) {
+ FEXCORE_PROFILE_SCOPED("InvalidateCodeBuffersCodeRange");
+
+ LOGMAN_THROW_A_FMT(CodeInvalidationMutex.try_lock() == false, "CodeInvalidationMutex needs to be unique_locked here");
+ std::scoped_lock lk {CodeBufferListLock};
++ bool Found = false;
+ auto it = CodeBufferList.begin();
+ while (it != CodeBufferList.end()) {
+ if (auto Strong = it->lock()) {
+- Strong->LookupCache->InvalidateRange(Start, Length);
++ Found |= Strong->LookupCache->InvalidateRange(Start, Length);
+ it++;
+ } else {
+ it = CodeBufferList.erase(it);
+ }
+ }
++ return Found;
+ }
+
+-void ContextImpl::InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) {
++void ContextImpl::InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length, bool CodeMayBeCached) {
+ LOGMAN_THROW_A_FMT(CodeInvalidationMutex.try_lock() == false, "CodeInvalidationMutex needs to be unique_locked here");
+
+ // Ensures now-modified mappings aren't cached as being in their previous non-executable state.
+ // Accessing FrontendDecoder is safe as the thread's code invalidation mutex must be locked here.
+ Thread->FrontendDecoder->ResetExecutableRangeCache();
+
++ if (!CodeMayBeCached) {
++ return;
++ }
++
+ if (Thread->LookupCache->InvalidateCacheRange(Start, Length)) {
+ FEXCORE_PROFILE_SCOPED("InvalidateCallRet");
++ FEXCORE_PROFILE_INSTANT_INCREMENT(Thread, AccumulatedCallRetFlushCount, 1);
+
+ // This may cause access violations in the thread on Windows as zeroing is not atomic, this is handled by the frontend
+ Allocator::VirtualDontNeed(Thread->CallRetStackBase, FEXCore::Core::InternalThreadState::CALLRET_STACK_SIZE);
+diff --git a/FEXCore/Source/Interface/Core/DiskCache.cpp b/FEXCore/Source/Interface/Core/DiskCache.cpp
+index 3c78b22da..d903216c1 100644
+--- a/FEXCore/Source/Interface/Core/DiskCache.cpp
++++ b/FEXCore/Source/Interface/Core/DiskCache.cpp
+@@ -11,6 +11,7 @@
+ #include
+ #include
+ #include
++#include
+ #include
+ #include
+ #include
+@@ -22,6 +23,23 @@
+ #include
+ #include
+
++namespace {
++template
++bool HashGuestMemory(UpdateFn&& Update, uint64_t Address, uint64_t Size) {
++ uint8_t Buffer[256];
++ while (Size) {
++ const uint64_t Chunk = std::min(Size, sizeof(Buffer));
++ if (!FEXCore::Utils::FaultSafeRead::Copy(Buffer, reinterpret_cast(Address), Chunk)) {
++ return false;
++ }
++ Update(Buffer, Chunk);
++ Address += Chunk;
++ Size -= Chunk;
++ }
++ return true;
++}
++}
++
+ namespace FEXCore {
+
+ namespace DiskCache {
+@@ -576,12 +594,18 @@ namespace DiskCache {
+ }
+ uint64_t HashStart = SubBlock.Entry;
+ // skip over masked in-block data and data/etc gaps between blocks
++ auto Update = [&](const uint8_t* Bytes, uint64_t Size) {
++ XXH3_64bits_update(&HashState, Bytes, Size);
++ };
+ for (auto& DataMask : SubBlock.DataMasks) {
+- XXH3_64bits_update(&HashState, reinterpret_cast(HashStart), DataMask.FieldAddress - HashStart);
++ if (!HashGuestMemory(Update, HashStart, DataMask.FieldAddress - HashStart)) {
++ return std::nullopt;
++ }
+ HashStart = DataMask.FieldAddress + DataMask.ValueSize;
+ }
+- if (HashStart != SubBlock.Entry + SubBlock.Size) {
+- XXH3_64bits_update(&HashState, reinterpret_cast(HashStart), SubBlock.Size - (HashStart - SubBlock.Entry));
++ if (HashStart != SubBlock.Entry + SubBlock.Size &&
++ !HashGuestMemory(Update, HashStart, SubBlock.Size - (HashStart - SubBlock.Entry))) {
++ return std::nullopt;
+ }
+ }
+ GuestCodeKey = XXH3_64bits_digest(&HashState);
+@@ -704,8 +728,13 @@ namespace DiskCache {
+ if (FirstHash || LastFootprintHashed != CurrentFootprint) {
+ XXH3_state_t HashState;
+ XXH3_128bits_reset(&HashState);
++ auto Update = [&](const uint8_t* Bytes, uint64_t Size) {
++ XXH3_128bits_update(&HashState, Bytes, Size);
++ };
+ for (uint32_t i = 0; i < Entry.GuestExtents.size(); i += 2) {
+- XXH3_128bits_update(&HashState, reinterpret_cast(GuestRIP) + Entry.GuestExtents[i], Entry.GuestExtents[i + 1]);
++ if (!HashGuestMemory(Update, GuestRIP + Entry.GuestExtents[i], Entry.GuestExtents[i + 1])) {
++ return std::nullopt;
++ }
+ }
+ LiveGuestHash = XXH3_128bits_digest(&HashState);
+ LastFootprintHashed = CurrentFootprint;
+diff --git a/FEXCore/Source/Interface/Core/DiskCache.h b/FEXCore/Source/Interface/Core/DiskCache.h
+index 0bd3c21e4..0f1490cba 100644
+--- a/FEXCore/Source/Interface/Core/DiskCache.h
++++ b/FEXCore/Source/Interface/Core/DiskCache.h
+@@ -249,7 +249,7 @@ namespace DiskCache {
+ // The current version of the diskcache.
+ // This must be changed any time codegen changes occur!
+ // Be aware of the impact of changing this frequently!
+- static constexpr uint16_t FormatVersion = 52;
++ static constexpr uint16_t FormatVersion = 0x8000 | (1 << 8) | 52;
+
+ static constexpr uint32_t LOOKUP_KEY_MAX_BUCKET_DEPTH = 500;
+
+diff --git a/FEXCore/Source/Interface/Core/Frontend.cpp b/FEXCore/Source/Interface/Core/Frontend.cpp
+index 94e4ac522..18cda8889 100644
+--- a/FEXCore/Source/Interface/Core/Frontend.cpp
++++ b/FEXCore/Source/Interface/Core/Frontend.cpp
+@@ -19,6 +19,7 @@ $end_info$
+ #include
+ #include
+ #include
++#include
+ #include
+ #include
+ #include
+@@ -108,6 +109,11 @@ int32_t Decoder::CheckRangeExecutable(uint64_t Address, uint64_t Size) {
+ }
+ }
+
++ if (const auto Epoch = CTX->ExecutableRangeEpoch.load(std::memory_order_acquire); Epoch != ExecutableRangeEpochSeen) {
++ ExecutableRangeEpochSeen = Epoch;
++ ResetExecutableRangeCache();
++ }
++
+ uint64_t RemainingSize = Size;
+ while (Address < ExecutableRangeBase || Address + RemainingSize > ExecutableRangeEnd) {
+ auto RangeInfo = CTX->SyscallHandler->QueryGuestExecutableRange(Thread, Address);
+@@ -132,8 +138,13 @@ int32_t Decoder::CheckRangeExecutable(uint64_t Address, uint64_t Size) {
+ }
+
+ uint8_t Decoder::ReadByte() {
++ if (InstructionSize >= MAX_INST_SIZE) {
++ HitInstructionLengthLimit = true;
++ return 0;
++ }
++
+ std::optional Byte = PeekByte(0);
+- if (!Byte || InstructionSize == MAX_INST_SIZE) {
++ if (!Byte) {
+ HitNonExecutableRange = true;
+ // Pretend we read 0, the main decode loop will see HitNonExecutableRange and rollback the instruction.
+ return 0;
+@@ -146,8 +157,10 @@ uint8_t Decoder::ReadByte() {
+
+ std::optional Decoder::PeekByte(uint8_t Offset) {
+ uint64_t ByteAddress = reinterpret_cast(InstStream.InstStream + InstructionSize + Offset);
+- if (CheckRangeExecutable(ByteAddress, 1) == 1) {
+- return InstStream.AdjustedInstStream[InstructionSize + Offset];
++ uint8_t Byte;
++ if (CheckRangeExecutable(ByteAddress, 1) == 1 &&
++ FEXCore::Utils::FaultSafeRead::Copy(&Byte, &InstStream.AdjustedInstStream[InstructionSize + Offset], 1)) {
++ return Byte;
+ } else {
+ return std::nullopt;
+ }
+@@ -160,13 +173,24 @@ std::pair Decoder::ReadData(uint8_t Size) {
+ uint64_t Address = reinterpret_cast(InstStream.InstStream + InstructionSize);
+ LastFieldReadOffset = (uint8_t)InstructionSize;
+ LastFieldReadSize = Size;
+- auto ReadableSize = CheckRangeExecutable(Address, Size);
+- if (ReadableSize == Size) {
+- std::memcpy(&Res, &InstStream.AdjustedInstStream[InstructionSize], Size);
+- } else {
+- HitNonExecutableRange = true;
+- // See PeekByte, this specific case may cause some executable memory to read as 0 but it doesn't matter as the entire instruction will be rolled back anyway.
++ int32_t ReadableSize {};
++ if (InstructionSize + Size > MAX_INST_SIZE) [[unlikely]] {
++ const int32_t FetchableSize = InstructionSize < MAX_INST_SIZE ? MAX_INST_SIZE - InstructionSize : 0;
++ ReadableSize = FetchableSize ? CheckRangeExecutable(Address, FetchableSize) : 0;
++ if (ReadableSize != FetchableSize) {
++ HitNonExecutableRange = true;
++ }
++ HitInstructionLengthLimit = true;
+ Res = 0;
++ } else {
++ ReadableSize = CheckRangeExecutable(Address, Size);
++ if (ReadableSize == Size && !FEXCore::Utils::FaultSafeRead::Copy(&Res, &InstStream.AdjustedInstStream[InstructionSize], Size)) {
++ ReadableSize = 0;
++ }
++ if (ReadableSize != Size) {
++ HitNonExecutableRange = true;
++ Res = 0;
++ }
+ }
+
+ // Skip the number of decoded bytes regardless to get instruction size.
+@@ -881,7 +905,7 @@ Decoder::DecodedBlockStatus Decoder::DecodeInstructionImpl(uint64_t PC) {
+
+ for (;;) {
+ if (InstructionSize >= MAX_INST_SIZE) {
+- return DecodedBlockStatus::INVALID_INST;
++ return DecodedBlockStatus::TOO_LONG_INST;
+ }
+ uint8_t Op = ReadByte();
+ switch (Op) {
+@@ -1108,11 +1132,12 @@ void Decoder::DecodeREXIfValid(int8_t ExpectedOffset) {
+ Decoder::DecodedBlockStatus Decoder::DecodeInstruction(uint64_t PC) {
+ // Will be set if DecodeInstructionImpl tries to read non-executable memory
+ HitNonExecutableRange = false;
++ HitInstructionLengthLimit = false;
+ HitBadRelocation = false;
+ HitBreakpoint = ~0U;
+ auto ErrorDuringDecoding = DecodeInstructionImpl(PC);
+
+- if (ErrorDuringDecoding != DecodedBlockStatus::SUCCESS || HitNonExecutableRange || HitBadRelocation) [[unlikely]] {
++ if (ErrorDuringDecoding != DecodedBlockStatus::SUCCESS || HitNonExecutableRange || HitInstructionLengthLimit || HitBadRelocation) [[unlikely]] {
+ // Put an invalid instruction in the stream so the core can raise SIGILL if hit
+ // Error while decoding instruction. We don't know the table or instruction size
+ DecodeInst->TableInfo = nullptr;
+@@ -1134,6 +1159,10 @@ Decoder::DecodedBlockStatus Decoder::DecodeInstruction(uint64_t PC) {
+ return DecodedBlockStatus::BAD_RELOCATION;
+ }
+
++ if (HitInstructionLengthLimit) {
++ return DecodedBlockStatus::TOO_LONG_INST;
++ }
++
+ return ErrorDuringDecoding;
+ } else if (!DecodeInst->TableInfo || (DecodeInst->TableInfo->Type == TYPE_INST && !DecodeInst->TableInfo->OpcodeDispatcher.OpDispatch)) {
+ // If there wasn't an error during decoding but we have no dispatcher for the instruction then claim invalid instruction.
+@@ -1693,6 +1722,7 @@ void Decoder::DecodeLoop(const uint8_t* _InstStream, uint64_t GuestSizePause) {
+ BlockIt->BlockStatus == DecodedBlockStatus::BREAKPOINT_3 ? "Breakpoint" :
+ BlockIt->BlockStatus == DecodedBlockStatus::INVALID_INST ? "Invalid" :
+ BlockIt->BlockStatus == DecodedBlockStatus::NOEXEC_INST ? "NoExec" :
++ BlockIt->BlockStatus == DecodedBlockStatus::TOO_LONG_INST ? "TooLong" :
+ BlockIt->BlockStatus == DecodedBlockStatus::BAD_RELOCATION ? "BadRelocation" :
+ BlockIt->BlockStatus == DecodedBlockStatus::UNIMPLEMENTED_INST ? "Unimplemented" :
+ "PartialDecode",
+diff --git a/FEXCore/Source/Interface/Core/Frontend.h b/FEXCore/Source/Interface/Core/Frontend.h
+index ade14bc44..6d279b22c 100644
+--- a/FEXCore/Source/Interface/Core/Frontend.h
++++ b/FEXCore/Source/Interface/Core/Frontend.h
+@@ -28,6 +28,7 @@ public:
+ INVALID_INST,
+ NOEXEC_INST,
+ PARTIAL_DECODE_INST,
++ TOO_LONG_INST,
+ BAD_RELOCATION,
+ UNIMPLEMENTED_INST,
+ BREAKPOINT_0,
+@@ -93,6 +94,8 @@ public:
+ ExecutableRangeBase = ExecutableRangeEnd = 0;
+ }
+
++ uint64_t ExecutableRangeEpochSeen {};
++
+ private:
+ // To pass any information from instruction prefixes
+ // down into the actual instruction handling machinery.
+@@ -159,6 +162,7 @@ private:
+ uint64_t ExecutableRangeEnd {};
+ bool ExecutableRangeWritable {};
+ bool HitNonExecutableRange {};
++ bool HitInstructionLengthLimit {};
+ bool HitBadRelocation {};
+ uint32_t HitBreakpoint {~0U};
+
+diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
+index c5e656d2c..7b9c15b61 100644
+--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
++++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
+@@ -195,6 +195,21 @@ DEF_OP(ExitFunction) {
+ ARMEmitter::ForwardLabel SkipFullLookup;
+ auto RipReg = GetReg(Op->NewRIP);
+
++ if (Op->Hint == IR::BranchHint::CheckTF || CompilingWithTF) {
++ ARMEmitter::ForwardLabel TFUnset;
++ ldrb(TMP1, STATE_PTR(CpuStateFrame, State.flags[X86State::RFLAG_TF_RAW_LOC]));
++ (void)cbz(ARMEmitter::Size::i32Bit, TMP1, &TFUnset);
++ if (Op->Hint == IR::BranchHint::Return) {
++ add(ARMEmitter::Size::i64Bit, REG_CALLRET_SP, REG_CALLRET_SP, 0x10);
++ } else if (Op->Hint == IR::BranchHint::Call) {
++ stp(ARMEmitter::XReg::zr, ARMEmitter::XReg::zr, REG_CALLRET_SP, -0x10);
++ }
++ str(RipReg.X(), STATE, offsetof(FEXCore::Core::CpuStateFrame, State.rip));
++ ldr(TMP2, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.DispatcherLoopTop));
++ br(TMP2);
++ (void)Bind(&TFUnset);
++ }
++
+ if (Op->Hint == IR::BranchHint::Return) {
+ // First try to pop from the call-ret stack, otherwise follow the normal path (but ending in a ret)
+ ldp(TMP1, TMP2, REG_CALLRET_SP, 0x10);
+diff --git a/FEXCore/Source/Interface/Core/JIT/JIT.cpp b/FEXCore/Source/Interface/Core/JIT/JIT.cpp
+index fa9c8c880..777b4b51d 100644
+--- a/FEXCore/Source/Interface/Core/JIT/JIT.cpp
++++ b/FEXCore/Source/Interface/Core/JIT/JIT.cpp
+@@ -862,6 +862,7 @@ CPUBackend::CompiledCode Arm64JITCore::EmitJITCode(uint64_t Entry, uint64_t Size
+ this->DebugData = DebugData;
+ this->IR = IR;
+ RequiresFarARM64Jumps = false;
++ CompilingWithTF = CheckTF;
+ SSANodeMultiplier = 24;
+
+ // Prepare restart via long jump in case branch encoding fails.
+diff --git a/FEXCore/Source/Interface/Core/JIT/JITClass.h b/FEXCore/Source/Interface/Core/JIT/JITClass.h
+index 55286855f..684ac9d9d 100644
+--- a/FEXCore/Source/Interface/Core/JIT/JITClass.h
++++ b/FEXCore/Source/Interface/Core/JIT/JITClass.h
+@@ -86,6 +86,7 @@ private:
+ // In the rare case when those assumptions are broken, FEX needs to safely restart the JIT.
+ RestartOptions RestartControl {};
+ bool RequiresFarARM64Jumps {};
++ bool CompilingWithTF {};
+ // Default to 6 instructions per SSA node.
+ uint32_t SSANodeMultiplier {24};
+
+diff --git a/FEXCore/Source/Interface/Core/JIT/MiscOps.cpp b/FEXCore/Source/Interface/Core/JIT/MiscOps.cpp
+index d15ef9aee..bc1fb9c19 100644
+--- a/FEXCore/Source/Interface/Core/JIT/MiscOps.cpp
++++ b/FEXCore/Source/Interface/Core/JIT/MiscOps.cpp
+@@ -86,6 +86,34 @@ DEF_OP(Break) {
+ br(TMP1);
+ }
+
++DEF_OP(BreakErrorCode) {
++ auto Op = IROp->C();
++
++ uxth(ARMEmitter::Size::i64Bit, TMP2, GetReg(Op->ErrorCode));
++ ResetStack();
++
++ Core::CpuStateFrame::SynchronousFaultDataStruct State = {
++ .FaultToTopAndGeneratedException = 1,
++ .Signal = Op->Reason.Signal,
++ .TrapNo = Op->Reason.TrapNumber,
++ .si_code = Op->Reason.si_code,
++ .err_code = 0,
++ .FaultAddress = 0,
++ };
++ static_assert(offsetof(Core::CpuStateFrame::SynchronousFaultDataStruct, err_code) == 4, "err_code is bits 32-47");
++
++ uint64_t Constant {};
++ memcpy(&Constant, &State, sizeof(uint64_t));
++
++ LoadConstant(ARMEmitter::Size::i64Bit, TMP1, static_cast(Constant));
++ bfi(ARMEmitter::Size::i64Bit, TMP1, TMP2, 32, 16);
++ str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, SynchronousFaultData));
++ str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, SynchronousFaultData) + 8);
++
++ ldr(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.GuestSignal_SynchronousFault));
++ br(TMP1);
++}
++
+ DEF_OP(GetRoundingMode) {
+ auto Dst = GetReg(Node);
+ mrs(Dst, ARMEmitter::SystemRegister::FPCR);
+diff --git a/FEXCore/Source/Interface/Core/LookupCache.h b/FEXCore/Source/Interface/Core/LookupCache.h
+index 391d48560..228d03969 100644
+--- a/FEXCore/Source/Interface/Core/LookupCache.h
++++ b/FEXCore/Source/Interface/Core/LookupCache.h
+@@ -125,7 +125,7 @@ struct GuestToHostMap {
+ return BlockList.erase(Address) != 0;
+ }
+
+- void InvalidateRange(uint64_t Start, uint64_t Length) {
++ bool InvalidateRange(uint64_t Start, uint64_t Length) {
+ auto lk = AcquireWriteLock();
+
+ auto lower = CodePages.lower_bound(Start >> 12);
+@@ -136,7 +136,9 @@ struct GuestToHostMap {
+ Erase(Entry, lk);
+ }
+ }
++ const bool Found = lower != upper;
+ CodePages.erase(lower, upper);
++ return Found;
+ }
+
+ void AddBlockLink(uint64_t GuestDestination, FEXCore::Context::ExitFunctionLinkData* HostLink,
+@@ -144,6 +146,11 @@ struct GuestToHostMap {
+ BlockLinks->insert({{GuestDestination, HostLink}, delinker});
+ }
+
++ bool HasBlockExecutableRange(uint64_t Page, const LookupCacheReadLockToken&) const {
++ auto it = CodePages.find(Page >> 12);
++ return it != CodePages.end() && !it->second.empty();
++ }
++
+ bool AddBlockExecutableRange(const std::ranges::input_range auto& Addresses, uint64_t Start, uint64_t Length, const LookupCacheWriteLockToken&) {
+ bool rv = false;
+
+@@ -282,6 +289,11 @@ public:
+
+ GuestToHostMap* Shared = nullptr;
+
++ bool HasBlockExecutableRange(uint64_t Page) {
++ auto lk = Shared->AcquireReadLock();
++ return Shared->HasBlockExecutableRange(Page, lk);
++ }
++
+ // Appends a list of Block {Address} to CodePages [Start, Start + Length)
+ // Returns true if new pages are marked as containing code
+ bool AddBlockExecutableRange(FEXCore::Core::InternalThreadState* Thread, auto& Addresses, uint64_t Start, uint64_t Length) {
+diff --git a/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp b/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp
+index 356fc3bb1..27491cea4 100644
+--- a/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp
++++ b/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp
+@@ -138,6 +138,31 @@ void OpDispatchBuilder::IRETOp(OpcodeArgs) {
+
+ const auto GPRSize = GetGPROpSize();
+
++ {
++ auto FaultBlock = CreateNewCodeBlockAfter(GetCurrentBlock());
++ auto ContinueBlock = CreateNewCodeBlockAfter(FaultBlock);
++
++ auto CondJump_ = CondJump(GetRFLAG(FEXCore::X86State::RFLAG_NT_LOC), CondClass::EQ);
++ SetTrueJumpTarget(CondJump_, ContinueBlock);
++ SetFalseJumpTarget(CondJump_, FaultBlock);
++
++ SetCurrentCodeBlock(FaultBlock);
++ StartNewBlock();
++
++ _StoreContextGPR(GPRSize, GetRelocatedPC(Op, -Op->InstSize), offsetof(FEXCore::Core::CPUState, rip));
++
++ IR::BreakDefinition Reason {};
++ Reason.ErrorRegister = 0;
++ Reason.Signal = Core::FAULT_SIGSEGV;
++ Reason.TrapNumber = X86State::X86_TRAPNO_GP;
++ Reason.si_code = 0x80;
++ BlockSetRIP = true;
++ Break(Reason);
++
++ SetCurrentCodeBlock(ContinueBlock);
++ StartNewBlock();
++ }
++
+ Ref SP = _RMWHandle(LoadGPRRegister(X86State::REG_RSP));
+
+ // RIP (64/32/16 bits)
+@@ -164,7 +189,7 @@ void OpDispatchBuilder::IRETOp(OpcodeArgs) {
+ StoreGPRRegister(X86State::REG_RSP, SP);
+ }
+
+- ExitFunction(NewRIP);
++ ExitFunction(NewRIP, BranchHint::CheckTF);
+ BlockSetRIP = true;
+ }
+
+@@ -1230,6 +1255,36 @@ void OpDispatchBuilder::FLAGControlOp(OpcodeArgs) {
+ }
+
+
++void OpDispatchBuilder::MOVSegFSGS64(OpcodeArgs, Ref Selector, uint32_t IndexOffset, uint32_t BaseOffset) {
++ Ref Index = _Bfe(OpSize::i32Bit, 13, 3, Selector);
++ Ref TI = _Bfe(OpSize::i32Bit, 1, 2, Selector);
++ Ref Allowed = _And(OpSize::i32Bit, _Lshr(OpSize::i32Bit, Constant(0x8071), Index), Constant(1));
++ Allowed = _Select(OpSize::i32Bit, OpSize::i32Bit, CondClass::ULT, Index, Constant(16), Allowed, Constant(0));
++ Allowed = _Select(OpSize::i32Bit, OpSize::i32Bit, CondClass::EQ, TI, Constant(0), Allowed, Constant(0));
++
++ auto FaultBlock = CreateNewCodeBlockAfter(GetCurrentBlock());
++ auto ContinueBlock = CreateNewCodeBlockAfter(FaultBlock);
++ auto CondJump_ = CondJump(Allowed, CondClass::NEQ);
++ SetTrueJumpTarget(CondJump_, ContinueBlock);
++ SetFalseJumpTarget(CondJump_, FaultBlock);
++
++ SetCurrentCodeBlock(FaultBlock);
++ StartNewBlock();
++ Ref FaultSelector = LoadSourceGPR_WithOpSize(Op, Op->Src[0], OpSize::i16Bit, Op->Flags);
++ _StoreContextGPR(GetGPROpSize(), GetRelocatedPC(Op, -Op->InstSize), offsetof(FEXCore::Core::CPUState, rip));
++ IR::BreakDefinition Reason {};
++ Reason.Signal = Core::FAULT_SIGSEGV;
++ Reason.TrapNumber = X86State::X86_TRAPNO_GP;
++ Reason.si_code = 0x80;
++ BlockSetRIP = true;
++ BreakErrorCode(_And(OpSize::i32Bit, FaultSelector, Constant(0xfffc)), Reason);
++
++ SetCurrentCodeBlock(ContinueBlock);
++ StartNewBlock();
++ _StoreContextGPR(OpSize::i16Bit, LoadSourceGPR_WithOpSize(Op, Op->Src[0], OpSize::i16Bit, Op->Flags), IndexOffset);
++ _StoreContextGPR(OpSize::i64Bit, Constant(0), BaseOffset);
++}
++
+ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) {
+ // In x86-64 mode the accesses to the segment registers end up being constant zero moves
+ // Aside from FS/GS
+@@ -1243,7 +1298,6 @@ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) {
+ // selected for the registers
+ // This statement is actually untrue, the instructions will /actually/ load 16bits in to the selector portion of the register!
+ // Tested on a Zen+ CPU, the selector is the portion that is modified!
+- // We don't currently support FS/GS selector modifying, so this needs to be asserted out
+ // The loads here also load the selector, NOT the base
+
+ if (ToSeg) {
+@@ -1283,8 +1337,7 @@ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) {
+ _StoreContextGPR(OpSize::i16Bit, Src, offsetof(FEXCore::Core::CPUState, gs_idx));
+ UpdatePrefixFromSegment(Src, FEXCore::X86Tables::DecodeFlags::FLAG_GS_PREFIX);
+ } else {
+- LogMan::Msg::EFmt("We don't support modifying GS selector in 64bit mode!");
+- DecodeFailure = true;
++ MOVSegFSGS64(Op, Src, offsetof(FEXCore::Core::CPUState, gs_idx), offsetof(FEXCore::Core::CPUState, gs_cached));
+ }
+ break;
+ case FEXCore::X86State::REG_RSP: // FS
+@@ -1293,8 +1346,7 @@ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) {
+ _StoreContextGPR(OpSize::i16Bit, Src, offsetof(FEXCore::Core::CPUState, fs_idx));
+ UpdatePrefixFromSegment(Src, FEXCore::X86Tables::DecodeFlags::FLAG_FS_PREFIX);
+ } else {
+- LogMan::Msg::EFmt("We don't support modifying FS selector in 64bit mode!");
+- DecodeFailure = true;
++ MOVSegFSGS64(Op, Src, offsetof(FEXCore::Core::CPUState, fs_idx), offsetof(FEXCore::Core::CPUState, fs_cached));
+ }
+ break;
+ default: UnimplementedOp(Op); return;
+@@ -1321,19 +1373,11 @@ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) {
+ break;
+ case FEXCore::X86State::REG_RBP: // GS
+ case FEXCore::X86State::REG_R13: // GS
+- if (Is64BitMode) {
+- Segment = Constant(0);
+- } else {
+- Segment = _LoadContextGPR(OpSize::i16Bit, offsetof(FEXCore::Core::CPUState, gs_idx));
+- }
++ Segment = _LoadContextGPR(OpSize::i16Bit, offsetof(FEXCore::Core::CPUState, gs_idx));
+ break;
+ case FEXCore::X86State::REG_RSP: // FS
+ case FEXCore::X86State::REG_R12: // FS
+- if (Is64BitMode) {
+- Segment = Constant(0);
+- } else {
+- Segment = _LoadContextGPR(OpSize::i16Bit, offsetof(FEXCore::Core::CPUState, fs_idx));
+- }
++ Segment = _LoadContextGPR(OpSize::i16Bit, offsetof(FEXCore::Core::CPUState, fs_idx));
+ break;
+ default: UnimplementedOp(Op); return;
+ }
+diff --git a/FEXCore/Source/Interface/Core/OpcodeDispatcher.h b/FEXCore/Source/Interface/Core/OpcodeDispatcher.h
+index d3e523d9b..601db6009 100644
+--- a/FEXCore/Source/Interface/Core/OpcodeDispatcher.h
++++ b/FEXCore/Source/Interface/Core/OpcodeDispatcher.h
+@@ -216,6 +216,10 @@ public:
+ }
+ return _Break(Reason, RelocatedPC);
+ }
++ IRPair BreakErrorCode(Ref ErrorCode, BreakDefinition Reason) {
++ FlushRegisterCache();
++ return _BreakErrorCode(ErrorCode, Reason);
++ }
+ IRPair Thunk(Ref ArgPtr, SHA256Sum ThunkNameHash) {
+ FlushRegisterCache();
+ return _Thunk(ArgPtr, ThunkNameHash);
+@@ -417,6 +421,7 @@ public:
+ void XCHGRAXOp(OpcodeArgs);
+ void SAHFOp(OpcodeArgs);
+ void LAHFOp(OpcodeArgs);
++ void MOVSegFSGS64(OpcodeArgs, Ref Selector, uint32_t IndexOffset, uint32_t BaseOffset);
+ void MOVSegOp(OpcodeArgs, bool ToSeg);
+ void FLAGControlOp(OpcodeArgs);
+ void MOVOffsetOp(OpcodeArgs);
+@@ -1974,8 +1979,8 @@ private:
+ // An exception should still be raised after an instruction that unsets TF, leave the unblocked bit set but unset
+ // the TF bit to cause such behaviour. The handling code at the start of the next block will then unset the
+ // unblocked bit before raising the exception.
+- auto NewPackedTF =
+- _Select(OpSize::i64Bit, OpSize::i64Bit, CondClass::EQ, Value, Constant(0), _And(OpSize::i32Bit, PackedTF, Constant(~1)), Constant(1));
++ auto NewPackedTF = _Select(OpSize::i64Bit, OpSize::i64Bit, CondClass::EQ, Value, Constant(0), _And(OpSize::i32Bit, PackedTF, Constant(~1)),
++ _Select(OpSize::i64Bit, OpSize::i64Bit, CondClass::EQ, PackedTF, Constant(3), Constant(3), Constant(1)));
+ _StoreContextGPR(OpSize::i8Bit, NewPackedTF, ARRAY_OFFSETOF(FEXCore::Core::CPUState, flags, BitOffset));
+ } else {
+ _StoreContextGPR(OpSize::i8Bit, Value, ARRAY_OFFSETOF(FEXCore::Core::CPUState, flags, BitOffset));
+diff --git a/FEXCore/Source/Interface/IR/IR.json b/FEXCore/Source/Interface/IR/IR.json
+index 4b79cf35c..0c01f580d 100644
+--- a/FEXCore/Source/Interface/IR/IR.json
++++ b/FEXCore/Source/Interface/IR/IR.json
+@@ -324,6 +324,12 @@
+ "Break BreakDefinition:$Reason, GPR:$FaultAddress": {
+ "HasSideEffects": true
+ },
++ "BreakErrorCode GPR:$ErrorCode, BreakDefinition:$Reason": {
++ "HasSideEffects": true,
++ "Desc": ["Break whose fault error code is the low 16 bits of $ErrorCode, known only at run time",
++ "(a #GP with a selector as its error code); Reason.ErrorRegister is not used"
++ ]
++ },
+ "CallbackReturn": {
+ "HasSideEffects": true
+ },
+diff --git a/FEXCore/Source/Interface/IR/IREmitter.cpp b/FEXCore/Source/Interface/IR/IREmitter.cpp
+index 6c8ed5d11..d8fd1431e 100644
+--- a/FEXCore/Source/Interface/IR/IREmitter.cpp
++++ b/FEXCore/Source/Interface/IR/IREmitter.cpp
+@@ -23,7 +23,8 @@ static bool IsFragmentExit(FEXCore::IR::IROps Op) {
+ case OP_SYSCALL:
+ case OP_CPUID:
+ case OP_EXITFUNCTION:
+- case OP_BREAK: return true;
++ case OP_BREAK:
++ case OP_BREAKERRORCODE: return true;
+ default: return false;
+ }
+ }
+diff --git a/FEXCore/Source/Utils/FaultSafeRead.cpp b/FEXCore/Source/Utils/FaultSafeRead.cpp
+new file mode 100644
+index 000000000..aaa7a80cf
+--- /dev/null
++++ b/FEXCore/Source/Utils/FaultSafeRead.cpp
+@@ -0,0 +1,46 @@
++// SPDX-License-Identifier: MIT
++#include
++
++#include
++
++namespace FEXCore::Utils::FaultSafeRead {
++#if defined(ARCHITECTURE_arm64) && !defined(_WIN32)
++__attribute__((naked)) static size_t CopyImpl(void* Dest, const void* Src, size_t Size) {
++ __asm volatile(R"(
++ // Early exit if a copy of size zero.
++ cbz x2, 2f;
++
++ 1:
++ .globl FEXCore_FaultSafeRead_FaultInst
++ FEXCore_FaultSafeRead_FaultInst:
++ ldrb w3, [x1], 1; // <- This line can fault.
++ strb w3, [x0], 1;
++ sub x2, x2, 1;
++ cbnz x2, 1b;
++2:
++ mov x0, 0;
++ ret;
++ )" ::
++ : "memory");
++}
++
++extern "C" uint64_t FEXCore_FaultSafeRead_FaultInst;
++
++bool Copy(void* Dest, const void* Src, size_t Size) {
++ return CopyImpl(Dest, Src, Size) == 0;
++}
++
++bool IsFaultLocation(uint64_t PC) {
++ return reinterpret_cast(PC) == &FEXCore_FaultSafeRead_FaultInst;
++}
++#else
++bool Copy(void* Dest, const void* Src, size_t Size) {
++ memcpy(Dest, Src, Size);
++ return true;
++}
++
++bool IsFaultLocation(uint64_t PC) {
++ return false;
++}
++#endif
++}
+diff --git a/FEXCore/include/FEXCore/Core/Context.h b/FEXCore/include/FEXCore/Core/Context.h
+index 7e1d30770..854c5ce1c 100644
+--- a/FEXCore/include/FEXCore/Core/Context.h
++++ b/FEXCore/include/FEXCore/Core/Context.h
+@@ -141,9 +141,11 @@ public:
+ virtual void FlushAndCloseCodeMap() = 0;
+
+ FEX_DEFAULT_VISIBILITY virtual void ClearCodeCache(FEXCore::Core::InternalThreadState* Thread, bool NewCodeBuffer = true) = 0;
+- FEX_DEFAULT_VISIBILITY virtual void InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) = 0;
++ FEX_DEFAULT_VISIBILITY virtual void InvalidateExecutableRangeCaches() = 0;
++
++ FEX_DEFAULT_VISIBILITY virtual bool InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) = 0;
+ FEX_DEFAULT_VISIBILITY virtual void
+- InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) = 0;
++ InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length, bool CodeMayBeCached = true) = 0;
+ FEX_DEFAULT_VISIBILITY virtual FEXCore::Utils::WritePriorityMutex::Mutex& GetCodeInvalidationMutex() = 0;
+
+ FEX_DEFAULT_VISIBILITY virtual void
+diff --git a/FEXCore/include/FEXCore/Core/CoreState.h b/FEXCore/include/FEXCore/Core/CoreState.h
+index 7c02605f5..98ba8e150 100644
+--- a/FEXCore/include/FEXCore/Core/CoreState.h
++++ b/FEXCore/include/FEXCore/Core/CoreState.h
+@@ -282,6 +282,11 @@ struct alignas(64) CPUState {
+
+ // TODO: This should be moved to the frontend.
+ constexpr static uint32_t DEFAULT_USER_CS = 6;
++ constexpr static uint32_t DEFAULT_USER_DS = 5;
++
++ constexpr static uint32_t DEFAULT_USER_CS_SEL = (DEFAULT_USER_CS << 3) | 3;
++ constexpr static uint32_t DEFAULT_USER_DS_SEL = (DEFAULT_USER_DS << 3) | 3;
++ constexpr static uint32_t DEFAULT_USER32_CS_SEL = 0x23;
+
+ // Follows encoding of the TI bit in segment selector encoding.
+ constexpr static uint32_t SEGMENT_ARRAY_INDEX_GDT = 0;
+diff --git a/FEXCore/include/FEXCore/HLE/SyscallHandler.h b/FEXCore/include/FEXCore/HLE/SyscallHandler.h
+index 0ba0218e3..89e36d52e 100644
+--- a/FEXCore/include/FEXCore/HLE/SyscallHandler.h
++++ b/FEXCore/include/FEXCore/HLE/SyscallHandler.h
+@@ -33,6 +33,10 @@ public:
+ virtual void HandleSyscall(FEXCore::Core::CpuStateFrame* Frame) = 0;
+
+ virtual void MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) {}
++
++ virtual bool IsSMCHotPage(uint64_t Address) {
++ return false;
++ }
+ virtual void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) {}
+ virtual void MarkOvercommitRange(uint64_t Start, uint64_t Length) {}
+ virtual void UnmarkOvercommitRange(uint64_t Start, uint64_t Length) {}
+diff --git a/FEXCore/include/FEXCore/Utils/FaultSafeRead.h b/FEXCore/include/FEXCore/Utils/FaultSafeRead.h
+new file mode 100644
+index 000000000..1fc7213b5
+--- /dev/null
++++ b/FEXCore/include/FEXCore/Utils/FaultSafeRead.h
+@@ -0,0 +1,12 @@
++// SPDX-License-Identifier: MIT
++#pragma once
++#include
++
++#include
++#include
++
++namespace FEXCore::Utils::FaultSafeRead {
++FEX_DEFAULT_VISIBILITY bool Copy(void* Dest, const void* Src, size_t Size);
++
++FEX_DEFAULT_VISIBILITY bool IsFaultLocation(uint64_t PC);
++}
+diff --git a/FEXCore/include/FEXCore/Utils/SHMStats.h b/FEXCore/include/FEXCore/Utils/SHMStats.h
+index c5844fe10..d646c6a2f 100644
+--- a/FEXCore/include/FEXCore/Utils/SHMStats.h
++++ b/FEXCore/include/FEXCore/Utils/SHMStats.h
+@@ -74,7 +74,10 @@ struct ThreadStats {
+ uint64_t AccumulatedDiskCacheHitCount;
+ uint64_t AccumulatedDiskCacheMissCount;
+ uint64_t AccumulatedDiskCacheLookupTime;
+- uint64_t Padding;
++
++ uint64_t AccumulatedInvalidationCount;
++ uint64_t AccumulatedInvalidationTime;
++ uint64_t AccumulatedCallRetFlushCount;
+ };
+
+ // Ensure 16-byte alignment to take advantage of ARM single-copy atomicity.
+diff --git a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
+index e7e88f8f2..26b8186c8 100644
+--- a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
++++ b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
+@@ -602,8 +602,7 @@ int main(int argc, char** argv, char** const envp) {
+ // Create a thread without a RIP or stack pointer setup initially.
+ auto ParentThread = SyscallHandler->TM.CreateThread();
+ SyscallHandler->TM.TrackThread(ParentThread);
+- SignalDelegation->RegisterTLSState(ParentThread);
+- ThunkHandler->RegisterTLSState(ParentThread);
++ SyscallHandler->RegisterTLSState(ParentThread);
+
+ SyscallHandler->DeserializeSeccompFD(ParentThread, FEXSeccompFD);
+
+diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
+index 2e724929f..62135b824 100644
+--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
++++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
+@@ -20,6 +20,7 @@ namespace FEX::ArchHelpers::Context {
+
+ enum ContextFlags : uint32_t {
+ CONTEXT_FLAG_INJIT = (1U << 0),
++ CONTEXT_FLAG_SYSCALLINFO_CLEARED = (1U << 1),
+ };
+
+ #if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED
+@@ -40,7 +41,11 @@ struct X86ContextBackup {
+ FEXCore::x86_64::_libc_fpstate FPRState;
+ uint64_t sa_mask;
+ uint16_t InSyscallInfo;
++ uint16_t ClearedSyscallInfo;
+ bool FaultToTopAndGeneratedException;
++ uint64_t GuestSignalMask;
++ uint64_t SeccompTrapRIP;
++ uint64_t SavedJITStackSP;
+
+ // Guest state
+ int Signal;
+@@ -72,7 +77,11 @@ struct ArmContextBackup {
+ __uint128_t FPRs[32];
+ uint64_t sa_mask;
+ uint16_t InSyscallInfo;
++ uint16_t ClearedSyscallInfo;
+ bool FaultToTopAndGeneratedException;
++ uint64_t GuestSignalMask;
++ uint64_t SeccompTrapRIP;
++ uint64_t SavedJITStackSP;
+
+ // Guest state
+ int Signal;
+@@ -92,6 +101,11 @@ struct ArmContextBackup {
+ static constexpr int RedZoneSize = 0;
+ };
+
++template
++static inline uint16_t SavedSyscallInfo(const Backup* Context) {
++ return (Context->Flags & CONTEXT_FLAG_SYSCALLINFO_CLEARED) ? Context->ClearedSyscallInfo : Context->InSyscallInfo;
++}
++
+ static inline ucontext_t* GetUContext(void* ucontext) {
+ ucontext_t* _context = (ucontext_t*)ucontext;
+ return _context;
+diff --git a/Source/Tools/LinuxEmulation/CMakeLists.txt b/Source/Tools/LinuxEmulation/CMakeLists.txt
+index 715a8f132..3f02104ea 100644
+--- a/Source/Tools/LinuxEmulation/CMakeLists.txt
++++ b/Source/Tools/LinuxEmulation/CMakeLists.txt
+@@ -10,6 +10,9 @@ add_library(LinuxEmulation STATIC
+ LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
+ LinuxSyscalls/FaultSafeUserMemAccess.cpp
+ LinuxSyscalls/FileManagement.cpp
++ LinuxSyscalls/PtraceEmu.cpp
++ LinuxSyscalls/SamplingProfiler.cpp
++ LinuxSyscalls/SignalTrace.cpp
+ LinuxSyscalls/LinuxAllocator.cpp
+ LinuxSyscalls/Seccomp/SeccompEmulator.cpp
+ LinuxSyscalls/Seccomp/BPFEmitter.cpp
+diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
+index 2095d4dc5..eb12945e4 100644
+--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
+@@ -10,6 +10,7 @@ $end_info$
+
+ #include "Common/CPUInfo.h"
+ #include "Common/FDUtils.h"
++#include "LinuxSyscalls/PtraceEmu.h"
+ #include "LinuxSyscalls/Syscalls.h"
+ #include "LinuxSyscalls/EmulatedFiles/EmulatedFiles.h"
+
+@@ -24,6 +25,8 @@ $end_info$
+
+ #include
+
++#include
++#include
+ #include
+ #include
+ #include
+@@ -593,6 +596,10 @@ EmulatedFDManager::EmulatedFDManager(FEXCore::Context::Context* ctx)
+ FDReadCreators[procAuxv] = &EmulatedFDManager::ProcAuxv;
+ FDReadCreators["/proc/self/auxv"] = &EmulatedFDManager::ProcAuxv;
+
++ fextl::string procStatus = fextl::fmt::format("/proc/{}/status", getpid());
++ FDReadCreators[procStatus] = &EmulatedFDManager::ProcStatus;
++ FDReadCreators["/proc/self/status"] = &EmulatedFDManager::ProcStatus;
++
+ if (ThreadsConfig > 1) {
+ cpus_online = fextl::fmt::format("0-{}", ThreadsConfig - 1);
+ } else {
+@@ -602,6 +609,20 @@ EmulatedFDManager::EmulatedFDManager(FEXCore::Context::Context* ctx)
+
+ EmulatedFDManager::~EmulatedFDManager() {}
+
++static bool IsProcMapsPath(const char* Path) {
++ if (strncmp(Path, "/proc/", 6) != 0) {
++ return false;
++ }
++ const char* P = Path + 6;
++ if (!isdigit(*P)) {
++ return strcmp(P, "self/maps") == 0;
++ }
++ while (isdigit(*P)) {
++ ++P;
++ }
++ return strcmp(P, "/maps") == 0;
++}
++
+ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode) {
+ auto Creator = FDReadCreators.end();
+ if (pathname) {
+@@ -609,12 +630,148 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode)
+ }
+
+ if (Creator == FDReadCreators.end()) {
++ if (pathname && IsProcMapsPath(pathname)) {
++ return ProcMaps(CTX, AT_FDCWD, pathname, flags, mode);
++ }
+ return -1;
+ }
+
+ return Creator->second(CTX, AT_FDCWD, pathname, flags, mode);
+ }
+
++int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
++ int HostFD = ::open(pathname, O_RDONLY | O_CLOEXEC);
++ if (HostFD < 0) {
++ return -1;
++ }
++ fextl::string In;
++ char Buf[65536];
++ for (;;) {
++ const ssize_t Len = ::read(HostFD, Buf, sizeof(Buf));
++ if (Len > 0) {
++ In.append(Buf, Len);
++ } else if (Len == 0) {
++ break;
++ } else if (errno != EINTR) {
++ LogMan::Msg::EFmt("ProcMaps: reading {} failed: {}", pathname, errno);
++ ::close(HostFD);
++ return -1;
++ }
++ }
++ ::close(HostFD);
++
++ constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096;
++ fextl::string Out;
++ Out.reserve(In.size());
++ size_t Pos = 0;
++ while (Pos < In.size()) {
++ size_t Eol = In.find('\n', Pos);
++ const size_t End = Eol == fextl::string::npos ? In.size() : Eol + 1;
++ const uint64_t Start = strtoull(In.c_str() + Pos, nullptr, 16);
++ if (Start < X86_64TaskSizeMax) {
++ Out.append(In, Pos, End - Pos);
++ }
++ Pos = End;
++ }
++
++ int NewFD = GenTmpFD(pathname, flags);
++ if (NewFD < 0) {
++ LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno);
++ return -1;
++ }
++ for (size_t Done = 0; Done < Out.size();) {
++ const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done);
++ if (Wrote > 0) {
++ Done += Wrote;
++ } else if (Wrote < 0 && errno == EINTR) {
++ continue;
++ } else {
++ LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno);
++ ::close(NewFD);
++ return -1;
++ }
++ }
++ if (::lseek(NewFD, 0, SEEK_SET) != 0) {
++ LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno);
++ ::close(NewFD);
++ return -1;
++ }
++ SealTmpFD(NewFD);
++ return NewFD;
++}
++
++int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
++ char Buf[8192];
++ ssize_t Len = 0;
++ {
++ int HostFD = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC);
++ if (HostFD >= 0) {
++ Len = ::read(HostFD, Buf, sizeof(Buf) - 1);
++ ::close(HostFD);
++ }
++ }
++ if (Len < 0) {
++ Len = 0;
++ }
++ Buf[Len] = '\0';
++
++ uint32_t SeccompMode = SECCOMP_MODE_DISABLED;
++ if (auto* Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject()) {
++ SeccompMode = Thread->SeccompMode;
++ }
++
++ fextl::string Out;
++ Out.reserve(Len + 64);
++ const char* Cursor = Buf;
++ while (*Cursor) {
++ const char* Eol = strchr(Cursor, '\n');
++ const size_t LineLen = Eol ? static_cast(Eol - Cursor) + 1 : strlen(Cursor);
++ if (strncmp(Cursor, "Seccomp:", 8) == 0) {
++ Out += fextl::fmt::format("Seccomp:\t{}\n", SeccompMode);
++ } else if (strncmp(Cursor, "TracerPid:", 10) == 0) {
++ if (FEX::HLE::PtraceEmu::IsAttached()) {
++ Out.append(Cursor, LineLen);
++ } else {
++ Out += "TracerPid:\t0\n";
++ }
++ } else {
++ Out.append(Cursor, LineLen);
++ if (!Eol) {
++ break;
++ }
++ }
++ if (!Eol) {
++ break;
++ }
++ Cursor = Eol + 1;
++ }
++
++ int NewFD = GenTmpFD(pathname, flags);
++ if (NewFD < 0) {
++ LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno);
++ return -1;
++ }
++ for (size_t Done = 0; Done < Out.size();) {
++ const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done);
++ if (Wrote > 0) {
++ Done += Wrote;
++ } else if (Wrote < 0 && errno == EINTR) {
++ continue;
++ } else {
++ LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno);
++ ::close(NewFD);
++ return -1;
++ }
++ }
++ if (::lseek(NewFD, 0, SEEK_SET) != 0) {
++ LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno);
++ ::close(NewFD);
++ return -1;
++ }
++ SealTmpFD(NewFD);
++ return NewFD;
++}
++
+ int32_t EmulatedFDManager::ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
+ const auto [auxvBase, auxvSize] = FEX::HLE::_SyscallHandler->GetCodeLoader()->GetAuxv();
+ if (auxvBase == 0) {
+diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h
+index 854232341..b98ef4bda 100644
+--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h
++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h
+@@ -34,6 +34,8 @@ private:
+ fextl::unordered_map FDReadCreators;
+
+ static int32_t ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
++ static int32_t ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
++ static int32_t ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
+ const uint32_t ThreadsConfig;
+ };
+ } // namespace FEX::EmulatedFile
+diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FaultSafeUserMemAccess.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FaultSafeUserMemAccess.cpp
+index 6471e6483..7a7e068e2 100644
+--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FaultSafeUserMemAccess.cpp
++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FaultSafeUserMemAccess.cpp
+@@ -1,6 +1,8 @@
+ // SPDX-License-Identifier: MIT
+ #include "LinuxSyscalls/Syscalls.h"
+
++#include
++
+ namespace FEX::HLE::FaultSafeUserMemAccess {
+ #ifdef ARCHITECTURE_arm64
+ __attribute__((naked)) size_t CopyFromUser(void* Dest, const void* Src, size_t Size) {
+@@ -41,6 +43,26 @@ __attribute__((naked)) size_t CopyToUser(void* Dest, const void* Src, size_t Siz
+ : "memory");
+ }
+
++__attribute__((naked)) static size_t StringReadableImpl(const char* Src) {
++ __asm volatile(R"(
++ 1:
++ .globl StringReadable_FaultInst
++ StringReadable_FaultInst:
++ ldrb w1, [x0], 1; // <- This line can fault.
++ cbnz w1, 1b;
++ mov x0, 0;
++ ret;
++ )" ::
++ : "memory");
++}
++
++bool IsStringReadable(const char* Src) {
++ return Src == nullptr || StringReadableImpl(Src) == 0;
++}
++
++extern "C" uint64_t StringReadable_FaultInst;
++void* const StringReadable_FaultLocation = &StringReadable_FaultInst;
++
+ extern "C" uint64_t CopyFromUser_FaultInst;
+ void* const CopyFromUser_FaultLocation = &CopyFromUser_FaultInst;
+
+@@ -157,6 +179,8 @@ bool IsFaultLocation(uint64_t PC) {
+ bool IsMemcpyFault = false;
+ IsMemcpyFault |= reinterpret_cast(PC) == CopyToUser_FaultLocation;
+ IsMemcpyFault |= reinterpret_cast(PC) == CopyFromUser_FaultLocation;
++ IsMemcpyFault |= reinterpret_cast(PC) == StringReadable_FaultLocation;
++ IsMemcpyFault |= FEXCore::Utils::FaultSafeRead::IsFaultLocation(PC);
+ #if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED && defined(ARCHITECTURE_arm64)
+ IsMemcpyFault |= reinterpret_cast(PC) == UserReadable_FaultLocation;
+ IsMemcpyFault |= reinterpret_cast(PC) == UserWritable_FaultLocation;
+@@ -176,6 +200,10 @@ size_t CopyToUser(void* Dest, const void* Src, size_t Size) {
+ return Size;
+ }
+
++bool IsStringReadable(const char* Src) {
++ return true;
++}
++
+ bool IsFaultLocation(uint64_t PC) {
+ return false;
+ }
+diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
+index 2210e4508..62b6a2d27 100644
+--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
+@@ -13,6 +13,7 @@ $end_info$
+ #include "FEXCore/Config/Config.h"
+ #include "LinuxSyscalls/FileManagement.h"
+ #include "LinuxSyscalls/EmulatedFiles/EmulatedFiles.h"
++#include "LinuxSyscalls/PtraceEmu.h"
+ #include "LinuxSyscalls/Syscalls.h"
+ #include "LinuxSyscalls/x64/Syscalls.h"
+
+@@ -954,6 +955,27 @@ uint64_t FileManager::FAccessat2(int dirfd, const char* pathname, int mode, int
+ return ::syscall(SYSCALL_DEF(faccessat2), dirfd, SelfPath, mode, flags);
+ }
+
++static std::optional ReadlinkTraceeExe(const char* Path, char* Buf, size_t BufSize) {
++ if (!Path || strncmp(Path, "/proc/", 6) != 0) {
++ return std::nullopt;
++ }
++ char* End = nullptr;
++ const long Pid = strtol(Path + 6, &End, 10);
++ if (End == Path + 6 || strcmp(End, "/exe") != 0) {
++ return std::nullopt;
++ }
++ const auto Exe = PtraceEmu::TraceeExePath(static_cast(Pid));
++ if (!Exe) {
++ return std::nullopt;
++ }
++ const size_t Len = std::min(BufSize, Exe->size());
++ if (FaultSafeUserMemAccess::CopyToUser(Buf, Exe->data(), Len)) {
++ errno = EFAULT;
++ return -1;
++ }
++ return Len;
++}
++
+ uint64_t FileManager::Readlink(const char* pathname, char* buf, size_t bufsiz) {
+ // calculate the non-self link to exe
+ // Some executables do getpid, stat("/proc/$pid/exe")
+@@ -962,8 +984,16 @@ uint64_t FileManager::Readlink(const char* pathname, char* buf, size_t bufsiz) {
+
+ if (strcmp(pathname, "/proc/self/exe") == 0 || strcmp(pathname, "/proc/thread-self/exe") == 0 || strcmp(pathname, PidSelfPath) == 0) {
+ const auto& App = Filename();
+- strncpy(buf, App.c_str(), bufsiz);
+- return std::min(bufsiz, App.size());
++ const size_t Len = std::min(bufsiz, App.size());
++ if (FaultSafeUserMemAccess::CopyToUser(buf, App.c_str(), Len)) {
++ errno = EFAULT;
++ return -1;
++ }
++ return Len;
++ }
++
++ if (auto Traced = ReadlinkTraceeExe(pathname, buf, bufsiz)) {
++ return *Traced;
+ }
+
+ FDPathTmpData TmpFilename;
+@@ -1039,8 +1069,18 @@ uint64_t FileManager::Readlinkat(int dirfd, const char* pathname, char* buf, siz
+
+ if (Path == "/proc/self/exe" || Path == "/proc/thread-self/exe" || Path == PidSelfPath) {
+ const auto& App = Filename();
+- strncpy(buf, App.c_str(), bufsiz);
+- return std::min(bufsiz, App.size());
++ const size_t Len = std::min(bufsiz, App.size());
++ if (FaultSafeUserMemAccess::CopyToUser(buf, App.c_str(), Len)) {
++ errno = EFAULT;
++ return -1;
++ }
++ return Len;
++ }
++
++ if (!Path.empty() && Path[0] == '/') {
++ if (auto Traced = ReadlinkTraceeExe(Path.c_str(), buf, bufsiz)) {
++ return *Traced;
++ }
+ }
+
+ FDPathTmpData TmpFilename;
+diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp
+index 7ae8236b3..3be10d097 100644
+--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp
++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp
+@@ -50,6 +50,7 @@ public:
+
+ void* Mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) override;
+ int Munmap(void* addr, size_t length) override;
++ void TrackUnmapped(void* addr, size_t length) override;
+ void* Mremap(void* old_address, size_t old_size, size_t new_size, int flags, void* new_address) override;
+ uint64_t Shmat(int shmid, const void* shmaddr, int shmflg, uint32_t* ResultAddress) override;
+ uint64_t Shmdt(const void* shmaddr) override;
+@@ -333,6 +334,17 @@ int MemAllocator32Bit::Munmap(void* addr, size_t length) {
+ return 0;
+ }
+
++void MemAllocator32Bit::TrackUnmapped(void* addr, size_t length) {
++ std::scoped_lock lk {AllocMutex};
++
++ const uint64_t Addr = reinterpret_cast(addr);
++ const uint64_t PageAddr = std::max(Addr >> FEXCore::Utils::FEX_PAGE_SHIFT, BASE_KEY);
++ const uint64_t PageEnd = std::min(FEXCore::AlignUp(Addr + length, FEXCore::Utils::FEX_PAGE_SIZE) >> FEXCore::Utils::FEX_PAGE_SHIFT, TOP_KEY);
++ if (PageAddr < PageEnd) {
++ SetFreePages(PageAddr, PageEnd - PageAddr);
++ }
++}
++
+ void* MemAllocator32Bit::Mremap(void* old_address, size_t old_size, size_t new_size, int flags, void* new_address) {
+ size_t OldPagesLength = FEXCore::AlignUp(old_size, FEXCore::Utils::FEX_PAGE_SIZE) >> FEXCore::Utils::FEX_PAGE_SHIFT;
+ size_t NewPagesLength = FEXCore::AlignUp(new_size, FEXCore::Utils::FEX_PAGE_SIZE) >> FEXCore::Utils::FEX_PAGE_SHIFT;
+diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.h
+index dd6ae074f..c84f85b4a 100644
+--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.h
++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.h
+@@ -14,6 +14,7 @@ public:
+ virtual ~MemAllocator() = default;
+ virtual void* Mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) = 0;
+ virtual int Munmap(void* addr, size_t length) = 0;
++ virtual void TrackUnmapped(void* addr, size_t length) {}
+ virtual void* Mremap(void* old_address, size_t old_size, size_t new_size, int flags, void* new_address) = 0;
+ virtual uint64_t Shmat(int shmid, const void* shmaddr, int shmflg, uint32_t* ResultAddress) = 0;
+ virtual uint64_t Shmdt(const void* shmaddr) = 0;
+diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
+new file mode 100644
+index 000000000..ca4c86063
+--- /dev/null
++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
+@@ -0,0 +1,838 @@
++// SPDX-License-Identifier: MIT
++
++#include "LinuxSyscalls/PtraceEmu.h"
++#include "LinuxSyscalls/Syscalls.h"
++
++#include
++#include
++
++#include
++#include
++#include
++#include
++#include
++#include
++#include
++#include
++#include
++
++#include
++#include
++#include
++#include
++#include
++#include
++#include
++
++namespace FEX::HLE::PtraceEmu {
++namespace {
++#ifndef NT_X86_XSTATE
++ constexpr uintptr_t NT_X86_XSTATE = 0x202;
++#endif
++
++ enum UserReg : unsigned {
++ R15, R14, R13, R12, Rbp, Rbx, R11, R10, R9, R8, Rax, Rcx, Rdx, Rsi, Rdi, OrigRax, Rip, Cs, Eflags, Rsp, Ss, FsBase, GsBase, Ds, Es, Fs, Gs,
++ };
++ static_assert(Gs + 1 == NumUserRegs);
++
++ constexpr uintptr_t UserDebugRegByteOffset = 848;
++ constexpr uintptr_t UserDebugRegByteEnd = UserDebugRegByteOffset + 8 * sizeof(uint64_t);
++ constexpr uintptr_t UserStructSize = 928;
++
++ constexpr uint64_t UserTaskSizeMax = 0x00007ffffffff000ULL;
++
++ bool DrFieldValid(uint64_t Field, uint64_t* AlignMask) {
++ const uint64_t Len = Field & 0xC;
++ switch (Field & 0x3) {
++ case 0x0:
++ if (Len != 0x0) {
++ return false;
++ }
++ *AlignMask = 0;
++ return true;
++ case 0x1:
++ case 0x3:
++ switch (Len) {
++ case 0x0: *AlignMask = 0; return true;
++ case 0x4: *AlignMask = 1; return true;
++ case 0xC: *AlignMask = 3; return true;
++ case 0x8: *AlignMask = 7; return true;
++ default: return false;
++ }
++ default:
++ return false;
++ }
++ }
++
++ constexpr unsigned DrEnableShift(unsigned N) { return N * 2; }
++ constexpr unsigned DrFieldShift(unsigned N) { return 16 + N * 4; }
++
++ bool DrAddressValid(uint64_t Addr, uint64_t AlignMask) {
++ return Addr < UserTaskSizeMax && (Addr & AlignMask) == 0;
++ }
++
++ bool Dr7Valid(const uint64_t Dr[8], uint64_t NewDr7) {
++ for (unsigned N = 0; N < 4; ++N) {
++ const bool Enabled = (NewDr7 >> DrEnableShift(N)) & 0x3;
++ const bool Registered = Dr[N] != 0;
++ if (!Enabled && !Registered) {
++ continue;
++ }
++ const uint64_t Field = (NewDr7 >> DrFieldShift(N)) & 0xF;
++ uint64_t AlignMask = 0;
++ if (!DrFieldValid(Field, &AlignMask) || !DrAddressValid(Dr[N], AlignMask)) {
++ return false;
++ }
++ }
++ return true;
++ }
++
++ constexpr uint16_t UserCodeSegment = 0x33;
++ constexpr uint16_t UserStackSegment = 0x2b;
++ constexpr uint64_t UserFlags = 0x246;
++ constexpr uint64_t NoOverride = ~0ULL;
++
++ constexpr int X86_PTRACE_GETREGS = 12;
++ constexpr int X86_PTRACE_SETREGS = 13;
++ constexpr int X86_PTRACE_EVENT_EXEC = 4;
++
++ SharedState StaticState {SharedState::MagicValue};
++ SharedState* Current = &StaticState;
++ thread_local uint64_t PendingRip = 0;
++
++ struct OpenSyscall {
++ bool Open = false;
++ uint64_t Nr {};
++ uint64_t Args[6] {};
++ } Previous;
++
++ constexpr const char* SidecarDirs[] = {"/dev/shm", "/tmp"};
++
++ std::string SidecarPath(const char* Dir, const char* Kind, pid_t Pid) {
++ return std::string(Dir) + "/fex-ptrace-" + Kind + "-" + std::to_string(Pid);
++ }
++
++ int OpenSidecar(const char* Kind, pid_t Pid, int Flags) {
++ for (const char* Dir : SidecarDirs) {
++ const int fd = ::open(SidecarPath(Dir, Kind, Pid).c_str(), Flags | O_CLOEXEC, 0600);
++ if (fd >= 0) {
++ return fd;
++ }
++ }
++ return -1;
++ }
++
++ void RemoveSidecar(const char* Kind, pid_t Pid) {
++ for (const char* Dir : SidecarDirs) {
++ ::unlink(SidecarPath(Dir, Kind, Pid).c_str());
++ }
++ }
++
++ bool IsMainThread() {
++ return ::syscall(SYS_gettid) == ::getpid();
++ }
++
++ bool HasHostTracer() {
++ const int fd = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC);
++ if (fd < 0) {
++ return true;
++ }
++ char Buf[2048];
++ const ssize_t n = ::read(fd, Buf, sizeof(Buf) - 1);
++ ::close(fd);
++ if (n <= 0) {
++ return true;
++ }
++ Buf[n] = 0;
++ const char* Tag = strstr(Buf, "TracerPid:");
++ return !Tag || atoi(Tag + sizeof("TracerPid:") - 1) != 0;
++ }
++
++
++ void BuildRegs(const FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, bool Entry, uint64_t Ret, uint64_t* X) {
++ using namespace FEXCore::X86State;
++ const auto& S = Frame->State;
++ X[R15] = S.gregs[REG_R15];
++ X[R14] = S.gregs[REG_R14];
++ X[R13] = S.gregs[REG_R13];
++ X[R12] = S.gregs[REG_R12];
++ X[Rbp] = S.gregs[REG_RBP];
++ X[Rbx] = S.gregs[REG_RBX];
++ X[R11] = UserFlags;
++ X[R10] = S.gregs[REG_R10];
++ X[R9] = S.gregs[REG_R9];
++ X[R8] = S.gregs[REG_R8];
++ X[Rax] = Entry ? static_cast(-ENOSYS) : Ret;
++ X[Rcx] = S.gregs[REG_RCX];
++ X[Rdx] = S.gregs[REG_RDX];
++ X[Rsi] = S.gregs[REG_RSI];
++ X[Rdi] = S.gregs[REG_RDI];
++ X[OrigRax] = Nr;
++ X[Rip] = S.gregs[REG_RCX] ? S.gregs[REG_RCX] : S.rip;
++ X[Cs] = UserCodeSegment;
++ X[Eflags] = UserFlags;
++ X[Rsp] = S.gregs[REG_RSP];
++ X[Ss] = UserStackSegment;
++ X[FsBase] = S.fs_cached;
++ X[GsBase] = S.gs_cached;
++ X[Ds] = X[Es] = X[Fs] = X[Gs] = 0;
++ }
++
++ void Stop(uint64_t Nr, const uint64_t Args[6], bool Entry, uint64_t Ret, const uint64_t* Regs) {
++ SharedState& S = *Current;
++ if (!HasHostTracer()) {
++ S.SyscallStops = 0;
++ S.Attached = 0;
++ return;
++ }
++ for (unsigned i = 0; i < NumUserRegs; ++i) {
++ S.Regs[i] = Regs[i];
++ }
++ S.PendingNr = Nr;
++ for (unsigned i = 0; i < 6; ++i) {
++ S.PendingArgs[i] = Args[i];
++ }
++ S.PendingRet = Ret;
++ S.PendingIsEntry = Entry ? 1 : 0;
++ S.Pending = 1;
++ ::syscall(SYS_tgkill, ::getpid(), ::syscall(SYS_gettid), SIGSTOP);
++ S.Pending = 0;
++ }
++
++ uint64_t ApplyTracerWrites(FEXCore::Core::CpuStateFrame* Frame, bool Entry) {
++ using namespace FEXCore::X86State;
++ SharedState& S = *Current;
++
++ if (S.FlushLen) {
++ const uint64_t Addr = S.FlushAddr;
++ const uint64_t Len = S.FlushLen;
++ S.FlushLen = 0;
++ FEX::HLE::_SyscallHandler->InvalidateGuestCodeRange(Frame->Thread, Addr, Len);
++ }
++
++ const uint64_t Dirty = S.DirtyMask;
++ if (!Dirty) {
++ return NoOverride;
++ }
++
++ static constexpr int Map[15] = {REG_R15, REG_R14, REG_R13, REG_R12, REG_RBP, REG_RBX, -1, REG_R10, REG_R9, REG_R8, -1, REG_RCX, REG_RDX, REG_RSI, REG_RDI};
++ auto& State = Frame->State;
++ uint64_t Override = NoOverride;
++ for (unsigned i = 0; i < NumUserRegs; ++i) {
++ if (!(Dirty & (1ULL << i))) {
++ continue;
++ }
++ const uint64_t V = S.Regs[i];
++ if (i < 15) {
++ if (Map[i] >= 0) {
++ State.gregs[Map[i]] = V;
++ }
++ } else if (i == Rip) {
++ PendingRip = V;
++ } else if (i == Rsp) {
++ State.gregs[REG_RSP] = V;
++ } else if (i == FsBase) {
++ State.fs_cached = V;
++ } else if (i == GsBase) {
++ State.gs_cached = V;
++ }
++ if (i == Rax && !Entry) {
++ Override = V;
++ }
++ }
++ if (Entry && (Dirty & (1ULL << OrigRax))) {
++ State.gregs[REG_RAX] = S.Regs[OrigRax];
++ }
++ S.DirtyMask = 0;
++ return Override;
++ }
++
++ void PublishSharedPage() {
++ if (Current != &StaticState) {
++ return;
++ }
++ const int fd = OpenSidecar("state", ::getpid(), O_RDWR | O_CREAT | O_TRUNC);
++ if (fd < 0) {
++ return;
++ }
++ if (::ftruncate(fd, 4096) == 0) {
++ void* Page = ::mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
++ if (Page != MAP_FAILED) {
++ std::memcpy(Page, &StaticState, sizeof(SharedState));
++ Current = static_cast(Page);
++ }
++ }
++ ::close(fd);
++ }
++
++ struct Remote {
++ uint8_t* Mapped = nullptr;
++ uintptr_t StaticAddr = 0;
++ std::array FpRegs {};
++ bool FpValid = false;
++ std::array XState {};
++ bool XStateValid = false;
++ };
++ std::mutex RemotesLock;
++ std::unordered_map Remotes;
++ std::unordered_map ExePaths;
++
++ uintptr_t FindFexImageBase(pid_t Pid) {
++ static const std::string SelfExe = []() {
++ char Buf[512];
++ const ssize_t n = ::readlink("/proc/self/exe", Buf, sizeof(Buf) - 1);
++ return n > 0 ? std::string(Buf, n) : std::string();
++ }();
++ if (SelfExe.empty()) {
++ return 0;
++ }
++ const std::string Maps = Pid ? "/proc/" + std::to_string(Pid) + "/maps" : "/proc/self/maps";
++ FILE* F = fopen(Maps.c_str(), "r");
++ if (!F) {
++ return 0;
++ }
++ char Line[1024];
++ uintptr_t Lowest = 0;
++ while (fgets(Line, sizeof(Line), F)) {
++ if (!strstr(Line, SelfExe.c_str())) {
++ continue;
++ }
++ unsigned long long Start = 0, End = 0, Offset = 0;
++ if (sscanf(Line, "%llx-%llx %*s %llx", &Start, &End, &Offset) == 3 && Offset == 0 && (!Lowest || Start < Lowest)) {
++ Lowest = Start;
++ }
++ }
++ fclose(F);
++ return Lowest;
++ }
++
++ Remote* Lookup(pid_t Pid) {
++ auto It = Remotes.find(Pid);
++ if (It != Remotes.end()) {
++ return &It->second;
++ }
++ Remote R;
++ const int fd = OpenSidecar("state", Pid, O_RDWR);
++ if (fd >= 0) {
++ void* Page = ::mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
++ ::close(fd);
++ if (Page != MAP_FAILED) {
++ R.Mapped = static_cast(Page);
++ }
++ }
++ if (!R.Mapped) {
++ static const uintptr_t SelfBase = FindFexImageBase(0);
++ const uintptr_t TraceeBase = FindFexImageBase(Pid);
++ if (!SelfBase || !TraceeBase) {
++ return nullptr;
++ }
++ R.StaticAddr = TraceeBase + (reinterpret_cast(&StaticState) - SelfBase);
++ }
++ return &Remotes.emplace(Pid, std::move(R)).first->second;
++ }
++
++ void Forget(pid_t Pid, bool Exited) {
++ std::lock_guard lk(RemotesLock);
++ auto It = Remotes.find(Pid);
++ if (It != Remotes.end()) {
++ if (It->second.Mapped) {
++ ::munmap(It->second.Mapped, 4096);
++ }
++ Remotes.erase(It);
++ }
++ RemoveSidecar("state", Pid);
++ if (Exited) {
++ ExePaths.erase(Pid);
++ }
++ }
++
++ void CaptureExecPath(pid_t Pid) {
++ std::lock_guard lk(RemotesLock);
++ Remote* R = Lookup(Pid);
++ if (R && R->Mapped) {
++ auto* S = reinterpret_cast(R->Mapped);
++ if (S->Magic == SharedState::MagicValue && S->ExePath[0]) {
++ ExePaths[Pid] = std::string(S->ExePath, strnlen(S->ExePath, sizeof(S->ExePath)));
++ }
++ }
++ }
++
++ uint64_t HostPtrace(int Request, pid_t Pid, void* Addr, void* Data) {
++ const long R = ::syscall(SYS_ptrace, Request, Pid, Addr, Data);
++ return R == -1 ? static_cast(-errno) : static_cast(R);
++ }
++
++ bool ReadWord(pid_t Pid, size_t Offset, uint64_t* Out) {
++ std::lock_guard lk(RemotesLock);
++ Remote* R = Lookup(Pid);
++ if (!R) {
++ return false;
++ }
++ if (R->Mapped) {
++ *Out = *reinterpret_cast(R->Mapped + Offset);
++ return true;
++ }
++ return ::syscall(SYS_ptrace, PTRACE_PEEKDATA, Pid, R->StaticAddr + Offset, Out) == 0;
++ }
++
++ bool WriteWord(pid_t Pid, size_t Offset, uint64_t Value) {
++ std::lock_guard lk(RemotesLock);
++ Remote* R = Lookup(Pid);
++ if (!R) {
++ return false;
++ }
++ if (R->Mapped) {
++ *reinterpret_cast(R->Mapped + Offset) = Value;
++ return true;
++ }
++ return ::syscall(SYS_ptrace, PTRACE_POKEDATA, Pid, R->StaticAddr + Offset, Value) == 0;
++ }
++
++ bool IsFexTracee(pid_t Pid) {
++ uint64_t Magic = 0;
++ return ReadWord(Pid, offsetof(SharedState, Magic), &Magic) && Magic == SharedState::MagicValue;
++ }
++
++ bool ReadSlot(pid_t Pid, size_t Offset, uint64_t* Out) {
++ return ReadWord(Pid, Offset, Out);
++ }
++
++ void MarkDirty(pid_t Pid, uint64_t Mask) {
++ uint64_t Dirty = 0;
++ ReadWord(Pid, offsetof(SharedState, DirtyMask), &Dirty);
++ WriteWord(Pid, offsetof(SharedState, DirtyMask), Dirty | Mask);
++ }
++
++ constexpr size_t RegOffset(unsigned Index) {
++ return offsetof(SharedState, Regs) + Index * sizeof(uint64_t);
++ }
++
++ bool ReadDebugReg(pid_t Pid, unsigned N, uint64_t* Out) {
++ if (N == 4 || N == 5) {
++ *Out = 0;
++ return true;
++ }
++ if (N > 7) {
++ return false;
++ }
++ return ReadWord(Pid, offsetof(SharedState, DebugRegs) + N * sizeof(uint64_t), Out);
++ }
++
++ int WriteDebugReg(pid_t Pid, unsigned N, uint64_t Value) {
++ if (N == 4 || N == 5) {
++ return -EIO;
++ }
++ if (N <= 3) {
++ if (!DrAddressValid(Value, 0)) {
++ return -EINVAL;
++ }
++ return WriteWord(Pid, offsetof(SharedState, DebugRegs) + N * sizeof(uint64_t), Value) ? 0 : -ESRCH;
++ }
++ if (N == 6) {
++ return WriteWord(Pid, offsetof(SharedState, DebugRegs) + 6 * sizeof(uint64_t), Value) ? 0 : -ESRCH;
++ }
++ uint64_t Dr[8] {};
++ for (unsigned I = 0; I < 8; ++I) {
++ if (!ReadWord(Pid, offsetof(SharedState, DebugRegs) + I * sizeof(uint64_t), &Dr[I])) {
++ return -ESRCH;
++ }
++ }
++ if (!Dr7Valid(Dr, Value)) {
++ return -EINVAL;
++ }
++ return WriteWord(Pid, offsetof(SharedState, DebugRegs) + 7 * sizeof(uint64_t), Value) ? 0 : -ESRCH;
++ }
++
++ Remote* XStateState(pid_t Pid) {
++ std::lock_guard lk(RemotesLock);
++ Remote* R = Lookup(Pid);
++ if (R && !R->XStateValid) {
++ R->XStateValid = true;
++ }
++ return R;
++ }
++
++ Remote* FpState(pid_t Pid) {
++ std::lock_guard lk(RemotesLock);
++ Remote* R = Lookup(Pid);
++ if (R && !R->FpValid) {
++ const uint16_t Fcw = 0x37f;
++ const uint32_t Mxcsr = 0x1f80, MxcsrMask = 0xffff;
++ std::memcpy(&R->FpRegs[0], &Fcw, sizeof(Fcw));
++ std::memcpy(&R->FpRegs[24], &Mxcsr, sizeof(Mxcsr));
++ std::memcpy(&R->FpRegs[28], &MxcsrMask, sizeof(MxcsrMask));
++ R->FpValid = true;
++ }
++ return R;
++ }
++}
++
++
++bool IsAttached() {
++ return Current->Attached != 0;
++}
++
++bool WantsSyscallStops() {
++ return Current->SyscallStops && IsMainThread();
++}
++
++uint64_t SyscallEntryStop(FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, const uint64_t Args[6]) {
++ uint64_t Regs[NumUserRegs];
++ if (Previous.Open) {
++ BuildRegs(Frame, Previous.Nr, false, 0, Regs);
++ Stop(Previous.Nr, Previous.Args, false, 0, Regs);
++ }
++ BuildRegs(Frame, Nr, true, 0, Regs);
++ Stop(Nr, Args, true, 0, Regs);
++ ApplyTracerWrites(Frame, true);
++
++ const uint64_t NewNr = Frame->State.gregs[FEXCore::X86State::REG_RAX];
++ Previous.Open = Current->SyscallStops != 0;
++ Previous.Nr = NewNr;
++ std::copy(Args, Args + 6, Previous.Args);
++ return NewNr;
++}
++
++uint64_t SyscallExitStop(FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, const uint64_t Args[6], uint64_t Result) {
++ uint64_t Regs[NumUserRegs];
++ BuildRegs(Frame, Nr, false, Result, Regs);
++ Stop(Nr, Args, false, Result, Regs);
++ const uint64_t Override = ApplyTracerWrites(Frame, false);
++ Previous.Open = false;
++ return Override != NoOverride ? Override : Result;
++}
++
++void OnForkedChild(bool SharesAddressSpace) {
++ if (SharesAddressSpace) {
++ return;
++ }
++ Current = &StaticState;
++ StaticState.SyscallStops = 0;
++ StaticState.Attached = 0;
++ StaticState.Pending = 0;
++ Previous.Open = false;
++}
++
++void ApplyPendingFlush(FEXCore::Core::CpuStateFrame* Frame) {
++ SharedState& S = *Current;
++ if (S.FlushLen) {
++ const uint64_t Addr = S.FlushAddr;
++ const uint64_t Len = S.FlushLen;
++ S.FlushLen = 0;
++ FEX::HLE::_SyscallHandler->InvalidateGuestCodeRange(Frame->Thread, Addr, Len);
++ }
++}
++
++uint64_t TakePendingRip() {
++ const uint64_t Rip = PendingRip;
++ PendingRip = 0;
++ return Rip;
++}
++
++bool TryGuestSignalStop(FEXCore::Core::CpuStateFrame* Frame, int Signal) {
++ if (Signal != SIGTRAP && Signal != SIGSEGV) {
++ return false;
++ }
++ if (!Frame->SynchronousFaultData.FaultToTopAndGeneratedException || !Current->Attached || !IsMainThread()) {
++ return false;
++ }
++
++ uint64_t Regs[NumUserRegs];
++ const uint64_t NoArgs[6] {};
++ BuildRegs(Frame, ~0ULL, false, Frame->State.gregs[FEXCore::X86State::REG_RAX], Regs);
++ Regs[Rip] = Frame->State.rip;
++
++ Current->SignalNumber = static_cast(Signal);
++ Stop(~0ULL, NoArgs, false, 0, Regs);
++ Current->SignalNumber = 0;
++
++ const uint64_t Override = ApplyTracerWrites(Frame, false);
++ if (Override != NoOverride) {
++ Frame->State.gregs[FEXCore::X86State::REG_RAX] = Override;
++ }
++ if (const uint64_t NewRip = TakePendingRip()) {
++ Frame->State.rip = NewRip;
++ }
++ return true;
++}
++
++void RecordExecPath(const std::string& GuestPath) {
++ if (!Current->Attached) {
++ return;
++ }
++ const size_t Len = std::min(GuestPath.size(), sizeof(Current->ExePath) - 1);
++ std::memcpy(Current->ExePath, GuestPath.data(), Len);
++ Current->ExePath[Len] = 0;
++}
++
++
++std::optional TraceeExePath(pid_t Pid) {
++ if (Pid <= 0 || Pid == ::getpid()) {
++ return std::nullopt;
++ }
++ std::lock_guard lk(RemotesLock);
++ auto It = ExePaths.find(Pid);
++ return It != ExePaths.end() ? std::optional(It->second) : std::nullopt;
++}
++
++bool FixupWaitStatus(pid_t Pid, int* Status) {
++ if (!Status || Pid <= 0) {
++ return false;
++ }
++ const int St = *Status;
++
++ if (WIFEXITED(St) || WIFSIGNALED(St)) {
++ Forget(Pid, true);
++ return false;
++ }
++ if (!WIFSTOPPED(St)) {
++ return false;
++ }
++
++ if ((St >> 16) == 0 && (WSTOPSIG(St) == SIGTRAP || WSTOPSIG(St) == SIGSEGV) && IsFexTracee(Pid)) {
++ HostPtrace(PTRACE_CONT, Pid, nullptr, reinterpret_cast(static_cast(WSTOPSIG(St))));
++ return true;
++ }
++
++ if ((St >> 16) == 0 && WSTOPSIG(St) == SIGBUS && IsFexTracee(Pid)) {
++ siginfo_t Info {};
++ if (HostPtrace(PTRACE_GETSIGINFO, Pid, nullptr, &Info) == 0 && Info.si_code == BUS_ADRALN) {
++ HostPtrace(PTRACE_CONT, Pid, nullptr, reinterpret_cast(static_cast(SIGBUS)));
++ return true;
++ }
++ }
++
++ if ((St >> 16) == 0 && WSTOPSIG(St) == SIGPROF && IsFexTracee(Pid)) {
++ HostPtrace(PTRACE_CONT, Pid, nullptr, nullptr);
++ return true;
++ }
++
++ if ((St >> 16) == X86_PTRACE_EVENT_EXEC) {
++ CaptureExecPath(Pid);
++ Forget(Pid, false);
++ }
++
++ if (WSTOPSIG(St) == SIGSTOP) {
++ uint64_t Pending = 0;
++ if (ReadWord(Pid, offsetof(SharedState, Pending), &Pending) && Pending) {
++ uint64_t Signal = 0;
++ ReadWord(Pid, offsetof(SharedState, SignalNumber), &Signal);
++ *Status = (St & ~0xff00) | (static_cast(Signal ? Signal : (SIGTRAP | 0x80)) << 8);
++ }
++ }
++ return false;
++}
++
++bool HandleRequest(int Request, pid_t Pid, void* Addr, void* Data, uint64_t* Result) {
++ switch (Request) {
++ case PTRACE_TRACEME:
++ *Result = HostPtrace(Request, Pid, Addr, Data);
++ if (*Result == 0) {
++ PublishSharedPage();
++ Current->Attached = 1;
++ }
++ return true;
++
++ case PTRACE_KILL:
++ case PTRACE_SEIZE:
++ case PTRACE_INTERRUPT:
++ case PTRACE_SETOPTIONS:
++ case PTRACE_GETEVENTMSG:
++ case PTRACE_SINGLESTEP:
++ case PTRACE_GETSIGINFO: *Result = HostPtrace(Request, Pid, Addr, Data); return true;
++
++ case PTRACE_POKETEXT:
++ case PTRACE_POKEDATA: {
++ *Result = HostPtrace(Request, Pid, Addr, Data);
++ if (*Result == 0 && IsFexTracee(Pid)) {
++ const uint64_t Lo = reinterpret_cast(Addr) & ~0xfffULL;
++ const uint64_t Hi = Lo + 0x2000;
++ uint64_t OldAddr = 0, OldLen = 0;
++ ReadWord(Pid, offsetof(SharedState, FlushAddr), &OldAddr);
++ ReadWord(Pid, offsetof(SharedState, FlushLen), &OldLen);
++ uint64_t NewLo = Lo, NewHi = Hi;
++ if (OldLen) {
++ NewLo = std::min(OldAddr, Lo);
++ NewHi = std::max(OldAddr + OldLen, Hi);
++ }
++ WriteWord(Pid, offsetof(SharedState, FlushAddr), NewLo);
++ WriteWord(Pid, offsetof(SharedState, FlushLen), NewHi - NewLo);
++ }
++ return true;
++ }
++
++ case PTRACE_CONT:
++ case PTRACE_SYSCALL: {
++ uint64_t Magic = 0;
++ if (ReadWord(Pid, offsetof(SharedState, Magic), &Magic) && Magic == SharedState::MagicValue) {
++ WriteWord(Pid, offsetof(SharedState, SyscallStops), Request == PTRACE_SYSCALL ? 1 : 0);
++ WriteWord(Pid, offsetof(SharedState, Attached), 1);
++ }
++ *Result = HostPtrace(PTRACE_CONT, Pid, Addr, Data);
++ return true;
++ }
++
++ case PTRACE_DETACH: {
++ if (IsFexTracee(Pid)) {
++ WriteWord(Pid, offsetof(SharedState, SyscallStops), 0);
++ WriteWord(Pid, offsetof(SharedState, Attached), 0);
++ }
++ *Result = HostPtrace(Request, Pid, Addr, Data);
++ Forget(Pid, false);
++ return true;
++ }
++
++ case PTRACE_PEEKUSER: {
++ const uintptr_t Off = reinterpret_cast(Addr);
++ if ((Off % sizeof(uint64_t)) != 0 || Off >= UserStructSize) {
++ *Result = static_cast(-EIO);
++ return true;
++ }
++ uint64_t V = 0;
++ if (Off < NumUserRegs * sizeof(uint64_t)) {
++ if (!ReadSlot(Pid, RegOffset(Off / 8), &V)) {
++ *Result = static_cast(-ESRCH);
++ return true;
++ }
++ } else if (Off >= UserDebugRegByteOffset && Off < UserDebugRegByteEnd) {
++ if (!ReadDebugReg(Pid, static_cast((Off - UserDebugRegByteOffset) / sizeof(uint64_t)), &V)) {
++ *Result = static_cast(-ESRCH);
++ return true;
++ }
++ }
++ *static_cast(Data) = V;
++ *Result = 0;
++ return true;
++ }
++
++ case PTRACE_POKEUSER: {
++ const uintptr_t Off = reinterpret_cast(Addr);
++ if ((Off % sizeof(uint64_t)) != 0 || Off >= UserStructSize) {
++ *Result = static_cast(-EIO);
++ return true;
++ }
++ if (Off < NumUserRegs * sizeof(uint64_t)) {
++ if (!WriteWord(Pid, RegOffset(Off / 8), reinterpret_cast(Data))) {
++ *Result = static_cast(-ESRCH);
++ return true;
++ }
++ MarkDirty(Pid, 1ULL << (Off / 8));
++ *Result = 0;
++ return true;
++ }
++ if (Off >= UserDebugRegByteOffset && Off < UserDebugRegByteEnd) {
++ *Result = static_cast(WriteDebugReg(Pid, static_cast((Off - UserDebugRegByteOffset) / sizeof(uint64_t)), reinterpret_cast(Data)));
++ return true;
++ }
++ *Result = static_cast(-EIO);
++ return true;
++ }
++
++ case X86_PTRACE_GETREGS: {
++ for (unsigned i = 0; i < NumUserRegs; ++i) {
++ uint64_t V = 0;
++ if (!ReadSlot(Pid, RegOffset(i), &V)) {
++ *Result = static_cast(-ESRCH);
++ return true;
++ }
++ static_cast(Data)[i] = V;
++ }
++ *Result = 0;
++ return true;
++ }
++
++ case X86_PTRACE_SETREGS: {
++ uint64_t Mask = 0;
++ for (unsigned i = 0; i < NumUserRegs; ++i) {
++ if (!WriteWord(Pid, RegOffset(i), static_cast(Data)[i])) {
++ *Result = static_cast(-ESRCH);
++ return true;
++ }
++ Mask |= 1ULL << i;
++ }
++ MarkDirty(Pid, Mask);
++ *Result = 0;
++ return true;
++ }
++
++ case PTRACE_GETREGSET:
++ case PTRACE_SETREGSET: {
++ const auto NtType = reinterpret_cast(Addr);
++ auto* Iov = static_cast(Data);
++ if (!Iov) {
++ return false;
++ }
++ const bool Get = Request == PTRACE_GETREGSET;
++
++ if (NtType == NT_PRSTATUS) {
++ if (Get) {
++ uint64_t Image[NumUserRegs];
++ for (unsigned i = 0; i < NumUserRegs; ++i) {
++ if (!ReadSlot(Pid, RegOffset(i), &Image[i])) {
++ *Result = static_cast(-ESRCH);
++ return true;
++ }
++ }
++ const size_t Len = std::min(Iov->iov_len, sizeof(Image));
++ std::memcpy(Iov->iov_base, Image, Len);
++ Iov->iov_len = Len;
++ } else {
++ const size_t Slots = std::min(Iov->iov_len / sizeof(uint64_t), NumUserRegs);
++ uint64_t Mask = 0;
++ for (size_t i = 0; i < Slots; ++i) {
++ if (!WriteWord(Pid, RegOffset(i), static_cast(Iov->iov_base)[i])) {
++ *Result = static_cast(-ESRCH);
++ return true;
++ }
++ Mask |= 1ULL << i;
++ }
++ MarkDirty(Pid, Mask);
++ Iov->iov_len = NumUserRegs * sizeof(uint64_t);
++ }
++ *Result = 0;
++ return true;
++ }
++
++ if (NtType == NT_PRFPREG) {
++ Remote* R = FpState(Pid);
++ if (!R) {
++ *Result = static_cast(-ESRCH);
++ return true;
++ }
++ const size_t Len = std::min(Iov->iov_len, R->FpRegs.size());
++ if (Get) {
++ std::memcpy(Iov->iov_base, R->FpRegs.data(), Len);
++ } else {
++ std::memcpy(R->FpRegs.data(), Iov->iov_base, Len);
++ }
++ Iov->iov_len = Len;
++ *Result = 0;
++ return true;
++ }
++
++ if (NtType == NT_X86_XSTATE) {
++ Remote* R = XStateState(Pid);
++ if (!R) {
++ *Result = static_cast(-ESRCH);
++ return true;
++ }
++ const size_t Len = std::min(Iov->iov_len, R->XState.size());
++ if (Get) {
++ std::memcpy(Iov->iov_base, R->XState.data(), Len);
++ } else {
++ std::memcpy(R->XState.data(), Iov->iov_base, Len);
++ }
++ Iov->iov_len = Len;
++ *Result = 0;
++ return true;
++ }
++
++ *Result = static_cast(-EINVAL);
++ return true;
++ }
++
++ default: return false;
++ }
++}
++
++}
+diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.h
+new file mode 100644
+index 000000000..59194979a
+--- /dev/null
++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.h
+@@ -0,0 +1,63 @@
++// SPDX-License-Identifier: MIT
++#pragma once
++
++#include
++#include
++#include
++#include
++
++namespace FEXCore::Core {
++struct CpuStateFrame;
++}
++
++namespace FEX::HLE::PtraceEmu {
++
++constexpr unsigned NumUserRegs = 27;
++
++struct SharedState {
++ static constexpr uint64_t MagicValue = 0xFE8E5E57CAFE0001ULL;
++
++ volatile uint64_t Magic;
++ volatile uint64_t SyscallStops;
++ volatile uint64_t Attached;
++ volatile uint64_t Pending;
++ volatile uint64_t PendingIsEntry;
++ volatile uint64_t PendingNr;
++ volatile uint64_t PendingArgs[6];
++ volatile uint64_t PendingRet;
++ volatile uint64_t Regs[NumUserRegs];
++ volatile uint64_t DebugRegs[8];
++ volatile uint64_t DirtyMask;
++ volatile uint64_t SignalNumber;
++ volatile uint64_t FlushAddr;
++ volatile uint64_t FlushLen;
++ char ExePath[1024];
++};
++
++
++bool WantsSyscallStops();
++
++uint64_t SyscallEntryStop(FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, const uint64_t Args[6]);
++
++uint64_t SyscallExitStop(FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, const uint64_t Args[6], uint64_t Result);
++
++void OnForkedChild(bool SharesAddressSpace);
++
++void ApplyPendingFlush(FEXCore::Core::CpuStateFrame* Frame);
++
++uint64_t TakePendingRip();
++
++bool TryGuestSignalStop(FEXCore::Core::CpuStateFrame* Frame, int Signal);
++
++void RecordExecPath(const std::string& GuestPath);
++
++bool IsAttached();
++
++
++bool HandleRequest(int Request, pid_t Pid, void* Addr, void* Data, uint64_t* Result);
++
++bool FixupWaitStatus(pid_t Pid, int* Status);
++
++std::optional TraceeExePath(pid_t Pid);
++
++}
+diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SMCHotPages.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SMCHotPages.h
+new file mode 100644
+index 000000000..3f36e79fd
+--- /dev/null
++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SMCHotPages.h
+@@ -0,0 +1,90 @@
++// SPDX-License-Identifier: MIT
++#pragma once
++
++#include
++#include
++#include
++#include
++
++namespace FEX::HLE {
++
++class SMCHotPageTracker final {
++public:
++ static constexpr uint64_t PageShift = 12;
++
++ bool RecordFault(uint64_t Address, uint32_t FaultThreshold) {
++ if (!FaultThreshold) {
++ return false;
++ }
++ const uint64_t Page = Address >> PageShift;
++ auto& Slot = Counters[Hash(Page) & (CounterSlots - 1)];
++
++ uint64_t Old = Slot.load(std::memory_order_relaxed);
++ uint64_t New;
++ do {
++ const uint64_t Count = (Old >> CountBits) == Page ? (Old & CountMask) + 1 : 1;
++ New = (Page << CountBits) | (Count < CountMask ? Count : CountMask);
++ } while (!Slot.compare_exchange_weak(Old, New, std::memory_order_relaxed));
++
++ return (New & CountMask) == FaultThreshold && MakeHot(Page);
++ }
++
++ bool MarkHot(uint64_t Address) {
++ return MakeHot(Address >> PageShift);
++ }
++
++ bool IsHot(uint64_t Address) const {
++ if (HotCount.load(std::memory_order_relaxed) == 0) {
++ return false;
++ }
++
++ const uint64_t Key = (Address >> PageShift) + 1;
++ for (size_t i = 0, Idx = Hash(Key - 1); i < HotSlots; ++i, ++Idx) {
++ const uint64_t Entry = Hot[Idx & (HotSlots - 1)].load(std::memory_order_relaxed);
++ if (Entry == Key) {
++ return true;
++ }
++ if (Entry == 0) {
++ return false;
++ }
++ }
++ return false;
++ }
++
++private:
++ static constexpr size_t CounterSlots = 4096;
++ static constexpr size_t HotSlots = 2048;
++ static constexpr unsigned CountBits = 20;
++ static constexpr uint64_t CountMask = (1ULL << CountBits) - 1;
++ static_assert((CounterSlots & (CounterSlots - 1)) == 0 && (HotSlots & (HotSlots - 1)) == 0);
++
++ static size_t Hash(uint64_t Page) {
++ return static_cast((Page * 0x9E3779B97F4A7C15ULL) >> 40);
++ }
++
++ bool MakeHot(uint64_t Page) {
++ if (HotCount.load(std::memory_order_relaxed) >= HotSlots / 4 * 3) {
++ return false;
++ }
++
++ const uint64_t Key = Page + 1;
++ for (size_t i = 0, Idx = Hash(Page); i < HotSlots; ++i, ++Idx) {
++ auto& Entry = Hot[Idx & (HotSlots - 1)];
++ uint64_t Expected = 0;
++ if (Entry.compare_exchange_strong(Expected, Key, std::memory_order_relaxed)) {
++ HotCount.fetch_add(1, std::memory_order_relaxed);
++ return true;
++ }
++ if (Expected == Key) {
++ return false;
++ }
++ }
++ return false;
++ }
++
++ std::array, CounterSlots> Counters {};
++ std::array, HotSlots> Hot {};
++ std::atomic HotCount {};
++};
++
++}
+diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.cpp
+new file mode 100644
+index 000000000..abc3284a3
+--- /dev/null
++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.cpp
+@@ -0,0 +1,278 @@
++// SPDX-License-Identifier: MIT
++#include "LinuxSyscalls/SamplingProfiler.h"
++#include "LinuxSyscalls/SignalDelegator.h"
++#include "LinuxSyscalls/PtraceEmu.h"
++#include "ArchHelpers/MContext.h"
++
++#include
++#include
++#include
++#include
++
++#include
++#include
++#include
++#include
++#include
++#include
++#include
++#include
++#include
++#include
++#include
++#include
++#include
++
++namespace FEX::HLE {
++namespace {
++ struct Sample {
++ uint64_t HostPC;
++ uint64_t Info;
++ };
++ constexpr size_t MaxSamples = 1 << 18;
++ std::atomic RecordsPtr {nullptr};
++ Sample* Records = nullptr;
++ std::atomic Count {0};
++
++ struct SnapRecord {
++ uint64_t Tid;
++ uint64_t HostPC;
++ uint64_t Rip;
++ uint64_t FutexWord;
++ uint64_t FutexExpected;
++ uint64_t FutexAddr;
++ uint64_t Gregs[16];
++ uint64_t Stack[138];
++ };
++ static_assert(sizeof(SnapRecord) == 160 * 8);
++ constexpr size_t MaxSnaps = 1024;
++ SnapRecord* Snaps = nullptr;
++ std::atomic SnapCount {0};
++ std::atomic SnapMode {false};
++ bool ExternalMode = false;
++ FEX::HLE::SignalDelegator* Delegator = nullptr;
++ std::atomic ExternalOpen {false};
++
++ void OpenExternalSnaps() {
++ if (ExternalOpen.exchange(true)) {
++ return;
++ }
++ char Path[64];
++ snprintf(Path, sizeof(Path), "/dev/shm/fex-%d-snap", static_cast(getpid()));
++ const int fd = open(Path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
++ if (fd < 0 || ftruncate(fd, sizeof(SnapRecord) * MaxSnaps) != 0) {
++ return;
++ }
++ void* Map = mmap(nullptr, sizeof(SnapRecord) * MaxSnaps, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
++ close(fd);
++ if (Map != MAP_FAILED) {
++ Snaps = static_cast(Map);
++ }
++ }
++
++ bool IsInteresting(pid_t Tid) {
++ static thread_local std::unordered_map Last;
++ char Path[64];
++ snprintf(Path, sizeof(Path), "/proc/self/task/%d/stat", Tid);
++ FILE* F = fopen(Path, "r");
++ if (!F) {
++ return false;
++ }
++ char Buf[512];
++ const bool Ok = fgets(Buf, sizeof(Buf), F) != nullptr;
++ fclose(F);
++ if (!Ok) {
++ return false;
++ }
++ const char* P = strrchr(Buf, ')');
++ unsigned long Ut = 0, St = 0;
++ if (!P || sscanf(P + 2, "%*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu %lu", &Ut, &St) != 2) {
++ return false;
++ }
++ auto& L = Last[Tid];
++ const bool Busy = (Ut + St) > L;
++ L = Ut + St;
++ return Busy;
++ }
++
++ bool OpenRecords(pid_t Pid) {
++ if (Records) {
++ return true;
++ }
++ const std::string Path = "/dev/shm/fex-" + std::to_string(Pid) + "-samples";
++ const int fd = open(Path.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
++ if (fd < 0 || ftruncate(fd, sizeof(Sample) * MaxSamples) != 0) {
++ return false;
++ }
++ void* Map = mmap(nullptr, sizeof(Sample) * MaxSamples, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
++ close(fd);
++ if (Map == MAP_FAILED) {
++ return false;
++ }
++ Records = static_cast(Map);
++ return true;
++ }
++
++ void TakeSnapshot(pid_t Pid) {
++ if (!Snaps) {
++ const std::string Path = "/dev/shm/fex-" + std::to_string(Pid) + "-snap";
++ const int fd = open(Path.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
++ if (fd < 0 || ftruncate(fd, sizeof(SnapRecord) * MaxSnaps) != 0) {
++ return;
++ }
++ void* Map = mmap(nullptr, sizeof(SnapRecord) * MaxSnaps, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
++ close(fd);
++ if (Map == MAP_FAILED) {
++ return;
++ }
++ Snaps = static_cast(Map);
++ }
++ memset(Snaps, 0, sizeof(SnapRecord) * MaxSnaps);
++ SnapCount = 0;
++ SnapMode = true;
++ if (DIR* D = opendir("/proc/self/task")) {
++ while (auto* E = readdir(D)) {
++ const pid_t Tid = atoi(E->d_name);
++ if (Tid > 0 && Tid != static_cast(syscall(SYS_gettid))) {
++ syscall(SYS_tgkill, Pid, Tid, SIGPROF);
++ }
++ }
++ closedir(D);
++ }
++ usleep(700000);
++ SnapMode = false;
++ }
++
++ void* SamplerThread(void* Arg) {
++ const uint32_t Hz = static_cast(reinterpret_cast(Arg) & 0xffff);
++ const bool All = (reinterpret_cast(Arg) >> 16) != 0;
++ const pid_t Pid = getpid();
++ const std::string Trigger = "/dev/shm/fex-" + std::to_string(Pid) + "-sample-on";
++ const std::string SnapTrigger = "/dev/shm/fex-" + std::to_string(Pid) + "-snapshot";
++ for (;;) {
++ if (access(SnapTrigger.c_str(), F_OK) == 0) {
++ unlink(SnapTrigger.c_str());
++ TakeSnapshot(Pid);
++ continue;
++ }
++ if (access(Trigger.c_str(), F_OK) != 0) {
++ usleep(100000);
++ continue;
++ }
++ if (!OpenRecords(Pid)) {
++ usleep(100000);
++ continue;
++ }
++ usleep(1000000 / Hz);
++ if (FEX::HLE::PtraceEmu::IsAttached()) {
++ continue;
++ }
++ if (All) {
++ if (DIR* D = opendir("/proc/self/task")) {
++ while (auto* E = readdir(D)) {
++ const pid_t Tid = atoi(E->d_name);
++ if (Tid > 0 && Tid != static_cast(syscall(SYS_gettid)) && IsInteresting(Tid)) {
++ syscall(SYS_tgkill, Pid, Tid, SIGPROF);
++ }
++ }
++ closedir(D);
++ }
++ } else {
++ syscall(SYS_tgkill, Pid, Pid, SIGPROF);
++ }
++ }
++ return nullptr;
++ }
++}
++
++void StartSamplingProfiler(FEX::HLE::SignalDelegator* Signals, uint32_t Hz, bool AllThreads, bool External) {
++ if (!Hz) {
++ return;
++ }
++ ExternalMode = External;
++ Delegator = Signals;
++ Signals->RegisterHostSignalHandler(
++ SIGPROF,
++ [](FEXCore::Core::InternalThreadState* Thread, int, void*, void* UContext) {
++ if (ExternalMode) {
++ OpenExternalSnaps();
++ }
++ if (ExternalMode || SnapMode.load(std::memory_order_relaxed)) {
++ uint32_t SIdx = SnapCount.fetch_add(1, std::memory_order_relaxed);
++ const uint32_t Seq = SIdx;
++ if (ExternalMode) {
++ SIdx %= MaxSnaps;
++ }
++ if (Snaps && SIdx < MaxSnaps) {
++ SnapRecord& R = Snaps[SIdx];
++ R.Tid = static_cast(syscall(SYS_gettid));
++ R.HostPC = ArchHelpers::Context::GetPc(UContext);
++ if (Thread) {
++ const auto& St = Thread->CurrentFrame->State;
++ R.Rip = St.rip;
++ for (unsigned i = 0; i < 16; ++i) {
++ R.Gregs[i] = St.gregs[i];
++ }
++ iovec Local {R.Stack, sizeof(R.Stack)};
++ iovec Remote {reinterpret_cast(St.gregs[FEXCore::X86State::REG_RSP]), sizeof(R.Stack)};
++ process_vm_readv(getpid(), &Local, 1, &Remote, 1, 0);
++
++ const uint64_t Nr = St.gregs[FEXCore::X86State::REG_RAX];
++ if (Nr == 202 || Nr == 449) {
++ uint64_t Addr = St.gregs[FEXCore::X86State::REG_RDI];
++ uint64_t Expected = St.gregs[FEXCore::X86State::REG_RDX];
++ if (Nr == 449) {
++ uint64_t Waiter[3] {};
++ iovec WL {Waiter, sizeof(Waiter)};
++ iovec WR {reinterpret_cast(Addr), sizeof(Waiter)};
++ Addr = process_vm_readv(getpid(), &WL, 1, &WR, 1, 0) == static_cast(sizeof(Waiter)) ? Waiter[1] : 0;
++ Expected = Waiter[0];
++ }
++ uint32_t Word = 0;
++ iovec FL {&Word, sizeof(Word)};
++ iovec FR {reinterpret_cast(Addr), sizeof(Word)};
++ if (Addr && process_vm_readv(getpid(), &FL, 1, &FR, 1, 0) == static_cast(sizeof(Word))) {
++ R.FutexWord = (1ULL << 63) | Word;
++ R.FutexExpected = Expected;
++ R.FutexAddr = Addr;
++ }
++ }
++ }
++ if (ExternalMode) {
++ R.FutexWord = 0;
++ R.FutexExpected = Seq;
++ R.FutexAddr = ArchHelpers::Context::GetSp(UContext);
++ if (Thread && Thread->CTX->IsAddressInCodeBuffer(Thread, R.HostPC)) {
++ R.FutexWord = 1;
++ R.Rip = Thread->CTX->RestoreRIPFromHostPC(Thread, R.HostPC);
++ const auto& Cfg = Delegator->GetConfig();
++ for (size_t i = 0; i < Cfg.SRAGPRCount && i < 16; ++i) {
++ R.Gregs[i] = ArchHelpers::Context::GetArmReg(UContext, Cfg.SRAGPRMapping[i]);
++ }
++ iovec Local {R.Stack, sizeof(R.Stack)};
++ iovec Remote {reinterpret_cast(R.Gregs[FEXCore::X86State::REG_RSP]), sizeof(R.Stack)};
++ process_vm_readv(getpid(), &Local, 1, &Remote, 1, 0);
++ }
++ }
++ }
++ return true;
++ }
++ const uint32_t Idx = Count.fetch_add(1, std::memory_order_relaxed);
++ if (Records && Idx < MaxSamples) {
++ Records[Idx] = {ArchHelpers::Context::GetPc(UContext),
++ static_cast(static_cast(syscall(SYS_gettid))) | (Thread ? (Thread->CurrentFrame->State.rip << 32) : 0)};
++ }
++ return true;
++ },
++ true);
++
++ if (External) {
++ return;
++ }
++ pthread_t T;
++ pthread_attr_t Attr;
++ pthread_attr_init(&Attr);
++ pthread_attr_setdetachstate(&Attr, PTHREAD_CREATE_DETACHED);
++ pthread_create(&T, &Attr, SamplerThread, reinterpret_cast(static_cast(Hz | (AllThreads ? 0x10000 : 0))));
++}
++}
+diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.h
+new file mode 100644
+index 000000000..b6b433eca
+--- /dev/null
++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.h
+@@ -0,0 +1,13 @@
++// SPDX-License-Identifier: MIT
++#pragma once
++
++#include
++
++namespace FEXCore::Core {
++struct InternalThreadState;
++}
++namespace FEX::HLE {
++class SignalDelegator;
++
++void StartSamplingProfiler(FEX::HLE::SignalDelegator* Signals, uint32_t Hz, bool AllThreads, bool External = false);
++}
+diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.cpp
+index a7dcd128d..830ae3721 100644
+--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.cpp
++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.cpp
+@@ -119,6 +119,16 @@ $end_info$
+ // TRACE_syscall
+ // - ptrace unsupported
+
++#ifndef PR_SET_SYSCALL_USER_DISPATCH
++#define PR_SET_SYSCALL_USER_DISPATCH 59
++#define PR_SYS_DISPATCH_OFF 0
++#define PR_SYS_DISPATCH_ON 1
++#endif
++#ifndef SYSCALL_DISPATCH_FILTER_ALLOW
++#define SYSCALL_DISPATCH_FILTER_ALLOW 0
++#define SYSCALL_DISPATCH_FILTER_BLOCK 1
++#endif
++
+ namespace FEX::HLE {
+ uint64_t SeccompEmulator::Handle(FEXCore::Core::CpuStateFrame* Frame, uint32_t Op, uint32_t flags, void* arg) {
+ // If seccomp isn't enabled then say so.
+@@ -314,6 +324,60 @@ void SeccompEmulator::DeserializeFilters(FEXCore::Core::CpuStateFrame* Frame, in
+ close(FD);
+ }
+
++void SeccompEmulator::QueueTrapSignal(FEX::HLE::ThreadStateObject* Thread, int Code, uint32_t Errno, uint64_t PostSyscallRIP,
++ uint64_t SyscallNumber, uint32_t Arch) {
++ siginfo_t Info {
++ .si_signo = SIGSYS,
++ .si_errno = static_cast(Errno),
++ .si_code = Code,
++ };
++
++ Info.si_call_addr = reinterpret_cast(PostSyscallRIP);
++ Info.si_syscall = SyscallNumber;
++ Info.si_arch = Arch;
++
++ Thread->SeccompTrapRIP = PostSyscallRIP;
++
++ SignalDelegation->PrepareForcedGuestSignal(Thread, SIGSYS);
++ SignalDelegation->QueueSignal(::getpid(), ::gettid(), SIGSYS, &Info, true);
++}
++
++void SeccompEmulator::ForceExitSignal(FEX::HLE::ThreadStateObject* Thread, int Signal) {
++ uint64_t Mask = 1ULL << (Signal - 1);
++ SignalDelegation->GuestSigProcMask(Thread, SIG_UNBLOCK, &Mask, nullptr);
++ SignalDelegation->UninstallHostHandler(Signal);
++ FHU::Syscalls::tgkill(::getpid(), ::gettid(), Signal);
++}
++
++SeccompEmulator::ExecuteFilterResult
++SeccompEmulator::ExecuteSyscallUserDispatch(FEXCore::Core::CpuStateFrame* Frame, uint64_t JITPC, uint64_t SyscallNumber) {
++ auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame);
++ const auto& SUD = Thread->SyscallUserDispatch;
++ const uint64_t PostSyscallRIP = Thread->Thread->CTX->RestoreRIPFromHostPC(Frame->Thread, JITPC) + 2;
++
++ if (PostSyscallRIP - SUD.Offset < SUD.Length) {
++ return {false, 0};
++ }
++
++ if (SUD.Selector) {
++ uint8_t State {};
++ if (FaultSafeUserMemAccess::CopyFromUser(&State, reinterpret_cast(SUD.Selector), sizeof(State))) {
++ ForceExitSignal(Thread, SIGSEGV);
++ return {true, SyscallNumber};
++ }
++ if (State == SYSCALL_DISPATCH_FILTER_ALLOW) {
++ return {false, 0};
++ }
++ if (State != SYSCALL_DISPATCH_FILTER_BLOCK) {
++ ForceExitSignal(Thread, SIGSYS);
++ return {true, SyscallNumber};
++ }
++ }
++
++ QueueTrapSignal(Thread, 2 , 0, PostSyscallRIP, SyscallNumber, Is64BitMode() ? AUDIT_ARCH_X86_64 : AUDIT_ARCH_I386);
++ return {true, SyscallNumber};
++}
++
+ SeccompEmulator::ExecuteFilterResult
+ SeccompEmulator::ExecuteFilter(FEXCore::Core::CpuStateFrame* Frame, uint64_t JITPC, FEX::HLE::SyscallArguments* Args) {
+ if (!HasFilter(Frame)) {
+@@ -330,6 +394,8 @@ SeccompEmulator::ExecuteFilter(FEXCore::Core::CpuStateFrame* Frame, uint64_t JIT
+ ::prctl(PR_SET_NO_NEW_PRIVS, 1L, 0, 0, 0);
+ }
+
++ const uint64_t PostSyscallRIP = RIP + 2;
++
+ const auto Arch = Is64BitMode() ? AUDIT_ARCH_X86_64 : AUDIT_ARCH_I386;
+ bool ShouldLog {};
+ uint32_t SeccompResult {};
+@@ -425,18 +491,9 @@ SeccompEmulator::ExecuteFilter(FEXCore::Core::CpuStateFrame* Frame, uint64_t JIT
+ break;
+ }
+ case SECCOMP_RET_TRAP: {
+- siginfo_t Info {
+- .si_signo = SIGSYS,
+- .si_errno = static_cast(DataMasked),
+- .si_code = 1, // SYS_SECCOMP
+- };
+-
+- Info.si_call_addr = reinterpret_cast(RIP);
+- Info.si_syscall = Args->Argument[0];
+- Info.si_arch = Arch;
++ QueueTrapSignal(Thread, 1 , DataMasked, PostSyscallRIP, Args->Argument[0], Arch);
+
+- SignalDelegation->QueueSignal(::getpid(), ::gettid(), SIGSYS, &Info, true);
+- break;
++ return {true, Args->Argument[0]};
+ }
+ case SECCOMP_RET_ERRNO: {
+ // errno return is clamped.
+@@ -671,7 +728,8 @@ uint64_t SeccompEmulator::SetModeFilter(FEXCore::Core::CpuStateFrame* Frame, uin
+ return -EINVAL;
+ }
+
+- if (!prog) {
++ sock_fprog UserProg;
++ if (FaultSafeUserMemAccess::CopyFromUser(&UserProg, prog, sizeof(UserProg))) {
+ return -EFAULT;
+ }
+
+@@ -680,12 +738,22 @@ uint64_t SeccompEmulator::SetModeFilter(FEXCore::Core::CpuStateFrame* Frame, uin
+ return -EACCES;
+ }
+
+- if (prog->len > BPF_MAXINSNS || prog->len == 0) {
++ if (UserProg.len > BPF_MAXINSNS || UserProg.len == 0) {
+ // operation specified SECCOMP_SET_MODE_FILTER, but the filter program pointed to by args was not valid or the length of the filter
+ // program was zero or exceeded BPF_MAXINSNS (4096) instructions.
+ return -EINVAL;
+ }
+
++ fextl::vector Instructions(UserProg.len);
++ if (FaultSafeUserMemAccess::CopyFromUser(Instructions.data(), UserProg.filter, UserProg.len * sizeof(sock_filter))) {
++ return -EFAULT;
++ }
++ const sock_fprog LocalProg {
++ .len = UserProg.len,
++ .filter = Instructions.data(),
++ };
++ prog = &LocalProg;
++
+ // Don't interrupt me while I'm jitting.
+ auto lk = FEXCore::MaskSignalsAndLockMutex(FilterMutex);
+
+diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.h
+index a4c7b70e0..31b489216 100644
+--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.h
++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.h
+@@ -61,6 +61,8 @@ public:
+ };
+ ExecuteFilterResult ExecuteFilter(FEXCore::Core::CpuStateFrame* Frame, uint64_t JITPC, FEX::HLE::SyscallArguments* Args);
+
++ ExecuteFilterResult ExecuteSyscallUserDispatch(FEXCore::Core::CpuStateFrame* Frame, uint64_t JITPC, uint64_t SyscallNumber);
++
+ bool HasFilter(FEXCore::Core::CpuStateFrame* Frame) const {
+ auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame);
+ return !Thread->Filters.empty();
+@@ -101,6 +103,9 @@ private:
+ const sock_fprog* GetStrictModeFilter() const;
+ void KillProcess(ThreadStateObject* Thread);
+ void KillThread(FEXCore::Core::CpuStateFrame* Thread);
++ void QueueTrapSignal(FEX::HLE::ThreadStateObject* Thread, int Code, uint32_t Errno, uint64_t PostSyscallRIP, uint64_t SyscallNumber,
++ uint32_t Arch);
++ void ForceExitSignal(FEX::HLE::ThreadStateObject* Thread, int Signal);
+
+ // Multiple filter instruction count penalty.
+ // When multiple filters are installed there is a penalty per filter counted towards the maximum number of instructions.
+diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
+index e8e04b056..87b890e19 100644
+--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
+@@ -8,6 +8,8 @@ $end_info$
+
+ #include "LinuxSyscalls/SignalDelegator.h"
+ #include "LinuxSyscalls/Syscalls.h"
++#include "LinuxSyscalls/PtraceEmu.h"
++#include "LinuxSyscalls/SignalTrace.h"
+
+ #include
+ #include
+@@ -219,6 +221,10 @@ ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore::
+ Context->UContextLocation = 0;
+ Context->SigInfoLocation = 0;
+ Context->InSyscallInfo = 0;
++ Context->ClearedSyscallInfo = 0;
++ Context->GuestSignalMask = 0;
++ Context->SeccompTrapRIP = 0;
++ Context->SavedJITStackSP = 0;
+
+ // Store fault to top status and then reset it
+ Context->FaultToTopAndGeneratedException = Thread->CurrentFrame->SynchronousFaultData.FaultToTopAndGeneratedException;
+@@ -227,6 +233,8 @@ ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore::
+ return Context;
+ }
+
++static void CheckForPendingSignals(const FEX::HLE::ThreadStateObject* Thread);
++
+ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thread, void* ucontext, RestoreType Type) {
+ uint64_t OldSP {};
+ if (Type == RestoreType::TYPE_PAUSE) [[unlikely]] {
+@@ -315,8 +323,36 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
+ uintptr_t NewSP = OldSP;
+ auto Context = reinterpret_cast(NewSP);
+
++ if (Type != RestoreType::TYPE_PAUSE) {
++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread);
++ for (size_t i = ThreadObject->TrapSignalFrameCount; i > 0; --i) {
++ if (ThreadObject->TrapSignalFrames[i - 1].ContextBackup == NewSP) {
++ ThreadObject->TrapSignalFrameCount = i - 1;
++ break;
++ }
++ }
++ }
++
+ // Restore host state
+ ArchHelpers::Context::RestoreContext(ucontext, Context);
++ Thread->CurrentFrame->InSyscallInfo = ArchHelpers::Context::SavedSyscallInfo(Context);
++
++ {
++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread);
++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::SigReturn, 0, Thread->CurrentFrame->State.gregs[FEXCore::X86State::REG_RSP],
++ Context->GuestSignalMask);
++ if (Type != RestoreType::TYPE_PAUSE && SignalMaskFix()) {
++ uint64_t NewGuestMask = Context->GuestSignalMask;
++ if (Is64BitMode && Context->UContextLocation) {
++ auto* GuestUContext = reinterpret_cast(Context->UContextLocation);
++ NewGuestMask = GuestUContext->uc_sigmask.val[0] & ~((1ULL << (SIGKILL - 1)) | (1ULL << (SIGSTOP - 1)));
++ }
++ ThreadObject->SignalInfo.CurrentSignalMask.Val = NewGuestMask;
++ CheckForPendingSignals(ThreadObject);
++ }
++ }
++
++ FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->JITStackSP = Context->SavedJITStackSP;
+
+ // Reset the guest state
+ memcpy(&Thread->CurrentFrame->State, &Context->GuestState, sizeof(FEXCore::Core::CPUState));
+@@ -327,7 +363,7 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
+ // XXX: Unsupported since it needs state reconstruction
+ // If we are in the JIT then SRA might need to be restored to values from the context
+ // We can't currently support this since it might result in tearing without real state reconstruction
+- Frame->InSyscallInfo = Context->InSyscallInfo;
++ Frame->InSyscallInfo = ArchHelpers::Context::SavedSyscallInfo(Context);
+
+ if (Is64BitMode) {
+ RestoreFrame_x64(Thread, Context, Frame, ucontext);
+@@ -343,7 +379,36 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
+
+ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadState* Thread, int Signal, void* info, void* ucontext,
+ GuestSigAction* GuestAction, stack_t* GuestStack) {
++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread);
++
++ const int SigSysCode = Signal == SIGSYS ? static_cast(info)->si_code : 0;
++ const bool IsTrapSignal = (SigSysCode == 1 || SigSysCode == 2 ) && ThreadObject->SeccompTrapRIP &&
++ !CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext));
++ if (IsTrapSignal) {
++ const uint64_t GuestRSP = Thread->CurrentFrame->State.gregs[FEXCore::X86State::REG_RSP];
++ while (ThreadObject->TrapSignalFrameCount) {
++ const auto& Abandoned = ThreadObject->TrapSignalFrames[ThreadObject->TrapSignalFrameCount - 1];
++ if (GuestRSP <= Abandoned.GuestFrame || GuestRSP < Abandoned.GuestRSP) {
++ break;
++ }
++ ThreadObject->JITStackSP = Abandoned.JITStackSP;
++ --ThreadObject->TrapSignalFrameCount;
++ --Thread->CurrentFrame->SignalHandlerRefCounter;
++ }
++ const uint64_t Level = ThreadObject->JITStackSP ? ThreadObject->JITStackSP : Thread->CurrentFrame->ReturningStackLocation;
++ if (Level > ArchHelpers::Context::GetSp(ucontext)) {
++ ArchHelpers::Context::SetSp(ucontext, Level);
++ }
++ }
++
+ auto ContextBackup = StoreThreadState(Thread, Signal, ucontext);
++ ContextBackup->GuestSignalMask = ThreadObject->SignalInfo.CurrentSignalMask.Val;
++
++ if (SigSysCode == 1 || SigSysCode == 2 ) {
++ ContextBackup->SeccompTrapRIP = ThreadObject->SeccompTrapRIP;
++ ThreadObject->SeccompTrapRIP = 0;
++ }
++ ContextBackup->SavedJITStackSP = ThreadObject->JITStackSP;
+
+ auto Frame = Thread->CurrentFrame;
+ auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo;
+@@ -382,8 +447,13 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
+ ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo;
+ Thread->CurrentFrame->InSyscallInfo = 0;
+ } else {
+- ContextBackup->InSyscallInfo = Frame->InSyscallInfo;
+- Frame->InSyscallInfo = 0;
++ ThreadObject->JITStackSP = ArchHelpers::Context::GetSp(ucontext);
++
++ if (Thread->CurrentFrame->InSyscallInfo != 0) {
++ ContextBackup->ClearedSyscallInfo = Thread->CurrentFrame->InSyscallInfo;
++ ContextBackup->Flags |= ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_SYSCALLINFO_CLEARED;
++ Thread->CurrentFrame->InSyscallInfo = 0;
++ }
+
+ if (!IsAddressInDispatcher(OldPC)) {
+ // This is likely to cause issues but in some cases it isn't fatal
+@@ -462,6 +532,14 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
+
+ if (Is64BitMode) {
+ NewGuestSP = SetupFrame_x64(Thread, ContextBackup, Frame, Signal, HostSigInfo, ucontext, GuestAction, GuestStack, NewGuestSP, eflags);
++ if (IsTrapSignal && ThreadObject->TrapSignalFrameCount < ThreadObject->MaxTrapSignalFrames) {
++ ThreadObject->TrapSignalFrames[ThreadObject->TrapSignalFrameCount++] = {
++ .GuestFrame = NewGuestSP,
++ .GuestRSP = OldGuestSP,
++ .JITStackSP = ContextBackup->SavedJITStackSP,
++ .ContextBackup = reinterpret_cast(ContextBackup),
++ };
++ }
+ } else {
+ const bool SigInfoFrame = (GuestAction->sa_flags & SA_SIGINFO) == SA_SIGINFO;
+ if (SigInfoFrame) {
+@@ -483,8 +561,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
+ // This way signal handlers always go back to their original operating mode.
+ // Doesn't matter for 32-bit processes as they can only be 32-bit, but does
+ // matter for 64-bit processes as they could have potentially installed a 32-bit code segment.
+- Frame->State.cs_idx = FEXCore::Core::CPUState::DEFAULT_USER_CS << 3;
+- Frame->State.ss_idx = 0;
++ Frame->State.cs_idx = Is64BitMode ? FEXCore::Core::CPUState::DEFAULT_USER_CS_SEL : FEXCore::Core::CPUState::DEFAULT_USER32_CS_SEL;
++ Frame->State.ss_idx = FEXCore::Core::CPUState::DEFAULT_USER_DS_SEL;
+ Frame->State.cs_cached = Frame->State.CalculateGDTBase(*Frame->State.GetSegmentFromIndex(Frame->State, Frame->State.cs_idx));
+ Frame->State.ss_cached = Frame->State.CalculateGDTBase(*Frame->State.GetSegmentFromIndex(Frame->State, Frame->State.ss_idx));
+
+@@ -690,7 +768,7 @@ bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState*
+ auto SigInfo = *static_cast(Info);
+
+ if (FaultSafeUserMemAccess::TryHandleSafeFault(Signal, SigInfo, UContext)) {
+- ERROR_AND_DIE_FMT("Received invalid data to syscall. Crashing now!");
++ return true;
+ }
+
+ #ifdef ARCHITECTURE_arm64
+@@ -714,10 +792,21 @@ bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState*
+
+ void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObject, int Signal, void* Info, void* UContext) {
+ auto Thread = ThreadObject->Thread;
++
++ if (PtraceEmu::TryGuestSignalStop(Thread->CurrentFrame, Signal)) {
++ Thread->CurrentFrame->SynchronousFaultData.FaultToTopAndGeneratedException = false;
++ ArchHelpers::Context::SetPc(UContext, Config.AbsoluteLoopTopAddressFillSRA);
++ ArchHelpers::Context::SetFillSRASingleInst(UContext, false);
++ ArchHelpers::Context::SetState(UContext, reinterpret_cast(Thread->CurrentFrame));
++ return;
++ }
++
+ ucontext_t* _context = (ucontext_t*)UContext;
+ auto SigInfo = *static_cast(Info);
+
+ auto MustDeferSignal = (Thread->CurrentFrame->State.DeferredSignalRefCount.Load() != 0);
++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::HostArrive, Signal, ThreadObject->SignalInfo.CurrentSignalMask.Val,
++ (static_cast(MustDeferSignal) << 32) | static_cast(SigInfo.si_code));
+ if (Signal == SIGSEGV && SigInfo.si_code == SEGV_ACCERR && SigInfo.si_addr == reinterpret_cast(&Thread->InterruptFaultPage)) {
+ if (!MustDeferSignal) {
+ // We just reached the end of the outermost signal-deferring section and faulted to check for pending signals.
+@@ -781,6 +870,8 @@ void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObjec
+ // This allows us to maintain the expected signal mask through the guest signal handling and then all the way back again
+ sigmask_val[0] = GetNewSigMask(Signal);
+
++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::Deferred, Signal, 0, 0);
++
+ // Now update the faulting page permissions so it will fault on write.
+ mprotect(reinterpret_cast(&Thread->InterruptFaultPage), sizeof(Thread->InterruptFaultPage), PROT_NONE);
+
+@@ -793,6 +884,7 @@ void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObjec
+ // This signal is masked, must defer until the guest updates the signal mask.
+ // Add it to the pending signal list
+ ThreadObject->SignalInfo.PendingSignals |= 1ULL << (Signal - 1);
++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::Masked, Signal, ThreadObject->SignalInfo.CurrentSignalMask.Val, ThreadObject->SignalInfo.PendingSignals);
+ return;
+ }
+
+@@ -814,6 +906,21 @@ void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObjec
+ if (Handler.GuestHandler &&
+ Handler.GuestHandler(Thread, Signal, &SigInfo, UContext, &Handler.GuestAction, &ThreadObject->SignalInfo.GuestAltStack)) {
+ uint64_t NewMask = GetNewSigMask(Signal);
++ if (SignalMaskFix()) {
++ uint64_t GuestNew = ThreadObject->SignalInfo.CurrentSignalMask.Val | Handler.GuestAction.sa_mask.Val;
++ if (!(Handler.GuestAction.sa_flags & SA_NODEFER)) {
++ GuestNew |= 1ULL << (Signal - 1);
++ }
++ GuestNew &= ~((1ULL << (SIGKILL - 1)) | (1ULL << (SIGSTOP - 1)));
++ ThreadObject->SignalInfo.CurrentSignalMask.Val = GuestNew;
++ NewMask = GuestNew;
++ for (size_t i = 0; i < MAX_SIGNALS; ++i) {
++ if (HostHandlers[i + 1].Required.load(std::memory_order_relaxed)) {
++ NewMask &= ~(1ULL << i);
++ }
++ }
++ }
++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::Delivered, Signal, reinterpret_cast(Handler.GuestAction.sigaction_handler.sigaction), NewMask);
+
+ // Update our host signal mask so we don't hit race conditions with signals
+ // This allows us to maintain the expected signal mask through the guest signal handling and then all the way back again
+@@ -961,6 +1068,30 @@ void SignalDelegator::UninstallHostHandler(int Signal) {
+ ::syscall(SYS_rt_sigaction, Signal, &SignalHandler.OldAction, nullptr, 8);
+ }
+
++void SignalDelegator::ForceGuestSigSegv(uint64_t BadSP) {
++ static std::atomic Logged {false};
++ if (!Logged.exchange(true, std::memory_order_relaxed)) {
++ LogMan::Msg::EFmt("Cannot write the guest signal frame at stack pointer 0x{:x}; forcing SIGSEGV "
++ "(Linux force_sigsegv). The guest stack pointer is not a live, writable mapping.",
++ BadSP);
++ }
++
++ SignalHandler& Handler = HostHandlers[SIGSEGV];
++ Handler.GuestAction.sigaction_handler.handler = SIG_DFL;
++ Handler.OldAction.handler = SIG_DFL;
++ ::signal(SIGSEGV, SIG_DFL);
++
++ CTX->FlushAndCloseCodeMap();
++ FEX::HLE::_SyscallHandler->TM.CleanupForExit();
++
++ uint64_t SegvMask = 1ULL << (SIGSEGV - 1);
++ ::syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, &SegvMask, nullptr, 8);
++ ::raise(SIGSEGV);
++
++ ::syscall(SYS_exit, 128 + SIGSEGV);
++ FEX_UNREACHABLE;
++}
++
+ void SignalDelegator::QueueSignal(pid_t tgid, pid_t tid, int Signal, siginfo_t* info, bool IgnoreMask) {
+ bool WasIgnored {};
+ bool WasMasked {};
+@@ -995,11 +1126,34 @@ void SignalDelegator::QueueSignal(pid_t tgid, pid_t tid, int Signal, siginfo_t*
+ }
+ }
+
++void SignalDelegator::PrepareForcedGuestSignal(FEX::HLE::ThreadStateObject* Thread, int Signal) {
++ const uint64_t SignalMask = 1ULL << (Signal - 1);
++ const bool Blocked = Thread->SignalInfo.CurrentSignalMask.Val & SignalMask;
++
++ GuestSigAction Action {};
++ RegisterGuestSignalHandler(Signal, nullptr, &Action);
++ const bool Ignored = Action.sigaction_handler.handler == SIG_IGN;
++
++ if (!Blocked && !Ignored) {
++ return;
++ }
++
++ Action.sigaction_handler.handler = SIG_DFL;
++ RegisterGuestSignalHandler(Signal, &Action, nullptr);
++ if (Blocked) {
++ GuestSigProcMask(Thread, SIG_UNBLOCK, &SignalMask, nullptr);
++ }
++}
++
+ SignalDelegator::SignalDelegator(FEXCore::Context::Context* _CTX, const std::string_view ApplicationName, bool SupportsAVX, bool SupportsSVE256)
+ : CTX {_CTX}
+ , ApplicationName {ApplicationName}
+ , SupportsAVX {SupportsAVX}
+ , SupportsSVE256 {SupportsSVE256} {
++ if (SignalTrace()) {
++ SigTrace::Init();
++ }
++
+ // Signal zero isn't real
+ HostHandlers[0].Installed = true;
+
+@@ -1162,23 +1316,36 @@ void SignalDelegator::RegisterTLSState(FEX::HLE::ThreadStateObject* Thread) {
+ }
+ }
+
+-void SignalDelegator::UninstallTLSState(FEX::HLE::ThreadStateObject* Thread) {
+- FEXCore::Allocator::munmap(Thread->SignalInfo.AltStackPtr, SIGSTKSZ * 16);
+-
+- Thread->SignalInfo.AltStackPtr = nullptr;
+-
++void SignalDelegator::ReleaseAltStack(FEX::HLE::ThreadStateObject* Thread) {
+ stack_t altstack {};
+ altstack.ss_flags = SS_DISABLE;
+-
+- // Uninstall the alt stack
+ const int Result = sigaltstack(&altstack, nullptr);
+ if (Result == -1) {
+ LogMan::Msg::EFmt("Failed to uninstall alternative signal stack {}", strerror(errno));
+ }
+
++ FEXCore::Allocator::munmap(Thread->SignalInfo.AltStackPtr, SIGSTKSZ * 16);
++ Thread->SignalInfo.AltStackPtr = nullptr;
++ Thread->SignalInfo.AltStackReleaseDeferred = false;
++}
++
++void SignalDelegator::UninstallTLSState(FEX::HLE::ThreadStateObject* Thread) {
++ stack_t Current {};
++ if (sigaltstack(nullptr, &Current) == 0 && (Current.ss_flags & SS_ONSTACK)) {
++ Thread->SignalInfo.AltStackReleaseDeferred = true;
++ } else {
++ ReleaseAltStack(Thread);
++ }
++
+ FEXCore::Allocator::UninstallTLSData(Thread->Thread);
+ }
+
++void SignalDelegator::ReleaseDeferredTLSState(FEX::HLE::ThreadStateObject* Thread) {
++ if (Thread->SignalInfo.AltStackReleaseDeferred) {
++ ReleaseAltStack(Thread);
++ }
++}
++
+ void SignalDelegator::FrontendRegisterHostSignalHandler(int Signal, bool Required) {
+ // Linux signal handlers are per-process rather than per thread
+ // Multiple threads could be calling in to this
+@@ -1321,6 +1488,7 @@ static void CheckForPendingSignals(const FEX::HLE::ThreadStateObject* Thread) {
+ if (PendingSignals != 0) {
+ for (int i = 0; i < 64; ++i) {
+ if (PendingSignals & (1ULL << i)) {
++ SigTrace::Log(Thread->ThreadInfo.TID, SigTrace::Reraise, i + 1, Thread->SignalInfo.CurrentSignalMask.Val, Thread->SignalInfo.PendingSignals);
+ FHU::Syscalls::tgkill(Thread->ThreadInfo.PID, Thread->ThreadInfo.TID, i + 1);
+ // We might not even return here which is spooky
+ }
+@@ -1361,6 +1529,9 @@ uint64_t SignalDelegator::GuestSigProcMask(FEX::HLE::ThreadStateObject* Thread,
+ }
+
+ ::syscall(SYS_rt_sigprocmask, SIG_SETMASK, &HostMask, nullptr, 8);
++ if (Thread->Thread->CurrentFrame->SignalHandlerRefCounter != 0) {
++ SigTrace::Log(Thread->ThreadInfo.TID, SigTrace::ProcMask, how, *set, Thread->SignalInfo.CurrentSignalMask.Val);
++ }
+ }
+
+ if (oldset) {
+diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
+index 43898e700..0d5b5597d 100644
+--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
+@@ -65,6 +65,8 @@ public:
+
+ void RegisterTLSState(FEX::HLE::ThreadStateObject* Thread);
+ void UninstallTLSState(FEX::HLE::ThreadStateObject* Thread);
++ void ReleaseDeferredTLSState(FEX::HLE::ThreadStateObject* Thread);
++ void ReleaseAltStack(FEX::HLE::ThreadStateObject* Thread);
+
+ /**
+ * @brief Registers a signal handler for the host to handle a signal
+@@ -109,6 +111,10 @@ public:
+ void UninstallHostHandler(int Signal);
+ void QueueSignal(pid_t tgid, pid_t tid, int Signal, siginfo_t* info, bool IgnoreMask);
+
++ void PrepareForcedGuestSignal(FEX::HLE::ThreadStateObject* Thread, int Signal);
++
++ [[noreturn]] void ForceGuestSigSegv(uint64_t BadSP);
++
+ void SetVDSOSymbols() {
+ // Get symbols from VDSO.
+ VDSOPointers = FEX::VDSO::GetVDSOSymbols();
+@@ -187,6 +193,8 @@ private:
+ FEXCore::Context::Context* CTX;
+
+ FEX_CONFIG_OPT(Is64BitMode, IS64BIT_MODE);
++ FEX_CONFIG_OPT(SignalMaskFix, SIGNALMASKFIX);
++ FEX_CONFIG_OPT(SignalTrace, SIGNALTRACE);
+ const fextl::string ApplicationName;
+ FEX_CONFIG_OPT(HalfBarrierTSOEnabled, HALFBARRIERTSOENABLED);
+
+diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
+index 38dc524f1..d0bcdbecb 100644
+--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
+@@ -7,6 +7,7 @@ $end_info$
+ */
+
+ #include "LinuxSyscalls/SignalDelegator.h"
++#include "LinuxSyscalls/Syscalls.h"
+
+ #include
+ #include
+@@ -14,11 +15,15 @@ $end_info$
+ #include