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 + #include + #include ++#include + ++#include + #include + #include + #include + #include ++#include ++#include + + namespace FEX::HLE { + constexpr uint32_t X86_SA_RESTORER = 0x04000000; +@@ -106,26 +111,42 @@ template + static void SetXStateInfo(T* xstate, bool is_avx_enabled) { + auto* fpstate = &xstate->fpstate; + +- fpstate->sw_reserved.magic1 = is_avx_enabled ? FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_1 : 0; +- fpstate->sw_reserved.extended_size = is_avx_enabled ? sizeof(T) : 0; ++ fpstate->sw_reserved.magic1 = FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_1; + + fpstate->sw_reserved.xfeatures |= FEXCore::x86_64::fpx_sw_bytes::FEATURE_FP | FEXCore::x86_64::fpx_sw_bytes::FEATURE_SSE; + if (is_avx_enabled) { + fpstate->sw_reserved.xfeatures |= FEXCore::x86_64::fpx_sw_bytes::FEATURE_YMM; + } + +- fpstate->sw_reserved.xstate_size = fpstate->sw_reserved.extended_size; ++ if constexpr (std::is_same_v) { ++ if (!is_avx_enabled) { ++ fpstate->sw_reserved.xstate_size = sizeof(FEXCore::x86_64::_libc_fpstate); ++ fpstate->sw_reserved.extended_size = sizeof(FEXCore::x86_64::_libc_fpstate) + sizeof(uint32_t); ++ return; ++ } + +- if (is_avx_enabled) { +- xstate->xstate_hdr.xfeatures = 0; +- xstate->magic2.magic = FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_2; ++ const uint32_t UserSize = offsetof(FEXCore::x86_64::xstate, ymmh) + sizeof(FEXCore::x86_64::ymmh_state); ++ fpstate->sw_reserved.xstate_size = UserSize; ++ fpstate->sw_reserved.extended_size = UserSize + sizeof(uint32_t); ++ ++ xstate->xstate_hdr.xfeatures = fpstate->sw_reserved.xfeatures; ++ ++ *reinterpret_cast(reinterpret_cast(fpstate) + UserSize) = ++ FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_2; ++ } else { ++ fpstate->sw_reserved.extended_size = is_avx_enabled ? sizeof(T) : 0; ++ fpstate->sw_reserved.xstate_size = fpstate->sw_reserved.extended_size; ++ if (is_avx_enabled) { ++ xstate->xstate_hdr.xfeatures = 0; ++ xstate->magic2.magic = FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_2; ++ } + } + } + + void SignalDelegator::ResumeWithGuestGPRs(ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext, + const uint64_t* GuestGPRs, size_t Count, uint64_t Mask) { + #ifdef ARCHITECTURE_arm64 +- const uint32_t Spilled = Context->InSyscallInfo & 0xFFFF; ++ const uint32_t Spilled = ArchHelpers::Context::SavedSyscallInfo(Context) & 0xFFFF; + const bool AllSpilled = Spilled == 0xFFFF; + if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { + return; +@@ -153,14 +174,19 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa + auto* guest_uctx = reinterpret_cast(Context->UContextLocation); + [[maybe_unused]] auto* guest_siginfo = reinterpret_cast(Context->SigInfoLocation); + +- // If the guest modified the RIP then we need to take special precautions here +- if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) { ++ CTX->SetFlagsFromCompactedEFLAGS(Thread, guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_EFL]); ++ ++ if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException || ++ Context->SeccompTrapRIP) { + + // Restore previous `InSyscallInfo` structure. + Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it ++ if (!(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { ++ ArchHelpers::Context::SetSp(ucontext, Context->SavedJITStackSP ? Context->SavedJITStackSP : Frame->ReturningStackLocation); ++ } + ArchHelpers::Context::SetPc(ucontext, Config.AbsoluteLoopTopAddressFillSRA); + ArchHelpers::Context::SetFillSRASingleInst(ucontext, false); + // Set our state register to point to our guest thread data +@@ -176,9 +202,6 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa + 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)); + +- // XXX: Full context setting +- CTX->SetFlagsFromCompactedEFLAGS(Thread, guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_EFL]); +- + #define COPY_REG(x) Frame->State.gregs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x]; + COPY_REG(R8); + COPY_REG(R9); +@@ -256,12 +279,15 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre + FEXCore::Core::CpuStateFrame* Frame, void* ucontext) { + SigFrame_i32* guest_uctx = reinterpret_cast(Context->UContextLocation); + // If the guest modified the RIP then we need to take special precautions here +- if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException) { ++ if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException || Context->SeccompTrapRIP) { + // Restore previous `InSyscallInfo` structure. + Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it ++ if (!(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { ++ ArchHelpers::Context::SetSp(ucontext, Context->SavedJITStackSP ? Context->SavedJITStackSP : Frame->ReturningStackLocation); ++ } + ArchHelpers::Context::SetPc(ucontext, Config.AbsoluteLoopTopAddressFillSRA); + ArchHelpers::Context::SetFillSRASingleInst(ucontext, false); + // Set our state register to point to our guest thread data +@@ -345,13 +371,17 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th + FEXCore::Core::CpuStateFrame* Frame, void* ucontext) { + RTSigFrame_i32* guest_uctx = reinterpret_cast(Context->UContextLocation); + // If the guest modified the RIP then we need to take special precautions here +- if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) { ++ if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException || ++ Context->SeccompTrapRIP) { + + // Restore previous `InSyscallInfo` structure. + Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it ++ if (!(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { ++ ArchHelpers::Context::SetSp(ucontext, Context->SavedJITStackSP ? Context->SavedJITStackSP : Frame->ReturningStackLocation); ++ } + ArchHelpers::Context::SetPc(ucontext, Config.AbsoluteLoopTopAddressFillSRA); + ArchHelpers::Context::SetFillSRASingleInst(ucontext, false); + // Set our state register to point to our guest thread data +@@ -431,9 +461,42 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th + } + } + ++static bool GuestFrameWritable(uint64_t Begin, uint64_t End) { ++ if (End < Begin) { ++ return false; ++ } ++ ++ auto& VMATracking = FEX::HLE::_SyscallHandler->VMATracking; ++ ++ constexpr uint64_t PageSize = 4096; ++ constexpr uint64_t MaxPages = 4096; ++ const uint64_t FirstPage = Begin & ~(PageSize - 1); ++ const uint64_t LastPage = End & ~(PageSize - 1); ++ ++ auto lk = FEXCore::MaskSignalsAndLockMutex(VMATracking.Mutex); ++ ++ for (uint64_t Page = FirstPage, PageCount = 0; Page <= LastPage; Page += PageSize, ++PageCount) { ++ if (PageCount >= MaxPages) { ++ return false; ++ } ++ ++ const auto Entry = VMATracking.FindVMAEntry(Page); ++ if (Entry == VMATracking.VMAs.end()) { ++ return false; ++ } ++ ++ if (!Entry->second.Prot.Writable || (Entry->first + Entry->second.Length) < (Page + PageSize)) { ++ return false; ++ } ++ } ++ ++ return true; ++} ++ + uint64_t SignalDelegator::SetupFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* ContextBackup, + FEXCore::Core::CpuStateFrame* Frame, int Signal, siginfo_t* HostSigInfo, void* ucontext, + GuestSigAction* GuestAction, stack_t* GuestStack, uint64_t NewGuestSP, const uint32_t eflags) { ++ const uint64_t RequestedGuestSP = NewGuestSP; + + // Back up past the redzone, which is 128bytes + // 32-bit doesn't have a redzone +@@ -475,6 +538,16 @@ uint64_t SignalDelegator::SetupFrame_x64(FEXCore::Core::InternalThreadState* Thr + ContextBackup->UContextLocation = UContextLocation; + ContextBackup->SigInfoLocation = SigInfoLocation; + ++ const uint64_t UContextEnd = UContextLocation + sizeof(FEXCore::x86_64::ucontext_t); ++ const uint64_t FPStateEnd = ++ FPStateLocation + (SupportsAVX ? sizeof(FEXCore::x86_64::xstate) : sizeof(FEXCore::x86_64::_libc_fpstate)); ++ const uint64_t HostStackEnd = HostStackLocation + sizeof(uint64_t); ++ const uint64_t FrameEnd = std::max({UContextEnd, FPStateEnd, HostStackEnd}); ++ ++ if (!GuestFrameWritable(UContextLocation, FrameEnd)) { ++ ForceGuestSigSegv(RequestedGuestSP); ++ } ++ + FEXCore::x86_64::ucontext_t* guest_uctx = reinterpret_cast(UContextLocation); + siginfo_t* guest_siginfo = reinterpret_cast(SigInfoLocation); + // Store where the host context lives in the guest stack. +@@ -488,7 +561,8 @@ uint64_t SignalDelegator::SetupFrame_x64(FEXCore::Core::InternalThreadState* Thr + auto* xstate = reinterpret_cast(FPStateLocation); + SetXStateInfo(xstate, SupportsAVX); + +- guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] = ContextBackup->OriginalRIP; ++ guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] = ++ ContextBackup->SeccompTrapRIP ? ContextBackup->SeccompTrapRIP : ContextBackup->OriginalRIP; + guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_EFL] = eflags; + // This stores the CS/GS/FS selectors. It ALSO stores the SS selector in the top 16 bits...For some reason. + // Despite the naming, the endianness is swapped from what you'd expect. +@@ -568,6 +642,9 @@ uint64_t SignalDelegator::SetupFrame_x64(FEXCore::Core::InternalThreadState* Thr + guest_uctx->uc_stack.ss_sp = GuestStack->ss_sp; + guest_uctx->uc_stack.ss_size = GuestStack->ss_size; + ++ memset(guest_uctx->uc_sigmask.val, 0, sizeof(guest_uctx->uc_sigmask.val)); ++ guest_uctx->uc_sigmask.val[0] = ContextBackup->GuestSignalMask; ++ + // Apparently RAX is always set to zero in case of badly misbehaving C applications and variadics. + Frame->State.gregs[FEXCore::X86State::REG_RAX] = 0; + Frame->State.gregs[FEXCore::X86State::REG_RDI] = Signal; +@@ -643,7 +720,7 @@ uint64_t SignalDelegator::SetupFrame_ia32(FEXCore::Core::InternalThreadState* Th + guest_uctx->sc.err = ConvertSignalToError(ucontext, Signal, HostSigInfo); + } + +- guest_uctx->sc.ip = ContextBackup->OriginalRIP; ++ guest_uctx->sc.ip = ContextBackup->SeccompTrapRIP ? ContextBackup->SeccompTrapRIP : ContextBackup->OriginalRIP; + guest_uctx->sc.flags = eflags; + guest_uctx->sc.sp_at_signal = 0; + +@@ -779,7 +856,8 @@ uint64_t SignalDelegator::SetupRTFrame_ia32(FEXCore::Core::InternalThreadState* + guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_ERR] = ConvertSignalToError(ucontext, Signal, HostSigInfo); + } + +- guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] = ContextBackup->OriginalRIP; ++ guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] = ++ ContextBackup->SeccompTrapRIP ? ContextBackup->SeccompTrapRIP : ContextBackup->OriginalRIP; + guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EFL] = eflags; + guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_UESP] = Frame->State.gregs[FEXCore::X86State::REG_RSP]; + guest_uctx->uc.uc_mcontext.cr2 = 0; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.cpp +new file mode 100644 +index 000000000..5db61d312 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.cpp +@@ -0,0 +1,45 @@ ++// SPDX-License-Identifier: MIT ++#include "LinuxSyscalls/SignalTrace.h" ++ ++#include ++#include ++#include ++#include ++ ++namespace FEX::HLE::SigTrace { ++Rec* Buf = nullptr; ++std::atomic Idx {0}; ++ ++namespace { ++ std::string PathFor(pid_t Pid) { ++ return "/dev/shm/fex-" + std::to_string(Pid) + "-sigtrace"; ++ } ++} ++ ++void Init() { ++ if (Buf) { ++ return; ++ } ++ const std::string Path = PathFor(getpid()); ++ const int fd = open(Path.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); ++ if (fd < 0) { ++ return; ++ } ++ if (ftruncate(fd, sizeof(Rec) * Recs) != 0) { ++ close(fd); ++ return; ++ } ++ void* Map = mmap(nullptr, sizeof(Rec) * Recs, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ close(fd); ++ if (Map != MAP_FAILED) { ++ Buf = static_cast(Map); ++ } ++} ++ ++void CleanupForExit() { ++ if (!Buf) { ++ return; ++ } ++ unlink(PathFor(getpid()).c_str()); ++} ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.h +new file mode 100644 +index 000000000..d1a1bb8a6 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.h +@@ -0,0 +1,54 @@ ++// SPDX-License-Identifier: MIT ++#pragma once ++ ++#include ++#include ++ ++namespace FEX::HLE::SigTrace { ++enum Event : uint16_t { ++ HostArrive = 1, ++ Masked = 2, ++ Deferred = 3, ++ Delivered = 4, ++ SigReturn = 5, ++ ProcMask = 6, ++ Reraise = 7, ++ Kill = 8, ++ Read16 = 9, ++ Write16 = 10, ++ EpollCtl = 11, ++}; ++ ++struct Rec { ++ uint64_t Tsc; ++ uint32_t Tid; ++ uint16_t Ev; ++ uint16_t Sig; ++ uint64_t A; ++ uint64_t B; ++}; ++ ++constexpr uint32_t Recs = 1u << 19; ++extern Rec* Buf; ++extern std::atomic Idx; ++ ++void Init(); ++ ++void CleanupForExit(); ++ ++inline bool Enabled() { ++ return Buf != nullptr; ++} ++ ++inline void Log(uint32_t Tid, uint16_t Ev, uint16_t Sig, uint64_t A, uint64_t B) { ++ if (!Buf) { ++ return; ++ } ++ uint64_t Tsc = 0; ++#if defined(__aarch64__) ++ asm volatile("mrs %0, cntvct_el0" : "=r"(Tsc)); ++#endif ++ Rec& R = Buf[Idx.fetch_add(1, std::memory_order_relaxed) & (Recs - 1)]; ++ R = {Tsc, Tid, Ev, Sig, A, B}; ++} ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +index 4a77d8716..607ab0b97 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +@@ -15,6 +15,8 @@ $end_info$ + + #include "LinuxSyscalls/LinuxAllocator.h" + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/PtraceEmu.h" ++#include + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/Syscalls/Thread.h" + #include "LinuxSyscalls/Utils/Threads.h" +@@ -235,6 +237,11 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + return -ENOENT; + } + ++ if (PtraceEmu::IsAttached()) { ++ char Resolved[PATH_MAX]; ++ PtraceEmu::RecordExecPath(pathname[0] == '/' ? std::string(pathname) : std::string(realpath(Filename.c_str(), Resolved) ? Resolved : pathname)); ++ } ++ + int pid = getpid(); + + char PidSelfPath[50]; +@@ -332,7 +339,8 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + // - seccomp inheritance + // - FEXServer FD inheritance (unshare(CLONE_NEWNET)) + // - FD_CLOEXEC set on FD on anonymous file FD. +- const bool NeedsEnvpCopy = (IsFDExec && !(IsBinfmtCompatible || IsOtherELF)) || HasSeccomp || NeedsFDCopy || NeedsLoaderFD; ++ const bool NeedsExecveFD = (IsFDExec && !(IsBinfmtCompatible || IsOtherELF)) || NeedsFDCopy || NeedsLoaderFD; ++ const bool NeedsEnvpCopy = NeedsExecveFD || HasSeccomp; + + // We are trying to execute a shebang handled by a different architecture interpreter (e.g. /usr/bin/python from the host FS). + // In this case we just defer to the kernel. +@@ -348,7 +356,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + } + } + +- if (!IsBinfmtCompatible || NeedsFDCopy) { ++ if (NeedsExecveFD) { + if (NeedsFDCopy) { + // FEX needs the FD to live past execve when binfmt_misc isn't used, + // so duplicate the FD if FD_CLOEXEC is set, which removes the FD_CLOEXEC flag. +@@ -439,9 +447,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + + // It is valid to provide nullptr first argument. + if (*OldArgv) { +- // The direct fallback uses the executable path as argv[0]. An FD-backed load uses the +- // binfmt preserve-argv0 layout, so the caller-supplied argv[0] has to stay in the vector. +- if (!NeedsLoaderFD && !IsFDExec) { ++ if (!IsFDExec && !NeedsLoaderFD) { + ++OldArgv; + } + while (*OldArgv) { +@@ -814,6 +820,9 @@ SyscallHandler::SyscallHandler(FEXCore::Context::Context* _CTX, FEX::HLE::Signal + + SignalDelegation->RegisterHostSignalHandler(SIGSEGV, HandleSegfault, true); + ++ SignalDelegation->RegisterHostSignalHandler( ++ SIGTRAP, [](FEXCore::Core::InternalThreadState*, int, void*, void*) { return false; }, true); ++ + ExtendedMetaData = FEX::VolatileMetadata::ParseExtendedVolatileMetadata(FEXCore::Config::Get_EXTENDEDVOLATILEMETADATA()()); + } + +@@ -835,6 +844,14 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint + Thread->Thread->CurrentFrame->State.gregs[FEXCore::X86State::REG_RAX] = Result & Mask; + }; + ++ if (FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame)->SyscallUserDispatch.Enabled) [[unlikely]] { ++ const auto Result = SeccompEmulator.ExecuteSyscallUserDispatch(Frame, JITPC, GetArg(Is64Bit, Frame, 0)); ++ if (Result.EarlyReturn) { ++ SetResult(Frame, Result.Result); ++ return; ++ } ++ } ++ + if (SeccompEmulator.HasFilter(Frame)) { + FEX::HLE::SyscallArguments Args { + .Argument = +@@ -856,9 +873,23 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint + } + } + +- const auto SyscallNum = GetArg(Is64Bit, Frame, 0); ++ auto SyscallNum = GetArg(Is64Bit, Frame, 0); ++ ++ uint64_t TraceArgs[6] {}; ++ const bool ReportStops = Is64Bit && PtraceEmu::WantsSyscallStops(); ++ if (ReportStops) { ++ for (unsigned i = 0; i < 6; ++i) { ++ TraceArgs[i] = GetArg(Is64Bit, Frame, i + 1); ++ } ++ SyscallNum = PtraceEmu::SyscallEntryStop(Frame, SyscallNum, TraceArgs); ++ } ++ + if (SyscallNum >= Definitions.size()) { +- SetResult(Frame, -ENOSYS); ++ uint64_t Result = -ENOSYS; ++ if (ReportStops && PtraceEmu::WantsSyscallStops()) { ++ Result = PtraceEmu::SyscallExitStop(Frame, SyscallNum, TraceArgs, Result); ++ } ++ SetResult(Frame, Result); + return; + } + +@@ -891,6 +922,23 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint + #ifdef DEBUG_STRACE + Strace(Frame, Result); + #endif ++ ++ if constexpr (Is64Bit) { ++ PtraceEmu::ApplyPendingFlush(Frame); ++ if (Result == 0 && (SyscallNum == 56 || SyscallNum == 57 || SyscallNum == 58 || SyscallNum == 435)) { ++ constexpr uint64_t CloneVM = 0x100; ++ uint64_t Flags = 0; ++ if (SyscallNum == 56) { ++ Flags = GetArg(Is64Bit, Frame, 1); ++ } else if (SyscallNum == 435) { ++ Flags = *reinterpret_cast(GetArg(Is64Bit, Frame, 1)); ++ } ++ PtraceEmu::OnForkedChild((Flags & CloneVM) != 0); ++ } ++ if (ReportStops && PtraceEmu::WantsSyscallStops()) { ++ Result = PtraceEmu::SyscallExitStop(Frame, SyscallNum, TraceArgs, Result); ++ } ++ } + SetResult(Frame, Result); + } + +@@ -906,9 +954,12 @@ void SyscallHandler::HandleSyscall(FEXCore::Core::CpuStateFrame* Frame) { + HandleSyscallImpl(Frame, JITPC); + } + +- // Skip past the `syscall` or `int 0x80` instruction. Both of which are 2-bytes. + auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame); +- Thread->Thread->CurrentFrame->State.rip += 2; ++ if (const uint64_t NewRip = PtraceEmu::TakePendingRip()) { ++ Thread->Thread->CurrentFrame->State.rip = NewRip; ++ } else { ++ Thread->Thread->CurrentFrame->State.rip += 2; ++ } + } + + #ifdef DEBUG_STRACE +@@ -969,6 +1020,8 @@ void SyscallHandler::UnlockAfterFork(FEXCore::Core::InternalThreadState* LiveThr + // Code maps are closed upon fork in the child + FM.SetProtectedCodeMapFD(-1); + ++ FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(LiveThread)->SyscallUserDispatch = {}; ++ + VMATracking.Mutex.StealAndDropActiveLocks(); + CodeCachePatchingMutex.StealAndDropActiveLocks(); + } else { +@@ -985,10 +1038,16 @@ void SyscallHandler::UnlockAfterFork(FEXCore::Core::InternalThreadState* LiveThr + void SyscallHandler::RegisterTLSState(FEX::HLE::ThreadStateObject* Thread) { + SignalDelegation->RegisterTLSState(Thread); + ThunkHandler->RegisterTLSState(Thread); ++ FEX::HLE::ThreadManager::SetCurrentThreadObject(Thread); + } + + void SyscallHandler::UninstallTLSState(FEX::HLE::ThreadStateObject* Thread) { + SignalDelegation->UninstallTLSState(Thread); ++ FEX::HLE::ThreadManager::SetCurrentThreadObject(nullptr); ++} ++ ++void SyscallHandler::ReleaseDeferredTLSState(FEX::HLE::ThreadStateObject* Thread) { ++ SignalDelegation->ReleaseDeferredTLSState(Thread); + } + + static bool isHEX(char c) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h +index f55bce4fc..d643b4975 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h +@@ -14,6 +14,7 @@ $end_info$ + #include "LinuxSyscalls/LinuxAllocator.h" + #include "LinuxSyscalls/ThreadManager.h" + #include "LinuxSyscalls/Seccomp/SeccompEmulator.h" ++#include "LinuxSyscalls/SMCHotPages.h" + #include "LinuxSyscalls/SyscallsVMATracking.h" + #include "ArchHelpers/MContext.h" + +@@ -203,6 +204,7 @@ public: + FEX_CONFIG_OPT(RootFSPath, ROOTFS); + FEX_CONFIG_OPT(Is64BitMode, IS64BIT_MODE); + FEX_CONFIG_OPT(SMCChecks, SMCCHECKS); ++ FEX_CONFIG_OPT(SMCHotPageFaults, SMCHOTPAGEFAULTS); + FEX_CONFIG_OPT(NeedsSeccomp, NEEDSSECCOMP); + FEX_CONFIG_OPT(EnableCodeCaching, ENABLECODECACHINGWIP); + FEX_CONFIG_OPT(EnableDiskCache, DISKCACHE); +@@ -287,8 +289,13 @@ public: + + ///// VMA (Virtual Memory Area) tracking ///// + static bool HandleSegfault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* info, void* ucontext); ++ static void InvalidateWrittenCodePage(FEXCore::Core::InternalThreadState* Thread, uint64_t FaultBase, uint64_t EntryBase, ++ const FEX::HLE::VMATracking::VMAEntry& Mapping); + void MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; + void ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length); ++ bool IsSMCHotPage(uint64_t Address) override; ++ ++ void PrepareGuestBufferForKernelWrite(FEXCore::Core::InternalThreadState* Thread, const void* Buf, size_t Length); + void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; + std::optional + LookupExecutableFileSection(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestAddr) final override; +@@ -304,6 +311,7 @@ public: + + void RegisterTLSState(FEX::HLE::ThreadStateObject* Thread); + void UninstallTLSState(FEX::HLE::ThreadStateObject* Thread); ++ void ReleaseDeferredTLSState(FEX::HLE::ThreadStateObject* Thread); + + SourcecodeResolver* GetSourcecodeResolver() override { + return this; +@@ -363,6 +371,8 @@ private: + // std::mutex CodeCachePatchingMutex; + FEXCore::ForkableUniqueMutex CodeCachePatchingMutex; + ++ SMCHotPageTracker SMCHotPages; ++ + FEX::CodeLoader* LocalLoader {}; + bool NeedToCheckXID {true}; + +@@ -607,11 +617,13 @@ uint64_t GetDentsEmulation(int fd, T* dirp, uint32_t count); + namespace FaultSafeUserMemAccess { + // These are little helper functions for cases when FEX needs to copy data to or from the application in a robust fashion. + // CopyFromUser and CopyToUser are memcpy routines that expect to safely SIGSEGV when reading or writing application memory respectively. +- // Returns zero if the memcpy completed, or crashes with SIGABRT and a log message if it faults. + [[nodiscard]] + size_t CopyFromUser(void* Dest, const void* Src, size_t Size); + [[nodiscard]] + size_t CopyToUser(void* Dest, const void* Src, size_t Size); ++ ++ [[nodiscard]] ++ bool IsStringReadable(const char* Src); + #if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED && defined(ARCHITECTURE_arm64) + // These helpers just check if the user pointer is readable and writable. + // This is useful in an assert build that can be safely sprinkled through the syscall handler without overhead in release builds. +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FD.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FD.cpp +index 9acf01ff5..1601de1ef 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FD.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FD.cpp +@@ -38,6 +38,9 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(open, [](FEXCore::Core::CpuStateFrame* Frame, const char* pathname, int flags, uint32_t mode) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + flags = FEX::HLE::RemapFromX86Flags(flags); + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Open(pathname, flags, mode); + SYSCALL_ERRNO(); +@@ -59,6 +62,9 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(access, [](FEXCore::Core::CpuStateFrame* Frame, const char* pathname, int mode) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Access(pathname, mode); + SYSCALL_ERRNO(); + }); +@@ -80,22 +86,34 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(openat, [](FEXCore::Core::CpuStateFrame* Frame, int dirfs, const char* pathname, int flags, uint32_t mode) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + flags = FEX::HLE::RemapFromX86Flags(flags); + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Openat(dirfs, pathname, flags, mode); + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL(readlinkat, [](FEXCore::Core::CpuStateFrame* Frame, int dirfd, const char* pathname, char* buf, size_t bufsiz) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Readlinkat(dirfd, pathname, buf, bufsiz); + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL(faccessat, [](FEXCore::Core::CpuStateFrame* Frame, int dirfd, const char* pathname, int mode) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.FAccessat(dirfd, pathname, mode); + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL(faccessat2, [](FEXCore::Core::CpuStateFrame* Frame, int dirfd, const char* pathname, int mode, int flags) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.FAccessat2(dirfd, pathname, mode, flags); + SYSCALL_ERRNO(); + }); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FS.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FS.cpp +index 64c9aae22..9eee296ec 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FS.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FS.cpp +@@ -52,6 +52,9 @@ void RegisterFS(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(readlink, [](FEXCore::Core::CpuStateFrame* Frame, const char* pathname, char* buf, size_t bufsiz) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Readlink(pathname, buf, bufsiz); + SYSCALL_ERRNO(); + }); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Info.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Info.cpp +index 1b61282d3..f83006c0a 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Info.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Info.cpp +@@ -6,6 +6,7 @@ $end_info$ + */ + + #include "LinuxSyscalls/Syscalls.h" ++#include "LinuxSyscalls/PtraceEmu.h" + #include "LinuxSyscalls/x64/Syscalls.h" + #include "LinuxSyscalls/x32/Syscalls.h" + +@@ -34,9 +35,11 @@ using cap_user_header_t = void*; + using cap_user_data_t = void*; + + void RegisterInfo(FEX::HLE::SyscallHandler* Handler) { +- REGISTER_SYSCALL_IMPL(uname, [](FEXCore::Core::CpuStateFrame* Frame, struct utsname* buf) -> uint64_t { ++ REGISTER_SYSCALL_IMPL(uname, [](FEXCore::Core::CpuStateFrame* Frame, struct utsname* ubuf) -> uint64_t { + auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame); + ++ struct utsname Out {}; ++ auto buf = &Out; + struct utsname Local {}; + if (::uname(&Local) == 0) { + memcpy(buf->nodename, Local.nodename, sizeof(Local.nodename)); +@@ -66,6 +69,9 @@ void RegisterInfo(FEX::HLE::SyscallHandler* Handler) { + // Tell the guest that we are a 64bit kernel + strcpy(buf->machine, "x86_64"); + } ++ if (FaultSafeUserMemAccess::CopyToUser(ubuf, &Out, sizeof(Out))) { ++ return -EFAULT; ++ } + return 0; + }); + +@@ -97,13 +103,14 @@ void RegisterInfo(FEX::HLE::SyscallHandler* Handler) { + ptrace, [](FEXCore::Core::CpuStateFrame* Frame, int /*enum __ptrace_request*/ request, pid_t pid, void* addr, void* data) -> uint64_t { + uint64_t Result {}; + ++ if (PtraceEmu::HandleRequest(request, pid, addr, data, &Result)) { ++ return Result; ++ } ++ + switch (request) { + case PTRACE_PEEKTEXT: + case PTRACE_PEEKDATA: +- case PTRACE_POKETEXT: +- case PTRACE_POKEDATA: + case PTRACE_ATTACH: +- case PTRACE_DETACH: + // Passthrough these requests. Allows Wine to run the Ubisoft launcher. + Result = ::syscall(SYSCALL_DEF(ptrace), request, pid, addr, data); + SYSCALL_ERRNO(); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +index 21816674e..602e17570 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +@@ -9,6 +9,13 @@ $end_info$ + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/x64/Syscalls.h" + #include "LinuxSyscalls/x32/Syscalls.h" ++#include "LinuxSyscalls/PtraceEmu.h" ++#include "LinuxSyscalls/SignalTrace.h" ++ ++#include ++#include ++#include ++#include + + #include + #include +@@ -252,8 +259,23 @@ uint64_t SyscallPathPassthrough5(FEXCore::Core::CpuStateFrame* Frame, uint64_t a + } + + static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { +- REGISTER_SYSCALL_IMPL(read, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(write, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(read, [](FEXCore::Core::CpuStateFrame* Frame, int fd, void* buf, size_t count) -> uint64_t { ++ FEX::HLE::_SyscallHandler->PrepareGuestBufferForKernelWrite(Frame->Thread, buf, count); ++ uint64_t Result = ::syscall(SYSCALL_DEF(read), fd, buf, count); ++ if (count == 16 && SigTrace::Enabled()) { ++ const int Errno = errno; ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Read16, fd, Result, Result == 16 ? *static_cast(buf) : (1ULL << 63) | Errno); ++ } ++ SYSCALL_ERRNO(); ++ }); ++ REGISTER_SYSCALL_IMPL(write, [](FEXCore::Core::CpuStateFrame* Frame, int fd, const void* buf, size_t count) -> uint64_t { ++ uint64_t Result = ::syscall(SYSCALL_DEF(write), fd, buf, count); ++ if (count == 16 && SigTrace::Enabled()) { ++ const int Errno = errno; ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Write16, fd, Result, Result == 16 ? *static_cast(buf) : (1ULL << 63) | Errno); ++ } ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(lseek, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(sched_yield, SyscallPassthrough0); + REGISTER_SYSCALL_IMPL(msync, SyscallPassthrough3); +@@ -264,14 +286,26 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(socket, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(connect, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(sendto, SyscallPassthrough6); +- REGISTER_SYSCALL_IMPL(recvfrom, SyscallPassthrough6); ++ REGISTER_SYSCALL_IMPL(recvfrom, ++ [](FEXCore::Core::CpuStateFrame* Frame, int sockfd, void* buf, size_t len, int flags, struct sockaddr* src_addr, ++ socklen_t* addrlen) -> uint64_t { ++ FEX::HLE::_SyscallHandler->PrepareGuestBufferForKernelWrite(Frame->Thread, buf, len); ++ uint64_t Result = ::syscall(SYSCALL_DEF(recvfrom), sockfd, buf, len, flags, src_addr, addrlen); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(shutdown, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(bind, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(listen, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(getsockname, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(getpeername, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(socketpair, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL(kill, SyscallPassthrough2); ++ REGISTER_SYSCALL_IMPL(kill, [](FEXCore::Core::CpuStateFrame* Frame, pid_t pid, int sig) -> uint64_t { ++ if (SigTrace::Enabled()) { ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Kill, sig, pid, 0); ++ } ++ uint64_t Result = ::syscall(SYSCALL_DEF(kill), pid, sig); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(semget, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(msgget, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(msgsnd, SyscallPassthrough4); +@@ -334,7 +368,13 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(fgetxattr, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL(flistxattr, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(fremovexattr, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL(tkill, SyscallPassthrough2); ++ REGISTER_SYSCALL_IMPL(tkill, [](FEXCore::Core::CpuStateFrame* Frame, pid_t tid, int sig) -> uint64_t { ++ if (SigTrace::Enabled()) { ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Kill, sig, tid, 0); ++ } ++ uint64_t Result = ::syscall(SYSCALL_DEF(tkill), tid, sig); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(sched_setaffinity, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(sched_getaffinity, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(io_setup, SyscallPassthrough2); +@@ -344,7 +384,13 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(remap_file_pages, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL(timer_getoverrun, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(timer_delete, SyscallPassthrough1); +- REGISTER_SYSCALL_IMPL(tgkill, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(tgkill, [](FEXCore::Core::CpuStateFrame* Frame, pid_t tgid, pid_t tid, int sig) -> uint64_t { ++ if (SigTrace::Enabled()) { ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Kill, sig, tid, tgid); ++ } ++ uint64_t Result = ::syscall(SYSCALL_DEF(tgkill), tgid, tid, sig); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(mbind, SyscallPassthrough6); + REGISTER_SYSCALL_IMPL(set_mempolicy, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(get_mempolicy, SyscallPassthrough5); +@@ -459,7 +505,11 @@ namespace x64 { + RegisterCommon(Handler); + REGISTER_SYSCALL_IMPL_X64(ftruncate, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL_X64(ioctl, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL_X64(pread_64, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X64(pread_64, [](FEXCore::Core::CpuStateFrame* Frame, int fd, void* buf, size_t count, off_t offset) -> uint64_t { ++ FEX::HLE::_SyscallHandler->PrepareGuestBufferForKernelWrite(Frame->Thread, buf, count); ++ uint64_t Result = ::syscall(SYSCALL_DEF(pread_64), fd, buf, count, offset); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL_X64(pwrite_64, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X64(readv, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL_X64(writev, SyscallPassthrough3); +@@ -473,7 +523,14 @@ namespace x64 { + REGISTER_SYSCALL_IMPL_X64(recvmsg, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL_X64(setsockopt, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL_X64(getsockopt, SyscallPathPassthrough5); +- REGISTER_SYSCALL_IMPL_X64(wait4, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X64(wait4, [](FEXCore::Core::CpuStateFrame* Frame, pid_t pid, int* status, int options, struct rusage* ru) -> uint64_t { ++ uint64_t Result; ++ do { ++ Result = ::syscall(SYSCALL_DEF(wait4), pid, status, options, ru); ++ Result = Result == -1 ? -errno : Result; ++ } while (static_cast(Result) > 0 && PtraceEmu::FixupWaitStatus(static_cast(Result), status)); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL_X64(semop, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL_X64(getrlimit, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL_X64(getrusage, SyscallPassthrough2); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Signals.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Signals.cpp +index 8723026ef..1956b0d52 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Signals.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Signals.cpp +@@ -25,13 +25,27 @@ struct GuestSigAction; + namespace FEX::HLE { + void RegisterSignals(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(rt_sigprocmask, [](FEXCore::Core::CpuStateFrame* Frame, int how, const uint64_t* set, uint64_t* oldset) -> uint64_t { +- return FEX::HLE::_SyscallHandler->GetSignalDelegator()->GuestSigProcMask(FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), +- how, set, oldset); ++ uint64_t NewSet; ++ uint64_t OldSet; ++ if (set && FaultSafeUserMemAccess::CopyFromUser(&NewSet, set, sizeof(NewSet))) { ++ return -EFAULT; ++ } ++ uint64_t Result = FEX::HLE::_SyscallHandler->GetSignalDelegator()->GuestSigProcMask( ++ FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), how, set ? &NewSet : nullptr, oldset ? &OldSet : nullptr); ++ if (Result == 0 && oldset && FaultSafeUserMemAccess::CopyToUser(oldset, &OldSet, sizeof(OldSet))) { ++ return -EFAULT; ++ } ++ return Result; + }); + + REGISTER_SYSCALL_IMPL(rt_sigpending, [](FEXCore::Core::CpuStateFrame* Frame, uint64_t* set, size_t sigsetsize) -> uint64_t { +- return FEX::HLE::_SyscallHandler->GetSignalDelegator()->GuestSigPending(FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), set, +- sigsetsize); ++ uint64_t Pending {}; ++ uint64_t Result = FEX::HLE::_SyscallHandler->GetSignalDelegator()->GuestSigPending( ++ FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), &Pending, sigsetsize); ++ if (Result == 0 && FaultSafeUserMemAccess::CopyToUser(set, &Pending, std::min(sigsetsize, sizeof(Pending)))) { ++ return -EFAULT; ++ } ++ return Result; + }); + + REGISTER_SYSCALL_IMPL(rt_sigsuspend, [](FEXCore::Core::CpuStateFrame* Frame, uint64_t* unewset, size_t sigsetsize) -> uint64_t { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Stubs.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Stubs.cpp +index 2c3edeef1..5ce7ee8bd 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Stubs.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Stubs.cpp +@@ -27,7 +27,9 @@ struct CpuStateFrame; + + namespace FEX::HLE { + void RegisterStubs(FEX::HLE::SyscallHandler* Handler) { +- REGISTER_SYSCALL_IMPL(restart_syscall, [](FEXCore::Core::CpuStateFrame* Frame) -> uint64_t { SYSCALL_STUB(restart_syscall); }); ++ REGISTER_SYSCALL_IMPL(restart_syscall, [](FEXCore::Core::CpuStateFrame* Frame) -> uint64_t { ++ return -EINTR; ++ }); + + REGISTER_SYSCALL_IMPL(rseq, [](FEXCore::Core::CpuStateFrame* Frame, struct rseq* rseq, uint32_t rseq_len, int flags, uint32_t sig) -> uint64_t { + // We don't support this +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Thread.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Thread.cpp +index 068fee23e..5f4a60480 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Thread.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Thread.cpp +@@ -8,6 +8,7 @@ $end_info$ + #include "CodeLoader.h" + + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/SignalTrace.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/Syscalls/Thread.h" + #include "LinuxSyscalls/x64/Syscalls.h" +@@ -43,6 +44,12 @@ $end_info$ + #include + #include + ++#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 ++ + ARG_TO_STR(idtype_t, "%u") + + namespace FEX::HLE { +@@ -500,6 +507,30 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + return FEX::HLE::_SyscallHandler->SeccompEmulator.Handle(Frame, Operation, 0, reinterpret_cast(arg3)); + } + case PR_GET_SECCOMP: return FEX::HLE::_SyscallHandler->SeccompEmulator.GetSeccomp(Frame); ++ case PR_SET_SYSCALL_USER_DISPATCH: { ++ auto& SUD = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame)->SyscallUserDispatch; ++ switch (arg2) { ++ case PR_SYS_DISPATCH_OFF: ++ if (arg3 || arg4 || arg5) { ++ return -EINVAL; ++ } ++ SUD = {}; ++ return 0; ++ case PR_SYS_DISPATCH_ON: ++ if (arg3 && arg3 + arg4 <= arg3) { ++ return -EINVAL; ++ } ++ if (arg5 && arg5 >= SyscallHandler::TASK_MAX_64BIT) { ++ return -EFAULT; ++ } ++ SUD.Offset = arg3; ++ SUD.Length = arg4; ++ SUD.Selector = arg5; ++ SUD.Enabled = true; ++ return 0; ++ default: return -EINVAL; ++ } ++ } + case PR_GET_AUXV: { + if (arg4 || arg5) { + return -EINVAL; +@@ -532,6 +563,7 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + return -EPERM; + } + Frame->State.gs_cached = addr; ++ Frame->State.gs_idx = 0; + Result = 0; + break; + case 0x1002: // ARCH_SET_FS +@@ -540,22 +572,27 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + return -EPERM; + } + Frame->State.fs_cached = addr; ++ Frame->State.fs_idx = 0; + Result = 0; + break; + case 0x1003: // ARCH_GET_FS +- *reinterpret_cast(addr) = Frame->State.fs_cached; +- Result = 0; ++ Result = FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(addr), &Frame->State.fs_cached, sizeof(uint64_t)) ? -EFAULT : 0; + break; + case 0x1004: // ARCH_GET_GS +- *reinterpret_cast(addr) = Frame->State.gs_cached; +- Result = 0; ++ Result = FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(addr), &Frame->State.gs_cached, sizeof(uint64_t)) ? -EFAULT : 0; + break; + case 0x3001: // ARCH_CET_STATUS + Result = -EINVAL; // We don't support CET, return EINVAL + break; + case 0x1011: // ARCH_GET_CPUID ++ if (!FEX::HLE::_SyscallHandler->TM.EnableCPUIDFaulting()) { ++ return 1; ++ } + return (Frame->State.CoreFlags & FEXCore::Core::CoreFlagsEnum::CPUID_ENABLED) == FEXCore::Core::CoreFlagsEnum::CPUID_ENABLED ? 1 : 0; + case 0x1012: // ARCH_SET_CPUID ++ if (!FEX::HLE::_SyscallHandler->TM.EnableCPUIDFaulting()) { ++ return -ENODEV; ++ } + if (addr == 0) { + // Disable CPUID (thus enabling CPUID faulting) + Frame->State.CoreFlags = Frame->State.CoreFlags & ~FEXCore::Core::CoreFlagsEnum::CPUID_ENABLED; +@@ -584,6 +621,7 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + // Save telemetry if we're exiting. + FEX::HLE::_SyscallHandler->GetSignalDelegator()->SaveTelemetry(); + FEX::HLE::_SyscallHandler->TM.CleanupForExit(); ++ FEX::HLE::SigTrace::CleanupForExit(); + + syscall(SYSCALL_DEF(exit_group), status); + // This will never be reached +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +index 5d6c850d8..f9e85a26f 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +@@ -42,6 +42,40 @@ static void HandleSegfaultForCodeCacheFinalization(FEXCore::Core::InternalThread + } + } + ++void SyscallHandler::InvalidateWrittenCodePage(FEXCore::Core::InternalThreadState* Thread, uint64_t FaultBase, uint64_t EntryBase, ++ const FEX::HLE::VMATracking::VMAEntry& Mapping) { ++ auto UnprotectRegionCallback = [](uintptr_t Start, uintptr_t Length) { ++ auto rv = mprotect((void*)Start, Length, PROT_READ | PROT_WRITE); ++ LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); ++ }; ++ ++ if (Mapping.Flags.Shared) { ++ LOGMAN_THROW_A_FMT(Mapping.Resource, "VMA tracking error"); ++ ++ auto Offset = FaultBase - EntryBase + Mapping.Offset; ++ ++ auto VMA = Mapping.Resource->FirstVMA; ++ LOGMAN_THROW_A_FMT(VMA, "VMA tracking error"); ++ ++ do { ++ if (VMA->Offset <= Offset && (VMA->Offset + VMA->Length) > Offset) { ++ auto FaultBaseMirrored = Offset - VMA->Offset + VMA->Base; ++ ++ if (VMA->Prot.Writable) { ++ _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBaseMirrored, FEXCore::Utils::FEX_PAGE_SIZE, UnprotectRegionCallback); ++ } else { ++ _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBaseMirrored, FEXCore::Utils::FEX_PAGE_SIZE); ++ } ++ ++ _SyscallHandler->SMCHotPages.RecordFault(FaultBaseMirrored, _SyscallHandler->SMCHotPageFaults()); ++ } ++ } while ((VMA = VMA->ResourceNextVMA)); ++ } else { ++ _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBase, FEXCore::Utils::FEX_PAGE_SIZE, UnprotectRegionCallback); ++ _SyscallHandler->SMCHotPages.RecordFault(FaultBase, _SyscallHandler->SMCHotPageFaults()); ++ } ++} ++ + // Handles segfaults from: + // - call-ret shadow stack overflow + // - guest-side self-modifying code (SMC) +@@ -52,9 +86,11 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread, + auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); + auto CallRetStackInfo = ThreadObject->GetCallRetStackInfo(); + if (FaultAddress >= CallRetStackInfo.AllocationBase && FaultAddress < CallRetStackInfo.AllocationEnd) { +- // Reset REG_CALLRET_SP to the default location to allow for underflows/overflows +- ArchHelpers::Context::SetArmReg(ucontext, 25, CallRetStackInfo.DefaultLocation); +- return true; ++ const uint64_t CallRetSP = ArchHelpers::Context::GetArmReg(ucontext, 25); ++ if (FaultAddress - (CallRetSP - 16) < 32) { ++ ArchHelpers::Context::SetArmReg(ucontext, 25, CallRetStackInfo.DefaultLocation); ++ return true; ++ } + } + + { +@@ -84,41 +120,16 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread, + } + + auto FaultBase = FEXCore::AlignDown(FaultAddress, FEXCore::Utils::FEX_PAGE_SIZE); +- +- auto UnprotectRegionCallback = [](uintptr_t Start, uintptr_t Length) { +- auto rv = mprotect((void*)Start, Length, PROT_READ | PROT_WRITE); +- LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); +- }; +- +- if (Entry->second.Flags.Shared) { +- LOGMAN_THROW_A_FMT(Entry->second.Resource, "VMA tracking error"); +- +- auto Offset = FaultBase - Entry->first + Entry->second.Offset; +- +- auto VMA = Entry->second.Resource->FirstVMA; +- LOGMAN_THROW_A_FMT(VMA, "VMA tracking error"); +- +- // Flush all mirrors, remap the page writable as needed +- do { +- if (VMA->Offset <= Offset && (VMA->Offset + VMA->Length) > Offset) { +- auto FaultBaseMirrored = Offset - VMA->Offset + VMA->Base; +- +- if (VMA->Prot.Writable) { +- _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBaseMirrored, FEXCore::Utils::FEX_PAGE_SIZE, UnprotectRegionCallback); +- } else { +- _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBaseMirrored, FEXCore::Utils::FEX_PAGE_SIZE); +- } +- } +- } while ((VMA = VMA->ResourceNextVMA)); +- } else { +- _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBase, FEXCore::Utils::FEX_PAGE_SIZE, UnprotectRegionCallback); +- } ++ InvalidateWrittenCodePage(Thread, FaultBase, Entry->first, Entry->second); + + FEXCORE_PROFILE_INSTANT_INCREMENT(Thread, AccumulatedSMCCount, 1); + ++ constexpr uint64_t MaxStoreSize = 64; ++ const uint64_t StoreWindowStart = FaultAddress > MaxStoreSize ? FaultAddress - MaxStoreSize : 0; ++ + auto CTX = Thread->CTX; + if (CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext)) && !CTX->IsCurrentBlockSingleInst(Thread) && +- CTX->IsAddressInCurrentBlock(Thread, FaultAddress & FEXCore::Utils::FEX_PAGE_MASK, FEXCore::Utils::FEX_PAGE_SIZE)) { ++ CTX->IsAddressInCurrentBlock(Thread, StoreWindowStart, 2 * MaxStoreSize)) { + // If we are not in a single-instruction block, and the SMC write address could intersect with the current block, + // reconstruct the context and repeat the faulting instruction as a single-instruction block so any SMC it performs + // is immediately picked up. +@@ -134,6 +145,48 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread, + } + } + ++void SyscallHandler::PrepareGuestBufferForKernelWrite(FEXCore::Core::InternalThreadState* Thread, const void* Buf, size_t Length) { ++ if (SMCChecks != FEXCore::Config::CONFIG_SMC_MTRACK || Length == 0) [[likely]] { ++ return; ++ } ++ ++ const uint64_t Start = FEXCore::AlignDown(reinterpret_cast(Buf), FEXCore::Utils::FEX_PAGE_SIZE); ++ const uint64_t Last = reinterpret_cast(Buf) + Length - 1 < reinterpret_cast(Buf) ? ++ UINT64_MAX : ++ reinterpret_cast(Buf) + Length - 1; ++ const uint64_t End = FEXCore::AlignDown(Last, FEXCore::Utils::FEX_PAGE_SIZE) + (Last >= UINT64_MAX - FEXCore::Utils::FEX_PAGE_SIZE ? 0 : FEXCore::Utils::FEX_PAGE_SIZE); ++ ++ auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread); ++ ++ auto Entry = VMATracking.VMAs.upper_bound(Start); ++ if (Entry != VMATracking.VMAs.begin() && std::prev(Entry)->first + std::prev(Entry)->second.Length > Start) { ++ --Entry; ++ } ++ ++ for (; Entry != VMATracking.VMAs.end() && Entry->first < End; ++Entry) { ++ const auto& Mapping = Entry->second; ++ if (!Mapping.Prot.Writable || !(Mapping.Prot.Executable || Mapping.Flags.Shared)) [[likely]] { ++ continue; ++ } ++ const uint64_t From = std::max(Start, Entry->first); ++ const uint64_t To = std::min(End, Entry->first + Mapping.Length); ++ if (Mapping.Flags.Shared) { ++ for (uint64_t Page = From; Page < To; Page += FEXCore::Utils::FEX_PAGE_SIZE) { ++ InvalidateWrittenCodePage(Thread, Page, Entry->first, Mapping); ++ } ++ } else { ++ TM.InvalidateGuestCodeRange(Thread, From, To - From, [](uintptr_t Start, uintptr_t Length) { ++ auto rv = mprotect(reinterpret_cast(Start), Length, PROT_READ | PROT_WRITE); ++ LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); ++ }); ++ } ++ } ++} ++ ++bool SyscallHandler::IsSMCHotPage(uint64_t Address) { ++ return SMCHotPages.IsHot(Address); ++} ++ + void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) { + const auto Base = Start & FEXCore::Utils::FEX_PAGE_MASK; + const auto Top = FEXCore::AlignUp(Start + Length, FEXCore::Utils::FEX_PAGE_SIZE); +@@ -143,6 +196,18 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState + return; + } + ++ for (auto Page = Base; Page < Top; Page += FEXCore::Utils::FEX_PAGE_SIZE) { ++ if (SMCHotPages.IsHot(Page)) { ++ if (Page > Base) { ++ MarkGuestExecutableRange(Thread, Base, Page - Base); ++ } ++ if (Page + FEXCore::Utils::FEX_PAGE_SIZE < Top) { ++ MarkGuestExecutableRange(Thread, Page + FEXCore::Utils::FEX_PAGE_SIZE, Top - (Page + FEXCore::Utils::FEX_PAGE_SIZE)); ++ } ++ return; ++ } ++ } ++ + auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread); + + // Find the first mapping at or after the range ends, or ::end(). +@@ -407,16 +472,24 @@ uint64_t SyscallHandler::GuestMunmap(bool Is64Bit, FEXCore::Core::InternalThread + // To be more optimal the frontend should provide this code with a valid Thread object earlier. + auto lk = FEXCore::GuardSignalDeferringSectionWithFallback(VMATracking.Mutex, Thread); + +- if (reinterpret_cast(addr) < 0x1'0000'0000ULL) { ++ if (!Is64Bit) { + Result = Get32BitAllocator()->Munmap(addr, length); + if (FEX::HLE::HasSyscallError(Result)) { + return Result; + } + } else { ++ constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - FEXCore::Utils::FEX_PAGE_SIZE; ++ const uint64_t Addr = reinterpret_cast(addr); ++ if (Addr > X86_64TaskSizeMax || Size > X86_64TaskSizeMax - Addr || (length != 0 && Size == 0)) { ++ return -EINVAL; ++ } + Result = ::munmap(addr, length); + if (Result == -1) { + return -errno; + } ++ if (reinterpret_cast(addr) < 0x1'0000'0000ULL) { ++ Get32BitAllocator()->TrackUnmapped(addr, length); ++ } + } + TrackMunmap(Thread, addr, length); + PendingResourceDeletion = VMATracking.HasPendingResourceDeletions(); +@@ -514,6 +587,21 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa + + { + auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread); ++ ++ fextl::vector UnlockedCode; ++ constexpr uint64_t MaxUnlockedCodePages = 64; ++ const auto Base = reinterpret_cast(addr) & FEXCore::Utils::FEX_PAGE_MASK; ++ const auto Top = FEXCore::AlignUp(reinterpret_cast(addr) + len, FEXCore::Utils::FEX_PAGE_SIZE); ++ if (SMCChecks == FEXCore::Config::CONFIG_SMC_MTRACK && SMCHotPageFaults() && (prot & PROT_WRITE) && (prot & PROT_EXEC) && ++ Top > Base && (Top - Base) / FEXCore::Utils::FEX_PAGE_SIZE <= MaxUnlockedCodePages) { ++ for (auto Page = Base; Page < Top; Page += FEXCore::Utils::FEX_PAGE_SIZE) { ++ auto Entry = VMATracking.FindVMAEntry(Page); ++ if (Entry != VMATracking.VMAs.end() && Entry->second.Prot.Executable && !Entry->second.Prot.Writable) { ++ UnlockedCode.push_back(Page); ++ } ++ } ++ } ++ + Result = ::mprotect(addr, len, prot); + if (Result == -1) { + return -errno; +@@ -523,6 +611,10 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa + if (prot & PROT_WRITE) { + ProtectWritableAliasOfCode(reinterpret_cast(addr), FEXCore::AlignUp(len, FEXCore::Utils::FEX_PAGE_SIZE)); + } ++ ++ for (auto Page : UnlockedCode) { ++ SMCHotPages.MarkHot(Page); ++ } + } + + InvalidateCodeRangeIfNecessary(Thread, reinterpret_cast(addr), len, false); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp +index 8e7d466ed..2e59f2fb5 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp +@@ -1,6 +1,7 @@ + // SPDX-License-Identifier: MIT + + #include "LinuxSyscalls/ThreadManager.h" ++#include "LinuxSyscalls/SamplingProfiler.h" + + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/SignalDelegator.h" +@@ -158,6 +159,16 @@ void ThreadManager::StatAlloc::UnlockAfterFork(FEXCore::Core::InternalThreadStat + ThreadObject->Thread->ThreadStats = AllocateSlot(ThreadObject->ThreadInfo.TID); + } + ++static thread_local FEX::HLE::ThreadStateObject* CurrentThreadObject {}; ++ ++FEX::HLE::ThreadStateObject* ThreadManager::GetCurrentThreadObject() { ++ return CurrentThreadObject; ++} ++ ++void ThreadManager::SetCurrentThreadObject(FEX::HLE::ThreadStateObject* Thread) { ++ CurrentThreadObject = Thread; ++} ++ + uint64_t ThreadManager::SetSignalMask(uint64_t Mask) { + ::syscall(SYSCALL_DEF(rt_sigprocmask), SIG_SETMASK, &Mask, &Mask, 8); + return Mask; +@@ -197,6 +208,16 @@ ThreadManager::CreateThread(const FEXCore::Core::CPUState* NewThreadState, uint6 + Frame->State.callret_sp = ThreadStateObject->GetCallRetStackInfo().DefaultLocation; + + ThreadStateObject->Thread->FrontendPtr = ThreadStateObject; ++ ++ { ++ static std::atomic ThreadCount {0}; ++ FEX_CONFIG_OPT(ProfileSampleHz, PROFILESAMPLEHZ); ++ FEX_CONFIG_OPT(ProfileSampleAllThreads, PROFILESAMPLEALLTHREADS); ++ FEX_CONFIG_OPT(ProfileSampleMinThreads, PROFILESAMPLEMINTHREADS); ++ if (ProfileSampleHz() && ThreadCount.fetch_add(1) + 1 == std::max(ProfileSampleMinThreads(), 1)) { ++ StartSamplingProfiler(SignalDelegation, ProfileSampleHz(), ProfileSampleAllThreads(), ProfileSampleMinThreads() == 0); ++ } ++ } + if (ProfileStats()) { + ThreadStateObject->Thread->ThreadStats = Stat.AllocateSlot(ThreadStateObject->ThreadInfo.TID); + } +@@ -222,8 +243,8 @@ ThreadManager::CreateThread(const FEXCore::Core::CPUState* NewThreadState, uint6 + } + } else { + // Without any thread data to inherit, setup the default gdt. +- // Default code segment indexes match the numbers that the Linux kernel uses. +- Frame->State.cs_idx = FEXCore::Core::CPUState::DEFAULT_USER_CS << 3; ++ Frame->State.cs_idx = ++ Is64BitMode() ? FEXCore::Core::CPUState::DEFAULT_USER_CS_SEL : FEXCore::Core::CPUState::DEFAULT_USER32_CS_SEL; + auto GDT = FEXCore::Core::CPUState::GetSegmentFromIndex(Frame->State, Frame->State.cs_idx); + FEXCore::Core::CPUState::SetGDTBase(GDT, 0); + FEXCore::Core::CPUState::SetGDTLimit(GDT, 0xF'FFFFU); +@@ -237,6 +258,14 @@ ThreadManager::CreateThread(const FEXCore::Core::CPUState* NewThreadState, uint6 + GDT->L = 0; // L = Long Mode = 32-bit + GDT->D = 1; // D = Default Operand Size = 32-bit + } ++ ++ Frame->State.ss_idx = FEXCore::Core::CPUState::DEFAULT_USER_DS_SEL; ++ auto SSGDT = FEXCore::Core::CPUState::GetSegmentFromIndex(Frame->State, Frame->State.ss_idx); ++ FEXCore::Core::CPUState::SetGDTBase(SSGDT, 0); ++ FEXCore::Core::CPUState::SetGDTLimit(SSGDT, 0xF'FFFFU); ++ SSGDT->L = 0; ++ SSGDT->D = 1; ++ Frame->State.ss_cached = FEXCore::Core::CPUState::CalculateGDTBase(*SSGDT); + } + + if (InheritThread) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +index 408cddf71..0a46703ca 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +@@ -15,6 +15,7 @@ $end_info$ + + #include + #include ++#include + #include + #include + #include +@@ -68,6 +69,7 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { + SignalDelegator* Delegator {}; + + void* AltStackPtr {}; ++ bool AltStackReleaseDeferred {}; + stack_t GuestAltStack { + .ss_sp = nullptr, + .ss_flags = SS_DISABLE, // By default the guest alt stack is disabled +@@ -93,6 +95,27 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { + fextl::vector Filters {}; + std::atomic PrctlSetPending {false}; + ++ uint64_t SeccompTrapRIP {}; ++ ++ struct { ++ uint64_t Offset; ++ uint64_t Length; ++ uint64_t Selector; ++ bool Enabled; ++ } SyscallUserDispatch {}; ++ ++ uint64_t JITStackSP {}; ++ ++ struct TrapSignalFrame { ++ uint64_t GuestFrame; ++ uint64_t GuestRSP; ++ uint64_t JITStackSP; ++ uint64_t ContextBackup; ++ }; ++ static constexpr size_t MaxTrapSignalFrames = 16; ++ TrapSignalFrame TrapSignalFrames[MaxTrapSignalFrames] {}; ++ size_t TrapSignalFrameCount {}; ++ + // personality emulation. + uint32_t persona {}; + +@@ -190,6 +213,11 @@ public: + return static_cast(Thread->FrontendPtr); + } + ++ static FEX::HLE::ThreadStateObject* GetCurrentThreadObject(); ++ static void SetCurrentThreadObject(FEX::HLE::ThreadStateObject* Thread); ++ ++ FEX_CONFIG_OPT(EnableCPUIDFaulting, ENABLECPUIDFAULTING); ++ + FEX::HLE::ThreadStateObject* CreateThread(const FEXCore::Core::CPUState* NewThreadState = nullptr, uint64_t ParentTID = 0, + FEX::HLE::ThreadStateObject* InheritThread = nullptr); + void TrackThread(FEX::HLE::ThreadStateObject* Thread) { +@@ -220,29 +248,38 @@ public: + } + + void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* CallingThread, uint64_t Start, uint64_t Length) { ++ InvalidationStats Stats(CallingThread); + std::lock_guard lk(ThreadCreationMutex); + + // Potential deferred since Thread might not be valid. + // Thread object isn't valid very early in frontend's initialization. + // To be more optimal the frontend should provide this code with a valid Thread object earlier. + auto CodeInvalidationlk = FEXCore::GuardSignalDeferringSectionWithFallback(CTX->GetCodeInvalidationMutex(), CallingThread); +- CTX->InvalidateCodeBuffersCodeRange(Start, Length); +- for (auto& Thread : Threads) { +- CTX->InvalidateThreadCachedCodeRange(Thread->Thread, Start, Length); ++ const bool HadCode = CTX->InvalidateCodeBuffersCodeRange(Start, Length); ++ if (HadCode) { ++ for (auto& Thread : Threads) { ++ CTX->InvalidateThreadCachedCodeRange(Thread->Thread, Start, Length, true); ++ } ++ } else { ++ CTX->InvalidateExecutableRangeCaches(); + } + } + + void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* CallingThread, uint64_t Start, uint64_t Length, + FEXCore::Context::CodeRangeInvalidationFn after_callback) { ++ InvalidationStats Stats(CallingThread); + std::lock_guard lk(ThreadCreationMutex); + + // Potential deferred since Thread might not be valid. + // Thread object isn't valid very early in frontend's initialization. + // To be more optimal the frontend should provide this code with a valid Thread object earlier. + auto CodeInvalidationlk = FEXCore::GuardSignalDeferringSectionWithFallback(CTX->GetCodeInvalidationMutex(), CallingThread); +- CTX->InvalidateCodeBuffersCodeRange(Start, Length); +- for (auto& Thread : Threads) { +- CTX->InvalidateThreadCachedCodeRange(Thread->Thread, Start, Length); ++ if (CTX->InvalidateCodeBuffersCodeRange(Start, Length)) { ++ for (auto& Thread : Threads) { ++ CTX->InvalidateThreadCachedCodeRange(Thread->Thread, Start, Length, true); ++ } ++ } else { ++ CTX->InvalidateExecutableRangeCaches(); + } + + // Callback while holding the locks. +@@ -254,6 +291,20 @@ public: + } + + private: ++ struct InvalidationStats { ++ explicit InvalidationStats(FEXCore::Core::InternalThreadState* Thread) ++ : Thread {Thread} ++ , Begin {Thread && Thread->ThreadStats ? FEXCore::SHMStats::GetCycleCounter() : 0} {} ++ ~InvalidationStats() { ++ if (Thread && Thread->ThreadStats) { ++ Thread->ThreadStats->AccumulatedInvalidationCount += 1; ++ Thread->ThreadStats->AccumulatedInvalidationTime += FEXCore::SHMStats::GetCycleCounter() - Begin; ++ } ++ } ++ FEXCore::Core::InternalThreadState* Thread; ++ uint64_t Begin; ++ }; ++ + StatAlloc Stat; + FEXCore::Context::Context* CTX; + FEX::HLE::SignalDelegator* SignalDelegation; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Utils/Threads.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Utils/Threads.cpp +index 8b9c25948..3b37e4a3e 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Utils/Threads.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Utils/Threads.cpp +@@ -347,6 +347,7 @@ namespace PThreads { + Thread->detach(); + + if (LongJumpExit) { ++ FEX::HLE::_SyscallHandler->ReleaseDeferredTLSState(ThreadObject); + // We have ownership of the thread object. Make sure to clean it up to prevent memory leaks. + FEX::HLE::_SyscallHandler->TM.DestroyThread(ThreadObject, true); + if (Status == 0) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x32/FD.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x32/FD.cpp +index 361bfbec1..25b3b0742 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x32/FD.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x32/FD.cpp +@@ -802,6 +802,7 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL_X32( + pread_64, [](FEXCore::Core::CpuStateFrame* Frame, int fd, void* buf, uint32_t count, uint32_t offset_low, uint32_t offset_high) -> uint64_t { + uint64_t Offset = (uint64_t(offset_high) << 32) | offset_low; ++ FEX::HLE::_SyscallHandler->PrepareGuestBufferForKernelWrite(Frame->Thread, buf, count); + uint64_t Result = ::pread64(fd, buf, count, Offset); + SYSCALL_ERRNO(); + }); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/EPoll.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/EPoll.cpp +index d1ab9cdf8..84c612940 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/EPoll.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/EPoll.cpp +@@ -6,6 +6,7 @@ tags: LinuxSyscalls|syscalls-x86-64 + $end_info$ + */ + ++#include "LinuxSyscalls/SignalTrace.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/Types.h" + #include "LinuxSyscalls/x64/Syscalls.h" +@@ -14,6 +15,7 @@ $end_info$ + #include + + #include ++#include + #include + #include + #include +@@ -50,6 +52,9 @@ void RegisterEpoll(FEX::HLE::SyscallHandler* Handler) { + EventPtr = &Event; + } + uint64_t Result = ::syscall(SYSCALL_DEF(epoll_ctl), epfd, op, fd, EventPtr); ++ if (SigTrace::Enabled()) { ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::EpollCtl, op, fd, (EventPtr ? EventPtr->events : 0) | (Result << 32)); ++ } + if (Result != -1 && event) { + FaultSafeUserMemAccess::VerifyIsWritable(event, sizeof(FEX::HLE::epoll_event_x86)); + *event = Event; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/FD.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/FD.cpp +index 91b5a103d..4eab76a59 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/FD.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/FD.cpp +@@ -63,14 +63,16 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL_X64(stat, [](FEXCore::Core::CpuStateFrame* Frame, const char* pathname, FEX::HLE::x64::guest_stat* buf) -> uint64_t { +- SYSCALL_EFAULT_IF_NULL(pathname); +- FaultSafeUserMemAccess::VerifyIsStringReadableMaxSize(pathname, PATH_MAX); ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + struct stat host_stat; + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Stat(pathname, &host_stat); + if (Result != -1) { +- SYSCALL_EFAULT_IF_NULL(buf); +- FaultSafeUserMemAccess::VerifyIsWritable(buf, sizeof(*buf)); +- *buf = host_stat; ++ FEX::HLE::x64::guest_stat guest = host_stat; ++ if (FaultSafeUserMemAccess::CopyToUser(buf, &guest, sizeof(guest))) { ++ return -EFAULT; ++ } + } + SYSCALL_ERRNO(); + }); +@@ -79,36 +81,41 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + struct stat host_stat; + uint64_t Result = ::fstat(fd, &host_stat); + if (Result != -1) { +- SYSCALL_EFAULT_IF_NULL(buf); +- FaultSafeUserMemAccess::VerifyIsWritable(buf, sizeof(*buf)); +- *buf = host_stat; ++ FEX::HLE::x64::guest_stat guest = host_stat; ++ if (FaultSafeUserMemAccess::CopyToUser(buf, &guest, sizeof(guest))) { ++ return -EFAULT; ++ } + } + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL_X64(lstat, [](FEXCore::Core::CpuStateFrame* Frame, const char* path, FEX::HLE::x64::guest_stat* buf) -> uint64_t { +- SYSCALL_EFAULT_IF_NULL(path); +- FaultSafeUserMemAccess::VerifyIsStringReadableMaxSize(path, PATH_MAX); ++ if (!FaultSafeUserMemAccess::IsStringReadable(path)) { ++ return -EFAULT; ++ } + struct stat host_stat; + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Lstat(path, &host_stat); + if (Result != -1) { +- SYSCALL_EFAULT_IF_NULL(buf); +- FaultSafeUserMemAccess::VerifyIsWritable(buf, sizeof(*buf)); +- *buf = host_stat; ++ FEX::HLE::x64::guest_stat guest = host_stat; ++ if (FaultSafeUserMemAccess::CopyToUser(buf, &guest, sizeof(guest))) { ++ return -EFAULT; ++ } + } + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL_X64( + newfstatat, [](FEXCore::Core::CpuStateFrame* Frame, int dirfd, const char* pathname, FEX::HLE::x64::guest_stat* buf, int flag) -> uint64_t { +- SYSCALL_EFAULT_IF_NULL(pathname); +- FaultSafeUserMemAccess::VerifyIsStringReadableMaxSize(pathname, PATH_MAX); ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + struct stat host_stat; + uint64_t Result = FEX::HLE::_SyscallHandler->FM.NewFSStatAt(dirfd, pathname, &host_stat, flag); + if (Result != -1) { +- SYSCALL_EFAULT_IF_NULL(buf); +- FaultSafeUserMemAccess::VerifyIsWritable(buf, sizeof(*buf)); +- *buf = host_stat; ++ FEX::HLE::x64::guest_stat guest = host_stat; ++ if (FaultSafeUserMemAccess::CopyToUser(buf, &guest, sizeof(guest))) { ++ return -EFAULT; ++ } + } + SYSCALL_ERRNO(); + }); +@@ -140,8 +147,9 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL_X64(statfs, [](FEXCore::Core::CpuStateFrame* Frame, const char* path, struct statfs* buf) -> uint64_t { +- SYSCALL_EFAULT_IF_NULL(path); +- FaultSafeUserMemAccess::VerifyIsStringReadableMaxSize(path, PATH_MAX); ++ if (!FaultSafeUserMemAccess::IsStringReadable(path)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Statfs(path, buf); + SYSCALL_ERRNO(); + }); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Signals.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Signals.cpp +index 36726ece6..c7b39bb46 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Signals.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Signals.cpp +@@ -25,10 +25,18 @@ void RegisterSignals(FEX::HLE::SyscallHandler* Handler) { + if (sigsetsize != 8) { + return -EINVAL; + } +- FaultSafeUserMemAccess::VerifyIsReadableOrNull(act, sizeof(GuestSigAction)); +- FaultSafeUserMemAccess::VerifyIsWritableOrNull(oldact, sizeof(GuestSigAction)); ++ GuestSigAction NewAct; ++ GuestSigAction OldAct; ++ if (act && FaultSafeUserMemAccess::CopyFromUser(&NewAct, act, sizeof(NewAct))) { ++ return -EFAULT; ++ } + +- return FEX::HLE::_SyscallHandler->GetSignalDelegator()->RegisterGuestSignalHandler(signum, act, oldact); ++ uint64_t Result = FEX::HLE::_SyscallHandler->GetSignalDelegator()->RegisterGuestSignalHandler(signum, act ? &NewAct : nullptr, ++ oldact ? &OldAct : nullptr); ++ if (Result == 0 && oldact && FaultSafeUserMemAccess::CopyToUser(oldact, &OldAct, sizeof(OldAct))) { ++ return -EFAULT; ++ } ++ return Result; + }); + + REGISTER_SYSCALL_IMPL_X64( +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Thread.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Thread.cpp +index c25ff5b94..0ec2933bc 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Thread.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Thread.cpp +@@ -233,6 +233,22 @@ enum Modify_ldt_func : int32_t { + LDT_WRITE = 0x11, + }; + ++static bool GatherStringArray(char* const* User, fextl::vector& Out) { ++ for (size_t i = 0;; ++i) { ++ const char* Str; ++ if (FaultSafeUserMemAccess::CopyFromUser(&Str, &User[i], sizeof(Str))) { ++ return false; ++ } ++ Out.push_back(Str); ++ if (!Str) { ++ return true; ++ } ++ if (!FaultSafeUserMemAccess::IsStringReadable(Str)) { ++ return false; ++ } ++ } ++} ++ + void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL_X64(modify_ldt, [](FEXCore::Core::CpuStateFrame* Frame, int func, void* ptr, unsigned long bytecount) -> uint64_t { + switch (func) { +@@ -278,10 +294,17 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + })); + + REGISTER_SYSCALL_IMPL_X64(sigaltstack, [](FEXCore::Core::CpuStateFrame* Frame, const stack_t* ss, stack_t* old_ss) -> uint64_t { +- FaultSafeUserMemAccess::VerifyIsReadableOrNull(ss, sizeof(*ss)); +- FaultSafeUserMemAccess::VerifyIsWritableOrNull(old_ss, sizeof(*old_ss)); +- return FEX::HLE::_SyscallHandler->GetSignalDelegator()->RegisterGuestSigAltStack( +- FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), ss, old_ss); ++ stack_t NewStack; ++ stack_t OldStack; ++ if (ss && FaultSafeUserMemAccess::CopyFromUser(&NewStack, ss, sizeof(NewStack))) { ++ return -EFAULT; ++ } ++ uint64_t Result = FEX::HLE::_SyscallHandler->GetSignalDelegator()->RegisterGuestSigAltStack( ++ FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), ss ? &NewStack : nullptr, old_ss ? &OldStack : nullptr); ++ if (Result == 0 && old_ss && FaultSafeUserMemAccess::CopyToUser(old_ss, &OldStack, sizeof(OldStack))) { ++ return -EFAULT; ++ } ++ return Result; + }); + + // launch a new process under fex +@@ -290,20 +313,9 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + fextl::vector Args; + fextl::vector Envp; + +- if (argv) { +- for (int i = 0; argv[i]; i++) { +- Args.push_back(argv[i]); +- } +- +- Args.push_back(nullptr); +- } +- +- if (envp) { +- for (int i = 0; envp[i]; i++) { +- Envp.push_back(envp[i]); +- } +- +- Envp.push_back(nullptr); ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname) || (argv && !GatherStringArray(argv, Args)) || ++ (envp && !GatherStringArray(envp, Envp))) { ++ return -EFAULT; + } + + auto* const* ArgsPtr = argv ? const_cast(Args.data()) : nullptr; +@@ -319,20 +331,9 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + fextl::vector Args; + fextl::vector Envp; + +- if (argv) { +- for (int i = 0; argv[i]; i++) { +- Args.push_back(argv[i]); +- } +- +- Args.push_back(nullptr); +- } +- +- if (envp) { +- for (int i = 0; envp[i]; i++) { +- Envp.push_back(envp[i]); +- } +- +- Envp.push_back(nullptr); ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname) || (argv && !GatherStringArray(argv, Args)) || ++ (envp && !GatherStringArray(envp, Envp))) { ++ return -EFAULT; + } + + FEX::HLE::ExecveAtArgs AtArgs { diff --git a/tools/fex/patches/0022-proc-maps-guest-only-on-small-address-space-hosts.patch b/tools/fex/patches/0022-proc-maps-guest-only-on-small-address-space-hosts.patch new file mode 100644 index 0000000000..0d62f092d4 --- /dev/null +++ b/tools/fex/patches/0022-proc-maps-guest-only-on-small-address-space-hosts.patch @@ -0,0 +1,132 @@ +From: maxjivi05 +Subject: [PATCH] List only guest mappings in /proc//maps on hosts below 47 address bits + +Builds on StonkGuy's /proc emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +index eb12945e4..65b0521c9 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +@@ -17,7 +17,11 @@ $end_info$ + #include + #include + #include ++#include + #include ++#include ++#include ++#include + #include + #include + #include +@@ -25,9 +29,13 @@ $end_info$ + + #include + ++#include + #include + #include + #include ++#include ++#include ++#include + #include + #include + #include +@@ -609,6 +617,37 @@ EmulatedFDManager::EmulatedFDManager(FEXCore::Context::Context* ctx) + + EmulatedFDManager::~EmulatedFDManager() {} + ++static bool IsSelfProcPath(const char* Path) { ++ const char* P = Path + 6; ++ if (!isdigit(*P)) { ++ return true; ++ } ++ return strtol(P, nullptr, 10) == ::getpid(); ++} ++ ++static bool IsHostArchModule(const char* Path, fextl::unordered_map& Seen) { ++ auto Known = Seen.find(Path); ++ if (Known != Seen.end()) { ++ return Known->second; ++ } ++ bool Host = false; ++ int FD = ::open(Path, O_RDONLY | O_CLOEXEC); ++ if (FD >= 0) { ++ Elf64_Ehdr Header {}; ++ if (::pread(FD, &Header, sizeof(Header), 0) >= static_cast(offsetof(Elf64_Ehdr, e_version)) && ++ memcmp(Header.e_ident, ELFMAG, SELFMAG) == 0) { ++#if defined(__aarch64__) ++ Host = Header.e_machine == EM_AARCH64; ++#else ++ Host = Header.e_machine != EM_X86_64 && Header.e_machine != EM_386; ++#endif ++ } ++ ::close(FD); ++ } ++ Seen.emplace(Path, Host); ++ return Host; ++} ++ + static bool IsProcMapsPath(const char* Path) { + if (strncmp(Path, "/proc/", 6) != 0) { + return false; +@@ -661,14 +700,56 @@ int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, + ::close(HostFD); + + constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096; ++ const bool HostSharesGuestRange = FEXCore::Allocator::GetHostVABits() < 47; ++ const bool Self = IsSelfProcPath(pathname); ++ fextl::vector> GuestRanges; ++ if (HostSharesGuestRange && Self && FEX::HLE::_SyscallHandler) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(FEX::HLE::_SyscallHandler->VMATracking.Mutex); ++ GuestRanges.reserve(FEX::HLE::_SyscallHandler->VMATracking.VMAs.size()); ++ for (const auto& [Base, VMA] : FEX::HLE::_SyscallHandler->VMATracking.VMAs) { ++ if (!GuestRanges.empty() && GuestRanges.back().second >= Base) { ++ GuestRanges.back().second = std::max(GuestRanges.back().second, Base + VMA.Length); ++ } else { ++ GuestRanges.emplace_back(Base, Base + VMA.Length); ++ } ++ } ++ } ++ auto IsGuestRange = [&GuestRanges](uint64_t Start, uint64_t End) { ++ auto It = std::upper_bound(GuestRanges.begin(), GuestRanges.end(), Start, ++ [](uint64_t Value, const std::pair& Range) { return Value < Range.first; }); ++ if (It != GuestRanges.begin() && std::prev(It)->second > Start) { ++ return true; ++ } ++ return It != GuestRanges.end() && It->first < End; ++ }; ++ fextl::unordered_map ModuleArch; + 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) { ++ char* Cursor {}; ++ const uint64_t Start = strtoull(In.c_str() + Pos, &Cursor, 16); ++ const uint64_t Stop = *Cursor == '-' ? strtoull(Cursor + 1, nullptr, 16) : Start; ++ bool Keep = Start < X86_64TaskSizeMax; ++ if (Keep && HostSharesGuestRange) { ++ if (Self) { ++ Keep = IsGuestRange(Start, Stop); ++ } else { ++ const size_t LineEnd = Eol == fextl::string::npos ? In.size() : Eol; ++ size_t Name = In.find_first_of("/[", Pos); ++ if (Name != fextl::string::npos && Name < LineEnd) { ++ fextl::string Path(In, Name, LineEnd - Name); ++ if (Path.starts_with("[anon:FEX")) { ++ Keep = false; ++ } else if (Path[0] == '/') { ++ Keep = !IsHostArchModule(Path.c_str(), ModuleArch); ++ } ++ } ++ } ++ } ++ if (Keep) { + Out.append(In, Pos, End - Pos); + } + Pos = End; diff --git a/tools/fex/patches/0023-proc-status-seccomp-of-calling-thread.patch b/tools/fex/patches/0023-proc-status-seccomp-of-calling-thread.patch new file mode 100644 index 0000000000..d0550e8db0 --- /dev/null +++ b/tools/fex/patches/0023-proc-status-seccomp-of-calling-thread.patch @@ -0,0 +1,53 @@ +From 597bfab6ff068e0f6c08f63d6940486446967b0d Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Wed, 2 Dec 2026 18:21:23 -0500 +Subject: [PATCH] Report the calling thread's seccomp mode in /proc/self/status + +Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). + +--- + .../LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp | 6 +++++- + .../Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h | 10 ++++++++++ + 2 files changed, 15 insertions(+), 1 deletion(-) + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +index 65b0521c9..ce36b988b 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +@@ -797,7 +797,11 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd + Buf[Len] = '\0'; + + uint32_t SeccompMode = SECCOMP_MODE_DISABLED; +- if (auto* Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject()) { ++ auto* Thread = FEX::HLE::_SyscallHandler ? FEX::HLE::_SyscallHandler->TM.FindThreadByTID(::gettid()) : nullptr; ++ if (!Thread) { ++ Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject(); ++ } ++ if (Thread) { + SeccompMode = Thread->SeccompMode; + } + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +index 0a46703ca..9c5f9f1c2 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +@@ -290,6 +290,16 @@ public: + return &Threads; + } + ++ FEX::HLE::ThreadStateObject* FindThreadByTID(uint32_t TID) { ++ std::lock_guard lk(ThreadCreationMutex); ++ for (auto* Thread : Threads) { ++ if (Thread->ThreadInfo.TID == TID) { ++ return Thread; ++ } ++ } ++ return nullptr; ++ } ++ + private: + struct InvalidationStats { + explicit InvalidationStats(FEXCore::Core::InternalThreadState* Thread) +-- +2.43.0 + diff --git a/tools/fex/patches/0024-read-host-status-directly.patch b/tools/fex/patches/0024-read-host-status-directly.patch new file mode 100644 index 0000000000..8a5268c7e7 --- /dev/null +++ b/tools/fex/patches/0024-read-host-status-directly.patch @@ -0,0 +1,105 @@ +From ab6a01db9e93e7f143b9a3da5b40dcb160b960f3 Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Wed, 2 Dec 2026 18:25:20 -0500 +Subject: [PATCH] Read FEX's own /proc/self/status with a direct openat system + call + +Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). + +--- + FEXHeaderUtils/FEXHeaderUtils/Syscalls.h | 30 +++++++++++++++++++ + .../EmulatedFiles/EmulatedFiles.cpp | 3 +- + .../LinuxSyscalls/PtraceEmu.cpp | 3 +- + 3 files changed, 34 insertions(+), 2 deletions(-) + +diff --git a/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h b/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h +index dae3d3bcc..c0f3eb3ed 100644 +--- a/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h ++++ b/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h +@@ -4,6 +4,7 @@ + #include + + #include ++#include + #include + #include + #include +@@ -123,4 +124,33 @@ inline int32_t gettid() { + + #endif + ++#ifndef _WIN32 ++inline int32_t openat_kernel(int dirfd, const char* pathname, int flags) { ++#if defined(__aarch64__) ++ register long x0 asm("x0") = dirfd; ++ register long x1 asm("x1") = reinterpret_cast(pathname); ++ register long x2 asm("x2") = flags; ++ register long x3 asm("x3") = 0; ++ register long x8 asm("x8") = SYS_openat; ++ asm volatile("svc #0" : "+r"(x0) : "r"(x1), "r"(x2), "r"(x3), "r"(x8) : "memory"); ++ if (x0 < 0) { ++ errno = static_cast(-x0); ++ return -1; ++ } ++ return static_cast(x0); ++#elif defined(__x86_64__) ++ long ret; ++ register long r10 asm("r10") = 0; ++ asm volatile("syscall" : "=a"(ret) : "a"(SYS_openat), "D"(dirfd), "S"(pathname), "d"(flags), "r"(r10) : "rcx", "r11", "memory"); ++ if (ret < 0) { ++ errno = static_cast(-ret); ++ return -1; ++ } ++ return static_cast(ret); ++#else ++ return static_cast(::syscall(SYS_openat, dirfd, pathname, flags)); ++#endif ++} ++#endif ++ + } // namespace FHU::Syscalls +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +index ce36b988b..19bfc814f 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +@@ -14,6 +14,7 @@ $end_info$ + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/EmulatedFiles/EmulatedFiles.h" + ++#include + #include + #include + #include +@@ -785,7 +786,7 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd + char Buf[8192]; + ssize_t Len = 0; + { +- int HostFD = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC); ++ int HostFD = FHU::Syscalls::openat_kernel(AT_FDCWD, "/proc/self/status", O_RDONLY | O_CLOEXEC); + if (HostFD >= 0) { + Len = ::read(HostFD, Buf, sizeof(Buf) - 1); + ::close(HostFD); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +index ca4c86063..49ece24a3 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +@@ -3,6 +3,7 @@ + #include "LinuxSyscalls/PtraceEmu.h" + #include "LinuxSyscalls/Syscalls.h" + ++#include + #include + #include + +@@ -133,7 +134,7 @@ namespace { + } + + bool HasHostTracer() { +- const int fd = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC); ++ const int fd = FHU::Syscalls::openat_kernel(AT_FDCWD, "/proc/self/status", O_RDONLY | O_CLOEXEC); + if (fd < 0) { + return true; + } +-- +2.43.0 + diff --git a/tools/fex/patches/0025-ptrace-state-across-exec.patch b/tools/fex/patches/0025-ptrace-state-across-exec.patch new file mode 100644 index 0000000000..6c1bcc618f --- /dev/null +++ b/tools/fex/patches/0025-ptrace-state-across-exec.patch @@ -0,0 +1,104 @@ +From 38ee3ef08d9bfd8312fccff688290572da82ef2a Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Wed, 2 Dec 2026 18:41:52 -0500 +Subject: [PATCH] Hand the tracee's ptrace state across exec + +Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). + +--- + .../LinuxSyscalls/PtraceEmu.cpp | 54 ++++++++++++++++++- + 1 file changed, 53 insertions(+), 1 deletion(-) + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +index 49ece24a3..62acdb0da 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +@@ -266,6 +266,38 @@ namespace { + ::close(fd); + } + ++ bool AdoptionTried = false; ++ ++ void AdoptSharedPage() { ++ if (AdoptionTried || Current != &StaticState || !IsMainThread()) { ++ return; ++ } ++ AdoptionTried = true; ++ const int fd = OpenSidecar("state", ::getpid(), O_RDWR); ++ if (fd < 0) { ++ return; ++ } ++ if (!HasHostTracer()) { ++ ::close(fd); ++ return; ++ } ++ void* Page = ::mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ ::close(fd); ++ if (Page == MAP_FAILED) { ++ return; ++ } ++ auto* S = static_cast(Page); ++ if (S->Magic != SharedState::MagicValue) { ++ ::munmap(Page, 4096); ++ return; ++ } ++ S->Pending = 0; ++ S->DirtyMask = 0; ++ S->SignalNumber = 0; ++ S->FlushLen = 0; ++ Current = S; ++ } ++ + struct Remote { + uint8_t* Mapped = nullptr; + uintptr_t StaticAddr = 0; +@@ -332,6 +364,22 @@ namespace { + return &Remotes.emplace(Pid, std::move(R)).first->second; + } + ++ bool KeepAcrossExec(pid_t Pid) { ++ { ++ std::lock_guard lk(RemotesLock); ++ auto It = Remotes.find(Pid); ++ if (It != Remotes.end()) { ++ return It->second.Mapped != nullptr; ++ } ++ } ++ const int fd = OpenSidecar("state", Pid, O_RDONLY); ++ if (fd < 0) { ++ return false; ++ } ++ ::close(fd); ++ return true; ++ } ++ + void Forget(pid_t Pid, bool Exited) { + std::lock_guard lk(RemotesLock); + auto It = Remotes.find(Pid); +@@ -470,10 +518,12 @@ namespace { + + + bool IsAttached() { ++ AdoptSharedPage(); + return Current->Attached != 0; + } + + bool WantsSyscallStops() { ++ AdoptSharedPage(); + return Current->SyscallStops && IsMainThread(); + } + +@@ -610,7 +660,9 @@ bool FixupWaitStatus(pid_t Pid, int* Status) { + + if ((St >> 16) == X86_PTRACE_EVENT_EXEC) { + CaptureExecPath(Pid); +- Forget(Pid, false); ++ if (!KeepAcrossExec(Pid)) { ++ Forget(Pid, false); ++ } + } + + if (WSTOPSIG(St) == SIGSTOP) { +-- +2.43.0 + diff --git a/tools/fex/patches/0026-emulated-proc-files-behind-host-memfd.patch b/tools/fex/patches/0026-emulated-proc-files-behind-host-memfd.patch new file mode 100644 index 0000000000..0ebaff5209 --- /dev/null +++ b/tools/fex/patches/0026-emulated-proc-files-behind-host-memfd.patch @@ -0,0 +1,78 @@ +From 834075bdee10fb0a1c7a7f499a0bb97162370b5d Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Wed, 2 Dec 2026 18:58:13 -0500 +Subject: [PATCH] Serve emulated proc files by the requested path when the host + returns a memfd + +Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). +--- + .../LinuxEmulation/LinuxSyscalls/FileManagement.cpp | 11 +++++++---- + .../LinuxEmulation/LinuxSyscalls/FileManagement.h | 2 +- + 2 files changed, 8 insertions(+), 5 deletions(-) + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp +index 62b6a2d27..b76e96e58 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp +@@ -785,7 +785,7 @@ static int OpenatWithoutOpenat2(int DirFD, const char* Pathname, int Flags, uint + return ::syscall(SYSCALL_DEF(openat), DirFD, Resolved, Flags, Mode); + } + +-bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) { ++bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode, const char* RequestedPath) { + char Tmp[PATH_MAX + 1]; + + if (fd < 0) { +@@ -801,6 +801,9 @@ bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) { + + // And try to open via EmuFD + auto EmuFd = EmuFD.Open(Tmp, flags, mode); ++ if (EmuFd == -1 && RequestedPath && RequestedPath[0] == '/' && strncmp(Tmp, "/memfd:", 7) == 0) { ++ EmuFd = EmuFD.Open(RequestedPath, flags, mode); ++ } + if (EmuFd == -1) { + return false; + } +@@ -841,7 +844,7 @@ uint64_t FileManager::Open(const char* pathname, int flags, uint32_t mode) { + fd = ::open(SelfPath, flags, mode); + } + +- ReplaceEmuFd(fd, flags, mode); ++ ReplaceEmuFd(fd, flags, mode, SelfPath); + } else { + fd = ::open(SelfPath, flags, mode); + } +@@ -1135,7 +1138,7 @@ uint64_t FileManager::Openat([[maybe_unused]] int dirfs, const char* pathname, i + fd = ::syscall(SYSCALL_DEF(openat), dirfs, SelfPath, flags, mode); + } + +- ReplaceEmuFd(fd, flags, mode); ++ ReplaceEmuFd(fd, flags, mode, SelfPath); + } else { + fd = ::syscall(SYSCALL_DEF(openat), dirfs, SelfPath, flags, mode); + } +@@ -1173,7 +1176,7 @@ uint64_t FileManager::Openat2(int dirfs, const char* pathname, FEX::HLE::open_ho + fd = ::syscall(SYSCALL_DEF(openat2), dirfs, SelfPath, how, usize); + } + +- ReplaceEmuFd(fd, how->flags, how->mode); ++ ReplaceEmuFd(fd, how->flags, how->mode, SelfPath); + } else { + fd = ::syscall(SYSCALL_DEF(openat2), dirfs, SelfPath, how, usize); + } +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h +index b11f096f7..a86539972 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h +@@ -102,7 +102,7 @@ public: + fextl::string GetEmulatedPath(const char* pathname, bool FollowSymlink = false) const; + fextl::string GetHostPath(fextl::string& Path, bool AliasedOnly) const; + +- bool ReplaceEmuFd(int fd, int flags, uint32_t mode); ++ bool ReplaceEmuFd(int fd, int flags, uint32_t mode, const char* RequestedPath); + + #if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED + void TrackFEXFD(int FD) noexcept { +-- +2.43.0 + diff --git a/tools/fex/patches/0027-fixed-guest-memory-above-host-address-limit.patch b/tools/fex/patches/0027-fixed-guest-memory-above-host-address-limit.patch new file mode 100644 index 0000000000..b19386b095 --- /dev/null +++ b/tools/fex/patches/0027-fixed-guest-memory-above-host-address-limit.patch @@ -0,0 +1,3258 @@ +From 4e237204720bf57c8e4b7dae1ff74b5e341763e6 Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Wed, 2 Dec 2026 20:01:44 -0500 +Subject: [PATCH] Map fixed guest memory above a small host address space + +Hosts with 39-bit or 42-bit user address spaces cannot place x86-64 +mappings that ask for a fixed address above that limit. Such mappings +are now backed by host memory at any address, and guest accesses to +them are redirected through a per-thread single-instruction trampoline. +Syscall arguments that point into these mappings are translated, and +writes to code in them invalidate translated blocks. + +Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). +--- + Source/Tools/LinuxEmulation/CMakeLists.txt | 1 + + .../LinuxSyscalls/GuestHighMemory.cpp | 2754 +++++++++++++++++ + .../LinuxSyscalls/GuestHighMemory.h | 74 + + .../LinuxSyscalls/SignalDelegator.cpp | 5 + + .../LinuxEmulation/LinuxSyscalls/Syscalls.cpp | 53 +- + .../LinuxSyscalls/Syscalls/Memory.cpp | 30 + + .../LinuxSyscalls/SyscallsSMCTracking.cpp | 61 +- + .../LinuxSyscalls/ThreadManager.cpp | 2 + + .../LinuxSyscalls/ThreadManager.h | 34 + + 9 files changed, 2984 insertions(+), 30 deletions(-) + create mode 100644 Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp + create mode 100644 Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h + +diff --git a/Source/Tools/LinuxEmulation/CMakeLists.txt b/Source/Tools/LinuxEmulation/CMakeLists.txt +index 3f02104..acf4c4c 100644 +--- a/Source/Tools/LinuxEmulation/CMakeLists.txt ++++ b/Source/Tools/LinuxEmulation/CMakeLists.txt +@@ -18,6 +18,7 @@ add_library(LinuxEmulation STATIC + LinuxSyscalls/Seccomp/BPFEmitter.cpp + LinuxSyscalls/Seccomp/Dumper.cpp + LinuxSyscalls/SignalDelegator.cpp ++ LinuxSyscalls/GuestHighMemory.cpp + LinuxSyscalls/Syscalls.cpp + LinuxSyscalls/SyscallsSMCTracking.cpp + LinuxSyscalls/SyscallsVMATracking.cpp +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp +new file mode 100644 +index 0000000..4483499 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp +@@ -0,0 +1,2754 @@ ++#include "LinuxSyscalls/GuestHighMemory.h" ++#include "LinuxSyscalls/Syscalls.h" ++#include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/ThreadManager.h" ++#include "LinuxSyscalls/x64/SyscallsEnum.h" ++#include "ArchHelpers/MContext.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace FEX::HLE::GuestHighMemory { ++namespace { ++ constexpr uint64_t TaskTop = (1ULL << 47) - FEXCore::Utils::FEX_PAGE_SIZE; ++ constexpr uint32_t MaxRegions = 1024; ++ ++ struct Region { ++ std::atomic Guest; ++ std::atomic Size; ++ std::atomic Host; ++ std::atomic Code; ++ std::atomic Prot; ++ }; ++ ++ struct RegionView { ++ uint64_t Guest; ++ uint64_t Size; ++ uint64_t Host; ++ uint32_t Index; ++ bool Code; ++ uint8_t Prot; ++ }; ++ ++ struct HostRange { ++ uint64_t Start; ++ uint64_t Size; ++ }; ++ ++ constexpr uint32_t MaxAccessPieces = 2; ++ ++ struct AccessPiece { ++ uint64_t Guest; ++ uint64_t Host; ++ uint64_t Size; ++ uint8_t Prot; ++ bool Code; ++ }; ++ ++ Region Regions[MaxRegions]; ++ std::atomic Count {0}; ++ HostRange Retired[MaxRegions]; ++ uint32_t RetiredCount {}; ++ std::atomic Sequence {0}; ++ ++ uint64_t HostLimit() { ++ static const uint64_t Limit = [] { ++ const auto Bits = FEXCore::Allocator::GetHostVABits(); ++ return Bits >= 47 ? TaskTop : (1ULL << Bits); ++ }(); ++ return Limit; ++ } ++ ++ void BeginWrite() { ++ Sequence.fetch_add(1, std::memory_order_acq_rel); ++ } ++ ++ void EndWrite() { ++ Sequence.fetch_add(1, std::memory_order_release); ++ } ++ ++ bool FindLocked(uint64_t Address, RegionView* Out) { ++ const auto Entries = Count.load(std::memory_order_acquire); ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto Size = Regions[i].Size.load(std::memory_order_relaxed); ++ if (Address >= Guest && Address - Guest < Size) { ++ Out->Guest = Guest; ++ Out->Size = Size; ++ Out->Host = Regions[i].Host.load(std::memory_order_relaxed); ++ Out->Code = Regions[i].Code.load(std::memory_order_relaxed); ++ Out->Prot = Regions[i].Prot.load(std::memory_order_relaxed); ++ Out->Index = i; ++ return true; ++ } ++ } ++ return false; ++ } ++ ++ template ++ auto ReadConsistent(Fn&& Body) { ++ for (;;) { ++ const auto Before = Sequence.load(std::memory_order_acquire); ++ if (Before & 1) { ++ continue; ++ } ++ const auto Result = Body(); ++ std::atomic_thread_fence(std::memory_order_acquire); ++ if (Sequence.load(std::memory_order_relaxed) == Before) { ++ return Result; ++ } ++ } ++ } ++ ++ bool SpanLocked(uint64_t Address, uint64_t Length, uint64_t* Host) { ++ RegionView View; ++ if (!FindLocked(Address, &View)) { ++ *Host = Address; ++ return true; ++ } ++ *Host = View.Host + (Address - View.Guest); ++ if (Length > TaskTop - Address) { ++ return false; ++ } ++ const auto End = Address + Length; ++ auto GuestEnd = View.Guest + View.Size; ++ auto HostEnd = View.Host + View.Size; ++ while (End > GuestEnd) { ++ if (!FindLocked(GuestEnd, &View) || View.Host != HostEnd) { ++ return false; ++ } ++ GuestEnd += View.Size; ++ HostEnd += View.Size; ++ } ++ return true; ++ } ++ ++ uint32_t PlanAccessLocked(uint64_t Address, uint64_t Size, AccessPiece* Pieces) { ++ uint32_t Parts = 0; ++ uint64_t Done = 0; ++ while (Done < Size) { ++ RegionView View; ++ if (Parts == MaxAccessPieces || !FindLocked(Address + Done, &View)) { ++ return 0; ++ } ++ const auto Offset = Address + Done - View.Guest; ++ const auto Length = std::min(Size - Done, View.Size - Offset); ++ Pieces[Parts++] = {Address + Done, View.Host + Offset, Length, View.Prot, View.Code}; ++ Done += Length; ++ } ++ return Parts; ++ } ++ ++ template ++ uint64_t ApplyToRegionsLocked(uint64_t Address, uint64_t Length, uint64_t WrapError, Fn&& Apply) { ++ if (Address & (FEXCore::Utils::FEX_PAGE_SIZE - 1)) { ++ return -EINVAL; ++ } ++ if (Length == 0) { ++ return 0; ++ } ++ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE); ++ if (Size == 0 || Size > UINT64_MAX - Address) { ++ return WrapError; ++ } ++ const auto End = Address + std::min(Size, TaskTop - Address); ++ uint64_t Covered = 0; ++ const auto Entries = Count.load(std::memory_order_acquire); ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto RegionEnd = Guest + Regions[i].Size.load(std::memory_order_relaxed); ++ if (RegionEnd <= Address || Guest >= End) { ++ continue; ++ } ++ const auto OverlapStart = std::max(Guest, Address); ++ const auto OverlapEnd = std::min(RegionEnd, End); ++ const auto Host = Regions[i].Host.load(std::memory_order_relaxed) + (OverlapStart - Guest); ++ if (Apply(reinterpret_cast(Host), OverlapEnd - OverlapStart, i) != 0) { ++ return -errno; ++ } ++ Covered += OverlapEnd - OverlapStart; ++ } ++ return Covered == Size ? 0 : -ENOMEM; ++ } ++ ++ uint64_t NeighbourHint(uint64_t Address, uint64_t Size) { ++ const auto Entries = Count.load(std::memory_order_relaxed); ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto RegionSize = Regions[i].Size.load(std::memory_order_relaxed); ++ const auto Host = Regions[i].Host.load(std::memory_order_relaxed); ++ if (Guest + RegionSize == Address) { ++ return Host + RegionSize; ++ } ++ if (Guest == Address + Size && Host >= Size) { ++ return Host - Size; ++ } ++ } ++ return 0; ++ } ++ ++ void SetEntry(uint32_t i, uint64_t Guest, uint64_t Size, uint64_t Host, bool Code, uint8_t Prot) { ++ Regions[i].Guest.store(Guest, std::memory_order_relaxed); ++ Regions[i].Size.store(Size, std::memory_order_relaxed); ++ Regions[i].Host.store(Host, std::memory_order_relaxed); ++ Regions[i].Code.store(Code, std::memory_order_relaxed); ++ Regions[i].Prot.store(Prot, std::memory_order_relaxed); ++ } ++ ++ void RemoveEntry(uint32_t i) { ++ const auto Last = Count.load(std::memory_order_relaxed) - 1; ++ if (i != Last) { ++ SetEntry(i, Regions[Last].Guest.load(std::memory_order_relaxed), Regions[Last].Size.load(std::memory_order_relaxed), ++ Regions[Last].Host.load(std::memory_order_relaxed), Regions[Last].Code.load(std::memory_order_relaxed), ++ Regions[Last].Prot.load(std::memory_order_relaxed)); ++ } ++ Count.store(Last, std::memory_order_release); ++ } ++ ++ bool AddEntry(uint64_t Guest, uint64_t Size, uint64_t Host, bool Code, uint8_t Prot) { ++ const auto Entries = Count.load(std::memory_order_relaxed); ++ if (Entries >= MaxRegions) { ++ return false; ++ } ++ SetEntry(Entries, Guest, Size, Host, Code, Prot); ++ Count.store(Entries + 1, std::memory_order_release); ++ return true; ++ } ++ ++ bool HasRoomLocked(uint64_t Address, uint64_t Length, uint32_t Added) { ++ const auto End = Address + Length; ++ const auto Entries = Count.load(std::memory_order_relaxed); ++ uint64_t After = Entries + Added; ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto RegionEnd = Guest + Regions[i].Size.load(std::memory_order_relaxed); ++ if (RegionEnd <= Address || Guest >= End) { ++ continue; ++ } ++ if (Guest >= Address && RegionEnd <= End) { ++ --After; ++ } else if (Guest < Address && RegionEnd > End) { ++ ++After; ++ } ++ } ++ return After <= MaxRegions; ++ } ++ ++ void ReleaseRetiredLocked() { ++ uint32_t i = 0; ++ while (i < RetiredCount) { ++ if (::munmap(reinterpret_cast(Retired[i].Start), Retired[i].Size) == 0) { ++ Retired[i] = Retired[--RetiredCount]; ++ } else { ++ ++i; ++ } ++ } ++ } ++ ++ void UnmapHost(uint64_t Start, uint64_t Size) { ++ if (::munmap(reinterpret_cast(Start), Size) == 0) { ++ return; ++ } ++ ::madvise(reinterpret_cast(Start), Size, MADV_DONTNEED); ++ for (uint32_t i = 0; i < RetiredCount; ++i) { ++ if (Retired[i].Start + Retired[i].Size == Start) { ++ Retired[i].Size += Size; ++ return; ++ } ++ if (Start + Size == Retired[i].Start) { ++ Retired[i] = {Start, Retired[i].Size + Size}; ++ return; ++ } ++ } ++ if (RetiredCount < MaxRegions) { ++ Retired[RetiredCount++] = {Start, Size}; ++ } ++ } ++ ++ int UnmapLocked(uint64_t Address, uint64_t Length) { ++ ReleaseRetiredLocked(); ++ if (!HasRoomLocked(Address, Length, 0)) { ++ return -ENOMEM; ++ } ++ const auto End = Address + Length; ++ uint32_t Overlapping = 0; ++ for (uint32_t i = 0; i < Count.load(std::memory_order_relaxed); ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ if (Guest < End && Guest + Regions[i].Size.load(std::memory_order_relaxed) > Address) { ++ ++Overlapping; ++ } ++ } ++ if (RetiredCount + Overlapping > MaxRegions) { ++ return -ENOMEM; ++ } ++ uint32_t i = 0; ++ while (i < Count.load(std::memory_order_relaxed)) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto Size = Regions[i].Size.load(std::memory_order_relaxed); ++ const auto Host = Regions[i].Host.load(std::memory_order_relaxed); ++ const auto Code = Regions[i].Code.load(std::memory_order_relaxed); ++ const auto Prot = Regions[i].Prot.load(std::memory_order_relaxed); ++ const auto RegionEnd = Guest + Size; ++ if (RegionEnd <= Address || Guest >= End) { ++ ++i; ++ continue; ++ } ++ const auto OverlapStart = std::max(Guest, Address); ++ const auto OverlapEnd = std::min(RegionEnd, End); ++ UnmapHost(Host + (OverlapStart - Guest), OverlapEnd - OverlapStart); ++ ++ if (OverlapStart == Guest && OverlapEnd == RegionEnd) { ++ RemoveEntry(i); ++ continue; ++ } ++ if (OverlapStart == Guest) { ++ SetEntry(i, OverlapEnd, RegionEnd - OverlapEnd, Host + (OverlapEnd - Guest), Code, Prot); ++ } else if (OverlapEnd == RegionEnd) { ++ SetEntry(i, Guest, OverlapStart - Guest, Host, Code, Prot); ++ } else { ++ if (!AddEntry(OverlapEnd, RegionEnd - OverlapEnd, Host + (OverlapEnd - Guest), Code, Prot)) { ++ return -ENOMEM; ++ } ++ SetEntry(i, Guest, OverlapStart - Guest, Host, Code, Prot); ++ } ++ ++i; ++ } ++ return 0; ++ } ++ ++ constexpr uint8_t TrackedProt(int Prot) { ++ return Prot & (PROT_READ | PROT_WRITE | PROT_EXEC); ++ } ++ ++ int SplitLocked(uint64_t Address, uint64_t Length) { ++ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE); ++ if (Size == 0) { ++ return 0; ++ } ++ const uint64_t Boundaries[] = {Address, Address + std::min(Size, TaskTop - Address)}; ++ uint32_t Needed = 0; ++ const auto Entries = Count.load(std::memory_order_relaxed); ++ for (const auto Boundary : Boundaries) { ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ if (Boundary > Guest && Boundary - Guest < Regions[i].Size.load(std::memory_order_relaxed)) { ++ ++Needed; ++ } ++ } ++ } ++ if (Entries + Needed > MaxRegions) { ++ return -ENOMEM; ++ } ++ for (const auto Boundary : Boundaries) { ++ for (uint32_t i = 0; i < Count.load(std::memory_order_relaxed); ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto RegionSize = Regions[i].Size.load(std::memory_order_relaxed); ++ if (Boundary <= Guest || Boundary - Guest >= RegionSize) { ++ continue; ++ } ++ const auto Host = Regions[i].Host.load(std::memory_order_relaxed); ++ const auto Code = Regions[i].Code.load(std::memory_order_relaxed); ++ const auto Prot = Regions[i].Prot.load(std::memory_order_relaxed); ++ AddEntry(Boundary, Guest + RegionSize - Boundary, Host + (Boundary - Guest), Code, Prot); ++ SetEntry(i, Guest, Boundary - Guest, Host, Code, Prot); ++ break; ++ } ++ } ++ return 0; ++ } ++ ++ void CoalesceLocked(uint64_t Address, uint64_t End) { ++ uint32_t i = 0; ++ while (i < Count.load(std::memory_order_relaxed)) { ++ const auto Entries = Count.load(std::memory_order_relaxed); ++ const auto Size = Regions[i].Size.load(std::memory_order_relaxed); ++ const auto RegionEnd = Regions[i].Guest.load(std::memory_order_relaxed) + Size; ++ const auto HostEnd = Regions[i].Host.load(std::memory_order_relaxed) + Size; ++ const auto Code = Regions[i].Code.load(std::memory_order_relaxed); ++ const auto Prot = Regions[i].Prot.load(std::memory_order_relaxed); ++ uint32_t Next = Entries; ++ if (RegionEnd >= Address && RegionEnd <= End) { ++ for (uint32_t j = 0; j < Entries; ++j) { ++ if (Regions[j].Guest.load(std::memory_order_relaxed) == RegionEnd && Regions[j].Host.load(std::memory_order_relaxed) == HostEnd && ++ Regions[j].Code.load(std::memory_order_relaxed) == Code && Regions[j].Prot.load(std::memory_order_relaxed) == Prot) { ++ Next = j; ++ break; ++ } ++ } ++ } ++ if (Next == Entries) { ++ ++i; ++ continue; ++ } ++ Regions[i].Size.store(Size + Regions[Next].Size.load(std::memory_order_relaxed), std::memory_order_relaxed); ++ RemoveEntry(Next); ++ if (i == Entries - 1 || Next < i) { ++ i = Next; ++ } ++ } ++ } ++ ++ constexpr uint32_t RtField(uint32_t Insn) { ++ return Insn & 0x1f; ++ } ++ ++ constexpr uint32_t RnField(uint32_t Insn) { ++ return (Insn >> 5) & 0x1f; ++ } ++ ++ constexpr uint32_t Rt2Field(uint32_t Insn) { ++ return (Insn >> 10) & 0x1f; ++ } ++ ++ constexpr uint32_t RsField(uint32_t Insn) { ++ return (Insn >> 16) & 0x1f; ++ } ++ ++ constexpr bool IsLoadStore(uint32_t Insn) { ++ return (Insn & 0x0a000000) == 0x08000000; ++ } ++ ++ constexpr bool IsLiteralLoad(uint32_t Insn) { ++ return (Insn & 0x3b000000) == 0x18000000; ++ } ++ ++ constexpr bool IsExclusive(uint32_t Insn) { ++ if ((Insn & 0x3f800000) != 0x08000000) { ++ return false; ++ } ++ return (Insn & (1U << 21)) == 0 || (Insn & (1U << 31)) != 0; ++ } ++ ++ constexpr bool IsSingleRegister(uint32_t Insn) { ++ return (Insn & 0x3a000000) == 0x38000000 || (Insn & 0x3f200c00) == 0x19000000; ++ } ++ ++ constexpr bool IsWrite(uint32_t Insn) { ++ if ((Insn & 0x3b200c00) == 0x38200000) { ++ return ((Insn >> 12) & 0xf) != 0xc; ++ } ++ if ((Insn & 0x3f200000) == 0x08200000 && Rt2Field(Insn) == 0x1f) { ++ return true; ++ } ++ if (IsSingleRegister(Insn)) { ++ const auto Opc = (Insn >> 22) & 3; ++ return ((Insn >> 26) & 1) ? (Opc & 1) == 0 : Opc == 0; ++ } ++ return (Insn & (1U << 22)) == 0; ++ } ++ ++ constexpr bool IsOrderedAccess(uint32_t Insn) { ++ if ((Insn & 0x3f200c00) == 0x19000000) { ++ const auto Opc = (Insn >> 22) & 3; ++ const auto SizeBits = Insn >> 30; ++ return Opc < 2 || (Opc == 2 && SizeBits < 3) || (Opc == 3 && SizeBits < 2); ++ } ++ return (Insn & 0x3fbf7c00) == 0x089f7c00 || (Insn & 0x3ffffc00) == 0x38bfc000; ++ } ++ ++ constexpr uint64_t ExtendOrdered(uint32_t Insn, uint64_t Value) { ++ const auto Bits = 8U << (Insn >> 30); ++ const auto Opc = (Insn >> 22) & 3; ++ if ((Insn & 0x3f200c00) != 0x19000000 || Bits == 64 || Opc < 2) { ++ return Value; ++ } ++ const auto Signed = static_cast(static_cast(Value << (64 - Bits)) >> (64 - Bits)); ++ return Opc == 3 ? Signed & 0xffffffffULL : Signed; ++ } ++ ++ constexpr uint32_t ProbeInstruction(uint32_t Scratch) { ++ return 0x39400000 | (Scratch << 5) | Scratch; ++ } ++ ++ constexpr bool IsExclusiveLoad(uint32_t Insn) { ++ return (Insn & (1U << 22)) != 0; ++ } ++ ++ constexpr bool IsExclusivePair(uint32_t Insn) { ++ return (Insn & (1U << 21)) != 0; ++ } ++ ++ constexpr bool ExclusiveReachable(uint32_t Insn, uint8_t Prot) { ++ if (IsExclusiveLoad(Insn)) { ++ return (Prot & (PROT_READ | PROT_WRITE)) != 0; ++ } ++ return (Prot & PROT_WRITE) != 0; ++ } ++ ++ constexpr uint32_t ExclusiveElementSize(uint32_t Insn) { ++ return 1U << (Insn >> 30); ++ } ++ ++ uint64_t ReadReg(void* UContext, uint32_t Reg) { ++ return Reg == 31 ? 0 : ArchHelpers::Context::GetArmReg(UContext, Reg); ++ } ++ ++ void WriteReg(void* UContext, uint32_t Reg, uint64_t Value) { ++ if (Reg != 31) { ++ ArchHelpers::Context::SetArmReg(UContext, Reg, Value); ++ } ++ } ++ ++ uint64_t ElementMask(uint32_t Size) { ++ return Size == 8 ? ~0ULL : (1ULL << (Size * 8)) - 1; ++ } ++ ++ uint64_t LoadElement(uint64_t Host, uint32_t Size) { ++ switch (Size) { ++ case 1: return __atomic_load_n(reinterpret_cast(Host), __ATOMIC_SEQ_CST); ++ case 2: return __atomic_load_n(reinterpret_cast(Host), __ATOMIC_SEQ_CST); ++ case 4: return __atomic_load_n(reinterpret_cast(Host), __ATOMIC_SEQ_CST); ++ default: return __atomic_load_n(reinterpret_cast(Host), __ATOMIC_SEQ_CST); ++ } ++ } ++ ++ bool CompareExchange(uint64_t Host, uint32_t Size, uint64_t ExpectedLow, uint64_t ExpectedHigh, uint64_t Low, uint64_t High) { ++ switch (Size) { ++ case 1: { ++ auto Expected = static_cast(ExpectedLow); ++ return __atomic_compare_exchange_n(reinterpret_cast(Host), &Expected, static_cast(Low), false, ++ __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); ++ } ++ case 2: { ++ auto Expected = static_cast(ExpectedLow); ++ return __atomic_compare_exchange_n(reinterpret_cast(Host), &Expected, static_cast(Low), false, ++ __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); ++ } ++ case 4: { ++ auto Expected = static_cast(ExpectedLow); ++ return __atomic_compare_exchange_n(reinterpret_cast(Host), &Expected, static_cast(Low), false, ++ __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); ++ } ++ case 8: { ++ auto Expected = ExpectedLow; ++ return __atomic_compare_exchange_n(reinterpret_cast(Host), &Expected, Low, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); ++ } ++ default: { ++ auto Expected = (static_cast(ExpectedHigh) << 64) | ExpectedLow; ++ const auto Desired = (static_cast(High) << 64) | Low; ++ return __atomic_compare_exchange_n(reinterpret_cast(Host), &Expected, Desired, false, __ATOMIC_SEQ_CST, ++ __ATOMIC_SEQ_CST); ++ } ++ } ++ } ++ ++ template ++ bool EmulateExclusive(MonitorType& Monitor, uint32_t Insn, uint64_t Host, void* UContext) { ++ const auto Element = ExclusiveElementSize(Insn); ++ const bool Pair = IsExclusivePair(Insn); ++ const auto Size = Pair ? Element * 2 : Element; ++ if (Host & (Size - 1)) { ++ return false; ++ } ++ ++ if (IsExclusiveLoad(Insn)) { ++ uint64_t Low {}; ++ uint64_t High {}; ++ if (Pair && Element == 8) { ++ Low = LoadElement(Host, 8); ++ High = LoadElement(Host + 8, 8); ++ WriteReg(UContext, RtField(Insn), Low); ++ WriteReg(UContext, Rt2Field(Insn), High); ++ } else if (Pair) { ++ Low = LoadElement(Host, 8); ++ WriteReg(UContext, RtField(Insn), Low & 0xffffffffULL); ++ WriteReg(UContext, Rt2Field(Insn), Low >> 32); ++ } else { ++ Low = LoadElement(Host, Element); ++ WriteReg(UContext, RtField(Insn), Low); ++ } ++ Monitor.Host = Host; ++ Monitor.Size = Size; ++ Monitor.Low = Low; ++ Monitor.High = High; ++ Monitor.Valid = true; ++ return true; ++ } ++ ++ uint64_t Low {}; ++ uint64_t High {}; ++ if (Pair && Element == 8) { ++ Low = ReadReg(UContext, RtField(Insn)); ++ High = ReadReg(UContext, Rt2Field(Insn)); ++ } else if (Pair) { ++ Low = (ReadReg(UContext, RtField(Insn)) & 0xffffffffULL) | (ReadReg(UContext, Rt2Field(Insn)) << 32); ++ } else { ++ Low = ReadReg(UContext, RtField(Insn)) & ElementMask(Element); ++ } ++ const bool Stored = Monitor.Valid && Monitor.Host == Host && Monitor.Size == Size && ++ CompareExchange(Host, Size, Monitor.Low, Monitor.High, Low, High); ++ Monitor.Valid = false; ++ WriteReg(UContext, RsField(Insn), Stored ? 0 : 1); ++ return true; ++ } ++ ++ int64_t SignedField(uint32_t Insn, uint32_t Shift, uint32_t Bits) { ++ return static_cast(static_cast(Insn >> Shift) << (64 - Bits)) >> (64 - Bits); ++ } ++ ++ bool DecodeAccess(uint32_t Insn, void* UContext, uint64_t* Address, uint32_t* Size, bool* Plain) { ++ const auto Base = ArchHelpers::Context::GetArmReg(UContext, RnField(Insn)); ++ const auto SizeBits = Insn >> 30; ++ const bool Vector = (Insn >> 26) & 1; ++ const auto Scale = Vector && ((Insn >> 23) & 1) && SizeBits == 0 ? 4U : SizeBits; ++ *Address = Base; ++ *Plain = false; ++ if ((Insn & 0x3f000000) == 0x08000000) { ++ const bool Pair = (Insn & (1U << 21)) && !(Insn & (1U << 23)); ++ *Size = Pair ? 8U << (SizeBits & 1) : 1U << SizeBits; ++ return true; ++ } ++ if ((Insn & 0x3f200c00) == 0x19000000) { ++ *Address = Base + SignedField(Insn, 12, 9); ++ *Size = 1U << SizeBits; ++ return true; ++ } ++ if ((Insn & 0x3b200c00) == 0x38200000) { ++ *Size = 1U << SizeBits; ++ return !Vector; ++ } ++ *Plain = true; ++ if ((Insn & 0x3b000000) == 0x39000000) { ++ *Address = Base + (static_cast((Insn >> 10) & 0xfff) << Scale); ++ *Size = 1U << Scale; ++ return true; ++ } ++ if ((Insn & 0x3b200000) == 0x38000000) { ++ *Address = ((Insn >> 10) & 3) == 1 ? Base : Base + SignedField(Insn, 12, 9); ++ *Size = 1U << Scale; ++ return true; ++ } ++ if ((Insn & 0x3b200c00) == 0x38200800) { ++ const auto Option = (Insn >> 13) & 7; ++ if ((Option & 2) == 0) { ++ return false; ++ } ++ auto Offset = ReadReg(UContext, RsField(Insn)); ++ if ((Option & 1) == 0) { ++ Offset = (Option & 4) ? static_cast(static_cast(static_cast(Offset))) : static_cast(Offset); ++ } ++ *Address = Base + (Offset << (((Insn >> 12) & 1) ? Scale : 0)); ++ *Size = 1U << Scale; ++ return true; ++ } ++ if ((Insn & 0x3a000000) == 0x28000000) { ++ if (SizeBits == 3) { ++ return false; ++ } ++ const auto Element = Vector ? 4U << SizeBits : (SizeBits == 2 ? 8U : 4U); ++ *Address = ((Insn >> 23) & 3) == 1 ? Base : Base + SignedField(Insn, 15, 7) * static_cast(Element); ++ *Size = 2 * Element; ++ return true; ++ } ++ if ((Insn & 0xbfbf0000) == 0x0c000000 || (Insn & 0xbfa00000) == 0x0c800000) { ++ uint32_t Registers = 0; ++ switch ((Insn >> 12) & 0xf) { ++ case 0x0: ++ case 0x2: Registers = 4; break; ++ case 0x4: ++ case 0x6: Registers = 3; break; ++ case 0x7: Registers = 1; break; ++ case 0x8: ++ case 0xa: Registers = 2; break; ++ default: return false; ++ } ++ *Size = Registers * ((Insn & (1U << 30)) ? 16U : 8U); ++ return true; ++ } ++ if ((Insn & 0xbf9f0000) == 0x0d000000 || (Insn & 0xbf800000) == 0x0d800000) { ++ const auto Opcode = (Insn >> 13) & 7; ++ const auto Elements = (((Opcode & 1) << 1) | ((Insn >> 21) & 1)) + 1; ++ const auto Bits = (Insn >> 10) & 3; ++ uint32_t Element = 0; ++ switch (Opcode >> 1) { ++ case 0: Element = 1; break; ++ case 1: Element = (Bits & 1) ? 0 : 2; break; ++ case 2: Element = Bits == 0 ? 4 : (Bits == 1 && !((Insn >> 12) & 1) ? 8 : 0); break; ++ default: Element = 1U << Bits; break; ++ } ++ *Size = Elements * Element; ++ return Element != 0; ++ } ++ return false; ++ } ++ ++ bool HostContiguous(const AccessPiece* Pieces, uint32_t Parts) { ++ for (uint32_t i = 1; i < Parts; ++i) { ++ if (Pieces[i - 1].Host + Pieces[i - 1].Size != Pieces[i].Host) { ++ return false; ++ } ++ } ++ return true; ++ } ++ ++ bool PiecesReachable(const AccessPiece* Pieces, uint32_t Parts, bool Write) { ++ const uint8_t Need = Write ? PROT_WRITE : PROT_READ | PROT_WRITE; ++ for (uint32_t i = 0; i < Parts; ++i) { ++ if ((Pieces[i].Prot & Need) == 0) { ++ return false; ++ } ++ } ++ return true; ++ } ++ ++ template ++ uint32_t CopyPieces(uint8_t* Bounce, const PieceType* Pieces, uint32_t Parts, bool Gather) { ++ uint64_t Offset = 0; ++ for (uint32_t i = 0; i < Parts; ++i) { ++ auto* Host = reinterpret_cast(Pieces[i].Host); ++ const auto Failed = Gather ? FaultSafeUserMemAccess::CopyFromUser(Bounce + Offset, Host, Pieces[i].Size) : ++ FaultSafeUserMemAccess::CopyToUser(Host, Bounce + Offset, Pieces[i].Size); ++ if (Failed != 0) { ++ return i; ++ } ++ Offset += Pieces[i].Size; ++ } ++ return Parts; ++ } ++ ++ template ++ uint32_t EmulateOrdered(uint32_t Insn, const PieceType* Pieces, uint32_t Parts, void* UContext) { ++ const auto Size = 1U << (Insn >> 30); ++ uint8_t Bytes[8] {}; ++ std::atomic_thread_fence(std::memory_order_seq_cst); ++ const auto Gathered = CopyPieces(Bytes, Pieces, Parts, true); ++ if (Gathered != Parts) { ++ return Gathered; ++ } ++ uint64_t Value {}; ++ if (IsWrite(Insn)) { ++ Value = ReadReg(UContext, RtField(Insn)); ++ memcpy(Bytes, &Value, Size); ++ const auto Scattered = CopyPieces(Bytes, Pieces, Parts, false); ++ std::atomic_thread_fence(std::memory_order_seq_cst); ++ return Scattered; ++ } ++ memcpy(&Value, Bytes, Size); ++ std::atomic_thread_fence(std::memory_order_seq_cst); ++ WriteReg(UContext, RtField(Insn), ExtendOrdered(Insn, Value)); ++ return Parts; ++ } ++ ++ constexpr int HeldSignals[] = {SIGSEGV, SIGBUS, SIGTRAP}; ++ ++ constexpr uint64_t HeldSignalMask() { ++ uint64_t Mask = 0; ++ for (int Sig : HeldSignals) { ++ Mask |= 1ULL << (Sig - 1); ++ } ++ return Mask; ++ } ++ ++ constexpr int HeldSignalSlot(int Signal) { ++ for (int Slot = 0; Slot < static_cast(std::size(HeldSignals)); ++Slot) { ++ if (HeldSignals[Slot] == Signal) { ++ return Slot; ++ } ++ } ++ return -1; ++ } ++ ++ template ++ bool DeferWhileHeld(HoldState& Hold, int Signal, const siginfo_t* Info) { ++ const int Slot = HeldSignalSlot(Signal); ++ if (!Hold.Held || Info->si_code > SI_USER || Slot < 0) { ++ return false; ++ } ++ Hold.Deferred |= 1U << Slot; ++ Hold.DeferredInfo[Slot] = *Info; ++ return true; ++ } ++ ++ template ++ uint64_t ReleaseMappings(HoldState& Hold) { ++ if (!Hold.Held) { ++ return 0; ++ } ++ FEX::HLE::_SyscallHandler->VMATracking.Mutex.unlock_shared(); ++ Hold.Held = false; ++ uint64_t Requeued = 0; ++ for (int Slot = 0; Slot < static_cast(std::size(HeldSignals)); ++Slot) { ++ if (Hold.Deferred & (1U << Slot)) { ++ Requeued |= 1ULL << (HeldSignals[Slot] - 1); ++ } ++ } ++ if (Requeued == 0) { ++ return 0; ++ } ++ ::syscall(SYS_rt_sigprocmask, SIG_BLOCK, &Requeued, nullptr, sizeof(Requeued)); ++ const auto Process = ::syscall(SYS_getpid); ++ const auto Self = ::syscall(SYS_gettid); ++ for (int Slot = 0; Slot < static_cast(std::size(HeldSignals)); ++Slot) { ++ if (Hold.Deferred & (1U << Slot)) { ++ ::syscall(SYS_rt_tgsigqueueinfo, Process, Self, HeldSignals[Slot], &Hold.DeferredInfo[Slot]); ++ } ++ } ++ Hold.Deferred = 0; ++ return Requeued; ++ } ++ ++ template ++ class MappingHold final { ++ public: ++ explicit MappingHold(HoldState& Hold, bool Deliver = false) ++ : Hold {Hold} ++ , Deliver {Deliver} { ++ const uint64_t All = ~0ULL; ++ ::syscall(SYS_rt_sigprocmask, SIG_SETMASK, &All, &Mask, sizeof(Mask)); ++ FEX::HLE::_SyscallHandler->VMATracking.Mutex.lock_shared(); ++ Hold.Held = true; ++ const uint64_t Blocked = ~HeldSignalMask(); ++ ::syscall(SYS_rt_sigprocmask, SIG_SETMASK, &Blocked, nullptr, sizeof(Blocked)); ++ } ++ MappingHold(const MappingHold&) = delete; ++ MappingHold& operator=(const MappingHold&) = delete; ++ ~MappingHold() { ++ if (!Kept) { ++ const uint64_t Requeued = ReleaseMappings(Hold); ++ const uint64_t Restored = Deliver ? Mask : Mask | Requeued; ++ ::syscall(SYS_rt_sigprocmask, SIG_SETMASK, &Restored, nullptr, sizeof(Restored)); ++ } ++ } ++ void Keep() { ++ Kept = true; ++ } ++ ++ private: ++ HoldState& Hold; ++ uint64_t Mask {}; ++ bool Deliver {}; ++ bool Kept {}; ++ }; ++ ++ int PickScratch(uint32_t Insn) { ++ constexpr int Candidates[] = {16, 17, 9, 10, 11, 12, 13, 14, 15, 8, 7, 6, 5, 4, 3, 2}; ++ for (auto Reg : Candidates) { ++ const auto R = static_cast(Reg); ++ if (R != RtField(Insn) && R != RnField(Insn) && R != Rt2Field(Insn) && R != RsField(Insn)) { ++ return Reg; ++ } ++ } ++ return -1; ++ } ++ ++ constexpr uint32_t TrapInstruction = 0xd4200000 | (0xf3e << 5); ++ ++ using TrapState = decltype(FEX::HLE::ThreadStateObject::HighMemoryTrap); ++ ++ bool EnsureTrapCode(TrapState& Trap) { ++ if (!Trap.Code) { ++ void* Page = FEXCore::Allocator::VirtualAlloc(FEXCore::Utils::FEX_PAGE_SIZE, true); ++ if (Page == MAP_FAILED || Page == nullptr) { ++ return false; ++ } ++ Trap.Code = static_cast(Page); ++ } ++ return true; ++ } ++ ++ void ArmTrap(TrapState& Trap, void* UContext, uint32_t Instruction, uint64_t ScratchValue, bool Probe) { ++ auto* Code = reinterpret_cast(Trap.Code); ++ Code[0] = Instruction; ++ Code[1] = TrapInstruction; ++ __builtin___clear_cache(reinterpret_cast(Code), reinterpret_cast(Code + 2)); ++ Trap.Probe = Probe; ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Scratch, ScratchValue); ++ ArchHelpers::Context::SetPc(UContext, reinterpret_cast(Code)); ++ Trap.Active = true; ++ } ++ ++ void ArmProbe(TrapState& Trap, void* UContext, uint64_t Guest, uint64_t Host) { ++ Trap.Parts = 0; ++ Trap.Delta = Host - Guest; ++ ArmTrap(Trap, UContext, ProbeInstruction(Trap.Scratch), Host, true); ++ } ++ ++ void LeaveTrap(TrapState& Trap, void* UContext, uint64_t ResumePC) { ++ memcpy(&ArchHelpers::Context::GetUContext(UContext)->uc_sigmask, &Trap.SavedMask, sizeof(Trap.SavedMask)); ++ ArchHelpers::Context::SetPc(UContext, ResumePC); ++ Trap.Parts = 0; ++ Trap.Probe = false; ++ Trap.Active = false; ++ ReleaseMappings(Trap.Mappings); ++ } ++ ++ void RedeliverFromTrap(TrapState& Trap, siginfo_t* SigInfo, void* UContext) { ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Scratch, Trap.SavedScratch); ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Base, Trap.BaseBefore); ++ SigInfo->si_addr = reinterpret_cast(reinterpret_cast(SigInfo->si_addr) - Trap.Delta); ++ LeaveTrap(Trap, UContext, Trap.ResumePC - 4); ++ } ++ ++ constexpr uint64_t MaxIoVectors = 1024; ++ ++ enum class VectorKind : uint8_t { ++ None, ++ Io, ++ SentMessage, ++ ReceivedMessage, ++ SentMessageArray, ++ ReceivedMessageArray, ++ IoSubmit, ++ IoEvents, ++ PageList, ++ FutexWaiters, ++ FutexRequeue, ++ FileControl, ++ Capabilities, ++ PerfAttribute, ++ SchedulerAttribute, ++ HandleAt, ++ OpenHandle, ++ MountRequest, ++ LandlockRule, ++ }; ++ ++ constexpr uint8_t BitmapElements = 0xff; ++ constexpr uint8_t MessageElements = 0xfe; ++ constexpr uint8_t PageElements = 0xfd; ++ ++ struct Layout { ++ uint8_t Pointers; ++ uint64_t Lengths; ++ VectorKind Vector {VectorKind::None}; ++ uint64_t ElementSizes {}; ++ uint64_t FixedSizes {}; ++ uint8_t Strings {}; ++ }; ++ ++ struct LayoutEntry { ++ uint32_t Syscall; ++ Layout Arguments; ++ }; ++ ++ constexpr uint8_t Ptr(uint32_t Arg) { ++ return 1U << Arg; ++ } ++ ++ constexpr uint64_t CountWord = 0x10; ++ constexpr uint64_t CountSigned = 0x20; ++ ++ constexpr uint64_t Sized(uint32_t Pointer, uint32_t Length) { ++ return static_cast(Length + 1) << (Pointer * 8); ++ } ++ ++ constexpr uint64_t IntSized(uint32_t Pointer, uint32_t Length) { ++ return Sized(Pointer, Length) | ((CountWord | CountSigned) << (Pointer * 8)); ++ } ++ ++ constexpr uint64_t UintSized(uint32_t Pointer, uint32_t Length) { ++ return Sized(Pointer, Length) | (CountWord << (Pointer * 8)); ++ } ++ ++ constexpr uint64_t LongSized(uint32_t Pointer, uint32_t Length) { ++ return Sized(Pointer, Length) | (CountSigned << (Pointer * 8)); ++ } ++ ++ constexpr uint64_t Through(uint32_t Pointer, uint32_t Length) { ++ return static_cast(Length + 9) << (Pointer * 8); ++ } ++ ++ constexpr uint32_t LengthArgument(const Layout& Arguments, uint32_t Pointer) { ++ return (Arguments.Lengths >> (Pointer * 8)) & 0x7; ++ } ++ ++ constexpr bool LengthThroughPointer(const Layout& Arguments, uint32_t Pointer) { ++ return (Arguments.Lengths >> (Pointer * 8)) & 0x8; ++ } ++ ++ constexpr uint64_t CountKind(const Layout& Arguments, uint32_t Pointer) { ++ return (Arguments.Lengths >> (Pointer * 8)) & (CountWord | CountSigned); ++ } ++ ++ constexpr uint64_t CountValue(const Layout& Arguments, uint32_t Pointer, uint64_t Raw) { ++ const auto Kind = CountKind(Arguments, Pointer); ++ int64_t Value = static_cast(Raw); ++ if (Kind == (CountWord | CountSigned)) { ++ Value = static_cast(Raw); ++ } else if (Kind == CountWord) { ++ return static_cast(Raw); ++ } else if (Kind == 0) { ++ return Raw; ++ } ++ return Value < 0 ? 0 : static_cast(Value); ++ } ++ ++ constexpr uint64_t Fixed(uint32_t Pointer, uint64_t Bytes) { ++ return Bytes << (Pointer * 10); ++ } ++ ++ constexpr uint64_t FixedSize(const Layout& Arguments, uint32_t Pointer) { ++ return (Arguments.FixedSizes >> (Pointer * 10)) & 0x3ff; ++ } ++ ++ constexpr uint8_t Text(uint32_t Arg) { ++ return 1U << Arg; ++ } ++ ++ constexpr uint64_t Each(uint32_t Pointer, uint8_t Size) { ++ return static_cast(Size) << (Pointer * 8); ++ } ++ ++ constexpr uint8_t ElementSize(const Layout& Arguments, uint32_t Pointer) { ++ return (Arguments.ElementSizes >> (Pointer * 8)) & 0xff; ++ } ++ ++ constexpr uint64_t PollFdSize = 8; ++ constexpr uint64_t EpollEventSize = 12; ++ constexpr uint64_t GroupIdSize = 4; ++ constexpr uint64_t IntSize = 4; ++ constexpr uint64_t PointerSize = 8; ++ constexpr uint64_t SemaphoreOpSize = 6; ++ constexpr uint64_t IoEventSize = 32; ++ constexpr uint64_t FutexWaitSize = 24; ++ constexpr uint64_t StatSize = 144; ++ constexpr uint64_t StatfsSize = 120; ++ constexpr uint64_t StatxSize = 256; ++ constexpr uint64_t TimeSize = 16; ++ constexpr uint64_t TimePairSize = 32; ++ constexpr uint64_t TimezoneSize = 8; ++ constexpr uint64_t LongSize = 8; ++ constexpr uint64_t FdPairSize = 8; ++ constexpr uint64_t UtimbufSize = 16; ++ constexpr uint64_t SigactionSize = 32; ++ constexpr uint64_t SiginfoSize = 128; ++ constexpr uint64_t SigeventSize = 64; ++ constexpr uint64_t StackSize = 24; ++ constexpr uint64_t RlimitSize = 16; ++ constexpr uint64_t RusageSize = 144; ++ constexpr uint64_t SysinfoSize = 112; ++ constexpr uint64_t TmsSize = 32; ++ constexpr uint64_t UtsnameSize = 390; ++ constexpr uint64_t TimexSize = 208; ++ constexpr uint64_t UstatSize = 32; ++ constexpr uint64_t UserDescSize = 16; ++ constexpr uint64_t MqAttrSize = 64; ++ constexpr uint64_t IoControlBlockSize = 64; ++ constexpr uint64_t IoEventObjectOffset = 8; ++ constexpr uint64_t CapHeaderSize = 8; ++ constexpr uint64_t CapDataSize = 12; ++ constexpr uint32_t CapVersion1 = 0x19980330; ++ constexpr uint32_t CapVersion2 = 0x20071026; ++ constexpr uint32_t CapVersion3 = 0x20080522; ++ constexpr uint64_t FileLockSize = 32; ++ constexpr uint64_t IoUringParamsSize = 120; ++ constexpr uint64_t CachestatRangeSize = 16; ++ constexpr uint64_t CachestatSize = 40; ++ constexpr uint64_t LandlockPathRuleSize = 12; ++ constexpr uint64_t LandlockPortRuleSize = 16; ++ constexpr uint64_t KcmpSlotSize = 12; ++ constexpr uint64_t KexecSegmentSize = 32; ++ constexpr uint64_t SigsetArgumentSize = 16; ++ constexpr uint64_t SocketAddressSize = 128; ++ constexpr uint64_t MessageHeaderSize = 8; ++ constexpr uint64_t MaxString = 4096; ++ constexpr uint64_t StringChunk = 256; ++ constexpr uint64_t MaxPageList = 65536; ++ constexpr uint64_t MaxFutexWaiters = 128; ++ constexpr uint64_t MaxElements = 1ULL << 32; ++ ++ bool ByteLength(const Layout& Arguments, uint32_t Pointer, uint64_t Count, uint64_t* Bytes) { ++ const auto Size = ElementSize(Arguments, Pointer); ++ if (Size == 0) { ++ *Bytes = Count; ++ return true; ++ } ++ if (Size == BitmapElements) { ++ const auto Elements = static_cast(Count); ++ *Bytes = (static_cast(Elements) + 63) / 64 * 8; ++ return true; ++ } ++ if (Size == PageElements) { ++ *Bytes = Count / FEXCore::Utils::FEX_PAGE_SIZE + (Count % FEXCore::Utils::FEX_PAGE_SIZE != 0); ++ return true; ++ } ++ if (Count >= MaxElements) { ++ return false; ++ } ++ if (Size == MessageElements) { ++ *Bytes = Count + MessageHeaderSize; ++ return true; ++ } ++ *Bytes = Count * Size; ++ return true; ++ } ++ ++ constexpr LayoutEntry LayoutEntries[] = { ++ {x64::SYSCALL_x64_read, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_write, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_open, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_stat, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(1, StatSize), Text(0)}}, ++ {x64::SYSCALL_x64_fstat, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, StatSize)}}, ++ {x64::SYSCALL_x64_lstat, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(1, StatSize), Text(0)}}, ++ {x64::SYSCALL_x64_poll, {Ptr(0), UintSized(0, 1), VectorKind::None, Each(0, PollFdSize)}}, ++ {x64::SYSCALL_x64_rt_sigaction, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, SigactionSize) | Fixed(2, SigactionSize)}}, ++ {x64::SYSCALL_x64_rt_sigprocmask, {Ptr(1) | Ptr(2), Sized(1, 3) | Sized(2, 3)}}, ++ {x64::SYSCALL_x64_ioctl, {Ptr(2)}}, ++ {x64::SYSCALL_x64_pread_64, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_pwrite_64, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_readv, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_writev, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_access, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_pipe, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, FdPairSize)}}, ++ {x64::SYSCALL_x64_select, {Ptr(1) | Ptr(2) | Ptr(3) | Ptr(4), IntSized(1, 0) | IntSized(2, 0) | IntSized(3, 0), VectorKind::None, Each(1, BitmapElements) | Each(2, BitmapElements) | Each(3, BitmapElements), Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_msync, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_mincore, {Ptr(0) | Ptr(2), Sized(0, 1) | Sized(2, 1), VectorKind::None, Each(2, PageElements)}}, ++ {x64::SYSCALL_x64_shmctl, {Ptr(2)}}, ++ {x64::SYSCALL_x64_nanosleep, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(0, TimeSize) | Fixed(1, TimeSize)}}, ++ {x64::SYSCALL_x64_getitimer, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimePairSize)}}, ++ {x64::SYSCALL_x64_setitimer, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, TimePairSize) | Fixed(2, TimePairSize)}}, ++ {x64::SYSCALL_x64_sendfile, {Ptr(2), 0, VectorKind::None, 0, Fixed(2, LongSize)}}, ++ {x64::SYSCALL_x64_connect, {Ptr(1), IntSized(1, 2)}}, ++ {x64::SYSCALL_x64_accept, {Ptr(1) | Ptr(2), Through(1, 2), VectorKind::None, 0, Fixed(1, SocketAddressSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_sendto, {Ptr(1) | Ptr(4), Sized(1, 2) | IntSized(4, 5)}}, ++ {x64::SYSCALL_x64_recvfrom, {Ptr(1) | Ptr(4) | Ptr(5), Sized(1, 2) | Through(4, 5), VectorKind::None, 0, Fixed(4, SocketAddressSize) | Fixed(5, IntSize)}}, ++ {x64::SYSCALL_x64_sendmsg, {0, 0, VectorKind::SentMessage}}, ++ {x64::SYSCALL_x64_recvmsg, {0, 0, VectorKind::ReceivedMessage}}, ++ {x64::SYSCALL_x64_bind, {Ptr(1), IntSized(1, 2)}}, ++ {x64::SYSCALL_x64_getsockname, {Ptr(1) | Ptr(2), Through(1, 2), VectorKind::None, 0, Fixed(1, SocketAddressSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_getpeername, {Ptr(1) | Ptr(2), Through(1, 2), VectorKind::None, 0, Fixed(1, SocketAddressSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_socketpair, {Ptr(3), 0, VectorKind::None, 0, Fixed(3, FdPairSize)}}, ++ {x64::SYSCALL_x64_setsockopt, {Ptr(3), IntSized(3, 4)}}, ++ {x64::SYSCALL_x64_getsockopt, {Ptr(3) | Ptr(4), Through(3, 4), VectorKind::None, 0, Fixed(4, IntSize)}}, ++ {x64::SYSCALL_x64_execve, {Ptr(0) | Ptr(1) | Ptr(2), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_wait4, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, Fixed(1, IntSize) | Fixed(3, RusageSize)}}, ++ {x64::SYSCALL_x64_uname, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, UtsnameSize)}}, ++ {x64::SYSCALL_x64_semop, {Ptr(1), UintSized(1, 2), VectorKind::None, Each(1, SemaphoreOpSize)}}, ++ {x64::SYSCALL_x64_semctl, {Ptr(3)}}, ++ {x64::SYSCALL_x64_msgsnd, {Ptr(1), Sized(1, 2), VectorKind::None, Each(1, MessageElements)}}, ++ {x64::SYSCALL_x64_msgrcv, {Ptr(1), Sized(1, 2), VectorKind::None, Each(1, MessageElements)}}, ++ {x64::SYSCALL_x64_msgctl, {Ptr(2)}}, ++ {x64::SYSCALL_x64_fcntl, {0, 0, VectorKind::FileControl}}, ++ {x64::SYSCALL_x64_truncate, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_getdents, {Ptr(1), UintSized(1, 2)}}, ++ {x64::SYSCALL_x64_getcwd, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_chdir, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_rename, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_mkdir, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_rmdir, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_creat, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_link, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_unlink, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_symlink, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_readlink, {Ptr(0) | Ptr(1), IntSized(1, 2), VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_chmod, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_chown, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_lchown, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_gettimeofday, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(0, TimeSize) | Fixed(1, TimezoneSize)}}, ++ {x64::SYSCALL_x64_getrlimit, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, RlimitSize)}}, ++ {x64::SYSCALL_x64_getrusage, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, RusageSize)}}, ++ {x64::SYSCALL_x64_sysinfo, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, SysinfoSize)}}, ++ {x64::SYSCALL_x64_times, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, TmsSize)}}, ++ {x64::SYSCALL_x64_syslog, {Ptr(1), IntSized(1, 2)}}, ++ {x64::SYSCALL_x64_getgroups, {Ptr(1), IntSized(1, 0), VectorKind::None, Each(1, GroupIdSize)}}, ++ {x64::SYSCALL_x64_setgroups, {Ptr(1), IntSized(1, 0), VectorKind::None, Each(1, GroupIdSize)}}, ++ {x64::SYSCALL_x64_getresuid, {Ptr(0) | Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(0, IntSize) | Fixed(1, IntSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_getresgid, {Ptr(0) | Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(0, IntSize) | Fixed(1, IntSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_capget, {Ptr(0), 0, VectorKind::Capabilities, 0, Fixed(0, CapHeaderSize)}}, ++ {x64::SYSCALL_x64_capset, {Ptr(0), 0, VectorKind::Capabilities, 0, Fixed(0, CapHeaderSize)}}, ++ {x64::SYSCALL_x64_rt_sigpending, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_rt_sigtimedwait, {Ptr(0) | Ptr(1) | Ptr(2), Sized(0, 3), VectorKind::None, 0, Fixed(1, SiginfoSize) | Fixed(2, TimeSize)}}, ++ {x64::SYSCALL_x64_rt_sigqueueinfo, {Ptr(2), 0, VectorKind::None, 0, Fixed(2, SiginfoSize)}}, ++ {x64::SYSCALL_x64_rt_sigsuspend, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_sigaltstack, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(0, StackSize) | Fixed(1, StackSize)}}, ++ {x64::SYSCALL_x64_utime, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(1, UtimbufSize), Text(0)}}, ++ {x64::SYSCALL_x64_mknod, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_uselib, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_ustat, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, UstatSize)}}, ++ {x64::SYSCALL_x64_statfs, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(1, StatfsSize), Text(0)}}, ++ {x64::SYSCALL_x64_fstatfs, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, StatfsSize)}}, ++ {x64::SYSCALL_x64_sysfs, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_sched_setparam, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, IntSize)}}, ++ {x64::SYSCALL_x64_sched_getparam, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, IntSize)}}, ++ {x64::SYSCALL_x64_sched_setscheduler, {Ptr(2), 0, VectorKind::None, 0, Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_sched_rr_get_interval, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimeSize)}}, ++ {x64::SYSCALL_x64_mlock, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_munlock, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_modify_ldt, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_pivot_root, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64__sysctl, {Ptr(0)}}, ++ {x64::SYSCALL_x64_adjtimex, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, TimexSize)}}, ++ {x64::SYSCALL_x64_setrlimit, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, RlimitSize)}}, ++ {x64::SYSCALL_x64_chroot, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_acct, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_settimeofday, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(0, TimeSize) | Fixed(1, TimezoneSize)}}, ++ {x64::SYSCALL_x64_mount, {Ptr(0) | Ptr(1) | Ptr(2) | Ptr(4), 0, VectorKind::None, 0, 0, Text(0) | Text(1) | Text(2)}}, ++ {x64::SYSCALL_x64_umount2, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_swapon, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_swapoff, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_reboot, {Ptr(3), 0, VectorKind::None, 0, 0, Text(3)}}, ++ {x64::SYSCALL_x64_sethostname, {Ptr(0), IntSized(0, 1)}}, ++ {x64::SYSCALL_x64_setdomainname, {Ptr(0), IntSized(0, 1)}}, ++ {x64::SYSCALL_x64_create_module, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_init_module, {Ptr(0) | Ptr(2), Sized(0, 1), VectorKind::None, 0, 0, Text(2)}}, ++ {x64::SYSCALL_x64_delete_module, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_get_kernel_syms, {Ptr(0)}}, ++ {x64::SYSCALL_x64_query_module, {Ptr(0) | Ptr(2) | Ptr(4), Sized(2, 3)}}, ++ {x64::SYSCALL_x64_quotactl, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_nfsservctl, {Ptr(1) | Ptr(2)}}, ++ {x64::SYSCALL_x64_setxattr, {Ptr(0) | Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_lsetxattr, {Ptr(0) | Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_fsetxattr, {Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_getxattr, {Ptr(0) | Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_lgetxattr, {Ptr(0) | Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_fgetxattr, {Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_listxattr, {Ptr(0) | Ptr(1), Sized(1, 2), VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_llistxattr, {Ptr(0) | Ptr(1), Sized(1, 2), VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_flistxattr, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_removexattr, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_lremovexattr, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_fremovexattr, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_time, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, LongSize)}}, ++ {x64::SYSCALL_x64_futex, {Ptr(0) | Ptr(3) | Ptr(4), 0, VectorKind::None, 0, Fixed(0, IntSize) | Fixed(3, TimeSize) | Fixed(4, IntSize)}}, ++ {x64::SYSCALL_x64_sched_setaffinity, {Ptr(2), UintSized(2, 1)}}, ++ {x64::SYSCALL_x64_sched_getaffinity, {Ptr(2), UintSized(2, 1)}}, ++ {x64::SYSCALL_x64_set_thread_area, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, UserDescSize)}}, ++ {x64::SYSCALL_x64_io_setup, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, LongSize)}}, ++ {x64::SYSCALL_x64_io_getevents, {Ptr(3) | Ptr(4), LongSized(3, 2), VectorKind::IoEvents, Each(3, IoEventSize), Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_io_submit, {Ptr(2), LongSized(2, 1), VectorKind::IoSubmit, Each(2, PointerSize)}}, ++ {x64::SYSCALL_x64_io_cancel, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, IoControlBlockSize) | Fixed(2, IoEventSize)}}, ++ {x64::SYSCALL_x64_get_thread_area, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, UserDescSize)}}, ++ {x64::SYSCALL_x64_lookup_dcookie, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_remap_file_pages, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_getdents64, {Ptr(1), UintSized(1, 2)}}, ++ {x64::SYSCALL_x64_semtimedop, {Ptr(1) | Ptr(3), UintSized(1, 2), VectorKind::None, Each(1, SemaphoreOpSize), Fixed(3, TimeSize)}}, ++ {x64::SYSCALL_x64_timer_create, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, SigeventSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_timer_settime, {Ptr(2) | Ptr(3), 0, VectorKind::None, 0, Fixed(2, TimePairSize) | Fixed(3, TimePairSize)}}, ++ {x64::SYSCALL_x64_timer_gettime, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimePairSize)}}, ++ {x64::SYSCALL_x64_clock_settime, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimeSize)}}, ++ {x64::SYSCALL_x64_clock_gettime, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimeSize)}}, ++ {x64::SYSCALL_x64_clock_getres, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimeSize)}}, ++ {x64::SYSCALL_x64_clock_nanosleep, {Ptr(2) | Ptr(3), 0, VectorKind::None, 0, Fixed(2, TimeSize) | Fixed(3, TimeSize)}}, ++ {x64::SYSCALL_x64_epoll_wait, {Ptr(1), IntSized(1, 2), VectorKind::None, Each(1, EpollEventSize)}}, ++ {x64::SYSCALL_x64_epoll_ctl, {Ptr(3), 0, VectorKind::None, 0, Fixed(3, EpollEventSize)}}, ++ {x64::SYSCALL_x64_utimes, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimePairSize), Text(0)}}, ++ {x64::SYSCALL_x64_mbind, {Ptr(0) | Ptr(3), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_set_mempolicy, {Ptr(1)}}, ++ {x64::SYSCALL_x64_get_mempolicy, {Ptr(0) | Ptr(1) | Ptr(3), 0, VectorKind::None, 0, Fixed(0, IntSize)}}, ++ {x64::SYSCALL_x64_mq_open, {Ptr(0) | Ptr(3), 0, VectorKind::None, 0, Fixed(3, MqAttrSize), Text(0)}}, ++ {x64::SYSCALL_x64_mq_unlink, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_mq_timedsend, {Ptr(1) | Ptr(4), Sized(1, 2), VectorKind::None, 0, Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_mq_timedreceive, {Ptr(1) | Ptr(3) | Ptr(4), Sized(1, 2), VectorKind::None, 0, Fixed(3, IntSize) | Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_mq_notify, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, SigeventSize)}}, ++ {x64::SYSCALL_x64_mq_getsetattr, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, MqAttrSize) | Fixed(2, MqAttrSize)}}, ++ {x64::SYSCALL_x64_kexec_load, {Ptr(2), Sized(2, 1), VectorKind::None, Each(2, KexecSegmentSize)}}, ++ {x64::SYSCALL_x64_waitid, {Ptr(2) | Ptr(4), 0, VectorKind::None, 0, Fixed(2, SiginfoSize) | Fixed(4, RusageSize)}}, ++ {x64::SYSCALL_x64_add_key, {Ptr(0) | Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_request_key, {Ptr(0) | Ptr(1) | Ptr(2), 0, VectorKind::None, 0, 0, Text(0) | Text(1) | Text(2)}}, ++ {x64::SYSCALL_x64_keyctl, {Ptr(1) | Ptr(2) | Ptr(3) | Ptr(4)}}, ++ {x64::SYSCALL_x64_inotify_add_watch, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_migrate_pages, {Ptr(2) | Ptr(3)}}, ++ {x64::SYSCALL_x64_openat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_mkdirat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_mknodat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_fchownat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_futimesat, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(2, TimePairSize), Text(1)}}, ++ {x64::SYSCALL_x64_newfstatat, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(2, StatSize), Text(1)}}, ++ {x64::SYSCALL_x64_unlinkat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_renameat, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_linkat, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_symlinkat, {Ptr(0) | Ptr(2), 0, VectorKind::None, 0, 0, Text(0) | Text(2)}}, ++ {x64::SYSCALL_x64_readlinkat, {Ptr(1) | Ptr(2), IntSized(2, 3), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_fchmodat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_faccessat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_pselect6, {Ptr(1) | Ptr(2) | Ptr(3) | Ptr(4) | Ptr(5), IntSized(1, 0) | IntSized(2, 0) | IntSized(3, 0), VectorKind::None, Each(1, BitmapElements) | Each(2, BitmapElements) | Each(3, BitmapElements), Fixed(4, TimeSize) | Fixed(5, SigsetArgumentSize)}}, ++ {x64::SYSCALL_x64_ppoll, {Ptr(0) | Ptr(2) | Ptr(3), UintSized(0, 1) | Sized(3, 4), VectorKind::None, Each(0, PollFdSize), Fixed(2, TimeSize)}}, ++ {x64::SYSCALL_x64_get_robust_list, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, PointerSize) | Fixed(2, PointerSize)}}, ++ {x64::SYSCALL_x64_splice, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, Fixed(1, LongSize) | Fixed(3, LongSize)}}, ++ {x64::SYSCALL_x64_vmsplice, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_move_pages, {Ptr(2) | Ptr(3) | Ptr(4), Sized(2, 1) | Sized(3, 1) | Sized(4, 1), VectorKind::PageList, Each(2, PointerSize) | Each(3, IntSize) | Each(4, IntSize)}}, ++ {x64::SYSCALL_x64_utimensat, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(2, TimePairSize), Text(1)}}, ++ {x64::SYSCALL_x64_epoll_pwait, {Ptr(1) | Ptr(4), IntSized(1, 2) | Sized(4, 5), VectorKind::None, Each(1, EpollEventSize)}}, ++ {x64::SYSCALL_x64_signalfd, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_timerfd_settime, {Ptr(2) | Ptr(3), 0, VectorKind::None, 0, Fixed(2, TimePairSize) | Fixed(3, TimePairSize)}}, ++ {x64::SYSCALL_x64_timerfd_gettime, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimePairSize)}}, ++ {x64::SYSCALL_x64_accept4, {Ptr(1) | Ptr(2), Through(1, 2), VectorKind::None, 0, Fixed(1, SocketAddressSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_signalfd4, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_pipe2, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, FdPairSize)}}, ++ {x64::SYSCALL_x64_preadv, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_pwritev, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_rt_tgsigqueueinfo, {Ptr(3), 0, VectorKind::None, 0, Fixed(3, SiginfoSize)}}, ++ {x64::SYSCALL_x64_perf_event_open, {0, 0, VectorKind::PerfAttribute}}, ++ {x64::SYSCALL_x64_recvmmsg, {Ptr(4), 0, VectorKind::ReceivedMessageArray, 0, Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_fanotify_mark, {Ptr(4), 0, VectorKind::None, 0, 0, Text(4)}}, ++ {x64::SYSCALL_x64_prlimit_64, {Ptr(2) | Ptr(3), 0, VectorKind::None, 0, Fixed(2, RlimitSize) | Fixed(3, RlimitSize)}}, ++ {x64::SYSCALL_x64_name_to_handle_at, {Ptr(1) | Ptr(3), 0, VectorKind::HandleAt, 0, Fixed(3, IntSize), Text(1)}}, ++ {x64::SYSCALL_x64_open_by_handle_at, {0, 0, VectorKind::OpenHandle}}, ++ {x64::SYSCALL_x64_clock_adjtime, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimexSize)}}, ++ {x64::SYSCALL_x64_sendmmsg, {0, 0, VectorKind::SentMessageArray}}, ++ {x64::SYSCALL_x64_getcpu, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(0, IntSize) | Fixed(1, IntSize)}}, ++ {x64::SYSCALL_x64_kcmp, {Ptr(4), 0, VectorKind::None, 0, Fixed(4, KcmpSlotSize)}}, ++ {x64::SYSCALL_x64_finit_module, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_sched_setattr, {0, 0, VectorKind::SchedulerAttribute}}, ++ {x64::SYSCALL_x64_sched_getattr, {Ptr(1), UintSized(1, 2)}}, ++ {x64::SYSCALL_x64_renameat2, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_seccomp, {Ptr(2)}}, ++ {x64::SYSCALL_x64_getrandom, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_memfd_create, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_kexec_file_load, {Ptr(3), Sized(3, 2)}}, ++ {x64::SYSCALL_x64_bpf, {Ptr(1), UintSized(1, 2)}}, ++ {x64::SYSCALL_x64_execveat, {Ptr(1) | Ptr(2) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_mlock2, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_copy_file_range, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, Fixed(1, LongSize) | Fixed(3, LongSize)}}, ++ {x64::SYSCALL_x64_preadv2, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_pwritev2, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_pkey_mprotect, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_statx, {Ptr(1) | Ptr(4), 0, VectorKind::None, 0, Fixed(4, StatxSize), Text(1)}}, ++ {x64::SYSCALL_x64_io_pgetevents, {Ptr(3) | Ptr(4) | Ptr(5), LongSized(3, 2), VectorKind::IoEvents, Each(3, IoEventSize), Fixed(4, TimeSize) | Fixed(5, SigsetArgumentSize)}}, ++ {x64::SYSCALL_x64_rseq, {Ptr(0), UintSized(0, 1)}}, ++ {x64::SYSCALL_x64_pidfd_send_signal, {Ptr(2), 0, VectorKind::None, 0, Fixed(2, SiginfoSize)}}, ++ {x64::SYSCALL_x64_io_uring_setup, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, IoUringParamsSize)}}, ++ {x64::SYSCALL_x64_io_uring_enter, {Ptr(4), Sized(4, 5)}}, ++ {x64::SYSCALL_x64_io_uring_register, {Ptr(2)}}, ++ {x64::SYSCALL_x64_open_tree, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_move_mount, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_fsopen, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_fsconfig, {Ptr(2) | Ptr(3), 0, VectorKind::None, 0, 0, Text(2)}}, ++ {x64::SYSCALL_x64_fspick, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_openat2, {Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_faccessat2, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_process_madvise, {Ptr(1)}}, ++ {x64::SYSCALL_x64_epoll_pwait2, {Ptr(1) | Ptr(3) | Ptr(4), IntSized(1, 2) | Sized(4, 5), VectorKind::None, Each(1, EpollEventSize), Fixed(3, TimeSize)}}, ++ {x64::SYSCALL_x64_mount_setattr, {Ptr(1) | Ptr(3), Sized(3, 4), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_quotactl_fd, {Ptr(3)}}, ++ {x64::SYSCALL_x64_landlock_create_ruleset, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_landlock_add_rule, {0, 0, VectorKind::LandlockRule}}, ++ {x64::SYSCALL_x64_futex_waitv, {Ptr(0) | Ptr(3), UintSized(0, 1), VectorKind::FutexWaiters, Each(0, FutexWaitSize), Fixed(3, TimeSize)}}, ++ {x64::SYSCALL_x64_set_mempolicy_home_node, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_cachestat, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, CachestatRangeSize) | Fixed(2, CachestatSize)}}, ++ {x64::SYSCALL_x64_fchmodat2, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_futex_wake, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, IntSize)}}, ++ {x64::SYSCALL_x64_futex_wait, {Ptr(0) | Ptr(4), 0, VectorKind::None, 0, Fixed(0, IntSize) | Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_futex_requeue, {Ptr(0), 0, VectorKind::FutexRequeue, 0, Fixed(0, 2 * FutexWaitSize)}}, ++ {x64::SYSCALL_x64_statmount, {Ptr(1), Sized(1, 2), VectorKind::MountRequest}}, ++ {x64::SYSCALL_x64_listmount, {Ptr(1), Sized(1, 2), VectorKind::MountRequest, Each(1, PointerSize)}}, ++ {x64::SYSCALL_x64_lsm_get_self_attr, {Ptr(1) | Ptr(2), Through(1, 2), VectorKind::None, 0, Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_lsm_set_self_attr, {Ptr(1), UintSized(1, 2)}}, ++ {x64::SYSCALL_x64_lsm_list_modules, {Ptr(0) | Ptr(1), Through(0, 1), VectorKind::None, 0, Fixed(1, IntSize)}}, ++ {x64::SYSCALL_x64_mseal, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_setxattrat, {Ptr(1) | Ptr(3) | Ptr(4), Sized(4, 5), VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_getxattrat, {Ptr(1) | Ptr(3) | Ptr(4), Sized(4, 5), VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_listxattrat, {Ptr(1) | Ptr(3), Sized(3, 4), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_removexattrat, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ }; ++ ++ constexpr uint32_t LayoutCount() { ++ uint32_t Max = 0; ++ for (const auto& Entry : LayoutEntries) { ++ Max = std::max(Max, Entry.Syscall); ++ } ++ return Max + 1; ++ } ++ ++ constexpr std::array BuildLayouts() { ++ std::array Table {}; ++ for (const auto& Entry : LayoutEntries) { ++ Table[Entry.Syscall] = Entry.Arguments; ++ } ++ return Table; ++ } ++ ++ constexpr auto Layouts = BuildLayouts(); ++ ++ constexpr bool LayoutsAreConsistent() { ++ for (size_t i = 0; i < std::size(LayoutEntries); ++i) { ++ for (size_t j = i + 1; j < std::size(LayoutEntries); ++j) { ++ if (LayoutEntries[i].Syscall == LayoutEntries[j].Syscall) { ++ return false; ++ } ++ } ++ const auto& Arguments = LayoutEntries[i].Arguments; ++ if ((Arguments.Strings & ~Arguments.Pointers) != 0) { ++ return false; ++ } ++ for (uint32_t Arg = 0; Arg < 6; ++Arg) { ++ const bool Pointer = Arguments.Pointers & Ptr(Arg); ++ const auto Length = LengthArgument(Arguments, Arg); ++ const bool Indirect = LengthThroughPointer(Arguments, Arg); ++ const auto Bytes = FixedSize(Arguments, Arg); ++ const bool String = Arguments.Strings & Ptr(Arg); ++ const bool Elements = ElementSize(Arguments, Arg) != 0; ++ if (CountKind(Arguments, Arg) != 0 && (Length == 0 || Indirect)) { ++ return false; ++ } ++ if (!Pointer && (Length != 0 || Indirect || Bytes != 0 || Elements)) { ++ return false; ++ } ++ if (String && (Length != 0 || Indirect || Bytes != 0)) { ++ return false; ++ } ++ if (Elements && (Length == 0 || Indirect)) { ++ return false; ++ } ++ if (Length == 0) { ++ if (Indirect) { ++ return false; ++ } ++ continue; ++ } ++ if (Length > 6) { ++ return false; ++ } ++ const bool Target = Arguments.Pointers & Ptr(Length - 1); ++ if (Indirect ? !Target : (Target || Bytes != 0)) { ++ return false; ++ } ++ } ++ } ++ return true; ++ } ++ ++ constexpr bool LeavesUntranslated(std::initializer_list Syscalls) { ++ for (const auto Syscall : Syscalls) { ++ if (Syscall < Layouts.size() && (Layouts[Syscall].Pointers != 0 || Layouts[Syscall].Vector != VectorKind::None)) { ++ return false; ++ } ++ } ++ return true; ++ } ++ ++ static_assert(LayoutsAreConsistent()); ++ static_assert(LeavesUntranslated({ ++ x64::SYSCALL_x64_mmap, ++ x64::SYSCALL_x64_mprotect, ++ x64::SYSCALL_x64_munmap, ++ x64::SYSCALL_x64_brk, ++ x64::SYSCALL_x64_rt_sigreturn, ++ x64::SYSCALL_x64_mremap, ++ x64::SYSCALL_x64_madvise, ++ x64::SYSCALL_x64_shmat, ++ x64::SYSCALL_x64_clone, ++ x64::SYSCALL_x64_shmdt, ++ x64::SYSCALL_x64_ptrace, ++ x64::SYSCALL_x64_prctl, ++ x64::SYSCALL_x64_arch_prctl, ++ x64::SYSCALL_x64_set_tid_address, ++ x64::SYSCALL_x64_set_robust_list, ++ x64::SYSCALL_x64_process_vm_readv, ++ x64::SYSCALL_x64_process_vm_writev, ++ x64::SYSCALL_x64_clone3, ++ x64::SYSCALL_x64_map_shadow_stack, ++ })); ++ ++ struct iovec* VectorCopy(ArgumentStorage* Storage, uint64_t Entries) { ++ if (Entries <= std::size(Storage->Inline)) { ++ return Storage->Inline; ++ } ++ Storage->Heap.resize(std::min(Entries, MaxIoVectors)); ++ return Storage->Heap.data(); ++ } ++ ++ uint64_t TranslateIoVector(uint64_t Vector, uint64_t Entries, struct iovec* Copy, uint64_t* Out, bool* Copied = nullptr) { ++ if (Entries == 0 || Entries > MaxIoVectors) { ++ return 0; ++ } ++ const auto Bytes = Entries * sizeof(struct iovec); ++ uint64_t HostVector {}; ++ if (!TranslateRange(Vector, Bytes, &HostVector)) { ++ return -EFAULT; ++ } ++ *Out = HostVector; ++ if (FaultSafeUserMemAccess::CopyFromUser(Copy, reinterpret_cast(HostVector), Bytes) != 0) { ++ return 0; ++ } ++ if (Copied) { ++ *Copied = true; ++ } ++ bool Changed = false; ++ for (uint64_t i = 0; i < Entries; ++i) { ++ const auto Base = reinterpret_cast(Copy[i].iov_base); ++ uint64_t Host {}; ++ if (!TranslateRange(Base, Copy[i].iov_len, &Host)) { ++ return -EFAULT; ++ } ++ if (Host != Base) { ++ Copy[i].iov_base = reinterpret_cast(Host); ++ Changed = true; ++ } ++ } ++ if (Changed) { ++ *Out = reinterpret_cast(Copy); ++ } ++ return 0; ++ } ++ ++ uint64_t TranslateMessageFields(struct msghdr* Message, struct iovec* Copy, bool* Changed, bool* Copied = nullptr) { ++ const auto Name = reinterpret_cast(Message->msg_name); ++ const auto Control = reinterpret_cast(Message->msg_control); ++ const auto Vector = reinterpret_cast(Message->msg_iov); ++ uint64_t HostName {}; ++ uint64_t HostControl {}; ++ uint64_t HostVector = Vector; ++ if (!TranslateRange(Name, Message->msg_namelen, &HostName) || !TranslateRange(Control, Message->msg_controllen, &HostControl)) { ++ return -EFAULT; ++ } ++ if (const auto Result = TranslateIoVector(Vector, Message->msg_iovlen, Copy, &HostVector, Copied); Result != 0) { ++ return Result; ++ } ++ *Changed = HostName != Name || HostControl != Control || HostVector != Vector; ++ Message->msg_name = reinterpret_cast(HostName); ++ Message->msg_control = reinterpret_cast(HostControl); ++ Message->msg_iov = reinterpret_cast(HostVector); ++ return 0; ++ } ++ ++ uint64_t TranslateMessage(uint64_t* Header, bool Received, ArgumentStorage* Storage) { ++ const auto GuestHeader = *Header; ++ uint64_t HostHeader {}; ++ if (!TranslateRange(GuestHeader, sizeof(struct msghdr), &HostHeader)) { ++ return -EFAULT; ++ } ++ *Header = HostHeader; ++ auto* Message = &Storage->Message; ++ if (FaultSafeUserMemAccess::CopyFromUser(Message, reinterpret_cast(HostHeader), sizeof(*Message)) != 0) { ++ return 0; ++ } ++ bool Changed = false; ++ if (const auto Result = TranslateMessageFields(Message, VectorCopy(Storage, Message->msg_iovlen), &Changed); Result != 0 || !Changed) { ++ return Result; ++ } ++ if (Received) { ++ Storage->ReceivedHeader = GuestHeader; ++ } ++ *Header = reinterpret_cast(Message); ++ return 0; ++ } ++ ++ template ++ bool WithStableMapping(uint64_t Address, Fn&& Body) { ++ auto* Thread = Contains(Address) ? FEX::HLE::ThreadManager::GetCurrentThreadObject() : nullptr; ++ if (Thread == nullptr || Thread->HighMemoryTrap.Mappings.Held) { ++ return Body(); ++ } ++ MappingHold Hold {Thread->HighMemoryTrap.Mappings, true}; ++ return Body(); ++ } ++ ++ bool CopyToGuest(uint64_t Address, const void* Value, uint64_t Size) { ++ return WithStableMapping(Address, [&] { ++ uint64_t Host {}; ++ return TranslateRange(Address, Size, &Host) && FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(Host), Value, Size) == 0; ++ }); ++ } ++ ++ uint64_t TranslateMessages(uint64_t* Args, bool Received, ArgumentStorage* Storage) { ++ auto* Array = &Args[1]; ++ auto* Entries = &Args[2]; ++ const uint64_t Messages = std::min(static_cast(*Entries), MaxIoVectors); ++ if (Messages == 0) { ++ return 0; ++ } ++ constexpr uint64_t Size = sizeof(struct mmsghdr); ++ const auto GuestArray = *Array; ++ uint64_t HostArray {}; ++ if (!TranslateRange(GuestArray, Size, &HostArray)) { ++ return -EFAULT; ++ } ++ Storage->Messages.resize(Messages); ++ auto* Copy = Storage->Messages.data(); ++ uint64_t Ready = 0; ++ bool Contiguous = true; ++ uint64_t Whole {}; ++ if (TranslateRange(GuestArray, Messages * Size, &Whole) && ++ FaultSafeUserMemAccess::CopyFromUser(Copy, reinterpret_cast(Whole), Messages * Size) == 0) { ++ Ready = Messages; ++ } else { ++ for (; Ready < Messages; ++Ready) { ++ uint64_t Host {}; ++ if (!TranslateRange(GuestArray + Ready * Size, Size, &Host) || ++ FaultSafeUserMemAccess::CopyFromUser(&Copy[Ready], reinterpret_cast(Host), Size) != 0) { ++ break; ++ } ++ Contiguous = Contiguous && Host == HostArray + Ready * Size; ++ } ++ } ++ if (Ready == 0) { ++ *Array = HostArray; ++ return 0; ++ } ++ uint64_t Vectors = 0; ++ for (uint64_t i = 0; i < Ready; ++i) { ++ if (Copy[i].msg_hdr.msg_iovlen <= MaxIoVectors) { ++ Vectors += Copy[i].msg_hdr.msg_iovlen; ++ } ++ } ++ Storage->Heap.resize(Vectors); ++ Storage->MessageLengths.assign(Ready, 0); ++ bool Changed = !Contiguous; ++ uint64_t Offset = 0; ++ for (uint64_t i = 0; i < Ready; ++i) { ++ const auto Length = Copy[i].msg_hdr.msg_iovlen; ++ auto* Local = Storage->Heap.data() + Offset; ++ bool Translated = false; ++ bool Copied = false; ++ if (const auto Result = TranslateMessageFields(&Copy[i].msg_hdr, Local, &Translated, &Copied); Result != 0) { ++ if (i == 0) { ++ return Result; ++ } ++ Ready = i; ++ break; ++ } ++ if (!Received && Length != 0 && !Copied) { ++ if (i == 0) { ++ *Array = HostArray; ++ return 0; ++ } ++ Ready = i; ++ break; ++ } ++ if (Copied && !Received) { ++ Copy[i].msg_hdr.msg_iov = Local; ++ for (uint64_t j = 0; j < Length; ++j) { ++ Storage->MessageLengths[i] += Local[j].iov_len; ++ } ++ } ++ if (Length <= MaxIoVectors) { ++ Offset += Length; ++ } ++ Changed = Changed || Translated; ++ } ++ Storage->Messages.resize(Ready); ++ Storage->MessageLengths.resize(Ready); ++ if (!Changed) { ++ *Array = HostArray; ++ if (HostArray != GuestArray || Ready < static_cast(*Entries)) { ++ *Entries = Ready; ++ } ++ return 0; ++ } ++ *Array = reinterpret_cast(Copy); ++ *Entries = Received ? Ready : 1; ++ Storage->GuestMessages = GuestArray; ++ Storage->ReceivedMessages = Received; ++ Storage->SendFlags = static_cast(Args[3]); ++ if (!Received && Ready > 1) { ++ Storage->Socket = fcntl(static_cast(Args[0]), F_DUPFD_CLOEXEC, 0); ++ if (Storage->Socket >= 0) { ++ Args[0] = static_cast(Storage->Socket); ++ } ++ } ++ return 0; ++ } ++ ++ bool ReturnMessageFields(uint64_t Guest, const struct msghdr& Message) { ++ return (Message.msg_name == nullptr || ++ CopyToGuest(Guest + offsetof(struct msghdr, msg_namelen), &Message.msg_namelen, sizeof(Message.msg_namelen))) && ++ CopyToGuest(Guest + offsetof(struct msghdr, msg_flags), &Message.msg_flags, sizeof(Message.msg_flags)) && ++ CopyToGuest(Guest + offsetof(struct msghdr, msg_controllen), &Message.msg_controllen, sizeof(Message.msg_controllen)); ++ } ++ ++ uint64_t StringLength(uint64_t Address) { ++ uint64_t Length = 0; ++ while (Length < MaxString) { ++ const auto Here = Address + Length; ++ const auto Chunk = std::min({FEXCore::Utils::FEX_PAGE_SIZE - (Here & (FEXCore::Utils::FEX_PAGE_SIZE - 1)), MaxString - Length, StringChunk}); ++ char Chars[StringChunk]; ++ uint64_t Host {}; ++ if (!TranslateRange(Here, Chunk, &Host) || (Host == Here && Contains(Here)) || ++ FaultSafeUserMemAccess::CopyFromUser(Chars, reinterpret_cast(Host), Chunk) != 0) { ++ return Length + 1; ++ } ++ if (const auto* End = static_cast(memchr(Chars, 0, Chunk)); End != nullptr) { ++ return Length + (End - Chars) + 1; ++ } ++ Length += Chunk; ++ } ++ return MaxString; ++ } ++ ++ bool PointerLength(const Layout& Arguments, uint32_t Pointer, const uint64_t* Args, uint32_t NumArgs, uint64_t* Length) { ++ if (Arguments.Strings & Ptr(Pointer)) { ++ *Length = StringLength(Args[Pointer]); ++ return true; ++ } ++ const auto LengthArg = LengthArgument(Arguments, Pointer); ++ const auto Cap = FixedSize(Arguments, Pointer); ++ if (LengthArg == 0 || LengthArg > NumArgs) { ++ *Length = Cap; ++ return true; ++ } ++ const auto Source = Args[LengthArg - 1]; ++ if (!LengthThroughPointer(Arguments, Pointer)) { ++ return ByteLength(Arguments, Pointer, CountValue(Arguments, Pointer, Source), Length); ++ } ++ *Length = 0; ++ uint32_t Value {}; ++ uint64_t Host {}; ++ if (Source == 0 || !TranslateRange(Source, sizeof(Value), &Host) || ++ FaultSafeUserMemAccess::CopyFromUser(&Value, reinterpret_cast(Host), sizeof(Value)) != 0) { ++ return true; ++ } ++ *Length = Cap != 0 ? std::min(Value, Cap) : Value; ++ return true; ++ } ++ ++ uint64_t FileControlSize(uint64_t Command) { ++ switch (static_cast(Command)) { ++ case F_GETLK: ++ case F_SETLK: ++ case F_SETLKW: ++ case F_OFD_GETLK: ++ case F_OFD_SETLK: ++ case F_OFD_SETLKW: return FileLockSize; ++ case F_GETOWN_EX: ++ case F_SETOWN_EX: ++ case F_GET_RW_HINT: ++ case F_SET_RW_HINT: ++ case F_GET_FILE_RW_HINT: ++ case F_SET_FILE_RW_HINT: return LongSize; ++ default: return 0; ++ } ++ } ++ ++ struct IoControlBlock { ++ uint64_t Data; ++ uint32_t Key; ++ int32_t ReadWriteFlags; ++ uint16_t Opcode; ++ int16_t Priority; ++ uint32_t File; ++ uint64_t Buffer; ++ uint64_t Bytes; ++ int64_t Offset; ++ uint64_t Reserved; ++ uint32_t Flags; ++ uint32_t ResultFile; ++ }; ++ static_assert(sizeof(IoControlBlock) == IoControlBlockSize); ++ ++ constexpr uint16_t IoRead = 0; ++ constexpr uint16_t IoWrite = 1; ++ constexpr uint16_t IoReadVector = 7; ++ constexpr uint16_t IoWriteVector = 8; ++ ++ uint64_t TranslateIoBuffer(const IoControlBlock& Block, struct iovec* Copy, uint64_t* Out) { ++ *Out = Block.Buffer; ++ switch (Block.Opcode) { ++ case IoRead: ++ case IoWrite: return TranslateRange(Block.Buffer, Block.Bytes, Out) ? 0 : -EFAULT; ++ case IoReadVector: ++ case IoWriteVector: return TranslateIoVector(Block.Buffer, Block.Bytes, Copy, Out); ++ default: return 0; ++ } ++ } ++ ++ struct IoCopy { ++ IoControlBlock Block; ++ uint64_t Context; ++ uint64_t Guest; ++ uint64_t Generation; ++ bool Used; ++ }; ++ static_assert(offsetof(IoCopy, Block) == 0); ++ ++ constexpr size_t MaxIoCopies = 1024; ++ std::mutex IoCopyMutex; ++ std::array IoCopies {}; ++ size_t IoCopyNext {}; ++ std::atomic IoCopyCount {0}; ++ ++ struct AioContextState { ++ uint64_t Generation; ++ uint64_t Active; ++ bool Live; ++ fextl::list> Batches; ++ }; ++ ++ using AioContextTable = fextl::unordered_map; ++ ++ AioContextTable& AioContextsLocked() { ++ static auto* Table = fextl::make_unique().release(); ++ return *Table; ++ } ++ ++ uint64_t AioGeneration {}; ++ ++ uint64_t ContextGenerationLocked(uint64_t Context) { ++ const auto& Table = AioContextsLocked(); ++ const auto Found = Table.find(Context); ++ return Found == Table.end() ? AioGeneration : Found->second.Generation; ++ } ++ ++ IoCopy* FindIoCopyLocked(uint64_t Address) { ++ const auto First = reinterpret_cast(IoCopies.data()); ++ if (Address < First || Address - First >= sizeof(IoCopies) || (Address - First) % sizeof(IoCopy) != 0) { ++ return nullptr; ++ } ++ auto* Copy = &IoCopies[(Address - First) / sizeof(IoCopy)]; ++ return Copy->Used ? Copy : nullptr; ++ } ++ ++ void ReleaseIoCopyLocked(IoCopy* Copy) { ++ Copy->Used = false; ++ IoCopyCount.fetch_sub(1, std::memory_order_release); ++ } ++ ++ uint64_t ClaimIoCopy(const IoControlBlock& Block, uint64_t Context, uint64_t Guest) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ for (size_t Tried = 0; Tried < MaxIoCopies; ++Tried) { ++ auto& Copy = IoCopies[IoCopyNext]; ++ IoCopyNext = (IoCopyNext + 1) % MaxIoCopies; ++ if (!Copy.Used) { ++ Copy = {Block, Context, Guest, ContextGenerationLocked(Context), true}; ++ IoCopyCount.fetch_add(1, std::memory_order_release); ++ return reinterpret_cast(&Copy); ++ } ++ } ++ return 0; ++ } ++ ++ void ReleaseIoCopies(const uint64_t* Copies, uint64_t Entries) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ for (uint64_t i = 0; i < Entries; ++i) { ++ if (auto* Copy = Copies[i] ? FindIoCopyLocked(Copies[i]) : nullptr) { ++ ReleaseIoCopyLocked(Copy); ++ } ++ } ++ } ++ ++ uint64_t ContextGeneration(uint64_t Context) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ return ContextGenerationLocked(Context); ++ } ++ ++ void ReleaseContext(uint64_t Context, uint64_t Generation) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ for (auto& Copy : IoCopies) { ++ if (Copy.Used && Copy.Context == Context && Copy.Generation <= Generation) { ++ ReleaseIoCopyLocked(&Copy); ++ } ++ } ++ auto& Table = AioContextsLocked(); ++ const auto Found = Table.find(Context); ++ if (Found != Table.end() && Found->second.Generation <= Generation) { ++ Table.erase(Found); ++ } ++ } ++ ++ uint64_t BeginContext(uint64_t Context) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ auto& Table = AioContextsLocked(); ++ Table.erase(Context); ++ Table[Context] = {++AioGeneration, 0, true, {}}; ++ return AioGeneration; ++ } ++ ++ uint64_t ReportedObject(uint64_t Object) { ++ if (IoCopyCount.load(std::memory_order_acquire) != 0) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ if (auto* Copy = FindIoCopyLocked(Object)) { ++ const auto Guest = Copy->Guest; ++ ReleaseIoCopyLocked(Copy); ++ return Guest; ++ } ++ } ++ return ToGuest(Object); ++ } ++ ++ uint64_t CancelTarget(uint64_t Context, uint64_t Guest, uint64_t Host) { ++ uint32_t Key {}; ++ if (IoCopyCount.load(std::memory_order_acquire) == 0 || ++ FaultSafeUserMemAccess::CopyFromUser(&Key, reinterpret_cast(Host + offsetof(IoControlBlock, Key)), sizeof(Key)) != 0 || ++ Key != 0) { ++ return Host; ++ } ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ for (auto& Copy : IoCopies) { ++ if (Copy.Used && Copy.Context == Context && Copy.Guest == Guest) { ++ return reinterpret_cast(&Copy); ++ } ++ } ++ return Host; ++ } ++ ++ constexpr uint64_t MaxIoEvents = 65536; ++ constexpr uint64_t IoEventWords = IoEventSize / sizeof(uint64_t); ++ constexpr uint64_t AioRingMagicOffset = 16; ++ constexpr uint32_t AioRingMagic = 0xa10a10a1; ++ ++ constexpr int64_t NanosPerSecond = 1'000'000'000; ++ constexpr int64_t ReapSlice = 20'000'000; ++ constexpr int64_t MaxWaitSeconds = 1LL << 32; ++ ++ struct StashTicket { ++ uint64_t Taken; ++ uint64_t Generation; ++ }; ++ ++ uint64_t TakeEventsLocked(AioContextState& State, uint64_t* Words, uint64_t Events) { ++ uint64_t Taken = 0; ++ while (Taken < Events && !State.Batches.empty()) { ++ auto& Batch = State.Batches.front(); ++ const auto Count = std::min(Batch.size() / IoEventWords, Events - Taken); ++ std::copy_n(Batch.begin(), Count * IoEventWords, Words + Taken * IoEventWords); ++ Taken += Count; ++ if (Count * IoEventWords == Batch.size()) { ++ State.Batches.pop_front(); ++ } else { ++ Batch.erase(Batch.begin(), Batch.begin() + Count * IoEventWords); ++ } ++ } ++ return Taken; ++ } ++ ++ StashTicket ReserveEvents(uint64_t Context, uint64_t* Words, uint64_t Events, bool Take) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ auto& State = AioContextsLocked()[Context]; ++ if (State.Generation == 0) { ++ State.Generation = ++AioGeneration; ++ } ++ ++State.Active; ++ return {Take ? TakeEventsLocked(State, Words, Events) : 0, State.Generation}; ++ } ++ ++ uint64_t TopUpEvents(uint64_t Context, uint64_t Generation, uint64_t* Words, uint64_t Events) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ auto& Table = AioContextsLocked(); ++ const auto Found = Table.find(Context); ++ if (Found == Table.end() || Found->second.Generation != Generation) { ++ return 0; ++ } ++ return TakeEventsLocked(Found->second, Words, Events); ++ } ++ ++ void SettleEvents(uint64_t Context, uint64_t Generation, ArgumentStorage* Storage, uint64_t Kept, bool Forget) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ auto& Table = AioContextsLocked(); ++ const auto Found = Table.find(Context); ++ if (Found == Table.end() || Found->second.Generation != Generation) { ++ return; ++ } ++ auto& State = Found->second; ++ --State.Active; ++ if (Kept != 0) { ++ auto& Batch = Storage->Recovery.front(); ++ Batch.swap(Storage->EventBuffer); ++ Batch.resize(Kept * IoEventWords); ++ State.Batches.splice(State.Batches.begin(), Storage->Recovery); ++ } ++ if (Forget && !State.Live && State.Active == 0 && State.Batches.empty()) { ++ Table.erase(Found); ++ } ++ } ++ ++ uint64_t WritableEvents(uint64_t Host, uint64_t Events) { ++ Events = std::min(Events, (~0ULL - Host) / IoEventSize); ++ const auto End = Host + Events * IoEventSize; ++ auto Probe = Host; ++ while (Probe < End) { ++ uint8_t Byte {}; ++ if (FaultSafeUserMemAccess::CopyFromUser(&Byte, reinterpret_cast(Probe), sizeof(Byte)) != 0 || ++ FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(Probe), &Byte, sizeof(Byte)) != 0) { ++ break; ++ } ++ Probe = (Probe | (FEXCore::Utils::FEX_PAGE_SIZE - 1)) + 1; ++ } ++ return (std::min(Probe, End) - Host) / IoEventSize; ++ } ++ ++ int64_t MonotonicNanos() { ++ struct timespec Now {}; ++ clock_gettime(CLOCK_MONOTONIC, &Now); ++ return Now.tv_sec * NanosPerSecond + Now.tv_nsec; ++ } ++ ++ void SetWait(ArgumentStorage* Storage, int64_t Left) { ++ const auto Wait = std::clamp(Left, 0, ReapSlice); ++ Storage->Wait[0] = Wait / NanosPerSecond; ++ Storage->Wait[1] = Wait % NanosPerSecond; ++ } ++ ++ bool StartWait(uint64_t Timeout, ArgumentStorage* Storage) { ++ int64_t Given[2] {}; ++ if (Timeout != 0 && (FaultSafeUserMemAccess::CopyFromUser(Given, reinterpret_cast(Timeout), sizeof(Given)) != 0 || ++ Given[0] < 0 || Given[1] < 0 || Given[1] >= NanosPerSecond)) { ++ return false; ++ } ++ const auto Now = MonotonicNanos(); ++ Storage->Deadline = Timeout != 0 && Given[0] < MaxWaitSeconds ? Now + Given[0] * NanosPerSecond + Given[1] : -1; ++ SetWait(Storage, Storage->Deadline < 0 ? ReapSlice : Storage->Deadline - Now); ++ Storage->Blocking = true; ++ return true; ++ } ++ ++ bool ContinueWait(ArgumentStorage* Storage) { ++ if (Storage->Deadline < 0) { ++ SetWait(Storage, ReapSlice); ++ return true; ++ } ++ const auto Left = Storage->Deadline - MonotonicNanos(); ++ SetWait(Storage, Left); ++ return Left > 0; ++ } ++ ++ uint64_t WaitForEvents(ArgumentStorage* Storage, uint64_t* Words, uint64_t Events, uint64_t Reaped) { ++ if (!FEX::HLE::ThreadManager::GetCurrentThreadObject()->SignalInfo.DeferredSignalFrames.empty()) { ++ return -EINTR; ++ } ++ const auto Result = ::syscall(Storage->EventSyscall, Storage->EventContext, Storage->Least - Reaped, Events - Reaped, ++ Words + Reaped * IoEventWords, Storage->Wait, Storage->EventMask); ++ return Result == -1 ? -errno : Result; ++ } ++ ++ uint64_t StartContext(uint64_t ContextPointer, uint64_t Ring) { ++ const auto Generation = BeginContext(Ring); ++ uint32_t Magic {}; ++ if (FaultSafeUserMemAccess::CopyFromUser(&Magic, reinterpret_cast(Ring + AioRingMagicOffset), sizeof(Magic)) == 0 && ++ Magic == AioRingMagic) { ++ Magic = 0; ++ static_cast(FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(Ring + AioRingMagicOffset), &Magic, sizeof(Magic))); ++ } ++ if (CopyToGuest(ContextPointer, &Ring, sizeof(Ring))) { ++ return 0; ++ } ++ static_cast(::syscall(SYS_io_destroy, Ring)); ++ ReleaseContext(Ring, Generation); ++ return -EFAULT; ++ } ++ ++ uint64_t TrackIoCopies(uint64_t Syscall, const uint64_t* Guest, uint64_t* Args, ArgumentStorage* Storage) { ++ switch (Syscall) { ++ case x64::SYSCALL_x64_io_setup: ++ if (FaultSafeUserMemAccess::CopyFromUser(&Storage->SetupId, reinterpret_cast(Args[1]), sizeof(Storage->SetupId)) != 0) { ++ return -EFAULT; ++ } ++ Storage->SetupContext = Guest[1]; ++ Args[1] = reinterpret_cast(&Storage->SetupId); ++ break; ++ case x64::SYSCALL_x64_io_getevents: ++ case x64::SYSCALL_x64_io_pgetevents: { ++ const auto Wanted = static_cast(Args[2]); ++ if (Wanted <= 0 || Guest[3] == 0) { ++ break; ++ } ++ const auto Events = std::max(WritableEvents(Args[3], std::min(Wanted, MaxIoEvents)), 1); ++ if (static_cast(Wanted) > Events) { ++ if (static_cast(Args[1]) > static_cast(Events) && static_cast(Args[1]) <= Wanted) { ++ Args[1] = Events; ++ } ++ Args[2] = Events; ++ } ++ Storage->EventBuffer.resize(Events * IoEventWords); ++ Storage->Recovery.emplace_back(); ++ Storage->Events = Guest[3]; ++ Storage->EventContext = Args[0]; ++ const auto Least = static_cast(Args[1]); ++ const bool Valid = Least >= 0 && Least <= static_cast(Events); ++ const auto Ticket = ReserveEvents(Args[0], Storage->EventBuffer.data(), Events, Valid); ++ Storage->Stashed = Ticket.Taken; ++ Storage->StashGeneration = Ticket.Generation; ++ if (Valid) { ++ Storage->Least = Least; ++ Args[1] = Ticket.Taken >= Storage->Least ? 0 : Storage->Least - Ticket.Taken; ++ if (Args[1] != 0 && StartWait(Args[4], Storage)) { ++ Storage->EventSyscall = Syscall == x64::SYSCALL_x64_io_pgetevents ? SYS_io_pgetevents : SYS_io_getevents; ++ Storage->EventMask = Args[5]; ++ Args[4] = reinterpret_cast(Storage->Wait); ++ } ++ } ++ Args[2] = Events - Ticket.Taken; ++ Args[3] = reinterpret_cast(Storage->EventBuffer.data() + Ticket.Taken * IoEventWords); ++ break; ++ } ++ case x64::SYSCALL_x64_io_cancel: Args[1] = CancelTarget(Args[0], Guest[1], Args[1]); break; ++ case x64::SYSCALL_x64_io_destroy: ++ Storage->DestroyedContext = Args[0]; ++ Storage->DestroyedGeneration = ContextGeneration(Args[0]); ++ Storage->Destroying = true; ++ break; ++ default: break; ++ } ++ return 0; ++ } ++ ++ uint64_t TranslateIoSubmit(uint64_t Context, uint64_t* Entries, uint64_t* Array, ArgumentStorage* Storage) { ++ const auto Requested = static_cast(*Entries); ++ if (Requested <= 0) { ++ return 0; ++ } ++ const auto Blocks = std::min(Requested, MaxIoVectors); ++ Storage->Words.resize(Blocks); ++ auto* List = Storage->Words.data(); ++ if (FaultSafeUserMemAccess::CopyFromUser(List, reinterpret_cast(*Array), Blocks * PointerSize) != 0) { ++ return 0; ++ } ++ Storage->IoCopies.reserve(Blocks); ++ Storage->IoKeys.reserve(Blocks); ++ Storage->IoKeyValues.reserve(Blocks); ++ bool Refused = false; ++ bool Changed = false; ++ uint64_t Vectors = 0; ++ uint64_t Usable = 0; ++ for (; Usable < Blocks; ++Usable) { ++ IoControlBlock Block {}; ++ uint64_t Host {}; ++ if (!TranslateRange(List[Usable], sizeof(Block), &Host) || ++ FaultSafeUserMemAccess::CopyFromUser(&Block, reinterpret_cast(Host), sizeof(Block)) != 0) { ++ break; ++ } ++ const bool Vectored = (Block.Opcode == IoReadVector || Block.Opcode == IoWriteVector) && Block.Bytes <= MaxIoVectors; ++ if (Vectored) { ++ if (Block.Bytes > MaxIoVectors - Vectors) { ++ break; ++ } ++ Storage->Heap.resize(MaxIoVectors); ++ } ++ uint64_t Buffer {}; ++ if (TranslateIoBuffer(Block, Storage->Heap.data() + Vectors, &Buffer) != 0) { ++ break; ++ } ++ uint64_t Submitted = Host; ++ if (Buffer != Block.Buffer) { ++ if (FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(Host + offsetof(IoControlBlock, Key)), &Block.Key, sizeof(Block.Key)) != 0) { ++ Storage->IoCopies.push_back(0); ++ Storage->IoKeys.push_back(0); ++ Storage->IoKeyValues.push_back(Block.Key); ++ Changed = Changed || Host != List[Usable]; ++ List[Usable++] = Host; ++ break; ++ } ++ Block.Buffer = Buffer; ++ Submitted = ClaimIoCopy(Block, Context, List[Usable]); ++ if (Submitted == 0) { ++ Refused = true; ++ break; ++ } ++ } ++ if (Vectored) { ++ Vectors += Block.Bytes; ++ } ++ Storage->IoCopies.push_back(Submitted != Host ? Submitted : 0); ++ Storage->IoKeys.push_back(Submitted != Host ? List[Usable] + offsetof(IoControlBlock, Key) : 0); ++ Storage->IoKeyValues.push_back(Block.Key); ++ Changed = Changed || Submitted != List[Usable]; ++ List[Usable] = Submitted; ++ } ++ if (Usable == 0) { ++ return Refused ? -EAGAIN : -EFAULT; ++ } ++ if (Changed) { ++ *Array = reinterpret_cast(List); ++ } ++ *Entries = Usable; ++ return 0; ++ } ++ ++ uint64_t TranslatePageList(uint64_t* Args, ArgumentStorage* Storage) { ++ const auto Process = static_cast(Args[0]); ++ const auto Pages = Args[1]; ++ if ((Process != 0 && Process != getpid()) || Pages == 0 || Pages > MaxPageList) { ++ return 0; ++ } ++ Storage->Words.resize(Pages); ++ auto* List = Storage->Words.data(); ++ if (FaultSafeUserMemAccess::CopyFromUser(List, reinterpret_cast(Args[2]), Pages * PointerSize) != 0) { ++ return 0; ++ } ++ bool Changed = false; ++ for (uint64_t i = 0; i < Pages; ++i) { ++ uint64_t Host {}; ++ if (!TranslateRange(List[i], 1, &Host)) { ++ return -EFAULT; ++ } ++ Changed = Changed || Host != List[i]; ++ List[i] = Host; ++ } ++ if (Changed) { ++ Args[2] = reinterpret_cast(List); ++ } ++ return 0; ++ } ++ ++ struct EmbeddedSize { ++ uint64_t Offset; ++ uint64_t Header; ++ uint64_t Default; ++ uint64_t Minimum; ++ uint64_t Maximum; ++ }; ++ ++ constexpr EmbeddedSize PerfAttributeSize {4, 0, 64, 64, FEXCore::Utils::FEX_PAGE_SIZE}; ++ constexpr EmbeddedSize SchedulerAttributeSize {0, 0, 48, 48, FEXCore::Utils::FEX_PAGE_SIZE}; ++ constexpr EmbeddedSize FileHandleSize {0, 8, 0, 0, 128}; ++ constexpr EmbeddedSize MountRequestSize {0, 0, 0, 24, FEXCore::Utils::FEX_PAGE_SIZE}; ++ ++ uint64_t TranslateEmbedded(uint64_t* Argument, const EmbeddedSize& Rule) { ++ if (!Contains(*Argument)) { ++ return 0; ++ } ++ const uint64_t Field = Rule.Offset + sizeof(uint32_t); ++ uint64_t Host {}; ++ if (!TranslateRange(*Argument, Field, &Host)) { ++ return -EFAULT; ++ } ++ uint64_t Span = std::max(Field, Rule.Header); ++ uint32_t Raw {}; ++ if (FaultSafeUserMemAccess::CopyFromUser(&Raw, reinterpret_cast(Host + Rule.Offset), sizeof(Raw)) == 0) { ++ const uint64_t Value = Raw == 0 ? Rule.Default : Raw; ++ if (Value >= Rule.Minimum && Value <= Rule.Maximum) { ++ Span = std::max(Field, Rule.Header + Value); ++ } ++ } ++ return TranslateRange(*Argument, Span, Argument) ? 0 : -EFAULT; ++ } ++ ++ uint64_t TranslateCapabilities(uint64_t* Header, uint64_t GuestHeader, uint64_t* Data, ArgumentStorage* Storage) { ++ if (!Contains(*Data)) { ++ return 0; ++ } ++ uint64_t Bytes = 0; ++ auto* Copy = Storage->CapabilityHeader; ++ if (FaultSafeUserMemAccess::CopyFromUser(Copy, reinterpret_cast(*Header), sizeof(Storage->CapabilityHeader)) == 0) { ++ const auto Version = Copy[0]; ++ Bytes = Version == CapVersion1 ? CapDataSize : (Version == CapVersion2 || Version == CapVersion3) ? 2 * CapDataSize : 0; ++ Storage->CapabilityVersion = Version; ++ Storage->GuestCapabilityHeader = GuestHeader; ++ *Header = reinterpret_cast(Copy); ++ } ++ return TranslateRange(*Data, Bytes, Data) ? 0 : -EFAULT; ++ } ++ ++ uint64_t TranslateLandlockRule(uint64_t Type, uint64_t* Rule) { ++ const uint64_t Bytes = Type == 1 ? LandlockPathRuleSize : Type == 2 ? LandlockPortRuleSize : 0; ++ return TranslateRange(*Rule, Bytes, Rule) ? 0 : -EFAULT; ++ } ++ ++ uint64_t TranslateWaiters(uint64_t* Waiters, uint64_t Entries, ArgumentStorage* Storage) { ++ constexpr uint64_t Words = FutexWaitSize / sizeof(uint64_t); ++ if (Entries == 0 || Entries > MaxFutexWaiters) { ++ return 0; ++ } ++ Storage->Words.resize(Entries * Words); ++ auto* Copy = Storage->Words.data(); ++ if (FaultSafeUserMemAccess::CopyFromUser(Copy, reinterpret_cast(*Waiters), Entries * FutexWaitSize) != 0) { ++ return 0; ++ } ++ bool Changed = false; ++ for (uint64_t i = 0; i < Entries; ++i) { ++ auto& Address = Copy[i * Words + 1]; ++ uint64_t Host {}; ++ if (!TranslateRange(Address, 1ULL << (Copy[i * Words + 2] & 3), &Host)) { ++ return -EFAULT; ++ } ++ Changed = Changed || Host != Address; ++ Address = Host; ++ } ++ if (Changed) { ++ *Waiters = reinterpret_cast(Copy); ++ } ++ return 0; ++ } ++} // namespace ++ ++bool Contains(uint64_t Address) { ++ return Address >= HostLimit() && Address < TaskTop; ++} ++ ++bool ClaimsMapping(uint64_t Address, uint64_t Length, int Flags) { ++ if (!(Flags & MAP_FIXED) || (Flags & MAP_FIXED_NOREPLACE) || Length == 0) { ++ return false; ++ } ++ if (Address & (FEXCore::Utils::FEX_PAGE_SIZE - 1)) { ++ return false; ++ } ++ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE); ++ return Contains(Address) && Size <= TaskTop - Address; ++} ++ ++uint64_t Map(uint64_t Address, uint64_t Length, int Prot, int Flags, int FD, off_t Offset) { ++ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE); ++ const int HostFlags = Flags & ~MAP_FIXED; ++ void* Host = MAP_FAILED; ++ if (const auto Hint = NeighbourHint(Address, Size); Hint != 0) { ++ Host = ::mmap(reinterpret_cast(Hint), Size, Prot, HostFlags | MAP_FIXED_NOREPLACE, FD, Offset); ++ } ++ if (Host == MAP_FAILED) { ++ Host = ::mmap(nullptr, Size, Prot, HostFlags, FD, Offset); ++ } ++ if (Host == MAP_FAILED) { ++ return -errno; ++ } ++ ++ BeginWrite(); ++ int Result = 0; ++ if (!HasRoomLocked(Address, Size, 1)) { ++ Result = -ENOMEM; ++ } else { ++ Result = UnmapLocked(Address, Size); ++ } ++ if (Result == 0 && !AddEntry(Address, Size, reinterpret_cast(Host), false, TrackedProt(Prot))) { ++ Result = -ENOMEM; ++ } ++ if (Result == 0) { ++ CoalesceLocked(Address, Address + Size); ++ } ++ EndWrite(); ++ if (Result != 0) { ++ ::munmap(Host, Size); ++ return Result; ++ } ++ return Address; ++} ++ ++uint64_t Unmap(uint64_t Address, uint64_t Length) { ++ if (Address & (FEXCore::Utils::FEX_PAGE_SIZE - 1)) { ++ return -EINVAL; ++ } ++ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE); ++ if (Size == 0 || Size > TaskTop - Address) { ++ return -EINVAL; ++ } ++ BeginWrite(); ++ const int Result = UnmapLocked(Address, Size); ++ EndWrite(); ++ return Result; ++} ++ ++uint64_t Protect(uint64_t Address, uint64_t Length, int Prot) { ++ BeginWrite(); ++ uint64_t Result = ApplyToRegionsLocked(Address, Length, -ENOMEM, [](void*, uint64_t, uint32_t) { return 0; }); ++ if (Result == 0) { ++ Result = SplitLocked(Address, Length); ++ } ++ if (Result == 0) { ++ Result = ApplyToRegionsLocked(Address, Length, -ENOMEM, [Prot](void* Host, uint64_t Size, uint32_t i) { ++ const int Applied = ::mprotect(Host, Size, Prot); ++ if (Applied == 0) { ++ Regions[i].Prot.store(TrackedProt(Prot), std::memory_order_relaxed); ++ } ++ return Applied; ++ }); ++ CoalesceLocked(Address, Address + std::min(FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE), TaskTop - Address)); ++ } ++ EndWrite(); ++ return Result; ++} ++ ++uint64_t Advise(uint64_t Address, uint64_t Length, int Advice, bool* Applied) { ++ *Applied = false; ++ return ApplyToRegionsLocked(Address, Length, -EINVAL, [Advice, Applied](void* Host, uint64_t Size, uint32_t) { ++ const int Result = ::madvise(Host, Size, Advice); ++ if (Result == 0) { ++ *Applied = true; ++ } ++ return Result; ++ }); ++} ++ ++bool DiscardsContents(int Advice) { ++ switch (Advice) { ++ case MADV_DONTNEED: ++ case MADV_FREE: ++ case MADV_REMOVE: ++ case MADV_DONTNEED_LOCKED: return true; ++ default: return false; ++ } ++} ++ ++uint64_t ToGuest(uint64_t Address) { ++ if (Count.load(std::memory_order_relaxed) == 0) [[likely]] { ++ return Address; ++ } ++ return ReadConsistent([&] { ++ const auto Entries = Count.load(std::memory_order_acquire); ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Host = Regions[i].Host.load(std::memory_order_relaxed); ++ const auto Size = Regions[i].Size.load(std::memory_order_relaxed); ++ if (Address >= Host && Address - Host < Size) { ++ return Regions[i].Guest.load(std::memory_order_relaxed) + (Address - Host); ++ } ++ } ++ return Address; ++ }); ++} ++ ++bool TranslateRange(uint64_t Address, uint64_t Length, uint64_t* Host) { ++ if (Count.load(std::memory_order_relaxed) == 0 || !Contains(Address)) [[likely]] { ++ *Host = Address; ++ return true; ++ } ++ return ReadConsistent([&] { return SpanLocked(Address, Length, Host); }); ++} ++ ++void MarkCode(uint64_t Address, uint64_t Length) { ++ const auto End = Address + Length; ++ const auto Entries = Count.load(std::memory_order_acquire); ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto RegionEnd = Guest + Regions[i].Size.load(std::memory_order_relaxed); ++ if (RegionEnd > Address && Guest < End) { ++ Regions[i].Code.store(true, std::memory_order_relaxed); ++ } ++ } ++} ++ ++uint64_t TranslateSyscallArguments(uint64_t Syscall, uint64_t* Args, uint32_t NumArgs, ArgumentStorage* Storage) { ++ if (Count.load(std::memory_order_relaxed) == 0) [[likely]] { ++ return TrackIoCopies(Syscall, Args, Args, Storage); ++ } ++ if (Syscall >= Layouts.size()) { ++ return 0; ++ } ++ const auto& Arguments = Layouts[Syscall]; ++ const auto Used = std::min(NumArgs, 6); ++ uint64_t Guest[6] {}; ++ std::copy_n(Args, Used, Guest); ++ uint64_t Lengths[6] {}; ++ for (uint32_t i = 0; i < Used; ++i) { ++ if ((Arguments.Pointers & Ptr(i)) && Contains(Args[i]) && !PointerLength(Arguments, i, Args, Used, &Lengths[i])) { ++ return -EFAULT; ++ } ++ } ++ for (uint32_t i = 0; i < Used; ++i) { ++ if ((Arguments.Pointers & Ptr(i)) && !TranslateRange(Args[i], Lengths[i], &Args[i])) { ++ return -EFAULT; ++ } ++ } ++ if (const auto Failed = TrackIoCopies(Syscall, Guest, Args, Storage); Failed != 0) { ++ return Failed; ++ } ++ if (Used < 6) { ++ return 0; ++ } ++ switch (Arguments.Vector) { ++ case VectorKind::Io: return TranslateIoVector(Args[1], Args[2], VectorCopy(Storage, Args[2]), &Args[1]); ++ case VectorKind::SentMessage: return TranslateMessage(&Args[1], false, Storage); ++ case VectorKind::ReceivedMessage: return TranslateMessage(&Args[1], true, Storage); ++ case VectorKind::SentMessageArray: return TranslateMessages(Args, false, Storage); ++ case VectorKind::ReceivedMessageArray: return TranslateMessages(Args, true, Storage); ++ case VectorKind::IoSubmit: return TranslateIoSubmit(Args[0], &Args[1], &Args[2], Storage); ++ case VectorKind::IoEvents: return 0; ++ case VectorKind::PageList: return TranslatePageList(Args, Storage); ++ case VectorKind::FutexWaiters: return TranslateWaiters(&Args[0], static_cast(Args[1]), Storage); ++ case VectorKind::FutexRequeue: return TranslateWaiters(&Args[0], 2, Storage); ++ case VectorKind::FileControl: return TranslateRange(Args[2], FileControlSize(Args[1]), &Args[2]) ? 0 : -EFAULT; ++ case VectorKind::Capabilities: return TranslateCapabilities(&Args[0], Guest[0], &Args[1], Storage); ++ case VectorKind::PerfAttribute: return TranslateEmbedded(&Args[0], PerfAttributeSize); ++ case VectorKind::SchedulerAttribute: return TranslateEmbedded(&Args[1], SchedulerAttributeSize); ++ case VectorKind::HandleAt: return TranslateEmbedded(&Args[2], FileHandleSize); ++ case VectorKind::OpenHandle: return TranslateEmbedded(&Args[1], FileHandleSize); ++ case VectorKind::MountRequest: return TranslateEmbedded(&Args[0], MountRequestSize); ++ case VectorKind::LandlockRule: return TranslateLandlockRule(static_cast(Args[1]), &Args[2]); ++ case VectorKind::None: break; ++ } ++ return 0; ++} ++ ++bool HoldsMappings(FEXCore::Core::InternalThreadState* Thread) { ++ return FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->HighMemoryTrap.Mappings.Held; ++} ++ ++uint64_t FinishSyscallArguments(uint64_t Result, ArgumentStorage* Storage) { ++ struct PinnedSocket { ++ int FD; ++ ~PinnedSocket() { ++ if (FD >= 0) { ++ close(FD); ++ } ++ } ++ } Socket {std::exchange(Storage->Socket, -1)}; ++ if (!Storage->IoCopies.empty()) { ++ const auto Submitted = FEX::HLE::HasSyscallError(Result) ? 0 : std::min(Result, Storage->IoCopies.size()); ++ const auto Examined = std::min(Submitted + 1, Storage->IoCopies.size()); ++ for (uint64_t i = 0; i < Examined; ++i) { ++ if (Storage->IoKeys[i] == 0) { ++ continue; ++ } ++ const uint32_t Key = i < Submitted ? 0 : reinterpret_cast(Storage->IoCopies[i])->Key; ++ if (Key != Storage->IoKeyValues[i]) { ++ static_cast(CopyToGuest(Storage->IoKeys[i], &Key, sizeof(Key))); ++ } ++ } ++ ReleaseIoCopies(Storage->IoCopies.data() + Submitted, Storage->IoCopies.size() - Submitted); ++ } ++ if (Storage->SetupContext != 0 && Result == 0) { ++ Result = StartContext(Storage->SetupContext, Storage->SetupId); ++ } ++ if (Storage->Destroying && Result == 0) { ++ ReleaseContext(Storage->DestroyedContext, Storage->DestroyedGeneration); ++ } ++ if (Storage->GuestCapabilityHeader != 0 && Storage->CapabilityHeader[0] != Storage->CapabilityVersion && ++ !CopyToGuest(Storage->GuestCapabilityHeader, &Storage->CapabilityHeader[0], sizeof(Storage->CapabilityHeader[0]))) { ++ return -EFAULT; ++ } ++ if (Storage->Events != 0) { ++ const auto Taken = Storage->Stashed; ++ auto* Words = Storage->EventBuffer.data(); ++ if (FEX::HLE::HasSyscallError(Result) && (Result != static_cast(-EINTR) || Taken == 0)) { ++ SettleEvents(Storage->EventContext, Storage->StashGeneration, Storage, Taken, Result == static_cast(-EINVAL)); ++ return Result; ++ } ++ const auto Events = Storage->EventBuffer.size() / IoEventWords; ++ auto Reaped = Taken; ++ while (!FEX::HLE::HasSyscallError(Result)) { ++ const auto Fresh = std::min(Result, Events - Reaped); ++ for (uint64_t i = Reaped; i < Reaped + Fresh; ++i) { ++ auto& Object = Words[i * IoEventWords + IoEventObjectOffset / sizeof(uint64_t)]; ++ Object = ReportedObject(Object); ++ } ++ Reaped += Fresh; ++ if (!Storage->Blocking || Reaped >= Storage->Least) { ++ break; ++ } ++ Reaped += TopUpEvents(Storage->EventContext, Storage->StashGeneration, Words + Reaped * IoEventWords, Events - Reaped); ++ if (Reaped >= Storage->Least || !ContinueWait(Storage)) { ++ break; ++ } ++ Result = WaitForEvents(Storage, Words, Events, Reaped); ++ if (FEX::HLE::HasSyscallError(Result) && Reaped == 0) { ++ SettleEvents(Storage->EventContext, Storage->StashGeneration, Storage, 0, Result == static_cast(-EINVAL)); ++ return Result; ++ } ++ } ++ const bool Delivered = Reaped == 0 || CopyToGuest(Storage->Events, Words, Reaped * IoEventSize); ++ SettleEvents(Storage->EventContext, Storage->StashGeneration, Storage, Delivered ? 0 : Reaped, false); ++ if (!Delivered) { ++ return -EFAULT; ++ } ++ Result = Reaped; ++ } ++ if (FEX::HLE::HasSyscallError(Result)) { ++ return Result; ++ } ++ if (Storage->GuestMessages != 0) { ++ const bool FollowUps = !Storage->ReceivedMessages && Socket.FD >= 0; ++ const auto Total = FollowUps ? Storage->Messages.size() : std::min(Result, Storage->Messages.size()); ++ uint64_t Done = 0; ++ for (; Done < Total; ++Done) { ++ auto& Message = Storage->Messages[Done]; ++ if (Done >= Result && ::sendmmsg(Socket.FD, &Message, 1, Storage->SendFlags) != 1) { ++ break; ++ } ++ const auto Guest = Storage->GuestMessages + Done * sizeof(struct mmsghdr); ++ if ((Storage->ReceivedMessages && !ReturnMessageFields(Guest + offsetof(struct mmsghdr, msg_hdr), Message.msg_hdr)) || ++ !CopyToGuest(Guest + offsetof(struct mmsghdr, msg_len), &Message.msg_len, sizeof(Message.msg_len))) { ++ return Done == 0 ? -EFAULT : Done; ++ } ++ if (FollowUps && Message.msg_len < Storage->MessageLengths[Done]) { ++ return Done + 1; ++ } ++ } ++ return Done; ++ } ++ if (Storage->ReceivedHeader != 0 && !ReturnMessageFields(Storage->ReceivedHeader, Storage->Message)) { ++ return -EFAULT; ++ } ++ return Result; ++} ++ ++bool HandleFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) { ++ auto* SigInfo = static_cast(Info); ++ const auto FaultAddress = reinterpret_cast(SigInfo->si_addr); ++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); ++ auto& Trap = ThreadObject->HighMemoryTrap; ++ const auto PC = ArchHelpers::Context::GetPc(UContext); ++ ++ if (DeferWhileHeld(Trap.Mappings, Signal, SigInfo)) { ++ return true; ++ } ++ if (Trap.Active && PC == reinterpret_cast(Trap.Code)) { ++ RedeliverFromTrap(Trap, SigInfo, UContext); ++ return false; ++ } ++ ++ if (SigInfo->si_code <= SI_USER || !Contains(FaultAddress) || Trap.Active || Trap.Mappings.Held) { ++ return false; ++ } ++ ++ const auto Insn = *reinterpret_cast(PC); ++ if (!IsLoadStore(Insn) || IsLiteralLoad(Insn) || RnField(Insn) == 31) { ++ return false; ++ } ++ ++ uint64_t Address {}; ++ uint32_t Size {}; ++ bool Plain {}; ++ if (!DecodeAccess(Insn, UContext, &Address, &Size, &Plain)) { ++ return false; ++ } ++ ++ MappingHold Hold {Trap.Mappings}; ++ AccessPiece Pieces[MaxAccessPieces] {}; ++ const auto Parts = ReadConsistent([&] { return PlanAccessLocked(Address, Size, Pieces); }); ++ if (Parts == 0) { ++ return false; ++ } ++ ++ const bool Write = IsWrite(Insn); ++ if (Write && std::any_of(Pieces, Pieces + Parts, [](const AccessPiece& Piece) { return Piece.Code; })) { ++ auto& VMATracking = FEX::HLE::_SyscallHandler->VMATracking; ++ for (uint32_t i = 0; i < Parts; ++i) { ++ if (!Pieces[i].Code) { ++ continue; ++ } ++ const auto Last = Pieces[i].Guest + Pieces[i].Size - 1; ++ for (auto FaultBase = FEXCore::AlignDown(Pieces[i].Guest, FEXCore::Utils::FEX_PAGE_SIZE); FaultBase <= Last; ++ FaultBase += FEXCore::Utils::FEX_PAGE_SIZE) { ++ const auto Entry = VMATracking.FindVMAEntry(FaultBase); ++ if (Entry != VMATracking.VMAs.end()) { ++ FEX::HLE::SyscallHandler::InvalidateWrittenCodePage(Thread, FaultBase, Entry->first, Entry->second); ++ } else { ++ FEX::HLE::_SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBase, FEXCore::Utils::FEX_PAGE_SIZE); ++ } ++ } ++ } ++ ++ constexpr uint64_t MaxStoreSize = 64; ++ const uint64_t StoreWindowStart = FaultAddress - MaxStoreSize; ++ auto CTX = Thread->CTX; ++ if (CTX->IsAddressInCodeBuffer(Thread, PC) && !CTX->IsCurrentBlockSingleInst(Thread) && ++ CTX->IsAddressInCurrentBlock(Thread, StoreWindowStart, 2 * MaxStoreSize)) { ++ ThreadObject->SignalInfo.Delegator->SpillSRA(Thread, UContext, Thread->CurrentFrame->InSyscallInfo & 0xFFFF); ++ const auto& Config = ThreadObject->SignalInfo.Delegator->GetConfig(); ++ ArchHelpers::Context::SetPc(UContext, Config.AbsoluteLoopTopAddressFillSRA); ++ ArchHelpers::Context::SetArmReg(UContext, 1, 1); ++ return true; ++ } ++ } ++ ++ if (IsExclusive(Insn)) { ++ if (Parts != 1 || !ExclusiveReachable(Insn, Pieces[0].Prot) || ++ !EmulateExclusive(Trap.Monitor, Insn, Pieces[0].Host, UContext)) { ++ return false; ++ } ++ ArchHelpers::Context::SetPc(UContext, PC + 4); ++ return true; ++ } ++ ++ const bool Bounced = !HostContiguous(Pieces, Parts); ++ if (Bounced && (!PiecesReachable(Pieces, Parts, Write) || (!Plain && !IsOrderedAccess(Insn)))) { ++ return false; ++ } ++ ++ const int Scratch = PickScratch(Insn); ++ if (Scratch < 0 || !EnsureTrapCode(Trap)) { ++ return false; ++ } ++ ++ Trap.Scratch = Scratch; ++ Trap.Base = RnField(Insn); ++ Trap.SavedScratch = ArchHelpers::Context::GetArmReg(UContext, Scratch); ++ Trap.BaseBefore = ArchHelpers::Context::GetArmReg(UContext, Trap.Base); ++ Trap.ResumePC = PC + 4; ++ Trap.Parts = 0; ++ Trap.Delta = Pieces[0].Host - Address; ++ ++ uint32_t Failed = Parts; ++ if (Bounced && !Plain) { ++ Failed = EmulateOrdered(Insn, Pieces, Parts, UContext); ++ if (Failed == Parts) { ++ ArchHelpers::Context::SetPc(UContext, PC + 4); ++ return true; ++ } ++ } else if (Bounced) { ++ Trap.BounceOffset = Address & 15; ++ Trap.Store = Write; ++ Trap.Parts = Parts; ++ for (uint32_t i = 0; i < Parts; ++i) { ++ Trap.Pieces[i].Guest = Pieces[i].Guest; ++ Trap.Pieces[i].Host = Pieces[i].Host; ++ Trap.Pieces[i].Size = Pieces[i].Size; ++ } ++ auto* Window = Trap.Bounce + Trap.BounceOffset; ++ Failed = CopyPieces(Window, Trap.Pieces, Parts, true); ++ Trap.Delta = reinterpret_cast(Window) - Address; ++ } ++ ++ auto* Mask = &ArchHelpers::Context::GetUContext(UContext)->uc_sigmask; ++ memcpy(&Trap.SavedMask, Mask, sizeof(Trap.SavedMask)); ++ const uint64_t Blocked = ~HeldSignalMask(); ++ memcpy(Mask, &Blocked, sizeof(Blocked)); ++ if (Failed != Parts) { ++ ArmProbe(Trap, UContext, Pieces[Failed].Guest, Pieces[Failed].Host); ++ } else { ++ ArmTrap(Trap, UContext, (Insn & ~(0x1fU << 5)) | (static_cast(Scratch) << 5), Trap.BaseBefore + Trap.Delta, false); ++ } ++ Hold.Keep(); ++ return true; ++} ++ ++bool HandleBusFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) { ++ auto* SigInfo = static_cast(Info); ++ auto& Trap = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->HighMemoryTrap; ++ const auto PC = ArchHelpers::Context::GetPc(UContext); ++ if (DeferWhileHeld(Trap.Mappings, Signal, SigInfo)) { ++ return true; ++ } ++ if (Trap.Active && PC == reinterpret_cast(Trap.Code)) { ++ RedeliverFromTrap(Trap, SigInfo, UContext); ++ return false; ++ } ++ if (SigInfo->si_code <= SI_USER || !FaultSafeUserMemAccess::IsFaultLocation(PC)) { ++ return false; ++ } ++ ArchHelpers::Context::SetArmReg(UContext, 0, EFAULT); ++ ArchHelpers::Context::SetPc(UContext, ArchHelpers::Context::GetArmReg(UContext, 30)); ++ return true; ++} ++ ++bool HandleTrap(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) { ++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); ++ auto& Trap = ThreadObject->HighMemoryTrap; ++ auto* SigInfo = static_cast(Info); ++ if (DeferWhileHeld(Trap.Mappings, Signal, SigInfo)) { ++ return true; ++ } ++ if (!Trap.Active || SigInfo->si_code != TRAP_BRKPT || ArchHelpers::Context::GetPc(UContext) != reinterpret_cast(Trap.Code) + 4) { ++ return false; ++ } ++ ++ if (Trap.Probe) { ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Scratch, Trap.SavedScratch); ++ LeaveTrap(Trap, UContext, Trap.ResumePC - 4); ++ return true; ++ } ++ ++ const auto ScratchAfter = ArchHelpers::Context::GetArmReg(UContext, Trap.Scratch); ++ if (ScratchAfter != Trap.BaseBefore + Trap.Delta) { ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Base, ScratchAfter - Trap.Delta); ++ } ++ if (Trap.Parts != 0 && Trap.Store) { ++ const auto Failed = CopyPieces(Trap.Bounce + Trap.BounceOffset, Trap.Pieces, Trap.Parts, false); ++ if (Failed != Trap.Parts) { ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Base, Trap.BaseBefore); ++ ArmProbe(Trap, UContext, Trap.Pieces[Failed].Guest, Trap.Pieces[Failed].Host); ++ return true; ++ } ++ } ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Scratch, Trap.SavedScratch); ++ LeaveTrap(Trap, UContext, Trap.ResumePC); ++ return true; ++} ++ ++void ReleaseThread(FEX::HLE::ThreadStateObject* Thread) { ++ if (Thread->HighMemoryTrap.Code) { ++ FEXCore::Allocator::munmap(Thread->HighMemoryTrap.Code, FEXCore::Utils::FEX_PAGE_SIZE); ++ Thread->HighMemoryTrap.Code = nullptr; ++ } ++} ++} // namespace FEX::HLE::GuestHighMemory +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h +new file mode 100644 +index 0000000..661b200 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h +@@ -0,0 +1,74 @@ ++#pragma once ++ ++#include ++#include ++ ++#include ++#include ++#include ++#include ++ ++namespace FEXCore::Core { ++struct InternalThreadState; ++} ++ ++namespace FEX::HLE { ++struct ThreadStateObject; ++} ++ ++namespace FEX::HLE::GuestHighMemory { ++struct ArgumentStorage { ++ struct iovec Inline[8]; ++ fextl::vector Heap; ++ struct msghdr Message; ++ uint64_t ReceivedHeader {}; ++ fextl::vector Messages; ++ fextl::vector MessageLengths; ++ uint64_t GuestMessages {}; ++ bool ReceivedMessages {}; ++ int Socket {-1}; ++ int SendFlags {}; ++ uint32_t CapabilityHeader[2] {}; ++ uint32_t CapabilityVersion {}; ++ uint64_t GuestCapabilityHeader {}; ++ fextl::vector Words; ++ fextl::vector IoCopies; ++ fextl::vector IoKeys; ++ fextl::vector IoKeyValues; ++ fextl::vector EventBuffer; ++ fextl::list> Recovery; ++ uint64_t Events {}; ++ uint64_t EventContext {}; ++ uint64_t Stashed {}; ++ uint64_t StashGeneration {}; ++ uint64_t Least {}; ++ int64_t Deadline {}; ++ int64_t Wait[2] {}; ++ long EventSyscall {}; ++ uint64_t EventMask {}; ++ bool Blocking {}; ++ uint64_t SetupContext {}; ++ uint64_t SetupId {}; ++ uint64_t DestroyedContext {}; ++ uint64_t DestroyedGeneration {}; ++ bool Destroying {}; ++}; ++ ++bool Contains(uint64_t Address); ++bool ClaimsMapping(uint64_t Address, uint64_t Length, int Flags); ++uint64_t Map(uint64_t Address, uint64_t Length, int Prot, int Flags, int FD, off_t Offset); ++uint64_t Unmap(uint64_t Address, uint64_t Length); ++uint64_t Protect(uint64_t Address, uint64_t Length, int Prot); ++uint64_t Advise(uint64_t Address, uint64_t Length, int Advice, bool* Applied); ++bool DiscardsContents(int Advice); ++uint64_t ToGuest(uint64_t Address); ++bool TranslateRange(uint64_t Address, uint64_t Length, uint64_t* Host); ++void MarkCode(uint64_t Address, uint64_t Length); ++uint64_t TranslateSyscallArguments(uint64_t Syscall, uint64_t* Args, uint32_t Count, ArgumentStorage* Storage); ++uint64_t FinishSyscallArguments(uint64_t Result, ArgumentStorage* Storage); ++bool HoldsMappings(FEXCore::Core::InternalThreadState* Thread); ++bool HandleFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext); ++bool HandleBusFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext); ++bool HandleTrap(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext); ++void ReleaseThread(FEX::HLE::ThreadStateObject* Thread); ++} // namespace FEX::HLE::GuestHighMemory +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +index 87b890e..ababed9 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -7,6 +7,7 @@ $end_info$ + */ + + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/GuestHighMemory.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/PtraceEmu.h" + #include "LinuxSyscalls/SignalTrace.h" +@@ -765,6 +766,10 @@ uint64_t SignalDelegator::GetNewSigMask(int Signal) const { + } + + bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) { ++ if (FEX::HLE::GuestHighMemory::HandleFault(Thread, Signal, Info, UContext)) { ++ return true; ++ } ++ + auto SigInfo = *static_cast(Info); + + if (FaultSafeUserMemAccess::TryHandleSafeFault(Signal, SigInfo, UContext)) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +index 607ab0b..5e684c4 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +@@ -16,6 +16,7 @@ $end_info$ + #include "LinuxSyscalls/LinuxAllocator.h" + #include "LinuxSyscalls/SignalDelegator.h" + #include "LinuxSyscalls/PtraceEmu.h" ++#include "LinuxSyscalls/GuestHighMemory.h" + #include + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/Syscalls/Thread.h" +@@ -820,6 +821,8 @@ SyscallHandler::SyscallHandler(FEXCore::Context::Context* _CTX, FEX::HLE::Signal + + SignalDelegation->RegisterHostSignalHandler(SIGSEGV, HandleSegfault, true); + ++ SignalDelegation->RegisterHostSignalHandler(SIGTRAP, FEX::HLE::GuestHighMemory::HandleTrap, true); ++ SignalDelegation->RegisterHostSignalHandler(SIGBUS, FEX::HLE::GuestHighMemory::HandleBusFault, true); + SignalDelegation->RegisterHostSignalHandler( + SIGTRAP, [](FEXCore::Core::InternalThreadState*, int, void*, void*) { return false; }, true); + +@@ -894,30 +897,34 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint + } + + auto& Def = Definitions[SyscallNum]; ++ uint64_t A[7] {}; ++ for (unsigned i = 1; i < 7; ++i) { ++ A[i] = GetArg(Is64Bit, Frame, i); ++ } ++ FEX::HLE::GuestHighMemory::ArgumentStorage HighMemoryArguments; + uint64_t Result {}; +- switch (Def.NumArgs) { +- case 0: Result = std::invoke(Def.Ptr0, Frame); break; +- case 1: Result = std::invoke(Def.Ptr1, Frame, GetArg(Is64Bit, Frame, 1)); break; +- case 2: Result = std::invoke(Def.Ptr2, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2)); break; +- case 3: Result = std::invoke(Def.Ptr3, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3)); break; +- case 4: +- Result = +- std::invoke(Def.Ptr4, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3), GetArg(Is64Bit, Frame, 4)); +- break; +- case 5: +- Result = std::invoke(Def.Ptr5, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3), +- GetArg(Is64Bit, Frame, 4), GetArg(Is64Bit, Frame, 5)); +- break; +- case 6: +- Result = std::invoke(Def.Ptr6, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3), +- GetArg(Is64Bit, Frame, 4), GetArg(Is64Bit, Frame, 5), GetArg(Is64Bit, Frame, 6)); +- break; +- // for missing syscalls +- case 255: Result = std::invoke(Def.Ptr1, Frame, GetArg(Is64Bit, Frame, 0)); break; +- default: +- LOGMAN_MSG_A_FMT("Unhandled syscall: {}", GetArg(Is64Bit, Frame, 0)); +- Result = -ENOSYS; +- break; ++ if constexpr (Is64Bit) { ++ Result = FEX::HLE::GuestHighMemory::TranslateSyscallArguments(SyscallNum, &A[1], 6, &HighMemoryArguments); ++ } ++ if (!FEX::HLE::HasSyscallError(Result)) { ++ switch (Def.NumArgs) { ++ case 0: Result = std::invoke(Def.Ptr0, Frame); break; ++ case 1: Result = std::invoke(Def.Ptr1, Frame, A[1]); break; ++ case 2: Result = std::invoke(Def.Ptr2, Frame, A[1], A[2]); break; ++ case 3: Result = std::invoke(Def.Ptr3, Frame, A[1], A[2], A[3]); break; ++ case 4: Result = std::invoke(Def.Ptr4, Frame, A[1], A[2], A[3], A[4]); break; ++ case 5: Result = std::invoke(Def.Ptr5, Frame, A[1], A[2], A[3], A[4], A[5]); break; ++ case 6: Result = std::invoke(Def.Ptr6, Frame, A[1], A[2], A[3], A[4], A[5], A[6]); break; ++ // for missing syscalls ++ case 255: Result = std::invoke(Def.Ptr1, Frame, GetArg(Is64Bit, Frame, 0)); break; ++ default: ++ LOGMAN_MSG_A_FMT("Unhandled syscall: {}", GetArg(Is64Bit, Frame, 0)); ++ Result = -ENOSYS; ++ break; ++ } ++ } ++ if constexpr (Is64Bit) { ++ Result = FEX::HLE::GuestHighMemory::FinishSyscallArguments(Result, &HighMemoryArguments); + } + #ifdef DEBUG_STRACE + Strace(Frame, Result); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Memory.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Memory.cpp +index 9397c9e..6095bf3 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Memory.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Memory.cpp +@@ -5,12 +5,19 @@ tags: LinuxSyscalls|syscalls-shared + $end_info$ + */ + ++#include "LinuxSyscalls/GuestHighMemory.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/x64/Syscalls.h" + #include "LinuxSyscalls/x32/Syscalls.h" + + #include ++#include ++#include ++#include ++#include + ++#include ++#include + #include + #include + #include +@@ -25,6 +32,29 @@ void RegisterMemory(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(madvise, [](FEXCore::Core::CpuStateFrame* Frame, void* addr, size_t length, int32_t advice) -> uint64_t { ++ if (FEX::HLE::GuestHighMemory::Contains(reinterpret_cast(addr))) { ++ uint64_t Result {}; ++ bool Applied {}; ++ { ++ auto lk = FEXCore::GuardSignalDeferringSection(FEX::HLE::_SyscallHandler->VMATracking.Mutex, Frame->Thread); ++ Result = FEX::HLE::GuestHighMemory::Advise(reinterpret_cast(addr), length, advice, &Applied); ++ } ++ if (Applied && FEX::HLE::GuestHighMemory::DiscardsContents(advice)) { ++ const auto Base = reinterpret_cast(addr); ++ const auto Size = std::min(FEXCore::AlignUp(length, FEXCore::Utils::FEX_PAGE_SIZE), UINT64_MAX - Base); ++ FEX::HLE::_SyscallHandler->TM.InvalidateGuestCodeRange(Frame->Thread, Base, Size, [](uintptr_t Start, uintptr_t Length) { ++ if (FEX::HLE::GuestHighMemory::Contains(Start)) { ++ return; ++ } ++ auto rv = mprotect(reinterpret_cast(Start), Length, PROT_READ | PROT_WRITE); ++ LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); ++ }); ++ } ++ if (!FEX::HLE::HasSyscallError(Result)) { ++ FEX::HLE::_SyscallHandler->TrackMadvise(Frame->Thread, (uintptr_t)addr, length, advice); ++ } ++ return Result; ++ } + uint64_t Result = ::madvise(addr, length, advice); + + if (Result != -1) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +index f9e85a2..2dff836 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +@@ -21,6 +21,7 @@ $end_info$ + + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/GuestHighMemory.h" + + #include + #include +@@ -45,6 +46,9 @@ static void HandleSegfaultForCodeCacheFinalization(FEXCore::Core::InternalThread + void SyscallHandler::InvalidateWrittenCodePage(FEXCore::Core::InternalThreadState* Thread, uint64_t FaultBase, uint64_t EntryBase, + const FEX::HLE::VMATracking::VMAEntry& Mapping) { + auto UnprotectRegionCallback = [](uintptr_t Start, uintptr_t Length) { ++ if (FEX::HLE::GuestHighMemory::Contains(Start)) { ++ return; ++ } + auto rv = mprotect((void*)Start, Length, PROT_READ | PROT_WRITE); + LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); + }; +@@ -93,6 +97,10 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread, + } + } + ++ if (FEX::HLE::GuestHighMemory::Contains(FaultAddress) || FEX::HLE::GuestHighMemory::HoldsMappings(Thread)) { ++ return false; ++ } ++ + { + // Can't use the deferred signal lock in the SIGSEGV handler. + auto lk = FEXCore::MaskSignalsAndLockMutex(_SyscallHandler->VMATracking.Mutex); +@@ -150,6 +158,7 @@ void SyscallHandler::PrepareGuestBufferForKernelWrite(FEXCore::Core::InternalThr + return; + } + ++ Buf = reinterpret_cast(FEX::HLE::GuestHighMemory::ToGuest(reinterpret_cast(Buf))); + const uint64_t Start = FEXCore::AlignDown(reinterpret_cast(Buf), FEXCore::Utils::FEX_PAGE_SIZE); + const uint64_t Last = reinterpret_cast(Buf) + Length - 1 < reinterpret_cast(Buf) ? + UINT64_MAX : +@@ -176,6 +185,9 @@ void SyscallHandler::PrepareGuestBufferForKernelWrite(FEXCore::Core::InternalThr + } + } else { + TM.InvalidateGuestCodeRange(Thread, From, To - From, [](uintptr_t Start, uintptr_t Length) { ++ if (FEX::HLE::GuestHighMemory::Contains(Start)) { ++ return; ++ } + auto rv = mprotect(reinterpret_cast(Start), Length, PROT_READ | PROT_WRITE); + LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); + }); +@@ -227,6 +239,10 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState + const auto ProtectBase = std::max(MapBase, Base); + const auto ProtectSize = std::min(MapTop, Top) - ProtectBase; + ++ const bool HighRange = FEX::HLE::GuestHighMemory::Contains(ProtectBase); ++ if (HighRange) { ++ FEX::HLE::GuestHighMemory::MarkCode(ProtectBase, ProtectSize); ++ } + if (Mapping->second.Flags.Shared) { + LOGMAN_THROW_A_FMT(Mapping->second.Resource, "VMA tracking error"); + +@@ -245,13 +261,17 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState + + const auto MirroredBase = std::max(VMAOffsetBase, OffsetBase); + const auto MirroredSize = std::min(OffsetTop, VMAOffsetTop) - MirroredBase; ++ if (FEX::HLE::GuestHighMemory::Contains(MirroredBase - VMAOffsetBase + VMABase)) { ++ FEX::HLE::GuestHighMemory::MarkCode(MirroredBase - VMAOffsetBase + VMABase, MirroredSize); ++ continue; ++ } + + auto rv = mprotect((void*)(MirroredBase - VMAOffsetBase + VMABase), MirroredSize, PROT_READ); + LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", MirroredBase, MirroredSize); + } + } while ((VMA = VMA->ResourceNextVMA)); + +- } else if (Mapping->second.Prot.Writable) { ++ } else if (!HighRange && Mapping->second.Prot.Writable) { + int rv = mprotect((void*)ProtectBase, ProtectSize, PROT_READ); + + LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", ProtectBase, ProtectSize); +@@ -293,6 +313,10 @@ void SyscallHandler::ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length) + + const auto OverlapBase = std::max(VMA->Offset, OffsetBase); + const auto OverlapTop = std::min(VMA->Offset + VMA->Length, OffsetTop); ++ if (FEX::HLE::GuestHighMemory::Contains(MapBase + (OverlapBase - OffsetBase))) { ++ FEX::HLE::GuestHighMemory::MarkCode(MapBase + (OverlapBase - OffsetBase), OverlapTop - OverlapBase); ++ continue; ++ } + auto rv = mprotect((void*)(MapBase + (OverlapBase - OffsetBase)), OverlapTop - OverlapBase, PROT_READ); + LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", OverlapBase, OverlapTop - OverlapBase); + } +@@ -429,6 +453,11 @@ void* SyscallHandler::GuestMmap(bool Is64Bit, FEXCore::Core::InternalThreadState + return reinterpret_cast(Result); + } + LOGMAN_THROW_A_FMT(Is64Bit || (Result >> 32) == 0 || (Result >> 32) == 0xFFFFFFFF, "values must fit to 32 bits"); ++ } else if (FEX::HLE::GuestHighMemory::ClaimsMapping(reinterpret_cast(addr), length, flags)) { ++ Result = FEX::HLE::GuestHighMemory::Map(reinterpret_cast(addr), length, prot, flags, fd, offset); ++ if (FEX::HLE::HasSyscallError(Result)) { ++ return reinterpret_cast(Result); ++ } + } else { + Result = reinterpret_cast(::mmap(reinterpret_cast(addr), length, prot, flags, fd, offset)); + if (Result == ~0ULL) { +@@ -483,9 +512,16 @@ uint64_t SyscallHandler::GuestMunmap(bool Is64Bit, FEXCore::Core::InternalThread + if (Addr > X86_64TaskSizeMax || Size > X86_64TaskSizeMax - Addr || (length != 0 && Size == 0)) { + return -EINVAL; + } +- Result = ::munmap(addr, length); +- if (Result == -1) { +- return -errno; ++ if (FEX::HLE::GuestHighMemory::Contains(Addr)) { ++ Result = FEX::HLE::GuestHighMemory::Unmap(Addr, length); ++ if (FEX::HLE::HasSyscallError(Result)) { ++ return Result; ++ } ++ } else { ++ Result = ::munmap(addr, length); ++ if (Result == -1) { ++ return -errno; ++ } + } + if (reinterpret_cast(addr) < 0x1'0000'0000ULL) { + Get32BitAllocator()->TrackUnmapped(addr, length); +@@ -511,6 +547,10 @@ uint64_t SyscallHandler::GuestMremap(bool Is64Bit, FEXCore::Core::InternalThread + { + auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread); + if (Is64Bit) { ++ if (FEX::HLE::GuestHighMemory::Contains(reinterpret_cast(old_address)) || ++ ((flags & MREMAP_FIXED) && FEX::HLE::GuestHighMemory::Contains(reinterpret_cast(new_address)))) { ++ return -EINVAL; ++ } + Result = reinterpret_cast(::mremap(old_address, old_size, new_size, flags, new_address)); + if (Result == -1) { + return -errno; +@@ -602,9 +642,16 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa + } + } + +- Result = ::mprotect(addr, len, prot); +- if (Result == -1) { +- return -errno; ++ if (FEX::HLE::GuestHighMemory::Contains(reinterpret_cast(addr))) { ++ Result = FEX::HLE::GuestHighMemory::Protect(reinterpret_cast(addr), len, prot); ++ if (FEX::HLE::HasSyscallError(Result)) { ++ return Result; ++ } ++ } else { ++ Result = ::mprotect(addr, len, prot); ++ if (Result == -1) { ++ return -errno; ++ } + } + + TrackMprotect(Thread, addr, len, prot); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp +index 2e59f2f..ee28680 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp +@@ -1,6 +1,7 @@ + // SPDX-License-Identifier: MIT + + #include "LinuxSyscalls/ThreadManager.h" ++#include "LinuxSyscalls/GuestHighMemory.h" + #include "LinuxSyscalls/SamplingProfiler.h" + + #include "LinuxSyscalls/Syscalls.h" +@@ -330,6 +331,7 @@ void ThreadManager::HandleThreadDeletion(FEX::HLE::ThreadStateObject* Thread, bo + FEXCore::Allocator::munmap(Thread->ldt_entries, Thread->ldt_entry_count * FEX::HLE::SyscallHandler::LDT_ENTRY_SIZE); + } + ++ FEX::HLE::GuestHighMemory::ReleaseThread(Thread); + CTX->DestroyThread(Thread->Thread); + FEX::HLE::_SyscallHandler->SeccompEmulator.FreeSeccompFilters(Thread); + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +index 9c5f9f1..e43dfc7 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +@@ -104,6 +104,40 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { + bool Enabled; + } SyscallUserDispatch {}; + ++ struct { ++ uint8_t* Code; ++ uint64_t ResumePC; ++ uint64_t SavedScratch; ++ uint64_t BaseBefore; ++ uint64_t Delta; ++ uint64_t SavedMask; ++ uint32_t Scratch; ++ uint32_t Base; ++ bool Active; ++ bool Store; ++ bool Probe; ++ struct { ++ bool Held; ++ uint32_t Deferred; ++ siginfo_t DeferredInfo[3]; ++ } Mappings; ++ uint32_t Parts; ++ uint32_t BounceOffset; ++ struct { ++ uint64_t Guest; ++ uint64_t Host; ++ uint64_t Size; ++ } Pieces[2]; ++ alignas(16) uint8_t Bounce[96]; ++ struct { ++ uint64_t Host; ++ uint64_t Low; ++ uint64_t High; ++ uint32_t Size; ++ bool Valid; ++ } Monitor; ++ } HighMemoryTrap {}; ++ + uint64_t JITStackSP {}; + + struct TrapSignalFrame { +-- +2.43.0 + diff --git a/tools/fex/patches/0028-guest-cmdline-without-checkpoint-restore.patch b/tools/fex/patches/0028-guest-cmdline-without-checkpoint-restore.patch new file mode 100644 index 0000000000..899b071568 --- /dev/null +++ b/tools/fex/patches/0028-guest-cmdline-without-checkpoint-restore.patch @@ -0,0 +1,58 @@ +From 0510284085165d39ef0eabb83e7604fe1bb74c76 Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Thu, 3 Dec 2026 03:26:13 -0500 +Subject: [PATCH] Show the guest command line when the argument area cannot be + remapped + +Kernels built without checkpoint/restore support refuse PR_SET_MM_MAP, +so /proc/pid/cmdline kept showing the FEX invocation instead of the +guest program and the argv rewrites it makes. For 64-bit guests whose +arguments fit, the guest argument strings now live in the original +argument area and argv points there, which needs no privilege. +--- + Source/Tools/FEXInterpreter/ELFCodeLoader.h | 23 ++++++++++++++++++++- + 1 file changed, 22 insertions(+), 1 deletion(-) + +diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +index b1a72d227..6d2157365 100644 +--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h ++++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +@@ -874,13 +874,34 @@ public: + + int r = prctl(PR_SET_MM, PR_SET_MM_MAP, &map, sizeof(map), 0L); + if (r != 0) { +- LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (prctl failed: result {}, errno {})", r, errno); ++ int Error = errno; ++ if (Is64BitMode() && MoveArgumentDataToHostArea(NewArgStart, ArgSize)) { ++ return; ++ } ++ LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (prctl failed: result {}, errno {})", r, Error); + } + } else { + LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (GetCurrentMap failed)"); + } + } + ++ bool MoveArgumentDataToHostArea(uintptr_t GuestArgStart, uint64_t ArgSize) { ++ struct prctl_mm_map map {}; ++ if (!GetCurrentMap(map) || map.arg_end <= map.arg_start || ArgSize > map.arg_end - map.arg_start) { ++ return false; ++ } ++ ++ auto HostArgs = reinterpret_cast(map.arg_start); ++ memmove(HostArgs, reinterpret_cast(GuestArgStart), ArgSize); ++ memset(HostArgs + ArgSize, 0, map.arg_end - map.arg_start - ArgSize); ++ ++ auto ArgumentPointers = reinterpret_cast(StackPointer + sizeof(uint64_t)); ++ for (size_t i = 0; i < ApplicationArgs.size(); ++i) { ++ ArgumentPointers[i] = ArgumentPointers[i] - GuestArgStart + map.arg_start; ++ } ++ return true; ++ } ++ + // Setups the stack initial data (argv, envp, auxv) + void SetupStack() { + StackPointer += StackSize(); +-- +2.43.0 + diff --git a/tools/fex/patches/0029-proc-mount-tables-describe-the-container-procfs.patch b/tools/fex/patches/0029-proc-mount-tables-describe-the-container-procfs.patch new file mode 100644 index 0000000000..61cf5004df --- /dev/null +++ b/tools/fex/patches/0029-proc-mount-tables-describe-the-container-procfs.patch @@ -0,0 +1,310 @@ +From fc926d0e9c63a3d5290a5d816029513349de78f6 Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Thu, 3 Dec 2026 08:03:20 -0500 +Subject: [PATCH] Describe the container's procfs in emulated mount tables + +Android mounts /proc with hidepid=invisible,gid=3009 so an app cannot see the +processes of other users. Every process of the container runs as the app's +user, so the container sees all of its own processes, as it would through a +procfs of its own in a PID namespace. The emulated /proc//mounts and +mountinfo now list the proc mount without the host instance's access options +(hidepid, gid, subset). Every other mount is passed through unchanged. +--- + .../EmulatedFiles/EmulatedFiles.cpp | 230 +++++++++++++----- + .../EmulatedFiles/EmulatedFiles.h | 1 + + 2 files changed, 170 insertions(+), 61 deletions(-) + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +index 19bfc814f..85f1b3e15 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +@@ -37,6 +37,7 @@ $end_info$ + #include + #include + #include ++#include + #include + #include + #include +@@ -649,6 +650,149 @@ static bool IsHostArchModule(const char* Path, fextl::unordered_map 0) { ++ Out.append(Buf, Len); ++ } else if (Len == 0) { ++ break; ++ } else if (errno != EINTR) { ++ LogMan::Msg::EFmt("Emulated /proc file: reading {} failed: {}", Path, errno); ++ ::close(HostFD); ++ return false; ++ } ++ } ++ ::close(HostFD); ++ return true; ++} ++ ++static int32_t SealedFileOf(const char* pathname, int32_t flags, const fextl::string& Data) { ++ int NewFD = GenTmpFD(pathname, flags); ++ if (NewFD < 0) { ++ LogMan::Msg::EFmt("Emulated /proc file: memfd_create failed: {}", errno); ++ return -1; ++ } ++ for (size_t Done = 0; Done < Data.size();) { ++ const ssize_t Wrote = ::write(NewFD, Data.data() + Done, Data.size() - Done); ++ if (Wrote > 0) { ++ Done += Wrote; ++ } else if (Wrote < 0 && errno == EINTR) { ++ continue; ++ } else { ++ LogMan::Msg::EFmt("Emulated /proc file: writing the synthesized file failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ } ++ if (::lseek(NewFD, 0, SEEK_SET) != 0) { ++ LogMan::Msg::EFmt("Emulated /proc file: lseek failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ SealTmpFD(NewFD); ++ return NewFD; ++} ++ ++static const char* ProcFileOfPid(const char* Path) { ++ if (strncmp(Path, "/proc/", 6) != 0) { ++ return nullptr; ++ } ++ const char* P = Path + 6; ++ if (strncmp(P, "self/", 5) == 0) { ++ return P + 5; ++ } ++ if (strncmp(P, "thread-self/", 12) == 0) { ++ return P + 12; ++ } ++ if (!isdigit(*P)) { ++ return P; ++ } ++ while (isdigit(*P)) { ++ ++P; ++ } ++ if (*P++ != '/') { ++ return nullptr; ++ } ++ if (strncmp(P, "task/", 5) == 0) { ++ P += 5; ++ if (!isdigit(*P)) { ++ return nullptr; ++ } ++ while (isdigit(*P)) { ++ ++P; ++ } ++ if (*P++ != '/') { ++ return nullptr; ++ } ++ } ++ return P; ++} ++ ++static bool IsProcMountTablePath(const char* Path) { ++ const char* File = ProcFileOfPid(Path); ++ return File && (strcmp(File, "mounts") == 0 || strcmp(File, "mountinfo") == 0); ++} ++ ++static fextl::string ContainerProcOptions(std::string_view Options) { ++ fextl::string Out; ++ size_t Pos = 0; ++ while (Pos <= Options.size()) { ++ size_t Comma = Options.find(',', Pos); ++ if (Comma == std::string_view::npos) { ++ Comma = Options.size(); ++ } ++ const std::string_view Option = Options.substr(Pos, Comma - Pos); ++ if (!Option.empty() && !Option.starts_with("hidepid=") && !Option.starts_with("gid=") && !Option.starts_with("subset=")) { ++ if (!Out.empty()) { ++ Out += ','; ++ } ++ Out.append(Option); ++ } ++ Pos = Comma + 1; ++ } ++ return Out; ++} ++ ++static fextl::string ContainerMountLine(std::string_view Line, bool MountInfo) { ++ fextl::vector Fields; ++ size_t Pos = 0; ++ while (Pos < Line.size()) { ++ size_t Space = Line.find(' ', Pos); ++ if (Space == std::string_view::npos) { ++ Space = Line.size(); ++ } ++ Fields.push_back(Line.substr(Pos, Space - Pos)); ++ Pos = Space + 1; ++ } ++ size_t Type = 2; ++ if (MountInfo) { ++ auto Dash = std::find(Fields.begin(), Fields.end(), std::string_view("-")); ++ Type = static_cast(Dash - Fields.begin()) + 1; ++ } ++ const size_t Options = MountInfo ? Type + 2 : Type + 1; ++ if (Options >= Fields.size() || Fields[Type] != "proc") { ++ return fextl::string(Line); ++ } ++ fextl::string Out; ++ for (size_t i = 0; i < Fields.size(); ++i) { ++ if (i) { ++ Out += ' '; ++ } ++ if (i == Options) { ++ Out += ContainerProcOptions(Fields[i]); ++ } else { ++ Out.append(Fields[i]); ++ } ++ } ++ return Out; ++} ++ + static bool IsProcMapsPath(const char* Path) { + if (strncmp(Path, "/proc/", 6) != 0) { + return false; +@@ -673,6 +817,9 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode) + if (pathname && IsProcMapsPath(pathname)) { + return ProcMaps(CTX, AT_FDCWD, pathname, flags, mode); + } ++ if (pathname && IsProcMountTablePath(pathname)) { ++ return ProcMounts(CTX, AT_FDCWD, pathname, flags, mode); ++ } + return -1; + } + +@@ -680,25 +827,10 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t 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; +- } ++ if (!ReadHostFile(pathname, In)) { ++ return -1; + } +- ::close(HostFD); + + constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096; + const bool HostSharesGuestRange = FEXCore::Allocator::GetHostVABits() < 47; +@@ -756,30 +888,29 @@ int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, + Pos = End; + } + +- int NewFD = GenTmpFD(pathname, flags); +- if (NewFD < 0) { +- LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno); ++ return SealedFileOf(pathname, flags, Out); ++} ++ ++int32_t EmulatedFDManager::ProcMounts(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { ++ fextl::string In; ++ if (!ReadHostFile(pathname, In)) { + 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; ++ const char* File = ProcFileOfPid(pathname); ++ const bool MountInfo = File && strcmp(File, "mountinfo") == 0; ++ 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 LineEnd = Eol == fextl::string::npos ? In.size() : Eol; ++ Out += ContainerMountLine(std::string_view(In).substr(Pos, LineEnd - Pos), MountInfo); ++ if (Eol != fextl::string::npos) { ++ Out += '\n'; + } ++ Pos = LineEnd + 1; + } +- if (::lseek(NewFD, 0, SEEK_SET) != 0) { +- LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno); +- ::close(NewFD); +- return -1; +- } +- SealTmpFD(NewFD); +- return NewFD; ++ return SealedFileOf(pathname, flags, Out); + } + + int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { +@@ -832,30 +963,7 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd + 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; ++ return SealedFileOf(pathname, flags, Out); + } + + int32_t EmulatedFDManager::ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h +index b98ef4bda..b1ec241a7 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h +@@ -35,6 +35,7 @@ private: + + 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 ProcMounts(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; + }; diff --git a/tools/fex/probes/guest-high-memory.c b/tools/fex/probes/guest-high-memory.c new file mode 100644 index 0000000000..fa4450183a --- /dev/null +++ b/tools/fex/probes/guest-high-memory.c @@ -0,0 +1,92 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include + +#define HIGH ((uintptr_t)0x7e0000000000ULL) +#define ALIAS ((uintptr_t)0x7e0000100000ULL) +#define THREADS 4 +#define ITERS 200000 + +static volatile uint64_t *counter; +static volatile uint64_t *cas; +static int fails; + +static void check(const char *name, int ok) { + printf("%s %s\n", ok ? "PASS" : "FAIL", name); + if (!ok) fails++; +} + +static void *worker(void *arg) { + (void)arg; + for (int i = 0; i < ITERS; i++) { + __atomic_fetch_add(counter, 1, __ATOMIC_SEQ_CST); + uint64_t old = __atomic_load_n(cas, __ATOMIC_RELAXED); + while (!__atomic_compare_exchange_n(cas, &old, old + 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) { + } + } + return NULL; +} + +int main(void) { + alarm(60); + uint8_t *high = mmap((void *)HIGH, 65536, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); + if (high == MAP_FAILED) { + printf("NOTCLAIMED errno=%d\n", errno); + return 0; + } + check("fixed-high-map", high == (uint8_t *)HIGH); + memset(high, 0x5a, 65536); + check("load-store", high[100] == 0x5a && high[65535] == 0x5a); + + counter = (uint64_t *)(high + 64); + cas = (uint64_t *)(high + 128); + *counter = 0; + *cas = 0; + pthread_t t[THREADS]; + for (int i = 0; i < THREADS; i++) pthread_create(&t[i], NULL, worker, NULL); + for (int i = 0; i < THREADS; i++) pthread_join(t[i], NULL); + check("atomic-add", *counter == (uint64_t)THREADS * ITERS); + check("atomic-cmpxchg", *cas == (uint64_t)THREADS * ITERS); + + int p[2]; + check("pipe", pipe(p) == 0); + memcpy(high + 4096, "hello ", 6); + memcpy(high + 8192, "world", 5); + struct iovec out[2] = {{high + 4096, 6}, {high + 8192, 5}}; + ssize_t w = writev(p[1], out, 2); + memset(high + 12288, 0, 64); + struct iovec in[2] = {{high + 12288, 3}, {high + 12291, 8}}; + ssize_t r = w == 11 ? readv(p[0], in, 2) : -1; + check("writev-readv", w == 11 && r == 11 && memcmp(high + 12288, "hello world", 11) == 0); + + int wrote = write(p[1], "abcdef", 6) == 6; + check("write", wrote); + check("read", wrote && read(p[0], high + 20000, 6) == 6 && memcmp(high + 20000, "abcdef", 6) == 0); + + high[30000] = 7; + check("madvise-dontneed", madvise(high + 28672, 4096, MADV_DONTNEED) == 0 && high[30000] == 0); + + int fd = memfd_create("code", 0); + check("memfd", fd >= 0 && ftruncate(fd, 4096) == 0); + static const uint8_t code[] = {0xb8, 0x01, 0x00, 0x00, 0x00, 0xc3}; + check("pwrite", pwrite(fd, code, sizeof code, 0) == (ssize_t)sizeof code); + uint8_t *low = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0); + uint8_t *alias = mmap((void *)ALIAS, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0); + check("alias-map", low != MAP_FAILED && alias == (uint8_t *)ALIAS); + int (*fn)(void) = (int (*)(void))low; + int before = fn(); + alias[1] = 2; + __atomic_thread_fence(__ATOMIC_SEQ_CST); + int after = fn(); + printf("alias before=%d after=%d\n", before, after); + check("smc-through-high-alias", before == 1 && after == 2); + + printf("%s\n", fails ? "RESULT FAIL" : "RESULT PASS"); + return fails != 0; +} diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex index 0b432bb5d3..6160d52bb0 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex @@ -664,7 +664,7 @@ def data_dir(env): return DATA_DIR -def guest_environment(fex, env): +def guest_environment(fex, env, keep_compat=False): result = dict(env) data = data_dir(env) for directory in (CONFIG_DIR, data, CACHE_DIR): @@ -672,7 +672,7 @@ def guest_environment(fex, env): result["FEX_APP_CONFIG_LOCATION"] = CONFIG_DIR + "/" result["FEX_APP_DATA_LOCATION"] = data + "/" result["FEX_APP_CACHE_LOCATION"] = CACHE_DIR + "/" - if result.get("STEAM_COMPAT_DATA_PATH"): + if result.get("STEAM_COMPAT_DATA_PATH") and not keep_compat: short = data if data != DATA_DIR else "/tmp/fex" os.makedirs(short, exist_ok=True) result["STEAM_COMPAT_DATA_PATH"] = short @@ -750,9 +750,12 @@ def vulkan_thunk_loads(fex, folder): def required_runtime(program): - text = read_text(os.path.join(os.path.dirname(program), "toolmanifest.vdf")) or "" - match = re.search(r'"require_tool_appid"\s+"(\d+)"', text) - return match.group(1) if match and match.group(1) in RUNTIMES else SNIPER_APPID + folder = os.path.dirname(program) + for name in ("toolmanifest.vdf.droiddeck-orig", "toolmanifest.vdf"): + match = re.search(r'"require_tool_appid"\s+"(\d+)"', read_text(os.path.join(folder, name)) or "") + if match and match.group(1) in RUNTIMES: + return match.group(1) + return SNIPER_APPID def resolve(program, env): @@ -761,7 +764,7 @@ def resolve(program, env): return shutil.which(program, path=env.get("PATH")) or program -def launch(command, env, mode, decide=None): +def launch(command, env, mode, decide=None, keep_compat=False): program = resolve(command[0], env) use = mode == "on" or (mode == "auto" and needs_fex(decide or program)) if not use: @@ -769,7 +772,7 @@ def launch(command, env, mode, decide=None): fex = prepare(required_runtime(program)) if fex is None: return 126 - guest = guest_environment(fex, env) + guest = guest_environment(fex, env, keep_compat) x86_64 = elf_arch(program) != "i386" thunks = "on" if "FEX_THUNKCONFIG" in guest else "off" folder = decide if decide and os.path.isdir(decide) else os.path.dirname(program) @@ -963,7 +966,7 @@ def parse_run(args): def main(argv): if not argv: - say("usage: droiddeck-fex steam VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | status") + say("usage: droiddeck-fex steam VERB CMD... | proton PROTON VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | update | status") return 2 action, args = argv[0], list(argv[1:]) if action == "steam": @@ -975,6 +978,10 @@ def main(argv): if not command: return 2 return launch(command, game_environment(dict(os.environ), command), os.environ.get("DROIDDECK_FEX", "auto")) + if action == "proton": + if len(args) < 2: + return 2 + return launch(args, game_environment(dict(os.environ), args[2:] or args), "on", keep_compat=True) if action == "run": try: mode, decide, command = parse_run(args) @@ -996,6 +1003,10 @@ def main(argv): return extract(args[0]) if action == "prepare": return 0 if prepare() else 1 + if action == "update": + with locked(): + update_own_fex() + return 0 if action == "status": with locked(): status = describe(fex_install(), runtime_platform(), graphics_platform()) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update index 25f445adee..f25d2a3394 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update @@ -29,10 +29,14 @@ fex_install() { return 1 fi (cd "$tmp/root" && find . ! -type d) > "$tmp/files" - for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do - [ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue - (cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done - done > "$tmp/stale" + { + for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do + [ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue + (cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done + done + f=usr/local/share/fex-emu/.droiddeck-patches + if [ -e "$dst$f" ] && ! grep -qxF "./$f" "$tmp/files"; then echo "$f"; fi + } > "$tmp/stale" mkdir "$tmp/old" while IFS= read -r f; do f=${f#./} diff --git a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility index 4eb7ba26f7..c3c10c8638 100755 --- a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility +++ b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility @@ -318,12 +318,72 @@ dd_vacdiag() { } """ +DD_ANTICHEAT_SETUP = """ +dd_anticheat_runtime() { + local current=$1 name=$2 bridge=$3 library + if [ -n "$current" ] && [ -n "$(find -L "$current" -iname "$bridge" -print -quit 2>/dev/null)" ]; then + printf '%s' "$current"; return 0 + fi + while IFS= read -r library; do + [ -n "$(find "$library/steamapps/common/$name" -iname "$bridge" -print -quit 2>/dev/null)" ] || continue + printf '%s' "$library/steamapps/common/$name"; return 0 + done < <(printf '%s\\n' "$DD_AC_ROOT" /mnt/droiddeck-sd; sed -n 's/^[[:space:]]*"path"[[:space:]]*"\\(.*\\)"[[:space:]]*$/\\1/p' "$DD_AC_ROOT/steamapps/libraryfolders.vdf" 2>/dev/null) + return 1 +} + +dd_x86_64_proton() { + [ -d "$1/files/lib/wine/x86_64-unix" ] && [ ! -d "$1/files/bin-arm64" ] +} + +dd_anticheat() { + case ${verb:-} in waitforexitandrun | run) ;; *) return 0 ;; esac + case ${DROIDDECK_ANTICHEAT:-auto} in off | 0 | false) return 0 ;; esac + local game=${STEAM_COMPAT_INSTALL_PATH:-} found tool runtime + [ -d "$game" ] || return 0 + found=$(find "$game" -maxdepth 3 \\( -ipath '*/easyanticheat/settings.json' -o -iname 'easyanticheat_x64.so' \\ + -o -iname 'beclient_x64.so' -o -iname 'beservice_x64.exe' \\) -print -quit 2>/dev/null) + [ -n "$found" ] || return 0 + case ${DD_AC_TOOL:-DroidDeck-Proton} in + DroidDeck-Proton*) ;; + *) + echo "droiddeck-proton: anti-cheat files in ${found#$game/}; ${DD_AC_TOOL} was chosen for this game, so it runs as chosen" >&2 + return 0 + ;; + esac + /usr/local/bin/droiddeck-fex update || true + if ! grep -qx fixed-guest-memory-above-host-address-limit /usr/local/share/fex-emu/.droiddeck-patches 2>/dev/null; then + echo "droiddeck-proton: anti-cheat files in ${found#$game/}; the installed FEX build cannot run anti-cheat, so this launch stays on ARM64" >&2 + return 0 + fi + DD_AC_ROOT=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam} + tool=$(cd "$DD_AC_ROOT/compatibilitytools.d" 2>/dev/null && for d in DroidDeck-Proton*; do + [ -x "$d/proton" ] && dd_x86_64_proton "$d" && printf '%s/%s\\n' "$PWD" "$d" + done | sort -V | tail -n 1) + if [ -z "$tool" ]; then + echo "droiddeck-proton: anti-cheat files in ${found#$game/}; no x86-64 DroidDeck-Proton is installed, so this launch stays on ARM64" >&2 + return 0 + fi + case ${found,,} in + *easyanticheat*) runtime=$(dd_anticheat_runtime "${PROTON_EAC_RUNTIME:-}" "Proton EasyAntiCheat Runtime" easyanticheat_x64.so) && export PROTON_EAC_RUNTIME="$runtime" ;; + *) runtime=$(dd_anticheat_runtime "${PROTON_BATTLEYE_RUNTIME:-}" "Proton BattlEye Runtime" beclient_x64.so) && export PROTON_BATTLEYE_RUNTIME="$runtime" ;; + esac + if [ -z "$runtime" ]; then + echo "droiddeck-proton: anti-cheat files in ${found#$game/}; its Proton runtime is not installed, so this launch stays on ARM64" >&2 + return 0 + fi + dd_game_cpus + declare -F dd_components >/dev/null && dd_components "$tool" + echo "droiddeck-proton: anti-cheat files in ${found#$game/}; running ${tool##*/} under FEX" >&2 + exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$tool/proton" "$verb" "$@" +} +""" + # DroidDeck-Bionic runs only without proot. With proot on, a launch Steam sends to a DroidDeck-Bionic tool goes to the # newest DroidDeck-Proton's wrapper before anything else runs, as if that Proton had been picked; the picks stay as set. DD_BIONIC_PROOT_FALLBACK = """ if [ -f "$here/bionic/launch.sh" ] && [ -z "${DDNATV_ROOT:-}" ]; then dd_fallback=$(cd "$here/.." 2>/dev/null && for d in DroidDeck-Proton*; do - [ -x "$d/droiddeck-proton-wrap" ] && [ ! -e "$d/bionic/launch.sh" ] || continue + [ -x "$d/droiddeck-proton-wrap" ] && [ ! -e "$d/bionic/launch.sh" ] && ! dd_x86_64_proton "$d" || continue v=${d#DroidDeck-Proton}; printf '%s\\t%s/%s\\n' "${v#[ -]}" "$PWD" "$d" done | sort -V | tail -n 1 | cut -f 2-) if [ -n "$dd_fallback" ]; then @@ -461,6 +521,7 @@ for name in %s; do [ -n "$depot" ] && break done if [ -n "$depot" ]; then + dd_anticheat "$@" dd_components "$depot" dd_directaudio "$depot" "$@" dd_game_cpus @@ -481,7 +542,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH def launcher_sh(sources=SOURCES): return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace( "verb=$1; shift", "verb=$1; shift\n" + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + DD_IDTECH3_SETUP - + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1) + + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP + DD_ANTICHEAT_SETUP, 1) LAUNCHER_SH = launcher_sh() @@ -516,6 +577,11 @@ if [ -n "${PROOT_FP_KEY:-}" ] && [ -f "$audit" ]; then *) LD_AUDIT="$audit${LD_AUDIT:+:$LD_AUDIT}"; export LD_AUDIT ;; esac fi +if dd_x86_64_proton "$here"; then + dd_game_cpus + exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$here/%s" "$verb" "$@" +fi +DD_AC_TOOL=$(basename "$(cd "$here" && pwd -P)") dd_anticheat "$@" dd_components "$here" dd_directaudio "$here" "$@" dd_game_cpus @@ -530,9 +596,9 @@ dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env "$DD_STORE_PROTON" "$ve def extra_wrapper_sh(entry_point): - return (EXTRA_WRAPPER_SH % entry_point).replace( + return (EXTRA_WRAPPER_SH % (entry_point, entry_point)).replace( 'here=$(dirname "$0")', - 'here=$(dirname "$0")\n' + DD_BIONIC_PROOT_FALLBACK + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + 'here=$(dirname "$0")\n' + DD_ANTICHEAT_SETUP + DD_BIONIC_PROOT_FALLBACK + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + DD_IDTECH3_SETUP + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1) @@ -1332,10 +1398,18 @@ def tool_catalog(steam_root, extras=None): continue extras[first_key(os.path.join(tool_dir, "compatibilitytool.vdf"), ["compatibilitytools", "compat_tools"]) or entry] = entry for name, entry in sorted(extras.items()): - catalog.append(tool_entry(name, display_name(entry), os.path.join(tools, entry), False)) + tool = tool_entry(name, display_name(entry), os.path.join(tools, entry), False) + if x86_64_layout(os.path.join(tools, entry)): + tool["x86_64"] = True + catalog.append(tool) return catalog +def x86_64_layout(path): + return (os.path.isdir(os.path.join(path, "files", "lib", "wine", "x86_64-unix")) and + not os.path.isdir(os.path.join(path, "files", "bin-arm64"))) + + def built_from(name, catalog, runnable=None): depot = VALVE_DEPOTS.get(name) tools = [t["name"] for t in catalog if depot and t["valve"] and t["dir"] == depot and @@ -1474,7 +1548,7 @@ ARCH_WORDS = re.compile(r"(?i)aarch64|arm64|x86_64|x86-64|amd64") def own_builds(tools): return [t for t in tools if isinstance(t, dict) and not t.get("valve") and - isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name")] + isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name") and not t.get("x86_64")] def build_key(name): @@ -1512,7 +1586,8 @@ def choose_default(steam_default, state, request, catalog, adopt_steam=True, app wanted = requested_tool(request, catalog) state["applied"] = seq if wanted: - if wanted != state.get("default"): + if wanted != state.get("default") or (state.get("source") not in ("app", "steam") and any( + t["name"] == wanted and t.get("x86_64") for t in catalog)): state.update(default=wanted, seq=now or now_ms(), source="app") else: print("steam-compatibility: the app asked for %s, which is not installed; kept %s" % ( @@ -1709,7 +1784,11 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non read_json(state_path("request.json", directory)), catalog) else: default = state.get("default") if state.get("default") in names else TOOL - if settle and newest and default == TOOL and state.get("source") not in ("app", "steam"): + automatic = state.get("source") not in ("app", "steam") + if settle and automatic and default in {t["name"] for t in catalog if t.get("x86_64")}: + default = newest or TOOL + state.update(default=default, seq=now_ms(), source="update") + elif settle and newest and default == TOOL and automatic: default = newest state.update(default=newest, seq=now_ms(), source="update") state.pop("own_proton", None) diff --git a/tools/linuxfs/preload/vdec.c b/tools/linuxfs/preload/vdec.c index 3bd38f3bc9..89e62129cf 100644 --- a/tools/linuxfs/preload/vdec.c +++ b/tools/linuxfs/preload/vdec.c @@ -957,8 +957,9 @@ __attribute__((visibility("hidden"))) void dd_vdec_closed(int fd) { __attribute__((visibility("hidden"))) int dd_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms, int (*real)(struct pollfd *, nfds_t, int), int *ret) { - if (n != 1 || vd_find(fds[0].fd) == NULL) return 0; + if (n != 1 || __atomic_load_n(&vd_open_count, __ATOMIC_ACQUIRE) == 0) return 0; struct vdec *v = vd_find(fds[0].fd); + if (v == NULL) return 0; pthread_mutex_lock(&vd_lock); short ready = (v->n_cap_done ? POLLIN | POLLRDNORM : 0) | (v->n_out_done ? POLLOUT | POLLWRNORM : 0); pthread_mutex_unlock(&vd_lock); diff --git a/tools/linuxfs/preload/zram.c b/tools/linuxfs/preload/zram.c index 6bed8315c0..c2c35b8f6a 100644 --- a/tools/linuxfs/preload/zram.c +++ b/tools/linuxfs/preload/zram.c @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -20,6 +21,9 @@ #include +#ifndef PR_SET_SYSCALL_USER_DISPATCH +#define PR_SET_SYSCALL_USER_DISPATCH 59 +#endif #ifndef MADV_PAGEOUT #define MADV_PAGEOUT 21 #endif @@ -929,13 +933,40 @@ static int zr_start(void) { return 0; } +static __thread volatile unsigned char *zr_dispatch __attribute__((tls_model("initial-exec"))); + +int prctl(int option, ...) { + va_list ap; + va_start(ap, option); + unsigned long arg2 = va_arg(ap, unsigned long); + unsigned long arg3 = va_arg(ap, unsigned long); + unsigned long arg4 = va_arg(ap, unsigned long); + unsigned long arg5 = va_arg(ap, unsigned long); + va_end(ap); + volatile unsigned char *dispatch = zr_dispatch; + unsigned char selector = dispatch != NULL ? *dispatch : 0; + if (selector) *dispatch = 0; + long result = zr_sys(SYS_prctl, option, arg2, arg3, arg4, arg5); + if (selector) *dispatch = selector; + if ((unsigned long)result > -4096UL) { + errno = (int)-result; + return -1; + } + if (option == PR_SET_SYSCALL_USER_DISPATCH) zr_dispatch = arg2 ? (volatile unsigned char *)arg5 : NULL; + return (int)result; +} + static void zr_handler(int sig, siginfo_t *info, void *context) { (void)sig; (void)context; if (info == NULL || info->si_code != SI_USER) return; + volatile unsigned char *dispatch = zr_dispatch; + unsigned char selector = dispatch != NULL ? *dispatch : 0; + if (selector) *dispatch = 0; int saved = errno; if (__atomic_fetch_add(&zr_requests, 1, __ATOMIC_ACQ_REL) == 0 && !zr_start()) zr_drain(0); errno = saved; + if (selector) *dispatch = selector; } static void zr_child(void) { diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index db55262540..ede8c4354d 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -374,6 +374,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e errno = ENOSYS; return -1; } + if (is_proc_self_exe(filename) && g_real_exe[0] != '\0') filename = g_real_exe; if (depth == 0 && !in_exec_rehearsal()) ddh_try(filename, argv, envp); // Scripts get the path exactly as the caller wrote it ("./x.sh" stays "./x.sh" in $0), diff --git a/tools/nativeguest/hook/fileops.c b/tools/nativeguest/hook/fileops.c index a515e6a248..81a10b89e5 100644 --- a/tools/nativeguest/hook/fileops.c +++ b/tools/nativeguest/hook/fileops.c @@ -422,6 +422,7 @@ static ssize_t copy_readlink_result(char *buf, size_t bufsiz, const char *out, s if (ret <= 0 || out == buf) return ret; size_t n = (size_t)ret < bufsiz ? (size_t)ret : bufsiz; memcpy(buf, out, n); + if (n < bufsiz) buf[n] = '\0'; return (ssize_t)n; } @@ -454,6 +455,7 @@ ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) { ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) { static ssize_t (*orig_readlinkat)(int, const char *, char *, size_t) = NULL; if (!orig_readlinkat) orig_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat"); + const char *given = pathname; DDNATV_AT_REMAP(dirfd, pathname); // after the remap: "proc/self/exe" relative to a descriptor for "/" is /proc/self/exe as well { @@ -478,7 +480,7 @@ ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) { const char *retry = usrmerge_retry_path(target, alt, sizeof(alt)); if (retry) ret = orig_readlinkat(dirfd, retry, out, outsiz); } - return copy_readlink_result(buf, bufsiz, out, postprocess_readlink(pathname, out, ret, outsiz)); + return copy_readlink_result(buf, bufsiz, out, postprocess_named_readlink(pathname, pathname == given ? pathname : NULL, out, ret, outsiz)); } // Fortified readlink variants used by dpkg / update-alternatives @@ -776,7 +778,7 @@ char *realpath(const char *path, char *resolved_path) { char pbuf[PATH_MAX]; const char *target = rewrite_path(path, pbuf, sizeof(pbuf)); char *res = orig_realpath ? orig_realpath(target, resolved_path) : NULL; - if (res && g_ddnatv_root[0] != '\0') { + if (res && g_ddnatv_root[0] != '\0' && !is_rootfs_real_path(path)) { size_t rlen = g_ddnatv_root_len; if (strncmp(res, g_ddnatv_root, rlen) == 0 && (res[rlen] == '/' || res[rlen] == '\0')) { size_t rem_len = strlen(res + rlen); diff --git a/tools/nativeguest/hook/files.c b/tools/nativeguest/hook/files.c index 318adb79ef..7ea658d006 100644 --- a/tools/nativeguest/hook/files.c +++ b/tools/nativeguest/hook/files.c @@ -197,6 +197,116 @@ static int open_proc_status_at(int dirfd, const char *name, int flags) { return open_proc_status(dir, flags); } +static long call_orig_syscall(long number, unsigned long a1, unsigned long a2, unsigned long a3, unsigned long a4, unsigned long a5, unsigned long a6); + +#ifndef F_SEAL_EXEC +#define F_SEAL_EXEC 0x0020 +#endif +#ifndef MFD_EXEC +#define MFD_EXEC 0x0010U +#endif + +static int own_fd_of_path(const char *path) { + if (!path) return -1; + const char *p; + if (strncmp(path, "/dev/fd/", 8) == 0) { + p = path + 8; + } else { + if (!is_proc_fd_link(path)) return -1; + const char *who = path + 6; + if (*who >= '0' && *who <= '9') { + long pid = 0; + while (*who >= '0' && *who <= '9') pid = pid * 10 + (*who++ - '0'); + if (pid != (long)call_orig_syscall(SYS_getpid, 0, 0, 0, 0, 0, 0)) { + char task[48]; + snprintf(task, sizeof(task), "/proc/self/task/%ld", pid); + if (call_orig_syscall(SYS_faccessat, (unsigned long)AT_FDCWD, (unsigned long)task, F_OK, 0, 0, 0) != 0) return -1; + } + } + p = strstr(path + 6, "/fd/") + 4; + } + if (*p < '0' || *p > '9') return -1; + long fd = 0; + while (*p >= '0' && *p <= '9') { + fd = fd * 10 + (*p++ - '0'); + if (fd > INT_MAX) return -1; + } + return *p == '\0' ? (int)fd : -1; +} + +static int copy_memfd_contents(int from, int to, off_t size) { + char chunk[32768]; + off_t at = 0; + while (at < size) { + size_t want = (size_t)(size - at) < sizeof(chunk) ? (size_t)(size - at) : sizeof(chunk); + long got = call_orig_syscall(SYS_pread64, (unsigned long)from, (unsigned long)chunk, want, (unsigned long)at, 0, 0); + if (got < 0 && errno == EINTR) continue; + if (got <= 0) return -1; + long done = 0; + while (done < got) { + long put = call_orig_syscall(SYS_write, (unsigned long)to, (unsigned long)(chunk + done), (unsigned long)(got - done), 0, 0, 0); + if (put < 0 && errno == EINTR) continue; + if (put <= 0) return -1; + done += put; + } + at += got; + } + return 0; +} + +static int copy_of_memfd(int src, int flags) { + char link[48], target[PATH_MAX]; + snprintf(link, sizeof(link), "/proc/thread-self/fd/%d", src); + long n = call_orig_syscall(SYS_readlinkat, (unsigned long)AT_FDCWD, (unsigned long)link, (unsigned long)target, sizeof(target) - 1, 0, 0); + if (n <= 7 || strncmp(target, "/memfd:", 7) != 0) return -1; + target[n] = '\0'; + char *name = target + 7; + size_t name_len = (size_t)n - 7; + if (name_len >= 10 && strcmp(name + name_len - 10, " (deleted)") == 0) name[name_len -= 10] = '\0'; + if (name_len > 249) name[249] = '\0'; + struct stat st; + if (call_orig_syscall(SYS_fstat, (unsigned long)src, (unsigned long)&st, 0, 0, 0, 0) != 0 || !S_ISREG(st.st_mode)) return -1; + long seals = call_orig_syscall(SYS_fcntl, (unsigned long)src, F_GET_SEALS, 0, 0, 0, 0); + if (seals < 0) return -1; + unsigned long mfd_flags = MFD_ALLOW_SEALING | ((flags & O_CLOEXEC) ? MFD_CLOEXEC : 0); + long copy = -1; + if (st.st_mode & 0111) copy = call_orig_syscall(SYS_memfd_create, (unsigned long)name, mfd_flags | MFD_EXEC, 0, 0, 0, 0); + if (copy < 0) copy = call_orig_syscall(SYS_memfd_create, (unsigned long)name, mfd_flags, 0, 0, 0, 0); + if (copy < 0) return -1; + int ok = copy_memfd_contents(src, (int)copy, st.st_size) == 0 && + call_orig_syscall(SYS_lseek, (unsigned long)copy, 0, SEEK_SET, 0, 0, 0) == 0 && + call_orig_syscall(SYS_fchmod, (unsigned long)copy, st.st_mode & 07777, 0, 0, 0, 0) == 0 && + call_orig_syscall(SYS_fcntl, (unsigned long)copy, F_ADD_SEALS, (unsigned long)(seals | F_SEAL_WRITE | F_SEAL_GROW | F_SEAL_SHRINK), 0, 0, 0) == 0; + if (!ok) { + call_orig_syscall(SYS_close, (unsigned long)copy, 0, 0, 0, 0, 0); + return -1; + } + return (int)copy; +} + +static int reopen_denied_memfd(const char *path, int flags) { + if ((flags & O_ACCMODE) != O_RDONLY || (flags & (O_CREAT | O_TRUNC | O_DIRECTORY | O_PATH))) return -1; + int named = own_fd_of_path(path); + if (named < 0) return -1; + long src = call_orig_syscall(SYS_fcntl, (unsigned long)named, F_DUPFD_CLOEXEC, 0, 0, 0, 0); + if (src < 0) return -1; + struct stat by_path, by_fd; + int same = call_orig_syscall(SYS_newfstatat, (unsigned long)AT_FDCWD, (unsigned long)path, (unsigned long)&by_path, 0, 0, 0) == 0 && + call_orig_syscall(SYS_fstat, (unsigned long)src, (unsigned long)&by_fd, 0, 0, 0, 0) == 0 && + by_path.st_dev == by_fd.st_dev && by_path.st_ino == by_fd.st_ino; + int copy = same ? copy_of_memfd((int)src, flags) : -1; + call_orig_syscall(SYS_close, (unsigned long)src, 0, 0, 0, 0, 0); + return copy; +} + +static int open_or_reopen_memfd(int fd, const char *path, int flags) { + if (fd >= 0 || errno != EACCES) return fd; + int copy = reopen_denied_memfd(path, flags); + if (copy >= 0) return copy; + errno = EACCES; + return -1; +} + // Hook open int open(const char *pathname, int flags, ...) { static int (*orig_open)(const char *, int, ...) = NULL; @@ -225,7 +335,7 @@ int open(const char *pathname, int flags, ...) { forget_proc_root_fd(fd); return fd; } - int fd = orig_open(target, flags); + int fd = open_or_reopen_memfd(orig_open(target, flags), pathname, flags); remember_proc_root_fd(fd, pathname); return fd; } @@ -259,7 +369,7 @@ int openat(int dirfd, const char *pathname, int flags, ...) { forget_proc_root_fd(fd); return fd; } - int fd = orig_openat(dirfd, target, flags); + int fd = open_or_reopen_memfd(orig_openat(dirfd, target, flags), (pathname && pathname[0] == '/') ? pathname : NULL, flags); remember_proc_root_fd(fd, pathname); return fd; } @@ -304,6 +414,11 @@ static long call_orig_syscall(long number, unsigned long a1, unsigned long a2, u return orig_syscall ? orig_syscall(number, a1, a2, a3, a4, a5, a6) : syscall(number, a1, a2, a3, a4, a5, a6); } +static int openat2_or_reopen_memfd(int fd, const char *pathname, const struct ddnatv_open_how *how) { + if (fd >= 0 || errno != EACCES || pathname[0] != '/' || !how || how->resolve) return fd; + return open_or_reopen_memfd(fd, pathname, (int)how->flags); +} + // Hook openat2 (used by GNU tar 1.35+/gnulib for RESOLVE_BENEATH traversal). // Rewrites absolute paths like openat, then delegates; on ENOSYS (kernels // without openat2, e.g. Android < 5.6) emulates with plain openat instead of @@ -334,12 +449,12 @@ int openat2(int dirfd, const char *pathname, struct ddnatv_open_how *how, size_t const char *target = (pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname; if (orig_openat2) { int ret = orig_openat2(dirfd, target, how, usize); - if (ret >= 0 || errno != ENOSYS) return ret; + if (ret >= 0 || errno != ENOSYS) return openat2_or_reopen_memfd(ret, pathname, how); } #ifdef __NR_openat2 long sret = call_orig_syscall(__NR_openat2, (unsigned long)dirfd, (unsigned long)target, (unsigned long)how, (unsigned long)usize, 0, 0); if (sret >= 0 || errno != ENOSYS) { - return (int)sret; + return openat2_or_reopen_memfd((int)sret, pathname, how); } #endif if (!how || usize < 16) { @@ -646,6 +761,7 @@ int lstat(const char *pathname, struct stat *statbuf) { int fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags) { static int (*orig_fstatat)(int, const char *, struct stat *, int) = NULL; if (!orig_fstatat) orig_fstatat = (int (*)(int, const char *, struct stat *, int))dlsym(RTLD_NEXT, "fstatat"); + const char *given = pathname; DDNATV_AT_REMAP(dirfd, pathname); char buf[PATH_MAX]; const char *target = (pathname && pathname[0] == '/') ? ((flags & AT_SYMLINK_NOFOLLOW) ? rewrite_path : rewrite_path_follow)(pathname, buf, sizeof(buf)) : pathname; @@ -665,7 +781,7 @@ int fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags) { if (!orig_readlinkat) orig_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat"); ssize_t llen = orig_readlinkat ? orig_readlinkat(dirfd, target, link_buf, sizeof(link_buf) - 1) : -1; if (llen > 0) { - ssize_t post_len = postprocess_readlink(pathname, link_buf, llen, sizeof(link_buf)); + ssize_t post_len = postprocess_named_readlink(pathname, pathname == given ? pathname : NULL, link_buf, llen, sizeof(link_buf)); if (post_len > 0) { statbuf->st_size = post_len; } diff --git a/tools/nativeguest/hook/paths.c b/tools/nativeguest/hook/paths.c index 74983a7552..e8f9060b45 100644 --- a/tools/nativeguest/hook/paths.c +++ b/tools/nativeguest/hook/paths.c @@ -952,6 +952,30 @@ static int is_proc_fd_link(const char *path) { return *p == '\0'; } +static int is_proc_cwd_link(const char *path) { + if (!path || strncmp(path, "/proc/", 6) != 0) return 0; + const char *p = path + 6; + if (strncmp(p, "self/", 5) == 0) { + p += 5; + } else if (strncmp(p, "thread-self/", 12) == 0) { + p += 12; + } else { + if (*p < '0' || *p > '9') return 0; + while (*p >= '0' && *p <= '9') p++; + if (*p != '/') return 0; + p++; + } + return strcmp(p, "cwd") == 0; +} + +static int is_rootfs_real_path(const char *path) { + return path && g_ddnatv_root_len > 0 && is_path_prefix(path, g_ddnatv_root, g_ddnatv_root_len); +} + +static int link_answers_in_kernel_form(const char *linkpath, const char *named) { + return is_proc_fd_link(linkpath) || is_proc_cwd_link(linkpath) || is_rootfs_real_path(named); +} + // The guest path of a folder that a session mount puts outside the rootfs, for what the kernel // reports as its real place (getcwd(), /proc/self/cwd and fd links). Wine found no DOS drive for // Sekiro's folder on the SD card library ("starting in the Windows directory"), and the game quit. @@ -989,7 +1013,7 @@ static char *guest_path_of_allocated_mount_source(char *res) { return grown; } -static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret, size_t bufsiz) { +static ssize_t postprocess_named_readlink(const char *linkpath, const char *named, char *buf, ssize_t ret, size_t bufsiz) { if (ret <= 0) return ret; if ((size_t)ret < bufsiz) { buf[ret] = '\0'; @@ -998,7 +1022,7 @@ static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret ret = (ssize_t)guest_path_of_mount_source(buf, (size_t)ret, bufsiz, NULL); // 1. Strip g_ddnatv_root if target starts with it - if (g_ddnatv_root_len > 0 && !is_proc_fd_link(linkpath)) { + if (g_ddnatv_root_len > 0 && !link_answers_in_kernel_form(linkpath, named)) { size_t rlen = g_ddnatv_root_len; if ((size_t)ret >= rlen && memcmp(buf, g_ddnatv_root, rlen) == 0 && ((size_t)ret == rlen || buf[rlen] == '/')) { @@ -1053,6 +1077,10 @@ static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret return ret; } +static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret, size_t bufsiz) { + return postprocess_named_readlink(linkpath, linkpath, buf, ret, bufsiz); +} + // Android's SELinux label, which the xattr hooks keep away from Ubuntu programs. static const char k_selinux_xattr[] = "security.selinux"; diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index 14ef7c6654..9fd5a8077f 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -235,8 +235,16 @@ static int sandbox_only_limit(int resource, const struct rlimit *rlim) { return 0; } +// The kernel checks RLIMIT_RTTIME on a thread that is realtime or has a CPU-time timer armed, and a +// limit of 0 is reached at once: SIGXCPU at the soft limit, SIGKILL at the hard one. SDL sets the +// RTTimeUSecMax it reads from org.freedesktop.portal.Realtime before it asks for a realtime thread, +// and xdg-desktop-portal reports 0 when it reaches no RealtimeKit, as in a session with no system bus. +static int fatal_limit(int resource, const struct rlimit *rlim) { + return rlim && resource == RLIMIT_RTTIME && rlim->rlim_cur == 0; +} + int setrlimit(__rlimit_resource_t resource, const struct rlimit *rlim) { - if (sandbox_only_limit((int)resource, rlim)) return 0; + if (sandbox_only_limit((int)resource, rlim) || fatal_limit((int)resource, rlim)) return 0; static int (*orig_setrlimit)(__rlimit_resource_t, const struct rlimit *) = NULL; #if defined(__USE_FILE_OFFSET64) && !defined(__LP64__) // With 64-bit file offsets on a 32-bit system this function is setrlimit64 @@ -660,6 +668,19 @@ long syscall(long number, ...) { } #endif +#ifdef __NR_execve + if (number == __NR_execve) { + return (long)execve((const char *)arg1, (char *const *)arg2, (char *const *)arg3); + } +#endif + +#ifdef __NR_execveat + if (number == __NR_execveat && arg2 && ((const char *)arg2)[0] != '\0' && + (((const char *)arg2)[0] == '/' || (int)arg1 == AT_FDCWD) && (arg5 & ~(unsigned long)AT_EMPTY_PATH) == 0) { + return (long)execve((const char *)arg2, (char *const *)arg3, (char *const *)arg4); + } +#endif + #ifdef __NR_clone3 if (number == __NR_clone3) { errno = ENOSYS; diff --git a/tools/nativeguest/hook/setup.c b/tools/nativeguest/hook/setup.c index 4b7d2bbb0f..d94956af5a 100644 --- a/tools/nativeguest/hook/setup.c +++ b/tools/nativeguest/hook/setup.c @@ -307,6 +307,7 @@ static ssize_t copy_guest_exe(const char *real_exe, char *buf, size_t bufsiz) { size_t len = strlen(out_path); size_t copy_len = (len < bufsiz) ? len : bufsiz; memcpy(buf, out_path, copy_len); + if (copy_len < bufsiz) buf[copy_len] = '\0'; return (ssize_t)copy_len; } diff --git a/tools/nativeguest/hook/signals.c b/tools/nativeguest/hook/signals.c index 4ed9522da4..3d370bae28 100644 --- a/tools/nativeguest/hook/signals.c +++ b/tools/nativeguest/hook/signals.c @@ -10,6 +10,12 @@ #define SYS_SECCOMP 1 #endif +#if defined(__aarch64__) +#define DDNATV_HOST_AUDIT_ARCH 0xC00000B7U +#else +#define DDNATV_HOST_AUDIT_ARCH 0x40000028U +#endif + static int (*get_real_sigaction(void))(int, const struct sigaction *, struct sigaction *); // A program's own SIGSYS handler, for the traps of a seccomp filter it installed itself (Firefox's @@ -57,7 +63,13 @@ static long sigsys_id_change(int nr, const unsigned long long *regs, long ret_va // Intercept SECCOMP blocked syscalls (SIGSYS), resolve sandbox/landlock gracefully, and advance PC static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) { if (!ctx || !info) return; - if (info->si_code != SYS_SECCOMP) { + int host_trap = info->si_code == SYS_SECCOMP && info->si_errno == 0 && info->si_arch == DDNATV_HOST_AUDIT_ARCH; + if (!host_trap && g_app_sigsys_set) { + if (g_app_sigsys.sa_flags & SA_SIGINFO) g_app_sigsys.sa_sigaction(sig, info, ctx); + else g_app_sigsys.sa_handler(sig); + return; + } + if (!host_trap) { int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction(); if (real_sig) { struct sigaction sa_dfl; @@ -69,11 +81,6 @@ static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) { raise(sig); return; } - if (info->si_errno != 0 && g_app_sigsys_set) { - if (g_app_sigsys.sa_flags & SA_SIGINFO) g_app_sigsys.sa_sigaction(sig, info, ctx); - else g_app_sigsys.sa_handler(sig); - return; - } ucontext_t *uctx = (ucontext_t *)ctx; int sys_nr = info->si_syscall; diff --git a/tools/tests/test_anticheat_routing.py b/tools/tests/test_anticheat_routing.py new file mode 100644 index 0000000000..518d194725 --- /dev/null +++ b/tools/tests/test_anticheat_routing.py @@ -0,0 +1,223 @@ +import json +import os +from pathlib import Path +import runpy +import subprocess +import tempfile +import unittest + + +BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" +COMPAT = runpy.run_path(str(BIN / "steam-compatibility"), run_name="steam_compatibility") +SETUP = COMPAT["DD_ANTICHEAT_SETUP"] + + +class AntiCheatRoutingTest(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.steam = self.root / "Steam" + self.common = self.steam / "steamapps" / "common" + self.tools = self.steam / "compatibilitytools.d" + self.game = self.common / "Some Game" + self.game.mkdir(parents=True) + self.tools.mkdir(parents=True) + self.record = self.root / "record.json" + self.fex = self.root / "droiddeck-fex" + self.fex.write_text("#!/bin/bash\nif [ \"$1\" = update ]; then echo \"$1\" >> \"$DD_RECORD.update\"; " + "[ -n \"${DD_UPDATED_PATCHES:-}\" ] && printf '%s\\n' \"$DD_UPDATED_PATCHES\" > \"$DD_PATCHES\"; exit 0; fi\n" + "python3 -c 'import json,os,sys; json.dump({\"argv\": sys.argv[2:], " + "\"eac\": os.environ.get(\"PROTON_EAC_RUNTIME\"), \"be\": os.environ.get(\"PROTON_BATTLEYE_RUNTIME\")}, " + "open(sys.argv[1], \"w\"))' \"$DD_RECORD\" \"$@\"\n") + self.fex.chmod(0o755) + self.patches = self.root / "fex-patches" + self.patches.write_text("openat2-enosys-fallback\nfixed-guest-memory-above-host-address-limit\n") + + def tool(self, name, x86_64=True): + tool = self.tools / name + (tool / "files" / "lib" / "wine" / ("x86_64-unix" if x86_64 else "aarch64-unix")).mkdir(parents=True) + if not x86_64: + (tool / "files" / "bin-arm64").mkdir() + (tool / "proton").write_text("#!/bin/sh\n") + (tool / "proton").chmod(0o755) + return tool + + def runtime(self, name, library): + folder = self.common / name / "v2" / "lib64" + folder.mkdir(parents=True) + (folder / library).write_text("") + return self.common / name + + def file(self, relative): + path = self.game / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("{}") + + def launch(self, verb="waitforexitandrun", extra=None): + script = SETUP.replace("/usr/local/bin/droiddeck-fex", str(self.fex)).replace( + "/usr/local/share/fex-emu/.droiddeck-patches", str(self.patches)) + ( + "dd_game_cpus() { :; }\n" + "verb=$1; shift\n" + "dd_anticheat \"$@\"\n" + "echo stayed\n") + env = {"PATH": os.environ["PATH"], "HOME": str(self.root), "DD_RECORD": str(self.record), "DD_PATCHES": str(self.patches), + "STEAM_COMPAT_INSTALL_PATH": str(self.game), "STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.steam)} + env.update(extra or {}) + result = subprocess.run(["bash", "-c", script, "launcher", verb, str(self.game / "game.exe")], + env=env, capture_output=True, text=True, timeout=30) + routed = json.loads(self.record.read_text()) if self.record.exists() else None + return result, routed + + def test_eos_easy_anti_cheat_runs_the_newest_x86_64_build_under_fex(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + newest = self.tool("DroidDeck-Proton-11.0-10-x86_64") + self.tool("DroidDeck-Proton-11.0-20", x86_64=False) + runtime = self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + result, routed = self.launch() + self.assertNotIn("stayed", result.stdout) + self.assertEqual(routed["argv"], ["proton", str(newest / "proton"), "waitforexitandrun", str(self.game / "game.exe")]) + self.assertEqual(routed["eac"], str(runtime)) + self.assertIn("running DroidDeck-Proton-11.0-10-x86_64 under FEX", result.stderr) + + def test_battleye_sets_its_own_runtime(self): + self.file("BattlEye/BEClient_x64.so") + tool = self.tool("DroidDeck-Proton-11.0-1-x86_64") + runtime = self.runtime("Proton BattlEye Runtime", "beclient_x64.so") + _, routed = self.launch() + self.assertEqual((routed["argv"][1], routed["be"], routed["eac"]), (str(tool / "proton"), str(runtime), None)) + + def test_a_runtime_already_set_with_files_is_kept(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + own = self.root / "own-eac" + (own / "v2").mkdir(parents=True) + (own / "v2" / "easyanticheat_x64.so").write_text("") + _, routed = self.launch(extra={"PROTON_EAC_RUNTIME": str(own)}) + self.assertEqual(routed["eac"], str(own)) + + def test_games_without_anti_cheat_files_stay_on_arm64(self): + self.file("Data/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + result, routed = self.launch() + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + self.assertEqual(result.stderr, "") + + def test_without_an_x86_64_build_the_launch_stays_on_arm64(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-20", x86_64=False) + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + result, routed = self.launch() + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + self.assertIn("no x86-64 DroidDeck-Proton is installed", result.stderr) + + def test_without_the_runtime_files_the_launch_stays_on_arm64(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + (self.common / "Proton EasyAntiCheat Runtime").mkdir(parents=True) + result, routed = self.launch() + self.assertIsNone(routed) + self.assertIn("its Proton runtime is not installed", result.stderr) + + def test_the_user_can_turn_routing_off(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"}) + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + + def test_a_tool_the_user_chose_is_kept(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + for chosen in ("GE-Proton11-15-aarch64", "DroidDeck-Bionic-14.1-r85", "proton_experimental"): + result, routed = self.launch(extra={"DD_AC_TOOL": chosen}) + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + self.assertIn("%s was chosen for this game, so it runs as chosen" % chosen, result.stderr) + + def test_droiddeck_proton_builds_still_route(self): + self.file("EasyAntiCheat/Settings.json") + newest = self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + for own in ("DroidDeck-Proton 11-14.1", "DroidDeck-Proton-11-14.2"): + self.record.unlink(missing_ok=True) + result, routed = self.launch(extra={"DD_AC_TOOL": own}) + self.assertEqual(routed["argv"][1], str(newest / "proton")) + + def test_a_fex_build_without_high_guest_memory_stays_on_arm64(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + for patches in ("openat2-enosys-fallback\n", None): + if patches is None: + self.patches.unlink() + else: + self.patches.write_text(patches) + result, routed = self.launch() + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + self.assertIn("the installed FEX build cannot run anti-cheat", result.stderr) + + def test_an_older_fex_build_is_updated_before_routing(self): + self.file("EasyAntiCheat/Settings.json") + tool = self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + self.patches.unlink() + result, routed = self.launch(extra={"DD_UPDATED_PATCHES": "fixed-guest-memory-above-host-address-limit"}) + self.assertEqual(routed["argv"][1], str(tool / "proton")) + self.assertNotIn("cannot run anti-cheat", result.stderr) + self.assertTrue((self.root / "record.json.update").exists()) + + def test_games_without_anti_cheat_files_do_not_update_fex(self): + self.file("Data/Settings.json") + self.launch() + self.assertFalse((self.root / "record.json.update").exists()) + + def test_choices_are_kept_the_same_with_an_older_fex_build(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + self.patches.unlink() + result, routed = self.launch(extra={"DD_AC_TOOL": "GE-Proton11-15-aarch64"}) + self.assertIsNone(routed) + self.assertIn("GE-Proton11-15-aarch64 was chosen for this game, so it runs as chosen", result.stderr) + result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"}) + self.assertIsNone(routed) + self.assertEqual(result.stderr, "") + + def test_the_fex_build_lists_its_patches(self): + build = (BIN.parents[4] / "fex" / "build-in-arch.sh").read_text() + self.assertIn("> out/usr/local/share/fex-emu/.droiddeck-patches", build) + names = {p.stem.split("-", 1)[1] for p in (BIN.parents[4] / "fex" / "patches").glob("*.patch")} + self.assertIn("fixed-guest-memory-above-host-address-limit", names) + + def test_adopted_tools_pass_their_own_folder_name(self): + wrapper = COMPAT["extra_wrapper_sh"]("proton") + self.assertIn('DD_AC_TOOL=$(basename "$(cd "$here" && pwd -P)") dd_anticheat "$@"', wrapper) + self.assertNotIn("DD_AC_TOOL=", COMPAT["LAUNCHER_SH"]) + + def test_other_verbs_are_left_alone(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + result, routed = self.launch(verb="getcompatpath") + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + + def test_launchers_check_before_arm64_setup_and_x86_64_tools_run_under_fex(self): + launcher = COMPAT["LAUNCHER_SH"] + self.assertLess(launcher.index('dd_anticheat "$@"'), launcher.index('dd_components "$depot"')) + wrapper = COMPAT["extra_wrapper_sh"]("proton") + self.assertLess(wrapper.index("dd_x86_64_proton() {"), wrapper.index("dd_fallback=")) + self.assertLess(wrapper.index('droiddeck-fex proton "$here/proton"'), wrapper.index('dd_components "$here"')) + self.assertIn('! dd_x86_64_proton "$d"', wrapper) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_bottom_mirror_composition.py b/tools/tests/test_bottom_mirror_composition.py new file mode 100644 index 0000000000..6ddee5a720 --- /dev/null +++ b/tools/tests/test_bottom_mirror_composition.py @@ -0,0 +1,38 @@ +from pathlib import Path +import unittest + +ROOT = Path(__file__).resolve().parents[2] +NATIVE = ROOT / "app/src/main/cpp/waylandcomp/src" +APP = ROOT / "app/src/main/java/com/droiddeck/launcher" + + +class BottomMirrorCompositionTest(unittest.TestCase): + def test_mirror_requests_composition_until_its_last_consumer_leaves(self): + panel = (APP / "ui/BottomMirrorPage.kt").read_text() + self.assertIn("actions.holdComposed(true)", panel) + self.assertIn("onDispose { actions.holdComposed(false) }", panel) + activity = (APP / "SessionActivity.kt").read_text() + hold = activity.split("private fun holdComposedOutput(", 1)[1].split("private fun zeroCopyActive", 1)[0] + self.assertIn("if (held == wasHeld) return", hold) + self.assertIn("nativeSetMirrorCapture(held)", hold) + self.assertIn("if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy", hold) + self.assertIn("CompositorHost.isStarted && !SessionState.hdr && SessionPrefs.zeroCopy", activity) + self.assertIn("nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode) && composedOutputFree())", activity) + self.assertIn("nativeSetZeroCopy(composedOutputFree())", hold) + self.assertNotIn("SessionPrefs.set", hold) + + def test_compositor_selects_readable_surface_without_dropping_unimportable_hdr(self): + jni = (NATIVE / "waylandcomp_jni.c").read_text() + self.assertIn("droiddeck_host_mirror_capture(on ? 1 : 0);", jni) + host = (NATIVE / "droiddeck_ext.c").read_text() + self.assertIn("case HOST_MIRROR_CAPTURE:\n droiddeck_set_mirror_capture(m->a);", host) + compositor = (NATIVE / "compositor.c").read_text() + self.assertIn("if (g_mirror_capture && hdr_route != 3 && hs.n_hdr > 0) {\n hdr_route = 2;", compositor) + self.assertIn("g_zero_copy && !g_mirror_capture && (!framegen || fg_layer)", compositor) + self.assertIn("if (un && g_zero_copy)", compositor) + self.assertIn("if (g_zero_copy && droiddeck_color_hdr_open()) note_hdr_unimported", compositor) + self.assertNotIn("if (g_mirror_capture) ls = NULL", compositor) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_droiddeck_fex.py b/tools/tests/test_droiddeck_fex.py index 79f7043cbb..2eecb9cfeb 100644 --- a/tools/tests/test_droiddeck_fex.py +++ b/tools/tests/test_droiddeck_fex.py @@ -1235,6 +1235,29 @@ class LaunchTest(FexTestCase): self.assertEqual(emulated.call_args[0][2]["FEX_ROOTFS"], str(platform / "files")) self.assertEqual(FEX["required_runtime"](str(self.proton("1391110"))), "1628350") + def test_an_adopted_proton_keeps_the_runtime_of_its_original_manifest(self): + proton = self.proton("4183110") + folder = proton.parent + os.rename(folder / "toolmanifest.vdf", folder / "toolmanifest.vdf.droiddeck-orig") + self.write(folder / "toolmanifest.vdf", '"manifest"\n{\n "commandline" "/droiddeck-proton-wrap %verb%"\n}\n') + self.assertEqual(FEX["required_runtime"](str(proton)), "4183110") + os.unlink(folder / "toolmanifest.vdf.droiddeck-orig") + self.assertEqual(FEX["required_runtime"](str(proton)), "1628350") + + def test_proton_action_keeps_the_prefix_and_runs_under_fex(self): + self.fex_tool() + self.runtime() + proton = self.proton("1628350") + prefix = str(self.tmp / "compatdata" / "730") + env = {"STEAM_COMPAT_DATA_PATH": prefix} + with mock.patch.dict(os.environ, env, clear=False), mock.patch("os.execve") as emulated: + self.quiet(FEX["main"], ["proton", str(proton), "waitforexitandrun", "game.exe"]) + command, guest = emulated.call_args[0][1], emulated.call_args[0][2] + self.assertEqual(command[1:], [str(proton), "waitforexitandrun", "game.exe"]) + self.assertEqual(guest["STEAM_COMPAT_DATA_PATH"], prefix) + self.assertNotEqual(FEX["guest_environment"]({"portable": True}, env)["STEAM_COMPAT_DATA_PATH"], prefix) + self.assertEqual(FEX["main"](["proton", str(proton)]), 2) + def test_native_programs_run_directly(self): program = self.write(self.tmp / "native", elf(183), 0o755) with mock.patch("os.execvpe") as native, mock.patch("os.execve") as emulated: diff --git a/tools/tests/test_droiddeck_proton_default.py b/tools/tests/test_droiddeck_proton_default.py index 2173a223a1..194bf022c9 100644 --- a/tools/tests/test_droiddeck_proton_default.py +++ b/tools/tests/test_droiddeck_proton_default.py @@ -15,6 +15,8 @@ VALVE_11 = {"name": COMPAT["TOOL_11"], "display": "Proton 11.0 ARM64", "dir": CO GE = {"name": "GE-Proton11-7", "display": "GE-Proton11-7", "dir": "GE-Proton11-7", "valve": False} GE10 = {"name": "GE-Proton10-3", "display": "GE-Proton10-3", "dir": "GE-Proton10-3", "valve": False} NEWER = {"name": "DroidDeck-Proton-11-12.1", "display": "DroidDeck-Proton 11-12.1", "dir": "DroidDeck-Proton 11-12.1", "valve": False} +X86 = {"name": "DroidDeck-Proton-11-14.2-x86_64", "display": "DroidDeck-Proton 11-14.2 x86-64", "dir": "DroidDeck-Proton 11-14.2 x86-64", + "valve": False, "x86_64": True} def config_text(entries): @@ -204,6 +206,50 @@ class DroidDeckProtonDefaultTest(unittest.TestCase): self.assertEqual(newest, "b") self.assertEqual(gone, {OLD["name"]}) + def test_an_x86_64_build_never_becomes_the_automatic_default(self): + default, mapping, state = self.run_default( + {"default": TOOL, "auto": {"42": TOOL}}, [("0", TOOL), ("42", TOOL)], [VALVE, NEW, X86], ["42"]) + self.assertEqual((default, mapping["0"]), (NEW["name"], NEW["name"])) + default, mapping, _ = self.run_default({"default": TOOL}, [("0", TOOL)], [VALVE, X86]) + self.assertEqual((default, mapping), (TOOL, {"0": TOOL})) + + def test_an_automatic_x86_64_default_moves_back_to_arm64(self): + default, mapping, state = self.run_default( + {"default": X86["name"], "written": X86["name"], "source": "update"}, [("0", X86["name"])], [VALVE, NEW, X86]) + self.assertEqual((default, mapping, state["source"]), (NEW["name"], {"0": NEW["name"]}, "update")) + default, mapping, _ = self.run_default( + {"default": X86["name"], "written": X86["name"], "source": "update"}, [("0", X86["name"])], [VALVE, X86]) + self.assertEqual((default, mapping), (TOOL, {"0": TOOL})) + + def test_an_x86_64_default_the_user_picked_is_kept(self): + for source in ("app", "steam"): + default, mapping, _ = self.run_default( + {"default": X86["name"], "written": X86["name"], "source": source}, [("0", X86["name"])], [VALVE, NEW, X86]) + self.assertEqual((default, mapping), (X86["name"], {"0": X86["name"]})) + + def test_a_request_for_the_automatic_x86_64_default_keeps_it(self): + default, mapping, state = self.run_default( + {"default": X86["name"], "written": X86["name"], "source": "update", "applied": 1}, [("0", X86["name"])], + [VALVE, NEW, X86], request={"seq": 2, "name": X86["name"]}) + self.assertEqual((default, mapping, state["source"]), (X86["name"], {"0": X86["name"]}, "app")) + default, mapping, state = self.run_default(state, [("0", X86["name"])], [VALVE, NEW, X86], + request={"seq": 2, "name": X86["name"]}) + self.assertEqual((default, mapping, state["source"]), (X86["name"], {"0": X86["name"]}, "app")) + + def test_x86_64_layouts_are_marked_in_the_catalog(self): + with tempfile.TemporaryDirectory() as tmp: + tools = Path(tmp) / "compatibilitytools.d" + for entry, arm in (("DroidDeck-Proton 11-14.2 x86-64", False), ("DroidDeck-Proton 11-14.2", True)): + (tools / entry / "files" / "lib" / "wine" / ("aarch64-unix" if arm else "x86_64-unix")).mkdir(parents=True) + if arm: + (tools / entry / "files" / "bin-arm64").mkdir() + (tools / entry / COMPAT["EXTRA_WRAPPER"]).write_text("") + catalog = {t["dir"]: t for t in COMPAT["tool_catalog"](tmp) if not t["valve"]} + self.assertTrue(catalog["DroidDeck-Proton 11-14.2 x86-64"].get("x86_64")) + self.assertNotIn("x86_64", catalog["DroidDeck-Proton 11-14.2"]) + newest, _ = COMPAT["own_proton_moves"]({}, list(catalog.values())) + self.assertEqual(newest, catalog["DroidDeck-Proton 11-14.2"]["name"]) + if __name__ == "__main__": unittest.main() diff --git a/tools/tests/test_fex_guest_high_memory.py b/tools/tests/test_fex_guest_high_memory.py new file mode 100644 index 0000000000..ff21c4adad --- /dev/null +++ b/tools/tests/test_fex_guest_high_memory.py @@ -0,0 +1,3392 @@ +import platform +import re +import shutil +import signal +import subprocess +import tempfile +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0027-fixed-guest-memory-above-host-address-limit.patch" +PROBE = REPO / "tools/fex/probes/guest-high-memory.c" + +SOURCE = "Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp" +HEADER = "Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h" + +KERNEL_NAMES = {"pread_64": "pread64", "pwrite_64": "pwrite64", "prlimit_64": "prlimit64"} +NEWER_SYSCALLS = { + "futex_wake": 454, "futex_wait": 455, "futex_requeue": 456, "statmount": 457, "listmount": 458, + "lsm_get_self_attr": 459, "lsm_set_self_attr": 460, "lsm_list_modules": 461, + "mseal": 462, "setxattrat": 463, "getxattrat": 464, "listxattrat": 465, "removexattrat": 466, +} +OLDEST_HEADERS_LAST_SYSCALL = 453 +HARNESS_SECONDS = 120 + +PRELUDE = r""" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace fextl { +template using vector = std::vector; +template using list = std::list; +template using unordered_map = std::unordered_map; +using std::make_unique; +} +namespace FEXCore { +namespace Utils { constexpr uint64_t FEX_PAGE_SIZE = 4096; } +constexpr uint64_t AlignUp(uint64_t V, uint64_t A) { return (V + A - 1) & ~(A - 1); } +namespace Allocator { inline uint64_t GetHostVABits() { return 39; } } +} +""" + +STUBS = r""" +static int MunmapFailures; +static int TestMunmap(void* Address, size_t Size) { + if (MunmapFailures > 0) { + --MunmapFailures; + errno = ENOMEM; + return -1; + } + return munmap(Address, Size); +} +#define munmap TestMunmap +static int SendCalls; +static int SendFailures; +static size_t SendLimit = ~size_t {}; +static int SentSocket = -1; +static size_t SentLengths[8]; +static struct iovec* GrowAfterSend; +static void* UnmapAfterSend; +static bool PassSend; +static int DupFailures; +static int TestSendmmsg(int Socket, struct mmsghdr* Messages, unsigned int Count, int Flags) { + if (PassSend) { + return sendmmsg(Socket, Messages, Count, Flags); + } + SentSocket = Socket; + if (Count != 1 || SendFailures > 0) { + SendFailures -= SendFailures > 0; + errno = EAGAIN; + return -1; + } + size_t Length = 0; + for (size_t i = 0; i < Messages[0].msg_hdr.msg_iovlen; ++i) { + Length += Messages[0].msg_hdr.msg_iov[i].iov_len; + } + Length = std::min(Length, SendLimit); + SentLengths[SendCalls++ & 7] = Length; + Messages[0].msg_len = Length; + if (GrowAfterSend) { + GrowAfterSend->iov_len = 64; + } + if (UnmapAfterSend) { + munmap(UnmapAfterSend, 4096); + UnmapAfterSend = nullptr; + } + return 1; +} +#define sendmmsg TestSendmmsg +static int TestFcntl(int FD, int Command, int Argument = 0) { + if (Command == F_DUPFD_CLOEXEC && DupFailures > 0) { + --DupFailures; + errno = EMFILE; + return -1; + } + return fcntl(FD, Command, Argument); +} +#define fcntl TestFcntl +static int ProtectCalls; +static int TestMprotect(void* Address, size_t Size, int Prot) { + ++ProtectCalls; + return mprotect(Address, Size, Prot); +} +#define mprotect TestMprotect +static uint64_t AioDestroyed; +static std::function AioDestroyHook; +static int AioReaps; +static uint64_t AioReapArgs[7]; +static std::function AioReapHook; +template static uint64_t SyscallWord(T Value) { + if constexpr (std::is_null_pointer_v) { + return 0; + } else if constexpr (std::is_pointer_v) { + return reinterpret_cast(Value); + } else { + return static_cast(Value); + } +} +template static long TestSyscall(long Number, T... Args) { + const uint64_t Words[] = {0, SyscallWord(Args)...}; + if (Number == SYS_io_getevents || Number == SYS_io_pgetevents) { + ++AioReaps; + std::copy_n(Words, std::min(std::size(Words), 7), AioReapArgs); + AioReapArgs[0] = Number; + if (AioReapHook) { + return AioReapHook(Words); + } + errno = EINTR; + return -1; + } + if (Number == SYS_io_destroy) { + AioDestroyed = Words[1]; + if (AioDestroyHook) { + AioDestroyHook(Words[1]); + } + errno = EINVAL; + return -1; + } + return syscall(Number, Args...); +} +#define syscall TestSyscall +namespace FEXCore { +template class LockType = std::unique_lock, typename MutexType> +inline auto MaskSignalsAndLockMutex(MutexType& Mutex, uint64_t = ~0ULL) { return LockType {Mutex}; } +} +namespace ArchHelpers::Context { +inline uint64_t GetArmReg(void* UContext, uint32_t Reg) { return static_cast(UContext)[Reg]; } +inline void SetArmReg(void* UContext, uint32_t Reg, uint64_t Value) { static_cast(UContext)[Reg] = Value; } +} +namespace FEX::HLE { +struct TestVMATracking { std::shared_mutex Mutex; }; +struct TestSyscallHandler { TestVMATracking VMATracking; }; +inline TestSyscallHandler TestHandler; +inline TestSyscallHandler* _SyscallHandler = &TestHandler; +struct TestThreadObject { + struct { + struct { + bool Held; + uint32_t Deferred; + siginfo_t DeferredInfo[3]; + } Mappings; + } HighMemoryTrap; + struct { + std::vector DeferredSignalFrames; + } SignalInfo; +}; +inline TestThreadObject TestThread {}; +struct ThreadManager { + static TestThreadObject* GetCurrentThreadObject() { return &TestThread; } +}; +inline bool HasSyscallError(uint64_t Result) { return Result >= 0xFFFF'FFFF'FFFF'0001ULL; } +namespace FaultSafeUserMemAccess { +inline size_t CopyFromUser(void* Dest, const void* Src, size_t Size) { + struct iovec Local {Dest, Size}; + struct iovec Remote {const_cast(Src), Size}; + return Size == 0 || process_vm_readv(getpid(), &Local, 1, &Remote, 1, 0) == static_cast(Size) ? 0 : Size; +} +inline void (*BeforeUserWrite)() = nullptr; +inline size_t CopyToUser(void* Dest, const void* Src, size_t Size) { + if (auto* Hook = std::exchange(BeforeUserWrite, nullptr)) { + Hook(); + } + struct iovec Local {const_cast(Src), Size}; + struct iovec Remote {Dest, Size}; + return Size == 0 || process_vm_writev(getpid(), &Local, 1, &Remote, 1, 0) == static_cast(Size) ? 0 : Size; +} +} +namespace x64 { +ENUM +} +} +""" + +MAIN = r""" +using namespace FEX::HLE::GuestHighMemory; +namespace Sys = FEX::HLE::x64; +static void Show(const char* Name, uint64_t Value) { std::printf("%s %llx\n", Name, static_cast(Value)); } +struct TestHold { + bool Held; + uint32_t Deferred; + siginfo_t DeferredInfo[3]; +}; +static std::atomic TrapsSeen; +static std::atomic TrapCode; +static std::atomic TrapValue; +static bool ExclusiveFromAnotherThread() { + std::thread Writer([] { std::unique_lock Exclusive {FEX::HLE::_SyscallHandler->VMATracking.Mutex}; }); + Writer.join(); + return true; +} +static void CountTrap(int, siginfo_t* Info, void*) { + ++TrapsSeen; + TrapCode = Info->si_code; + TrapValue = Info->si_value.sival_int; +} +static uint64_t Call(uint32_t Syscall, uint64_t* Args, ArgumentStorage* Storage) { return TranslateSyscallArguments(Syscall, Args, 6, Storage); } +template +static uint64_t FinishResult(uint64_t Result, Arguments* Storage) { + if constexpr (std::is_void_v) { + FinishSyscallArguments(Result, Storage); + return Result; + } else { + return FinishSyscallArguments(Result, Storage); + } +} +int main() { + alarm(HARNESS_SECONDS); + const uint64_t Page = 4096; + static bool FirstHighStoreHeld; + FEX::HLE::FaultSafeUserMemAccess::BeforeUserWrite = [] { FirstHighStoreHeld = FEX::HLE::TestThread.HighMemoryTrap.Mappings.Held; }; + const uint32_t FirstHighValue = 1; + Show("high_store_unmapped_result", CopyToGuest(0x720000000000ULL, &FirstHighValue, sizeof(FirstHighValue))); + Show("high_store_unmapped_held", FirstHighStoreHeld); + Show("high_store_unmapped_released", FEX::HLE::TestThread.HighMemoryTrap.Mappings.Held); + const uint64_t High = TaskTop - Page; + const uint64_t Low = 0x140000000ULL; + Show("contains_last_page", Contains(High)); + Show("contains_task_top", Contains(TaskTop)); + Show("contains_host_limit", Contains(1ULL << 39)); + Show("contains_below_limit", Contains((1ULL << 39) - Page)); + Show("claims_fixed", ClaimsMapping(High, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED)); + Show("claims_noreplace", ClaimsMapping(High, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE)); + Show("claims_low", ClaimsMapping(Low, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED)); + Show("claims_hint", ClaimsMapping(High, Page, MAP_PRIVATE | MAP_ANONYMOUS)); + Show("claims_task_top", ClaimsMapping(TaskTop, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED)); + + auto* Backing = static_cast(mmap(nullptr, 8 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Base = reinterpret_cast(Backing); + const uint64_t Single = 0x7f0000000000ULL; + const uint64_t Split = 0x7e0000000000ULL; + const uint64_t Joined = 0x7d0000000000ULL; + AddEntry(Single, Page, Base, false, PROT_READ | PROT_WRITE); + AddEntry(Split, Page, Base + 2 * Page, false, PROT_READ | PROT_WRITE); + AddEntry(Split + Page, Page, Base + 4 * Page, false, PROT_READ | PROT_WRITE); + AddEntry(Joined, Page, Base + 5 * Page, false, PROT_READ | PROT_WRITE); + AddEntry(Joined + Page, Page, Base + 6 * Page, false, PROT_READ | PROT_WRITE); + ArgumentStorage Storage; + const int Peer = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0); + + uint64_t Read[6] = {3, Single + 16, 32, 0, 0, 0}; + Show("read_result", Call(Sys::SYSCALL_x64_read, Read, &Storage)); + Show("read_buffer", Read[1] - Base); + + uint64_t Truncate[6] = {3, Single + 16, 0, 0, 0, 0}; + Show("ftruncate_result", Call(Sys::SYSCALL_x64_ftruncate, Truncate, &Storage)); + Show("ftruncate_length", Truncate[1] - Single); + + uint64_t Mapping[6] = {Single, Page, 0, 0, 0, 0}; + Show("mmap_result", Call(Sys::SYSCALL_x64_mmap, Mapping, &Storage)); + Show("mmap_address", Mapping[0] - Single); + + uint64_t Unknown[6] = {Single, Single, Single, Single, Single, Single}; + Show("unknown_result", Call(1000, Unknown, &Storage)); + Show("unknown_args", Unknown[0] - Single + Unknown[5] - Single); + + uint64_t Overrun[6] = {3, Single + Page - 8, 64, 0, 0, 0}; + Show("overrun_result", Call(Sys::SYSCALL_x64_read, Overrun, &Storage)); + + uint64_t Apart[6] = {3, Split + Page - 96, 200, 0, 0, 0}; + Show("split_result", Call(Sys::SYSCALL_x64_read, Apart, &Storage)); + + uint64_t Together[6] = {3, Joined + Page - 96, 200, 0, 0, 0}; + Show("joined_result", Call(Sys::SYSCALL_x64_read, Together, &Storage)); + Show("joined_buffer", Together[1] - Base); + + uint64_t Write[6] = {3, Split + Page - 96, 96, 0, 0, 0}; + Show("fits_result", Call(Sys::SYSCALL_x64_write, Write, &Storage)); + + uint64_t PollApart[6] = {Split + Page - 96, 25, 0, 0, 0, 0}; + Show("poll_split_result", Call(Sys::SYSCALL_x64_poll, PollApart, &Storage)); + uint64_t PollFits[6] = {Split + Page - 96, 12, 0, 0, 0, 0}; + Show("poll_fits_result", Call(Sys::SYSCALL_x64_poll, PollFits, &Storage)); + uint64_t PollJoined[6] = {Joined + Page - 96, 25, 0, 0, 0, 0}; + Show("poll_joined_result", Call(Sys::SYSCALL_x64_poll, PollJoined, &Storage)); + uint64_t PollHuge[6] = {Single, 1ULL << 61, 0, 0, 0, 0}; + Show("poll_huge_result", Call(Sys::SYSCALL_x64_poll, PollHuge, &Storage)); + uint64_t EpollApart[6] = {3, Split + Page - 96, 9, 0, 0, 0}; + Show("epoll_split_result", Call(Sys::SYSCALL_x64_epoll_wait, EpollApart, &Storage)); + uint64_t EpollFits[6] = {3, Split + Page - 96, 8, 0, 0, 0}; + Show("epoll_fits_result", Call(Sys::SYSCALL_x64_epoll_wait, EpollFits, &Storage)); + uint64_t SelectApart[6] = {1024, Split + Page - 64, 0, 0, 0, 0}; + Show("select_split_result", Call(Sys::SYSCALL_x64_select, SelectApart, &Storage)); + uint64_t SelectFits[6] = {512, Split + Page - 64, 0, 0, 0, 0}; + Show("select_fits_result", Call(Sys::SYSCALL_x64_select, SelectFits, &Storage)); + uint64_t SelectWide[6] = {(1ULL << 32) + 1, Single, 0, 0, 0, 0}; + Show("select_wide_result", Call(Sys::SYSCALL_x64_select, SelectWide, &Storage)); + Show("fits_buffer", Write[1] - Base); + + char LowBuffer[16]; + struct iovec Guest[2] = {{reinterpret_cast(Single + 64), 32}, {LowBuffer, sizeof(LowBuffer)}}; + uint64_t Vector[6] = {3, reinterpret_cast(Guest), 2, 0, 0, 0}; + Show("readv_result", Call(Sys::SYSCALL_x64_readv, Vector, &Storage)); + const auto* HostVector = reinterpret_cast(Vector[1]); + Show("readv_copied", HostVector != Guest); + Show("readv_high_base", reinterpret_cast(HostVector[0].iov_base) - Base); + Show("readv_low_base", HostVector[1].iov_base == LowBuffer); + Show("readv_guest_untouched", reinterpret_cast(Guest[0].iov_base) - Single); + + struct iovec LowOnly[1] = {{LowBuffer, sizeof(LowBuffer)}}; + uint64_t Plain[6] = {3, reinterpret_cast(LowOnly), 1, 0, 0, 0}; + Show("writev_result", Call(Sys::SYSCALL_x64_writev, Plain, &Storage)); + Show("writev_untouched", Plain[1] == reinterpret_cast(LowOnly)); + + struct iovec Straddle[1] = {{reinterpret_cast(Split + Page - 8), 16}}; + uint64_t Crossing[6] = {3, reinterpret_cast(Straddle), 1, 0, 0, 0}; + Show("writev_split_result", Call(Sys::SYSCALL_x64_writev, Crossing, &Storage)); + + ArgumentStorage Receive; + struct iovec Incoming[1] = {{reinterpret_cast(Single + 128), 64}}; + struct msghdr Header {}; + Header.msg_iov = Incoming; + Header.msg_iovlen = 1; + uint64_t Message[6] = {3, reinterpret_cast(&Header), 0, 0, 0, 0}; + Show("recvmsg_result", Call(Sys::SYSCALL_x64_recvmsg, Message, &Receive)); + const auto* HostHeader = reinterpret_cast(Message[1]); + Show("recvmsg_copied", HostHeader != &Header); + Show("recvmsg_base", reinterpret_cast(HostHeader->msg_iov[0].iov_base) - Base); + Receive.Message.msg_flags = MSG_TRUNC; + FinishSyscallArguments(64, &Receive); + Show("recvmsg_flags", Header.msg_flags); + Show("recvmsg_guest_iov", Header.msg_iov == Incoming); + + Show("to_guest", ToGuest(Base + 6 * Page + 8) - Joined); + Show("to_guest_low", ToGuest(Low) == Low); + + const uint32_t ExclusiveOps[] = {0xc85f7c20, 0x885ffc20, 0x085ffc20, 0x485f7c20, 0xc8027c20, 0xc802fc20, + 0x0802fc20, 0xc87f0820, 0x887f8820, 0xc8230820, 0xc8238820}; + const uint32_t OtherOps[] = {0xc8dffc20, 0xc89ffc20, 0xc8e0fc41, 0x4860fc82, 0x08207c82, 0xf8e00041, + 0xf8e08041, 0xf9400020, 0xf9000420, 0xa9000440, 0xf8bfc020}; + uint64_t Refused = 0; + for (auto Op : ExclusiveOps) { + Refused += IsExclusive(Op); + } + uint64_t Allowed = 0; + for (auto Op : OtherOps) { + Allowed += !IsExclusive(Op); + } + Show("exclusive_refused", Refused); + Show("others_allowed", Allowed); + + std::vector> Applied; + auto Record = [&](void* Host, uint64_t Size, uint32_t) { + Applied.emplace_back(reinterpret_cast(Host), Size); + return 0; + }; + Show("split_apply_result", ApplyToRegionsLocked(Split, 2 * Page, -EINVAL, Record)); + Show("split_apply_count", Applied.size()); + Show("split_apply_first", Applied[0].first - Base); + Show("split_apply_second", Applied[1].first - Base); + Show("split_apply_sizes", Applied[0].second + Applied[1].second); + Applied.clear(); + Show("gap_apply_result", ApplyToRegionsLocked(Single, 2 * Page, -EINVAL, Record)); + Show("gap_apply_count", Applied.size()); + bool Advised = false; + Show("advise_split", Advise(Split, 2 * Page, MADV_DONTNEED, &Advised)); + Show("advise_split_applied", Advised); + Show("advise_gap", Advise(Single, 2 * Page, MADV_DONTNEED, &Advised)); + Show("advise_gap_applied", Advised); + Show("advise_unaligned", Advise(Single + 8, Page, MADV_DONTNEED, &Advised)); + Show("advise_unaligned_applied", Advised); + Show("advise_zero", Advise(Single, 0, MADV_DONTNEED, &Advised)); + Show("advise_wrap", Advise(Single, UINT64_MAX - 16, MADV_DONTNEED, &Advised)); + Show("advise_wrap_applied", Advised); + Show("protect_split", Protect(Split, 2 * Page, PROT_READ | PROT_WRITE)); + Show("protect_zero", Protect(Single, 0, PROT_READ | PROT_WRITE)); + Show("protect_wrap", Protect(Single, UINT64_MAX - 16, PROT_READ | PROT_WRITE)); + + auto* Guarded = static_cast(mmap(nullptr, 3 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Guard = 0x7b0000000000ULL; + RegionView Part {}; + AddEntry(Guard, 3 * Page, reinterpret_cast(Guarded), false, PROT_READ | PROT_WRITE); + Show("guard_protect", Protect(Guard + Page, Page, PROT_READ)); + FindLocked(Guard, &Part); + Show("guard_low_size", Part.Size); + Show("guard_low_prot", Part.Prot); + FindLocked(Guard + Page, &Part); + Show("guard_mid_size", Part.Size); + Show("guard_mid_host", Part.Host - reinterpret_cast(Guarded)); + Show("guard_mid_prot", Part.Prot); + FindLocked(Guard + 2 * Page, &Part); + Show("guard_high_size", Part.Size); + Show("guard_high_prot", Part.Prot); + Show("guard_store_readonly", ExclusiveReachable(0xc8027c20, PROT_READ)); + Show("guard_load_readonly", ExclusiveReachable(0xc85f7c20, PROT_READ)); + Show("guard_store_writable", ExclusiveReachable(0xc8027c20, PROT_READ | PROT_WRITE)); + Show("guard_load_none", ExclusiveReachable(0xc85f7c20, PROT_NONE)); + Show("guard_pair_store_readonly", ExclusiveReachable(0xc8220c20, PROT_READ)); + Show("discards", DiscardsContents(MADV_DONTNEED) + DiscardsContents(MADV_FREE) + DiscardsContents(MADV_REMOVE) + + DiscardsContents(MADV_DONTNEED_LOCKED)); + Show("keeps", DiscardsContents(MADV_WILLNEED) + DiscardsContents(MADV_NORMAL) + DiscardsContents(MADV_HUGEPAGE)); + + auto* Spare = static_cast(mmap(nullptr, 2 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Retire = 0x7c0000000000ULL; + unsigned char Resident = 0; + RegionView View {}; + AddEntry(Retire, 2 * Page, reinterpret_cast(Spare), false, PROT_READ | PROT_WRITE); + MunmapFailures = 1; + Show("retire_unmap", UnmapLocked(Retire, Page)); + Show("retire_pending", RetiredCount); + Show("retire_untracked", !FindLocked(Retire, &View)); + Show("retire_host_held", mincore(Spare, Page, &Resident) == 0); + Show("retire_second", UnmapLocked(Retire + Page, Page)); + Show("retire_released", RetiredCount); + Show("retire_host_gone", mincore(Spare, Page, &Resident) != 0 && errno == ENOMEM); + Show("retire_rest_gone", mincore(Spare + Page, Page, &Resident) != 0 && errno == ENOMEM); + + auto* Kept = static_cast(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Full = 0x7a0000000000ULL; + AddEntry(Full, Page, reinterpret_cast(Kept), false, PROT_READ | PROT_WRITE); + for (uint32_t i = 0; i < MaxRegions; ++i) { + Retired[i] = {0x10000000ULL + i * 2 * Page, Page}; + } + RetiredCount = MaxRegions; + MunmapFailures = MaxRegions + 1; + Show("retire_full_unmap", UnmapLocked(Full, Page)); + Show("retire_full_tracked", FindLocked(Full, &View)); + Show("retire_full_host_held", mincore(Kept, Page, &Resident) == 0); + RetiredCount = 0; + MunmapFailures = 0; + Show("retire_full_after", UnmapLocked(Full, Page)); + Show("retire_full_gone", !FindLocked(Full, &View)); + + struct { + uint64_t Host; + uint64_t Low; + uint64_t High; + uint32_t Size; + bool Valid; + } Monitor {}; + uint64_t Context[32] {}; + alignas(16) uint64_t Cell[2] = {5, 0}; + const auto CellHost = reinterpret_cast(Cell); + EmulateExclusive(Monitor, 0xc85f7c20, CellHost, Context); + Show("ldxr_value", Context[0]); + Context[0] = 9; + EmulateExclusive(Monitor, 0xc8027c20, CellHost, Context); + Show("stxr_status", Context[2]); + Show("stxr_memory", Cell[0]); + EmulateExclusive(Monitor, 0xc85f7c20, CellHost, Context); + Cell[0] = 11; + Context[0] = 12; + EmulateExclusive(Monitor, 0xc8027c20, CellHost, Context); + Show("contended_status", Context[2]); + Show("contended_memory", Cell[0]); + Context[0] = 13; + EmulateExclusive(Monitor, 0xc8027c20, CellHost, Context); + Show("unarmed_status", Context[2]); + Show("unarmed_memory", Cell[0]); + Cell[0] = 1; + Cell[1] = 2; + EmulateExclusive(Monitor, 0xc87f0c20, CellHost, Context); + Show("ldxp_low", Context[0]); + Show("ldxp_high", Context[3]); + Context[0] = 7; + Context[3] = 8; + EmulateExclusive(Monitor, 0xc8220c20, CellHost, Context); + Show("stxp_status", Context[2]); + Show("stxp_memory", Cell[0] * 16 + Cell[1]); + Cell[0] = 0x1122334455667788ULL; + EmulateExclusive(Monitor, 0x085f7c20, CellHost, Context); + Show("ldxrb_value", Context[0]); + Context[0] = 0x1ab; + EmulateExclusive(Monitor, 0x0802fc20, CellHost, Context); + Show("stlxrb_status", Context[2]); + Show("stlxrb_memory", Cell[0]); + Show("misaligned", EmulateExclusive(Monitor, 0xc85f7c20, CellHost + 4, Context)); + + Show("writeonly_load", ExclusiveReachable(0xc85f7c20, PROT_WRITE)); + Show("writeonly_store", ExclusiveReachable(0xc8027c20, PROT_WRITE)); + Show("writeonly_pair_store", ExclusiveReachable(0xc8220c20, PROT_WRITE)); + Show("exec_only_load", ExclusiveReachable(0xc85f7c20, PROT_EXEC)); + + const uint32_t GuardEntries = Count.load(); + Show("guard_restore", Protect(Guard + Page, Page, PROT_READ | PROT_WRITE)); + FindLocked(Guard + Page, &Part); + Show("guard_restored_guest", Part.Guest - Guard); + Show("guard_restored_size", Part.Size); + Show("guard_restored_merged", GuardEntries - Count.load()); + Show("split_hosts_kept_apart", FindLocked(Split + Page, &Part) && Part.Guest == Split + Page && Part.Size == Page); + + const uint64_t Toggles = 1100; + auto* Striped = static_cast(mmap(nullptr, Toggles * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Stripe = 0x790000000000ULL; + AddEntry(Stripe, Toggles * Page, reinterpret_cast(Striped), false, PROT_READ | PROT_WRITE); + const uint32_t StripeEntries = Count.load(); + uint64_t ToggleFailures = 0; + for (uint64_t i = 0; i < Toggles; ++i) { + ToggleFailures += Protect(Stripe + i * Page, Page, PROT_READ) != 0; + ToggleFailures += Protect(Stripe + i * Page, Page, PROT_READ | PROT_WRITE) != 0; + } + Show("toggle_failures", ToggleFailures); + Show("toggle_entries", Count.load() - StripeEntries); + FindLocked(Stripe, &Part); + Show("toggle_pages", Part.Size / Page); + + uint64_t SemApart[6] = {1, Split + Page - 12, 3, 0, 0, 0}; + Show("semop_split_result", Call(Sys::SYSCALL_x64_semop, SemApart, &Storage)); + uint64_t SemFits[6] = {1, Split + Page - 12, 2, 0, 0, 0}; + Show("semop_fits_result", Call(Sys::SYSCALL_x64_semop, SemFits, &Storage)); + uint64_t GroupsApart[6] = {4, Split + Page - 12, 0, 0, 0, 0}; + Show("getgroups_split_result", Call(Sys::SYSCALL_x64_getgroups, GroupsApart, &Storage)); + uint64_t EventsApart[6] = {1, 1, 2, Split + Page - 32, 0, 0}; + Show("io_getevents_split_result", Call(Sys::SYSCALL_x64_io_getevents, EventsApart, &Storage)); + uint64_t EventsFit[6] = {1, 1, 1, Split + Page - 32, 0, 0}; + Show("io_getevents_fits_result", Call(Sys::SYSCALL_x64_io_getevents, EventsFit, &Storage)); + uint64_t PagesApart[6] = {0, 2, Split + Page - 8, 0, 0, 0}; + Show("move_pages_split_result", Call(Sys::SYSCALL_x64_move_pages, PagesApart, &Storage)); + + char BatchLow[16]; + struct iovec SendVectors[2] = {{reinterpret_cast(Single + 256), 32}, {BatchLow, sizeof(BatchLow)}}; + struct mmsghdr Outgoing[2] {}; + Outgoing[0].msg_hdr.msg_iov = &SendVectors[0]; + Outgoing[0].msg_hdr.msg_iovlen = 1; + Outgoing[1].msg_hdr.msg_iov = &SendVectors[1]; + Outgoing[1].msg_hdr.msg_iovlen = 1; + ArgumentStorage SendBatch; + uint64_t Send[6] = {static_cast(Peer), reinterpret_cast(Outgoing), 2, 0, 0, 0}; + Show("sendmmsg_result", Call(Sys::SYSCALL_x64_sendmmsg, Send, &SendBatch)); + auto* HostSend = reinterpret_cast(Send[1]); + Show("sendmmsg_copied", HostSend != Outgoing); + Show("sendmmsg_high_base", reinterpret_cast(HostSend[0].msg_hdr.msg_iov[0].iov_base) - Base); + Show("sendmmsg_low_base", HostSend[1].msg_hdr.msg_iov[0].iov_base == BatchLow); + Show("sendmmsg_guest_untouched", reinterpret_cast(Outgoing[0].msg_hdr.msg_iov[0].iov_base) - Single); + Show("sendmmsg_submitted", Send[2]); + SendCalls = 0; + HostSend[0].msg_len = 32; + Show("sendmmsg_finish", FinishResult(1, &SendBatch)); + Show("sendmmsg_later_sends", SendCalls); + Show("sendmmsg_lengths", Outgoing[0].msg_len * 0x100 + Outgoing[1].msg_len); + Outgoing[0].msg_len = 0; + Outgoing[1].msg_len = 0; + ArgumentStorage DeclinedBatch; + uint64_t Declined[6] = {static_cast(Peer), reinterpret_cast(Outgoing), 2, 0, 0, 0}; + Call(Sys::SYSCALL_x64_sendmmsg, Declined, &DeclinedBatch); + reinterpret_cast(Declined[1])[0].msg_len = 32; + SendFailures = 1; + Show("sendmmsg_refused_finish", FinishResult(1, &DeclinedBatch)); + Show("sendmmsg_refused_lengths", Outgoing[0].msg_len * 0x100 + Outgoing[1].msg_len); + + struct iovec ReceiveVectors[2] = {{reinterpret_cast(Single + 512), 64}, {BatchLow, sizeof(BatchLow)}}; + struct mmsghdr Arriving[2] {}; + Arriving[0].msg_hdr.msg_iov = &ReceiveVectors[0]; + Arriving[0].msg_hdr.msg_iovlen = 1; + Arriving[1].msg_hdr.msg_iov = &ReceiveVectors[1]; + Arriving[1].msg_hdr.msg_iovlen = 1; + ArgumentStorage ReceiveBatch; + uint64_t Batch[6] = {3, reinterpret_cast(Arriving), 2, 0, 0, 0}; + Show("recvmmsg_result", Call(Sys::SYSCALL_x64_recvmmsg, Batch, &ReceiveBatch)); + auto* HostReceive = reinterpret_cast(Batch[1]); + Show("recvmmsg_copied", HostReceive != Arriving); + Show("recvmmsg_base", reinterpret_cast(HostReceive[0].msg_hdr.msg_iov[0].iov_base) - Base); + HostReceive[0].msg_len = 40; + HostReceive[0].msg_hdr.msg_flags = MSG_TRUNC; + HostReceive[1].msg_len = 5; + FinishSyscallArguments(1, &ReceiveBatch); + Show("recvmmsg_first_length", Arriving[0].msg_len); + Show("recvmmsg_first_flags", Arriving[0].msg_hdr.msg_flags); + Show("recvmmsg_second_length", Arriving[1].msg_len); + Show("recvmmsg_guest_iov", Arriving[0].msg_hdr.msg_iov == &ReceiveVectors[0]); + + std::vector Many(1100); + Many[0].msg_hdr.msg_iov = &ReceiveVectors[0]; + Many[0].msg_hdr.msg_iovlen = 1; + ArgumentStorage ManyBatch; + uint64_t Wide[6] = {3, reinterpret_cast(Many.data()), Many.size(), 0, 0, 0}; + Show("recvmmsg_wide_result", Call(Sys::SYSCALL_x64_recvmmsg, Wide, &ManyBatch)); + Show("recvmmsg_wide_count", Wide[2]); + uint64_t BatchApart[6] = {3, Split + Page - 64, 2, 0, 0, 0}; + Show("sendmmsg_split_result", Call(Sys::SYSCALL_x64_sendmmsg, BatchApart, &ManyBatch)); + + ArgumentStorage Sizes; + uint64_t StatSplit[6] = {3, Split + Page - 64, 0, 0, 0, 0}; + Show("fstat_split_result", Call(Sys::SYSCALL_x64_fstat, StatSplit, &Sizes)); + uint64_t StatEdge[6] = {3, Single + Page - 144, 0, 0, 0, 0}; + Show("fstat_edge_result", Call(Sys::SYSCALL_x64_fstat, StatEdge, &Sizes)); + uint64_t NameEdge[6] = {Single + Page - 390, 0, 0, 0, 0, 0}; + Show("uname_edge_result", Call(Sys::SYSCALL_x64_uname, NameEdge, &Sizes)); + uint64_t NameOver[6] = {Single + Page - 389, 0, 0, 0, 0, 0}; + Show("uname_over_result", Call(Sys::SYSCALL_x64_uname, NameOver, &Sizes)); + uint64_t Action[6] = {10, Single + Page - 32, 0, 8, 0, 0}; + Show("sigaction_edge_result", Call(Sys::SYSCALL_x64_rt_sigaction, Action, &Sizes)); + uint64_t ActionOver[6] = {10, Single + Page - 24, 0, 8, 0, 0}; + Show("sigaction_over_result", Call(Sys::SYSCALL_x64_rt_sigaction, ActionOver, &Sizes)); + uint64_t MaskApart[6] = {0, Split + Page - 4, 0, 8, 0, 0}; + Show("sigprocmask_split_result", Call(Sys::SYSCALL_x64_rt_sigprocmask, MaskApart, &Sizes)); + uint64_t MaskFits[6] = {0, Split + Page - 8, 0, 8, 0, 0}; + Show("sigprocmask_fits_result", Call(Sys::SYSCALL_x64_rt_sigprocmask, MaskFits, &Sizes)); + uint64_t Sleep[6] = {Single + Page - 16, 0, 0, 0, 0, 0}; + Show("nanosleep_edge_result", Call(Sys::SYSCALL_x64_nanosleep, Sleep, &Sizes)); + uint64_t SleepOver[6] = {Single + Page - 8, 0, 0, 0, 0, 0}; + Show("nanosleep_over_result", Call(Sys::SYSCALL_x64_nanosleep, SleepOver, &Sizes)); + uint64_t Residency[6] = {Low, 3 * Page, Split + Page - 2, 0, 0, 0}; + Show("mincore_split_result", Call(Sys::SYSCALL_x64_mincore, Residency, &Sizes)); + uint64_t ResidencyFits[6] = {Low, 2 * Page, Split + Page - 2, 0, 0, 0}; + Show("mincore_fits_result", Call(Sys::SYSCALL_x64_mincore, ResidencyFits, &Sizes)); + uint64_t Lock[6] = {3, F_GETLK, Split + Page - 16, 0, 0, 0}; + Show("fcntl_lock_split_result", Call(Sys::SYSCALL_x64_fcntl, Lock, &Sizes)); + uint64_t LockFits[6] = {3, F_GETLK, Single + Page - 32, 0, 0, 0}; + Show("fcntl_lock_fits_result", Call(Sys::SYSCALL_x64_fcntl, LockFits, &Sizes)); + Show("fcntl_lock_fits_buffer", LockFits[2] - Base); + + std::memcpy(Backing + 3 * Page - 2, "ab", 2); + std::memcpy(Backing + 4 * Page, "cd", 3); + uint64_t PathApart[6] = {Split + Page - 2, 0, 0, 0, 0, 0}; + Show("open_split_result", Call(Sys::SYSCALL_x64_open, PathApart, &Sizes)); + std::memcpy(Backing + 6 * Page - 2, "ab", 2); + std::memcpy(Backing + 6 * Page, "cd", 3); + uint64_t PathJoined[6] = {Joined + Page - 2, 0, 0, 0, 0, 0}; + Show("open_joined_result", Call(Sys::SYSCALL_x64_open, PathJoined, &Sizes)); + Show("open_joined_path", PathJoined[0] - Base); + std::memcpy(Backing + 3000, "dir/file", 9); + uint64_t PathInside[6] = {static_cast(AT_FDCWD), Single + 3000, 0, 0, 0, 0}; + Show("openat_inside_result", Call(Sys::SYSCALL_x64_openat, PathInside, &Sizes)); + Show("openat_inside_path", PathInside[1] - Base); + std::memset(Backing + Page - 8, 'x', 8); + uint64_t PathOpen[6] = {Single + Page - 8, 0, 0, 0, 0, 0}; + Show("open_unterminated_result", Call(Sys::SYSCALL_x64_open, PathOpen, &Sizes)); + uint64_t RenameApart[6] = {Single + 3000, Split + Page - 2, 0, 0, 0, 0}; + Show("rename_split_result", Call(Sys::SYSCALL_x64_rename, RenameApart, &Sizes)); + + socklen_t AddressLength = 16; + uint64_t Accept[6] = {3, Split + Page - 16, reinterpret_cast(&AddressLength), 0, 0, 0}; + Show("accept_fits_result", Call(Sys::SYSCALL_x64_accept, Accept, &Sizes)); + AddressLength = 32; + uint64_t AcceptOver[6] = {3, Split + Page - 16, reinterpret_cast(&AddressLength), 0, 0, 0}; + Show("accept_split_result", Call(Sys::SYSCALL_x64_accept, AcceptOver, &Sizes)); + AddressLength = 4096; + uint64_t AcceptCapped[6] = {3, Single + Page - 128, reinterpret_cast(&AddressLength), 0, 0, 0}; + Show("accept_capped_result", Call(Sys::SYSCALL_x64_accept, AcceptCapped, &Sizes)); + const uint32_t HighLength = 32; + std::memcpy(Backing + 40, &HighLength, sizeof(HighLength)); + uint64_t AcceptHigh[6] = {3, Split + Page - 16, Single + 40, 0, 0, 0}; + Show("accept_high_length_result", Call(Sys::SYSCALL_x64_accept, AcceptHigh, &Sizes)); + uint32_t OptionLength = 8; + uint64_t Option[6] = {3, 1, 2, Split + Page - 4, reinterpret_cast(&OptionLength), 0}; + Show("getsockopt_split_result", Call(Sys::SYSCALL_x64_getsockopt, Option, &Sizes)); + OptionLength = 4; + uint64_t OptionFits[6] = {3, 1, 2, Split + Page - 4, reinterpret_cast(&OptionLength), 0}; + Show("getsockopt_fits_result", Call(Sys::SYSCALL_x64_getsockopt, OptionFits, &Sizes)); + + uint64_t QueueFits[6] = {1, Split + Page - 16, 8, 0, 0, 0}; + Show("msgsnd_fits_result", Call(Sys::SYSCALL_x64_msgsnd, QueueFits, &Sizes)); + uint64_t QueueOver[6] = {1, Split + Page - 16, 9, 0, 0, 0}; + Show("msgsnd_split_result", Call(Sys::SYSCALL_x64_msgsnd, QueueOver, &Sizes)); + uint64_t QueueReceive[6] = {1, Split + Page - 16, 9, 0, 0, 0}; + Show("msgrcv_split_result", Call(Sys::SYSCALL_x64_msgrcv, QueueReceive, &Sizes)); + uint64_t QueueHuge[6] = {1, Single, 1ULL << 40, 0, 0, 0}; + Show("msgsnd_huge_result", Call(Sys::SYSCALL_x64_msgsnd, QueueHuge, &Sizes)); + + std::memcpy(Backing + 100, "x", 2); + uint64_t ValidFailures = 0; + uint64_t ValidTranslated = 0; + uint64_t StatValid[6] = {Single + 100, Single + 1024, 0, 0, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_stat, StatValid, &Sizes) != 0; + ValidTranslated += StatValid[0] == Base + 100 && StatValid[1] == Base + 1024; + uint64_t StatxValid[6] = {static_cast(AT_FDCWD), Single + 100, 0, 0x7ff, Single + 1536, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_statx, StatxValid, &Sizes) != 0; + ValidTranslated += StatxValid[1] == Base + 100 && StatxValid[4] == Base + 1536; + uint64_t ClockValid[6] = {1, Single + 2048, 0, 0, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_clock_gettime, ClockValid, &Sizes) != 0; + ValidTranslated += ClockValid[1] == Base + 2048; + uint64_t WaitValid[6] = {static_cast(-1), Single + 64, 0, Single + 512, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_wait4, WaitValid, &Sizes) != 0; + ValidTranslated += WaitValid[1] == Base + 64 && WaitValid[3] == Base + 512; + uint64_t PipeValid[6] = {Single + 8, 0, 0, 0, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_pipe2, PipeValid, &Sizes) != 0; + ValidTranslated += PipeValid[0] == Base + 8; + uint64_t LimitValid[6] = {0, 7, Single + 2560, Single + 2600, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_prlimit_64, LimitValid, &Sizes) != 0; + ValidTranslated += LimitValid[2] == Base + 2560 && LimitValid[3] == Base + 2600; + uint64_t TimerValid[6] = {1, 0, Single + 2304, Single + 2336, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_timer_settime, TimerValid, &Sizes) != 0; + ValidTranslated += TimerValid[2] == Base + 2304 && TimerValid[3] == Base + 2336; + AddressLength = 16; + uint64_t AcceptValid[6] = {3, Single + 256, reinterpret_cast(&AddressLength), 0, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_accept, AcceptValid, &Sizes) != 0; + ValidTranslated += AcceptValid[1] == Base + 256; + uint64_t NameValid[6] = {Single, 0, 0, 0, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_uname, NameValid, &Sizes) != 0; + ValidTranslated += NameValid[0] == Base; + uint64_t SignalValid[6] = {10, Single + 2800, Single + 2900, 8, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_rt_sigaction, SignalValid, &Sizes) != 0; + ValidTranslated += SignalValid[1] == Base + 2800 && SignalValid[2] == Base + 2900; + Show("single_valid_failures", ValidFailures); + Show("single_valid_translated", ValidTranslated); + + struct TestIocb { + uint64_t Data; + uint32_t Key; + int32_t ReadWriteFlags; + uint16_t Opcode; + int16_t Priority; + uint32_t File; + uint64_t Buffer; + uint64_t Bytes; + int64_t Offset; + uint64_t Reserved; + uint32_t Flags; + uint32_t ResultFile; + }; + TestIocb ReadBlock {}; + ReadBlock.Data = 0x77; + ReadBlock.Key = 5; + ReadBlock.Buffer = Single + 768; + ReadBlock.Bytes = 64; + char VectorLow[16]; + struct iovec Scatter[2] = {{reinterpret_cast(Single + 800), 16}, {VectorLow, sizeof(VectorLow)}}; + TestIocb Vectored {}; + Vectored.Opcode = 7; + Vectored.Buffer = reinterpret_cast(Scatter); + Vectored.Bytes = 2; + TestIocb ReadExpected = ReadBlock; + const TestIocb VectoredExpected = Vectored; + auto GuestBlocksUntouched = [&] { + return std::memcmp(&ReadBlock, &ReadExpected, sizeof(TestIocb)) == 0 && std::memcmp(&Vectored, &VectoredExpected, sizeof(TestIocb)) == 0; + }; + struct TestEvent { + uint64_t Data; + uint64_t Object; + int64_t Result; + int64_t Result2; + }; + auto Deliver = [](const uint64_t* Args, const void* Events, size_t Size) { + static_cast(FEX::HLE::FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(Args[3]), Events, Size)); + }; + uint64_t Submitted[2] = {reinterpret_cast(&ReadBlock), reinterpret_cast(&Vectored)}; + ArgumentStorage Submit; + uint64_t SubmitArgs[6] = {1, 2, reinterpret_cast(Submitted), 0, 0, 0}; + const auto CopiesBefore = IoCopyCount.load(); + ProtectCalls = 0; + Show("io_submit_result", Call(Sys::SYSCALL_x64_io_submit, SubmitArgs, &Submit)); + Show("io_submit_count", SubmitArgs[1]); + Show("io_submit_list_copied", SubmitArgs[2] != reinterpret_cast(Submitted)); + const auto* Sent = reinterpret_cast(SubmitArgs[2]); + const auto* SentRead = reinterpret_cast(Sent[0]); + const auto* SentVector = reinterpret_cast(Sent[1]); + Show("io_submit_private_blocks", SentRead != &ReadBlock && SentVector != &Vectored); + Show("io_submit_buffer", SentRead->Buffer - Base); + Show("io_submit_fields_kept", SentRead->Data == 0x77 && SentRead->Bytes == 64 && SentRead->Key == 5); + const auto* HostScatter = reinterpret_cast(SentVector->Buffer); + Show("io_submit_vector_copied", HostScatter != Scatter); + Show("io_submit_vector_base", reinterpret_cast(HostScatter[0].iov_base) - Base); + Show("io_submit_vector_low", HostScatter[1].iov_base == VectorLow); + Show("io_submit_guest_key", ReadBlock.Key); + Show("io_submit_guest_untouched", GuestBlocksUntouched()); + Show("io_submit_copies", IoCopyCount.load() - CopiesBefore); + FinishSyscallArguments(2, &Submit); + Show("io_submit_accepted_key", ReadBlock.Key); + ReadExpected.Key = 0; + Show("io_submit_copies_kept", IoCopyCount.load() - CopiesBefore); + Show("io_submit_finished_untouched", GuestBlocksUntouched()); + + TestEvent CancelEvent {}; + ArgumentStorage Cancel; + uint64_t CancelArgs[6] = {1, reinterpret_cast(&ReadBlock), reinterpret_cast(&CancelEvent), 0, 0, 0}; + Show("io_cancel_result", Call(Sys::SYSCALL_x64_io_cancel, CancelArgs, &Cancel)); + Show("io_cancel_private", CancelArgs[1] == Sent[0]); + ArgumentStorage CancelElsewhere; + uint64_t ElsewhereArgs[6] = {2, reinterpret_cast(&ReadBlock), reinterpret_cast(&CancelEvent), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, ElsewhereArgs, &CancelElsewhere); + Show("io_cancel_other_context", ElsewhereArgs[1] == reinterpret_cast(&ReadBlock)); + + TestEvent Reaped[3] = {{0x77, Sent[0], 64, 0}, {0, Sent[1], 16, 0}, {8, Base + 1536, 16, 0}}; + ArgumentStorage ReapCopies; + uint64_t ReapCopiesArgs[6] = {1, 1, 3, reinterpret_cast(Reaped), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ReapCopiesArgs, &ReapCopies); + Show("io_getevents_host_buffer", ReapCopiesArgs[3] == reinterpret_cast(ReapCopies.EventBuffer.data())); + Deliver(ReapCopiesArgs, Reaped, sizeof(Reaped)); + FinishSyscallArguments(3, &ReapCopies); + Show("io_getevents_copy_object", Reaped[0].Object == reinterpret_cast(&ReadBlock)); + Show("io_getevents_vector_object", Reaped[1].Object == reinterpret_cast(&Vectored)); + Show("io_getevents_alias_object", Reaped[2].Object - Single); + Show("io_getevents_copies_freed", IoCopyCount.load() - CopiesBefore); + Show("io_getevents_untouched", GuestBlocksUntouched()); + Show("io_submit_protect_calls", ProtectCalls); + + auto* HighBlock = reinterpret_cast(Backing + 1536); + *HighBlock = {}; + HighBlock->Opcode = 1; + HighBlock->Buffer = reinterpret_cast(LowBuffer); + HighBlock->Bytes = sizeof(LowBuffer); + uint64_t HighList[1] = {Single + 1536}; + ArgumentStorage HighSubmit; + uint64_t HighArgs[6] = {1, 1, reinterpret_cast(HighList), 0, 0, 0}; + Show("io_submit_high_result", Call(Sys::SYSCALL_x64_io_submit, HighArgs, &HighSubmit)); + Show("io_submit_high_copied", HighArgs[2] != reinterpret_cast(HighList)); + Show("io_submit_high_block", reinterpret_cast(HighArgs[2])[0] - Base); + Show("io_submit_high_guest_list", HighList[0] - Single); + Show("io_submit_high_uncopied", IoCopyCount.load() - CopiesBefore); + FinishSyscallArguments(1, &HighSubmit); + + TestIocb BadBlock {}; + BadBlock.Buffer = Split + Page - 8; + BadBlock.Bytes = 16; + uint64_t Mixed[2] = {reinterpret_cast(&ReadBlock), reinterpret_cast(&BadBlock)}; + ArgumentStorage Partial; + uint64_t PartialArgs[6] = {1, 2, reinterpret_cast(Mixed), 0, 0, 0}; + Show("io_submit_partial_result", Call(Sys::SYSCALL_x64_io_submit, PartialArgs, &Partial)); + Show("io_submit_partial_count", PartialArgs[1]); + Show("io_submit_partial_copies", IoCopyCount.load() - CopiesBefore); + FinishSyscallArguments(static_cast(-EFAULT), &Partial); + Show("io_submit_partial_released", IoCopyCount.load() - CopiesBefore); + Show("io_submit_partial_untouched", GuestBlocksUntouched()); + ArgumentStorage Truncated; + uint64_t TruncatedArgs[6] = {1, 2, reinterpret_cast(Submitted), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, TruncatedArgs, &Truncated); + const uint64_t TruncatedFirst = reinterpret_cast(TruncatedArgs[2])[0]; + FinishSyscallArguments(1, &Truncated); + Show("io_submit_short_kept", IoCopyCount.load() - CopiesBefore); + Show("io_submit_short_first_live", FindIoCopyLocked(TruncatedFirst) != nullptr); + ArgumentStorage OtherContext; + uint64_t OtherContextArgs[6] = {3, 1, reinterpret_cast(Submitted), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, OtherContextArgs, &OtherContext); + FinishSyscallArguments(1, &OtherContext); + ArgumentStorage Destroy; + uint64_t DestroyArgs[6] = {1, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, DestroyArgs, &Destroy); + FinishSyscallArguments(0, &Destroy); + Show("io_destroy_released", IoCopyCount.load() - CopiesBefore); + ArgumentStorage DestroyFailed; + uint64_t DestroyFailedArgs[6] = {3, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, DestroyFailedArgs, &DestroyFailed); + FinishSyscallArguments(static_cast(-EINVAL), &DestroyFailed); + Show("io_destroy_failed_kept", IoCopyCount.load() - CopiesBefore); + ArgumentStorage DestroyOther; + uint64_t DestroyOtherArgs[6] = {3, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, DestroyOtherArgs, &DestroyOther); + FinishSyscallArguments(0, &DestroyOther); + Show("io_destroy_other_released", IoCopyCount.load() - CopiesBefore); + uint64_t OnlyCrossing[1] = {reinterpret_cast(&BadBlock)}; + ArgumentStorage FirstBad; + uint64_t FirstBadArgs[6] = {1, 1, reinterpret_cast(OnlyCrossing), 0, 0, 0}; + Show("io_submit_first_bad_result", Call(Sys::SYSCALL_x64_io_submit, FirstBadArgs, &FirstBad)); + FinishSyscallArguments(static_cast(-EFAULT), &FirstBad); + Show("io_submit_first_bad_copies", IoCopyCount.load() - CopiesBefore); + TestIocb KeyFirst = ReadBlock; + KeyFirst.Key = 5; + TestIocb KeySecond = ReadBlock; + KeySecond.Key = 6; + uint64_t KeyList[2] = {reinterpret_cast(&KeyFirst), reinterpret_cast(&KeySecond)}; + ArgumentStorage KeySubmit; + uint64_t KeySubmitArgs[6] = {4, 2, reinterpret_cast(KeyList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, KeySubmitArgs, &KeySubmit); + const uint64_t KeyFirstSent = reinterpret_cast(KeySubmitArgs[2])[0]; + Show("io_submit_keys_prepared", KeyFirst.Key == 5 && KeySecond.Key == 6); + TestEvent KeyCancelEvent {}; + ArgumentStorage EarlyCancel; + uint64_t EarlyCancelArgs[6] = {4, reinterpret_cast(&KeyFirst), reinterpret_cast(&KeyCancelEvent), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, EarlyCancelArgs, &EarlyCancel); + Show("io_cancel_keyed_native", EarlyCancelArgs[1] == reinterpret_cast(&KeyFirst)); + FinishSyscallArguments(1, &KeySubmit); + Show("io_submit_key_accepted", KeyFirst.Key); + Show("io_submit_key_after_rejected", KeySecond.Key); + Show("io_submit_key_rejected_released", IoCopyCount.load() - CopiesBefore); + ArgumentStorage LateCancel; + uint64_t LateCancelArgs[6] = {4, reinterpret_cast(&KeyFirst), reinterpret_cast(&KeyCancelEvent), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, LateCancelArgs, &LateCancel); + Show("io_cancel_accepted_private", LateCancelArgs[1] == KeyFirstSent); + TestIocb KeyA = ReadBlock; + KeyA.Key = 7; + TestIocb KeyB = ReadBlock; + KeyB.Key = 8; + TestIocb KeyC = ReadBlock; + KeyC.Key = 9; + uint64_t KeyTriple[3] = {reinterpret_cast(&KeyA), reinterpret_cast(&KeyB), reinterpret_cast(&KeyC)}; + ArgumentStorage RejectSubmit; + uint64_t RejectSubmitArgs[6] = {6, 3, reinterpret_cast(KeyTriple), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, RejectSubmitArgs, &RejectSubmit); + const auto* RejectSent = reinterpret_cast(RejectSubmitArgs[2]); + reinterpret_cast(RejectSent[0])->Key = 0; + reinterpret_cast(RejectSent[1])->Key = 0; + FinishSyscallArguments(1, &RejectSubmit); + Show("io_submit_rejected_key_cleared", KeyA.Key == 0 && KeyB.Key == 0); + Show("io_submit_unreached_key", KeyC.Key); + TestIocb KeyD = ReadBlock; + KeyD.Key = 3; + uint64_t KeySingle[1] = {reinterpret_cast(&KeyD)}; + ArgumentStorage FirstRejected; + uint64_t FirstRejectedArgs[6] = {6, 1, reinterpret_cast(KeySingle), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, FirstRejectedArgs, &FirstRejected); + reinterpret_cast(reinterpret_cast(FirstRejectedArgs[2])[0])->Key = 0; + FinishSyscallArguments(static_cast(-EBADF), &FirstRejected); + Show("io_submit_first_rejected_key", KeyD.Key); + ArgumentStorage RejectDestroy; + uint64_t RejectDestroyArgs[6] = {6, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, RejectDestroyArgs, &RejectDestroy); + FinishSyscallArguments(0, &RejectDestroy); + Show("io_submit_rejected_released", IoCopyCount.load() - CopiesBefore); + auto* SealedEvents = static_cast(mmap(nullptr, Page, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + int64_t NoWait[2] = {0, 0}; + const uint64_t Immediate = reinterpret_cast(NoWait); + ArgumentStorage UnwritableReap; + uint64_t UnwritableReapArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, UnwritableReapArgs, &UnwritableReap); + Show("io_getevents_unwritable_staged", UnwritableReapArgs[3] == reinterpret_cast(UnwritableReap.EventBuffer.data()) && + UnwritableReapArgs[2] == 1 && UnwritableReap.EventBuffer.size() == sizeof(TestEvent) / sizeof(uint64_t)); + Show("io_getevents_unwritable_result", FinishSyscallArguments(static_cast(-EFAULT), &UnwritableReap)); + Show("io_getevents_unwritable_kept", IoCopyCount.load() - CopiesBefore); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage SealedReap; + uint64_t SealedReapArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, SealedReapArgs, &SealedReap); + mprotect(SealedEvents, Page, PROT_READ); + const TestEvent SealedEvent {0x77, KeyFirstSent, 64, 0}; + Deliver(SealedReapArgs, &SealedEvent, sizeof(SealedEvent)); + Show("io_getevents_sealed_result", FinishSyscallArguments(1, &SealedReap)); + Show("io_getevents_sealed_released", IoCopyCount.load() - CopiesBefore); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage StashedReap; + uint64_t StashedReapArgs[6] = {4, 1, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, StashedReapArgs, &StashedReap); + Show("io_getevents_stash_nonblocking", StashedReapArgs[1] == 0 && StashedReapArgs[2] == 1 && + StashedReapArgs[3] == reinterpret_cast(StashedReap.EventBuffer.data() + sizeof(TestEvent) / sizeof(uint64_t))); + Show("io_getevents_stash_result", FinishSyscallArguments(0, &StashedReap)); + Show("io_getevents_stash_event", SealedEvents[0].Object == reinterpret_cast(&KeyFirst) && SealedEvents[0].Data == 0x77); + ArgumentStorage DrainedReap; + uint64_t DrainedReapArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), Immediate, 0}; + Call(Sys::SYSCALL_x64_io_getevents, DrainedReapArgs, &DrainedReap); + Show("io_getevents_stash_once", DrainedReapArgs[1] == 1 && DrainedReapArgs[2] == 1 && FinishSyscallArguments(0, &DrainedReap) == 0); + auto FailReap = [&](uint64_t Context, const TestEvent& Event) { + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage Failed; + uint64_t FailedArgs[6] = {Context, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, FailedArgs, &Failed); + mprotect(SealedEvents, Page, PROT_READ); + Deliver(FailedArgs, &Event, sizeof(Event)); + const auto Result = FinishSyscallArguments(1, &Failed); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + return Result; + }; + Show("io_getevents_stash_ready_failed", FailReap(4, {0x57, reinterpret_cast(&KeyD), 1, 0})); + ArgumentStorage ReadyReap; + uint64_t ReadyReapArgs[6] = {4, 1, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ReadyReapArgs, &ReadyReap); + const TestEvent Ready {0x58, reinterpret_cast(&KeyC), 1, 0}; + Deliver(ReadyReapArgs, &Ready, sizeof(Ready)); + Show("io_getevents_stash_ready_result", FinishSyscallArguments(1, &ReadyReap)); + Show("io_getevents_stash_ready_order", SealedEvents[0].Data == 0x57 && SealedEvents[1].Data == 0x58 && + SealedEvents[1].Object == reinterpret_cast(&KeyC)); + Show("io_getevents_stash_plain_failed", FailReap(4, {0x55, reinterpret_cast(&KeyD), 1, 0})); + ArgumentStorage TopUp; + uint64_t TopUpArgs[6] = {4, 2, 3, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, TopUpArgs, &TopUp); + Show("io_getevents_stash_topup_args", TopUpArgs[1] == 1 && TopUpArgs[2] == 2 && + TopUpArgs[3] == reinterpret_cast(TopUp.EventBuffer.data() + sizeof(TestEvent) / sizeof(uint64_t))); + const TestEvent Fresh {0x66, reinterpret_cast(&KeyA), 2, 0}; + Deliver(TopUpArgs, &Fresh, sizeof(Fresh)); + Show("io_getevents_stash_topup_result", FinishSyscallArguments(1, &TopUp)); + Show("io_getevents_stash_topup_order", SealedEvents[0].Data == 0x55 && SealedEvents[0].Object == reinterpret_cast(&KeyD) && + SealedEvents[1].Data == 0x66 && SealedEvents[1].Object == reinterpret_cast(&KeyA)); + FailReap(4, {0x44, reinterpret_cast(&KeyB), 1, 0}); + ArgumentStorage FaultedRetry; + uint64_t FaultedRetryArgs[6] = {4, 2, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, FaultedRetryArgs, &FaultedRetry); + Show("io_getevents_stash_fault_result", FinishSyscallArguments(static_cast(-EFAULT), &FaultedRetry)); + ArgumentStorage Interrupted; + uint64_t InterruptedArgs[6] = {4, 2, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, InterruptedArgs, &Interrupted); + Show("io_getevents_stash_kept_after_fault", InterruptedArgs[1] == 1 && InterruptedArgs[2] == 1); + Show("io_getevents_stash_interrupted", FinishSyscallArguments(static_cast(-EINTR), &Interrupted)); + Show("io_getevents_stash_interrupted_event", SealedEvents[0].Data == 0x44 && SealedEvents[0].Object == reinterpret_cast(&KeyB)); + FailReap(4, {0x45, reinterpret_cast(&KeyB), 1, 0}); + ArgumentStorage RejectedMask; + uint64_t RejectedMaskArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_pgetevents, RejectedMaskArgs, &RejectedMask); + Show("io_getevents_stash_einval_result", FinishSyscallArguments(static_cast(-EINVAL), &RejectedMask)); + ArgumentStorage AfterRejected; + uint64_t AfterRejectedArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, AfterRejectedArgs, &AfterRejected); + Show("io_getevents_stash_einval_kept", FinishSyscallArguments(0, &AfterRejected) == 1 && SealedEvents[0].Data == 0x45); + FailReap(12, {0x46, reinterpret_cast(&KeyB), 1, 0}); + ArgumentStorage InFlight; + uint64_t InFlightArgs[6] = {12, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, InFlightArgs, &InFlight); + ArgumentStorage InFlightDestroy; + uint64_t InFlightDestroyArgs[6] = {12, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, InFlightDestroyArgs, &InFlightDestroy); + FinishSyscallArguments(0, &InFlightDestroy); + ArgumentStorage Recreated; + uint64_t RecreatedArgs[6] = {12, 1, 1, reinterpret_cast(SealedEvents), Immediate, 0}; + Call(Sys::SYSCALL_x64_io_getevents, RecreatedArgs, &Recreated); + FinishSyscallArguments(static_cast(-EINVAL), &InFlight); + Show("io_getevents_stash_recreated_result", FinishSyscallArguments(0, &Recreated)); + ArgumentStorage AfterDestroy; + uint64_t AfterDestroyArgs[6] = {12, 1, 1, reinterpret_cast(SealedEvents), Immediate, 0}; + Call(Sys::SYSCALL_x64_io_getevents, AfterDestroyArgs, &AfterDestroy); + Show("io_getevents_stash_destroyed_in_flight", AfterDestroyArgs[1] == 1 && AfterDestroyArgs[2] == 1 && FinishSyscallArguments(0, &AfterDestroy) == 0); + std::vector FullStash(65536); + ArgumentStorage Filling; + uint64_t FillingArgs[6] = {31, 1, FullStash.size(), reinterpret_cast(FullStash.data()), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, FillingArgs, &Filling); + ArgumentStorage Contended; + uint64_t ContendedArgs[6] = {31, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ContendedArgs, &Contended); + Show("io_getevents_stash_blocking_kept", FillingArgs[2] == FullStash.size() && ContendedArgs[1] == 1 && ContendedArgs[2] == 1); + FinishSyscallArguments(0, &Contended); + FinishSyscallArguments(0, &Filling); + ArgumentStorage Uncrowded; + uint64_t UncrowdedArgs[6] = {31, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, UncrowdedArgs, &Uncrowded); + Show("io_getevents_stash_reserve_released", UncrowdedArgs[1] == 1 && UncrowdedArgs[2] == 1); + FinishSyscallArguments(0, &Uncrowded); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage Owned; + uint64_t OwnedArgs[6] = {32, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, OwnedArgs, &Owned); + const auto* OwnedBuffer = Owned.EventBuffer.data(); + const bool OwnedReady = Owned.Recovery.size() == 1; + mprotect(SealedEvents, Page, PROT_READ); + const TestEvent OwnedEvent {0x47, reinterpret_cast(&KeyB), 1, 0}; + Deliver(OwnedArgs, &OwnedEvent, sizeof(OwnedEvent)); + const auto OwnedResult = FinishSyscallArguments(1, &Owned); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + const auto& OwnedState = AioContextsLocked()[32]; + Show("io_getevents_recovery_preallocated", OwnedReady && OwnedResult == static_cast(-EFAULT) && Owned.Recovery.empty() && + OwnedState.Batches.size() == 1 && OwnedState.Batches.front().data() == OwnedBuffer); + ArgumentStorage OwnedRetry; + uint64_t OwnedRetryArgs[6] = {32, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, OwnedRetryArgs, &OwnedRetry); + Show("io_getevents_recovery_delivered", FinishSyscallArguments(0, &OwnedRetry) == 1 && SealedEvents[0].Data == 0x47); + uint32_t ReplacementRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + const uint64_t Replaced = reinterpret_cast(ReplacementRing); + FailReap(Replaced, {0x48, reinterpret_cast(&KeyB), 1, 0}); + const auto ReplacedCopies = IoCopyCount.load(); + ArgumentStorage OldSubmit; + uint64_t OldSubmitArgs[6] = {Replaced, 1, reinterpret_cast(Submitted), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, OldSubmitArgs, &OldSubmit); + const auto OldCopy = reinterpret_cast(OldSubmitArgs[2])[0]; + FinishSyscallArguments(1, &OldSubmit); + ArgumentStorage OldDestroy; + uint64_t OldDestroyArgs[6] = {Replaced, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, OldDestroyArgs, &OldDestroy); + uint64_t ReplacementContext = Replaced; + ArgumentStorage Replacement; + uint64_t ReplacementArgs[6] = {128, reinterpret_cast(&ReplacementContext), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, ReplacementArgs, &Replacement); + FinishSyscallArguments(0, &Replacement); + ArgumentStorage NewSubmit; + uint64_t NewSubmitArgs[6] = {Replaced, 1, reinterpret_cast(Submitted), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, NewSubmitArgs, &NewSubmit); + const auto NewCopy = reinterpret_cast(NewSubmitArgs[2])[0]; + FinishSyscallArguments(1, &NewSubmit); + ArgumentStorage StaleReap; + uint64_t StaleReapArgs[6] = {Replaced, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, StaleReapArgs, &StaleReap); + const bool StaleSkipped = StaleReapArgs[1] == 1 && StaleReapArgs[2] == 1; + FinishSyscallArguments(0, &StaleReap); + FailReap(Replaced, {0x49, reinterpret_cast(&KeyB), 1, 0}); + FinishSyscallArguments(0, &OldDestroy); + Show("io_destroy_replacement_copies_kept", StaleSkipped && IoCopyCount.load() - ReplacedCopies == 1 && OldCopy != NewCopy && + !FindIoCopyLocked(OldCopy) && FindIoCopyLocked(NewCopy)); + ArgumentStorage ReplacementRetry; + uint64_t ReplacementRetryArgs[6] = {Replaced, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ReplacementRetryArgs, &ReplacementRetry); + Show("io_destroy_replacement_stash_kept", FinishSyscallArguments(0, &ReplacementRetry) == 1 && SealedEvents[0].Data == 0x49); + ArgumentStorage NewDestroy; + uint64_t NewDestroyArgs[6] = {Replaced, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, NewDestroyArgs, &NewDestroy); + FinishSyscallArguments(0, &NewDestroy); + Show("io_destroy_replacement_released", IoCopyCount.load() - ReplacedCopies + (FindIoCopyLocked(NewCopy) != nullptr)); + uint32_t WakeRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + const uint64_t Woken = reinterpret_cast(WakeRing); + uint64_t WakeContext = Woken; + ArgumentStorage WakeSetup; + uint64_t WakeSetupArgs[6] = {128, reinterpret_cast(&WakeContext), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, WakeSetupArgs, &WakeSetup); + const bool SetupPrivate = WakeSetupArgs[1] == reinterpret_cast(&WakeSetup.SetupId); + FinishSyscallArguments(0, &WakeSetup); + const auto WakeGeneration = AioContextsLocked()[Woken].Generation; + ArgumentStorage WakeRejected; + uint64_t WakeRejectedArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, WakeRejectedArgs, &WakeRejected); + FinishSyscallArguments(static_cast(-EINVAL), &WakeRejected); + Show("io_setup_generation_kept", SetupPrivate && WakeGeneration != 0 && AioContextsLocked().count(Woken) == 1 && + AioContextsLocked()[Woken].Generation == WakeGeneration && AioContextsLocked()[Woken].Live); + const uint64_t EventWords = sizeof(TestEvent) / sizeof(uint64_t); + const int ReapsBefore = AioReaps; + ArgumentStorage Blocked; + uint64_t BlockedArgs[6] = {Woken, 2, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, BlockedArgs, &Blocked); + Show("io_getevents_blocking_sliced", Blocked.Blocking && BlockedArgs[1] == 2 && BlockedArgs[2] == 2 && + BlockedArgs[4] == reinterpret_cast(Blocked.Wait) && Blocked.Wait[0] == 0 && Blocked.Wait[1] == 20000000 && Blocked.Deadline < 0); + ArgumentStorage StashPair; + uint64_t StashPairArgs[6] = {Woken, 2, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, StashPairArgs, &StashPair); + mprotect(SealedEvents, Page, PROT_READ); + const TestEvent StashPairEvents[2] = {{0x4a, reinterpret_cast(&KeyB), 1, 0}, {0x4b, reinterpret_cast(&KeyC), 1, 0}}; + Deliver(StashPairArgs, StashPairEvents, sizeof(StashPairEvents)); + const auto StashPairResult = FinishSyscallArguments(2, &StashPair); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + Show("io_getevents_slice_collects_stash", StashPairResult == static_cast(-EFAULT) && FinishSyscallArguments(0, &Blocked) == 2 && + AioReaps == ReapsBefore && SealedEvents[0].Data == 0x4a && SealedEvents[1].Data == 0x4b && + SealedEvents[1].Object == reinterpret_cast(&KeyC)); + ArgumentStorage Waiting; + uint64_t WaitingArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, WaitingArgs, &Waiting); + bool SiblingStashed = false; + AioReapHook = [&](const uint64_t* Words) -> long { + SiblingStashed = Words[1] == Woken && Words[2] == 1 && Words[3] == 1 && Words[4] == reinterpret_cast(Waiting.EventBuffer.data()) && + Words[5] == reinterpret_cast(Waiting.Wait) && Waiting.Wait[1] == 20000000 && + FailReap(Woken, {0x4c, reinterpret_cast(&KeyB), 1, 0}) == static_cast(-EFAULT); + return 0; + }; + const auto WaitingResult = FinishSyscallArguments(0, &Waiting); + AioReapHook = nullptr; + Show("io_getevents_slice_without_notification", SiblingStashed && WaitingResult == 1 && AioReaps == ReapsBefore + 1 && + AioReapArgs[0] == SYS_io_getevents && SealedEvents[0].Data == 0x4c); + ArgumentStorage Gathering; + uint64_t GatheringArgs[6] = {Woken, 3, 3, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, GatheringArgs, &Gathering); + const TestEvent Trickle[3] = {{0x51, reinterpret_cast(&KeyA), 1, 0}, {0x52, reinterpret_cast(&KeyB), 1, 0}, + {0x53, reinterpret_cast(&KeyC), 1, 0}}; + Deliver(GatheringArgs, &Trickle[0], sizeof(TestEvent)); + int Waits = 0; + bool Remaining = true; + AioReapHook = [&](const uint64_t* Words) -> long { + ++Waits; + if (Waits == 1) { + Remaining = Remaining && Words[2] == 2 && Words[3] == 2 && Words[4] == reinterpret_cast(Gathering.EventBuffer.data() + EventWords); + return 0; + } + const uint64_t Have = Waits == 2 ? 1 : 2; + Remaining = Remaining && Words[2] == 3 - Have && Words[3] == 3 - Have && + Words[4] == reinterpret_cast(Gathering.EventBuffer.data() + Have * EventWords); + std::memcpy(reinterpret_cast(Words[4]), &Trickle[Have], sizeof(TestEvent)); + return 1; + }; + const auto GatheringResult = FinishSyscallArguments(1, &Gathering); + AioReapHook = nullptr; + Show("io_getevents_slices_accumulate", GatheringResult == 3 && Waits == 3 && Remaining && SealedEvents[0].Data == 0x51 && + SealedEvents[1].Data == 0x52 && SealedEvents[2].Data == 0x53 && SealedEvents[2].Object == reinterpret_cast(&KeyC)); + ArgumentStorage Interrupt; + uint64_t InterruptArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, InterruptArgs, &Interrupt); + const int ReapsInterrupt = AioReaps; + Show("io_getevents_slice_host_eintr", FinishSyscallArguments(0, &Interrupt) == static_cast(-EINTR) && AioReaps == ReapsInterrupt + 1); + FEX::HLE::TestThread.SignalInfo.DeferredSignalFrames.push_back(SIGUSR1); + ArgumentStorage Signalled; + uint64_t SignalledArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, SignalledArgs, &Signalled); + const int ReapsSignalled = AioReaps; + const auto SignalledResult = FinishSyscallArguments(0, &Signalled); + ArgumentStorage SignalledSome; + uint64_t SignalledSomeArgs[6] = {Woken, 2, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, SignalledSomeArgs, &SignalledSome); + Deliver(SignalledSomeArgs, &Trickle[1], sizeof(TestEvent)); + const auto SignalledSomeResult = FinishSyscallArguments(1, &SignalledSome); + FEX::HLE::TestThread.SignalInfo.DeferredSignalFrames.clear(); + Show("io_getevents_slice_deferred_signal", SignalledResult == static_cast(-EINTR) && SignalledSomeResult == 1 && + AioReaps == ReapsSignalled && SealedEvents[0].Data == 0x52); + ArgumentStorage Polled; + uint64_t PolledArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), Immediate, 0}; + Call(Sys::SYSCALL_x64_io_getevents, PolledArgs, &Polled); + const int ReapsPolled = AioReaps; + Show("io_getevents_zero_timeout", PolledArgs[4] == reinterpret_cast(Polled.Wait) && Polled.Wait[0] == 0 && Polled.Wait[1] == 0 && + FinishSyscallArguments(0, &Polled) == 0 && AioReaps == ReapsPolled); + int64_t ShortWait[2] = {0, 1000000}; + ArgumentStorage Timed; + uint64_t TimedArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), reinterpret_cast(ShortWait), 0}; + const auto TimedStart = std::chrono::steady_clock::now(); + Call(Sys::SYSCALL_x64_io_getevents, TimedArgs, &Timed); + const bool TimedFirst = Timed.Wait[0] == 0 && Timed.Wait[1] > 0 && Timed.Wait[1] <= 1000000; + bool TimedBounded = true; + AioReapHook = [&](const uint64_t* Words) -> long { + const auto* Wait = reinterpret_cast(Words[5]); + TimedBounded = TimedBounded && Wait[0] == 0 && Wait[1] > 0 && Wait[1] <= 1000000; + return 0; + }; + const auto TimedResult = FinishSyscallArguments(0, &Timed); + const auto TimedTook = std::chrono::steady_clock::now() - TimedStart; + AioReapHook = nullptr; + Show("io_getevents_timeout_returns_empty", TimedFirst && TimedBounded && TimedResult == 0 && TimedTook >= std::chrono::milliseconds(1) && + ShortWait[0] == 0 && ShortWait[1] == 1000000); + int64_t LongWait[2] = {5, 0}; + uint64_t MaskWords[2] = {0, 8}; + ArgumentStorage Masked; + uint64_t MaskedArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), reinterpret_cast(LongWait), reinterpret_cast(MaskWords)}; + Call(Sys::SYSCALL_x64_io_pgetevents, MaskedArgs, &Masked); + const bool MaskedSliced = Masked.Wait[0] == 0 && Masked.Wait[1] == 20000000 && Masked.Deadline > 0; + AioReapHook = [&](const uint64_t* Words) -> long { + std::memcpy(reinterpret_cast(Words[4]), &Trickle[2], sizeof(TestEvent)); + return 1; + }; + const auto MaskedResult = FinishSyscallArguments(0, &Masked); + AioReapHook = nullptr; + Show("io_pgetevents_slices_keep_mask", MaskedSliced && MaskedResult == 1 && AioReapArgs[0] == SYS_io_pgetevents && + AioReapArgs[6] == reinterpret_cast(MaskWords) && SealedEvents[0].Data == 0x53); + int64_t BadWait[2] = {0, 2000000000}; + ArgumentStorage Unsliced; + uint64_t UnslicedArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), reinterpret_cast(BadWait), 0}; + Call(Sys::SYSCALL_x64_io_getevents, UnslicedArgs, &Unsliced); + const int ReapsUnsliced = AioReaps; + Show("io_getevents_odd_timeout_native", !Unsliced.Blocking && UnslicedArgs[1] == 1 && UnslicedArgs[4] == reinterpret_cast(BadWait) && + FinishSyscallArguments(0, &Unsliced) == 0 && AioReaps == ReapsUnsliced); + uint64_t* Published = static_cast(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + uint32_t LostRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + *Published = reinterpret_cast(LostRing); + ArgumentStorage Unpublished; + uint64_t UnpublishedArgs[6] = {128, reinterpret_cast(Published), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, UnpublishedArgs, &Unpublished); + mprotect(Published, Page, PROT_READ); + Show("io_setup_unpublished_result", FinishSyscallArguments(0, &Unpublished)); + Show("io_setup_unpublished_destroyed", AioDestroyed == reinterpret_cast(LostRing) && + AioContextsLocked().count(reinterpret_cast(LostRing)) == 0); + mprotect(Published, Page, PROT_READ | PROT_WRITE); + uint32_t ReusedRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + const uint64_t Reused = reinterpret_cast(ReusedRing); + *Published = Reused; + uint64_t ReusedGeneration = 0; + AioDestroyHook = [&](uint64_t Ring) { ReusedGeneration = BeginContext(Ring); }; + ArgumentStorage ReusedSetup; + uint64_t ReusedSetupArgs[6] = {128, reinterpret_cast(Published), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, ReusedSetupArgs, &ReusedSetup); + mprotect(Published, Page, PROT_READ); + const auto ReusedResult = FinishSyscallArguments(0, &ReusedSetup); + AioDestroyHook = nullptr; + Show("io_setup_rollback_keeps_reused_context", ReusedResult == static_cast(-EFAULT) && ReusedGeneration != 0 && + AioContextsLocked().count(Reused) == 1 && AioContextsLocked()[Reused].Generation == ReusedGeneration); + ReleaseContext(Reused, ReusedGeneration); + mprotect(Published, Page, PROT_NONE); + ArgumentStorage UnreadableSetup; + uint64_t UnreadableArgs[6] = {128, reinterpret_cast(Published), 0, 0, 0, 0}; + Show("io_setup_unreadable_output_faults", Call(Sys::SYSCALL_x64_io_setup, UnreadableArgs, &UnreadableSetup) == static_cast(-EFAULT) && + UnreadableArgs[1] == reinterpret_cast(Published) && UnreadableSetup.SetupContext == 0 && + FinishSyscallArguments(static_cast(-EFAULT), &UnreadableSetup) == static_cast(-EFAULT)); + munmap(Published, Page); + ArgumentStorage BogusReap; + uint64_t BogusReapArgs[6] = {0x5bad, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, BogusReapArgs, &BogusReap); + FinishSyscallArguments(static_cast(-EINVAL), &BogusReap); + Show("io_getevents_invalid_context_forgotten", AioContextsLocked().count(0x5bad)); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage Pending; + uint64_t PendingArgs[6] = {33, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, PendingArgs, &Pending); + ArgumentStorage Rejected; + uint64_t RejectedArgs[6] = {33, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_pgetevents, RejectedArgs, &Rejected); + FinishSyscallArguments(static_cast(-EINVAL), &Rejected); + mprotect(SealedEvents, Page, PROT_READ); + const TestEvent PendingEvent {0x4a, reinterpret_cast(&KeyB), 1, 0}; + Deliver(PendingArgs, &PendingEvent, sizeof(PendingEvent)); + FinishSyscallArguments(1, &Pending); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage PendingRetry; + uint64_t PendingRetryArgs[6] = {33, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, PendingRetryArgs, &PendingRetry); + Show("io_getevents_rejected_sibling_kept", FinishSyscallArguments(0, &PendingRetry) == 1 && SealedEvents[0].Data == 0x4a); + FailReap(10, {0x33, reinterpret_cast(&KeyC), 1, 0}); + ArgumentStorage StashDestroy; + uint64_t StashDestroyArgs[6] = {10, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, StashDestroyArgs, &StashDestroy); + FinishSyscallArguments(0, &StashDestroy); + ArgumentStorage DestroyedReap; + uint64_t DestroyedReapArgs[6] = {10, 1, 1, reinterpret_cast(SealedEvents), Immediate, 0}; + Call(Sys::SYSCALL_x64_io_getevents, DestroyedReapArgs, &DestroyedReap); + Show("io_getevents_stash_destroyed", DestroyedReapArgs[2] == 1 && FinishSyscallArguments(0, &DestroyedReap) == 0); + ArgumentStorage TripleFailed; + uint64_t TripleFailedArgs[6] = {4, 3, 3, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, TripleFailedArgs, &TripleFailed); + mprotect(SealedEvents, Page, PROT_READ); + const TestEvent Triple[3] = {{0x31, reinterpret_cast(&KeyA), 1, 0}, {0x32, reinterpret_cast(&KeyB), 1, 0}, + {0x33, reinterpret_cast(&KeyC), 1, 0}}; + Deliver(TripleFailedArgs, Triple, sizeof(Triple)); + Show("io_getevents_stash_triple_failed", FinishSyscallArguments(3, &TripleFailed)); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage SealedRetry; + uint64_t SealedRetryArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, SealedRetryArgs, &SealedRetry); + mprotect(SealedEvents, Page, PROT_READ); + Show("io_getevents_stash_retry_failed", FinishSyscallArguments(0, &SealedRetry)); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage OrderedReap; + uint64_t OrderedReapArgs[6] = {4, 3, 3, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, OrderedReapArgs, &OrderedReap); + Show("io_getevents_stash_ordered_result", FinishSyscallArguments(0, &OrderedReap)); + Show("io_getevents_stash_ordered", SealedEvents[0].Data == 0x31 && SealedEvents[1].Data == 0x32 && SealedEvents[2].Data == 0x33 && + SealedEvents[2].Object == reinterpret_cast(&KeyC)); + static TestEvent ManyEvents[100]; + for (uint64_t i = 0; i < 100; ++i) { + ManyEvents[i] = {0x1000 + i, reinterpret_cast(&KeyA), 1, 0}; + } + ArgumentStorage ManyFailed; + uint64_t ManyFailedArgs[6] = {4, 100, 100, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ManyFailedArgs, &ManyFailed); + mprotect(SealedEvents, Page, PROT_READ); + Deliver(ManyFailedArgs, ManyEvents, sizeof(ManyEvents)); + Show("io_getevents_stash_many_failed", FinishSyscallArguments(100, &ManyFailed)); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage ManyRetry; + uint64_t ManyRetryArgs[6] = {4, 100, 100, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ManyRetryArgs, &ManyRetry); + bool ManyOrdered = FinishSyscallArguments(0, &ManyRetry) == 100; + for (uint64_t i = 0; i < 100; ++i) { + ManyOrdered = ManyOrdered && SealedEvents[i].Data == 0x1000 + i; + } + Show("io_getevents_stash_many_kept", ManyOrdered); + for (uint64_t Context = 100; Context < 120; ++Context) { + FailReap(Context, {Context, reinterpret_cast(&KeyA), 1, 0}); + } + bool EveryContext = true; + for (uint64_t Context = 100; Context < 120; ++Context) { + ArgumentStorage ContextRetry; + uint64_t ContextRetryArgs[6] = {Context, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ContextRetryArgs, &ContextRetry); + EveryContext = EveryContext && FinishSyscallArguments(0, &ContextRetry) == 1 && SealedEvents[0].Data == Context; + } + Show("io_getevents_stash_every_context", EveryContext); + TestIocb DirectBlock = ReadBlock; + uint64_t DirectList[1] = {reinterpret_cast(&DirectBlock)}; + auto SubmitDirect = [&] { + ArgumentStorage DirectSubmit; + uint64_t DirectSubmitArgs[6] = {11, 1, reinterpret_cast(DirectList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, DirectSubmitArgs, &DirectSubmit); + const auto Sent = reinterpret_cast(DirectSubmitArgs[2])[0]; + FinishSyscallArguments(1, &DirectSubmit); + return Sent; + }; + const auto DirectBefore = IoCopyCount.load(); + const auto DirectSent = SubmitDirect(); + mprotect(SealedEvents, Page, PROT_READ); + ArgumentStorage DirectReap; + uint64_t DirectReapArgs[6] = {11, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, DirectReapArgs, &DirectReap); + Show("io_getevents_unwritable_first_staged", DirectReapArgs[3] == reinterpret_cast(DirectReap.EventBuffer.data()) && DirectReapArgs[2] == 1); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + const TestEvent DirectEvent {0x21, DirectSent, 64, 0}; + Deliver(DirectReapArgs, &DirectEvent, sizeof(DirectEvent)); + Show("io_getevents_late_writable_result", FinishSyscallArguments(1, &DirectReap)); + Show("io_getevents_late_writable_object", SealedEvents[0].Object == reinterpret_cast(&DirectBlock)); + Show("io_getevents_late_writable_released", IoCopyCount.load() - DirectBefore); + const auto HiddenSent = SubmitDirect(); + SealedEvents[0] = {}; + mprotect(SealedEvents, Page, PROT_READ); + ArgumentStorage HiddenReap; + uint64_t HiddenReapArgs[6] = {11, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, HiddenReapArgs, &HiddenReap); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + const TestEvent HiddenEvent {0x22, HiddenSent, 64, 0}; + Deliver(HiddenReapArgs, &HiddenEvent, sizeof(HiddenEvent)); + mprotect(SealedEvents, Page, PROT_NONE); + Show("io_getevents_hidden_result", FinishSyscallArguments(1, &HiddenReap)); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + Show("io_getevents_hidden_no_private", SealedEvents[0].Object == 0); + Show("io_getevents_hidden_released", IoCopyCount.load() - DirectBefore); + ArgumentStorage HiddenRetry; + uint64_t HiddenRetryArgs[6] = {11, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, HiddenRetryArgs, &HiddenRetry); + Show("io_getevents_hidden_retry", FinishSyscallArguments(0, &HiddenRetry) == 1 && SealedEvents[0].Data == 0x22 && + SealedEvents[0].Object == reinterpret_cast(&DirectBlock)); + ArgumentStorage DirectDestroy; + uint64_t DirectDestroyArgs[6] = {11, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, DirectDestroyArgs, &DirectDestroy); + FinishSyscallArguments(0, &DirectDestroy); + munmap(SealedEvents, Page); + munmap(SealedEvents, Page); + ArgumentStorage WrappedReap; + uint64_t WrappedReapArgs[6] = {4, 1, 1024, 0xFFFF'FFFF'FFFF'F000ULL, 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, WrappedReapArgs, &WrappedReap); + Show("io_getevents_wrapped_staged", WrappedReapArgs[3] == reinterpret_cast(WrappedReap.EventBuffer.data()) && WrappedReapArgs[2] == 1 && + WrappedReap.EventBuffer.size() == sizeof(TestEvent) / sizeof(uint64_t)); + Show("io_getevents_wrapped_result", FinishSyscallArguments(static_cast(-EFAULT), &WrappedReap)); + auto* EdgeEvents = static_cast(mmap(nullptr, 2 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + mprotect(EdgeEvents + Page, Page, PROT_READ); + ArgumentStorage EdgeReap; + uint64_t EdgeReapArgs[6] = {4, 3, 4, reinterpret_cast(EdgeEvents + Page - 2 * sizeof(TestEvent)), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, EdgeReapArgs, &EdgeReap); + Show("io_getevents_writable_prefix", EdgeReapArgs[2]); + Show("io_getevents_writable_min", EdgeReapArgs[1]); + Show("io_getevents_writable_buffer", EdgeReap.EventBuffer.size() * sizeof(uint64_t) / sizeof(TestEvent)); + munmap(EdgeEvents, 2 * Page); + uint32_t Ring[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + uint64_t RingContext = reinterpret_cast(Ring); + ArgumentStorage Setup; + uint64_t SetupArgs[6] = {128, reinterpret_cast(&RingContext), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, SetupArgs, &Setup); + FinishSyscallArguments(0, &Setup); + Show("io_setup_magic", Ring[4]); + Show("io_setup_header_kept", Ring[0] == 0 && Ring[1] == 128 && Ring[2] == 0 && Ring[3] == 0 && Ring[5] == 1 && Ring[6] == 0 && Ring[7] == 32); + uint32_t KeptRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + uint64_t KeptContext = reinterpret_cast(KeptRing); + ArgumentStorage FailedSetup; + uint64_t FailedSetupArgs[6] = {128, reinterpret_cast(&KeptContext), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, FailedSetupArgs, &FailedSetup); + FinishSyscallArguments(static_cast(-EINVAL), &FailedSetup); + Show("io_setup_failed_magic", KeptRing[4]); + + TestEvent Completions[2] = {{7, Base + 1536, 16, 0}, {8, Base + 1536, 16, 0}}; + ArgumentStorage Reap; + uint64_t ReapArgs[6] = {1, 1, 2, reinterpret_cast(Completions), 0, 0}; + Show("io_getevents_result", Call(Sys::SYSCALL_x64_io_getevents, ReapArgs, &Reap)); + Deliver(ReapArgs, Completions, sizeof(Completions)); + FinishSyscallArguments(1, &Reap); + Show("io_getevents_object", Completions[0].Object - Single); + Show("io_getevents_unreported", Completions[1].Object - Base); + + uint64_t Pages[2] = {Single + 16, Low}; + int PageStatus[2] = {}; + ArgumentStorage Move; + uint64_t MoveArgs[6] = {0, 2, reinterpret_cast(Pages), 0, reinterpret_cast(PageStatus), 0}; + Show("move_pages_result", Call(Sys::SYSCALL_x64_move_pages, MoveArgs, &Move)); + Show("move_pages_copied", MoveArgs[2] != reinterpret_cast(Pages)); + Show("move_pages_first", reinterpret_cast(MoveArgs[2])[0] - Base); + Show("move_pages_second", reinterpret_cast(MoveArgs[2])[1] == Low); + Show("move_pages_guest_list", Pages[0] - Single); + ArgumentStorage Remote; + uint64_t RemoteArgs[6] = {1, 2, reinterpret_cast(Pages), 0, reinterpret_cast(PageStatus), 0}; + Show("move_pages_remote_result", Call(Sys::SYSCALL_x64_move_pages, RemoteArgs, &Remote)); + Show("move_pages_remote_kept", RemoteArgs[2] == reinterpret_cast(Pages)); + + uint32_t LowWord = 0; + uint64_t Waiters[2][3] = {{0, Single + 64, 2}, {0, reinterpret_cast(&LowWord), 2}}; + ArgumentStorage Wait; + uint64_t WaitArgs[6] = {reinterpret_cast(Waiters), 2, 0, 0, 1, 0}; + Show("futex_waitv_result", Call(Sys::SYSCALL_x64_futex_waitv, WaitArgs, &Wait)); + Show("futex_waitv_copied", WaitArgs[0] != reinterpret_cast(Waiters)); + Show("futex_waitv_first", reinterpret_cast(WaitArgs[0])[1] - Base); + Show("futex_waitv_second", reinterpret_cast(WaitArgs[0])[4] == reinterpret_cast(&LowWord)); + Show("futex_waitv_guest", Waiters[0][1] - Single); + uint64_t Straddling[1][3] = {{0, Split + Page - 2, 2}}; + ArgumentStorage WaitBad; + uint64_t WaitBadArgs[6] = {reinterpret_cast(Straddling), 1, 0, 0, 1, 0}; + Show("futex_waitv_split_result", Call(Sys::SYSCALL_x64_futex_waitv, WaitBadArgs, &WaitBad)); + uint64_t Requeue[2][3] = {{0, Single + 64, 2}, {0, Single + 128, 2}}; + ArgumentStorage RequeueStorage; + uint64_t RequeueArgs[6] = {reinterpret_cast(Requeue), 0, 1, 1, 0, 0}; + Show("futex_requeue_result", Call(Sys::SYSCALL_x64_futex_requeue, RequeueArgs, &RequeueStorage)); + Show("futex_requeue_second", reinterpret_cast(RequeueArgs[0])[4] - Base); + + const uint64_t Mapped = 0x780000000000ULL; + const int Anonymous = MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED; + Show("map_result", Map(Mapped, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0) - Mapped); + const uint32_t MappedEntries = Count.load(); + Show("map_unmap", Unmap(Mapped + Page, Page)); + Show("map_again", Map(Mapped + Page, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0) - Mapped); + FindLocked(Mapped, &Part); + Show("map_merged_size", Part.Size); + Show("map_merged_entries", Count.load() - MappedEntries); + Show("map_unmap_again", Unmap(Mapped + Page, Page)); + Show("map_readonly", Map(Mapped + Page, Page, PROT_READ, Anonymous, -1, 0) - Mapped); + FindLocked(Mapped, &Part); + Show("map_readonly_size", Part.Size); + Show("map_readonly_entries", Count.load() - MappedEntries); + + auto* Order = static_cast(mmap(nullptr, 5 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t OrderHost = reinterpret_cast(Order); + const uint64_t Ordered = 0x770000000000ULL; + const uint32_t OrderEntries = Count.load(); + AddEntry(Ordered + Page, Page, OrderHost + Page, false, PROT_READ); + AddEntry(Ordered + 3 * Page, Page, OrderHost + 4 * Page, false, PROT_READ); + AddEntry(Ordered, Page, OrderHost, false, PROT_READ); + AddEntry(Ordered + 2 * Page, Page, OrderHost + 3 * Page, false, PROT_READ); + Show("slot_order_restore", Protect(Ordered, 4 * Page, PROT_READ | PROT_WRITE)); + Show("slot_order_entries", Count.load() - OrderEntries); + FindLocked(Ordered + 2 * Page, &Part); + Show("slot_order_second_size", Part.Size); + + ArgumentStorage Widths; + uint64_t GroupsWide[6] = {(1ULL << 32) + 1, Single + Page - 4, 0, 0, 0, 0}; + Show("getgroups_wide_result", Call(Sys::SYSCALL_x64_getgroups, GroupsWide, &Widths)); + Show("getgroups_wide_list", GroupsWide[1] - Base); + uint64_t GroupsNegative[6] = {0xffffffffULL, Single + Page - 4, 0, 0, 0, 0}; + Show("getgroups_negative_result", Call(Sys::SYSCALL_x64_getgroups, GroupsNegative, &Widths)); + uint64_t GroupsLarge[6] = {(1ULL << 32) + 2, Single + Page - 4, 0, 0, 0, 0}; + Show("getgroups_large_result", Call(Sys::SYSCALL_x64_getgroups, GroupsLarge, &Widths)); + uint64_t PollWide[6] = {Single + Page - 8, (1ULL << 32) + 1, 0, 0, 0, 0}; + Show("poll_wide_result", Call(Sys::SYSCALL_x64_poll, PollWide, &Widths)); + uint64_t EpollNegative[6] = {3, Single + Page - 12, 0xffffffffULL, 0, 0, 0}; + Show("epoll_negative_result", Call(Sys::SYSCALL_x64_epoll_wait, EpollNegative, &Widths)); + ArgumentStorage NegativeReap; + uint64_t EventsNegative[6] = {1, 1, static_cast(-1), Single, 0, 0}; + Show("io_getevents_negative_result", Call(Sys::SYSCALL_x64_io_getevents, EventsNegative, &NegativeReap)); + + struct iovec PrefixVectors[2] = {{reinterpret_cast(Single + 256), 32}, {reinterpret_cast(Split + Page - 8), 16}}; + struct mmsghdr Prefix[2] {}; + Prefix[0].msg_hdr.msg_iov = &PrefixVectors[0]; + Prefix[0].msg_hdr.msg_iovlen = 1; + Prefix[1].msg_hdr.msg_iov = &PrefixVectors[1]; + Prefix[1].msg_hdr.msg_iovlen = 1; + ArgumentStorage PrefixBatch; + uint64_t PrefixArgs[6] = {3, reinterpret_cast(Prefix), 2, 0, 0, 0}; + Show("sendmmsg_prefix_result", Call(Sys::SYSCALL_x64_sendmmsg, PrefixArgs, &PrefixBatch)); + Show("sendmmsg_prefix_count", PrefixArgs[2]); + ArgumentStorage PrefixBad; + uint64_t PrefixBadArgs[6] = {3, reinterpret_cast(&Prefix[1]), 1, 0, 0, 0}; + Show("sendmmsg_first_bad_result", Call(Sys::SYSCALL_x64_sendmmsg, PrefixBadArgs, &PrefixBad)); + auto* ApartFirst = reinterpret_cast(Backing + 3 * Page - sizeof(struct mmsghdr)); + auto* ApartSecond = reinterpret_cast(Backing + 4 * Page); + char ApartLow[32]; + struct iovec ApartVectors[2] = {{ApartLow, 11}, {ApartLow, 22}}; + *ApartFirst = {}; + ApartFirst->msg_hdr.msg_iov = &ApartVectors[0]; + ApartFirst->msg_hdr.msg_iovlen = 1; + *ApartSecond = {}; + ApartSecond->msg_hdr.msg_iov = &ApartVectors[1]; + ApartSecond->msg_hdr.msg_iovlen = 1; + ArgumentStorage ApartBatch; + uint64_t HeadersApart[6] = {static_cast(Peer), Split + Page - sizeof(struct mmsghdr), 2, 0, 0, 0}; + Show("sendmmsg_headers_apart_result", Call(Sys::SYSCALL_x64_sendmmsg, HeadersApart, &ApartBatch)); + Show("sendmmsg_headers_apart_count", HeadersApart[2]); + auto* ApartHost = reinterpret_cast(HeadersApart[1]); + Show("sendmmsg_headers_apart_first", ApartHost[0].msg_hdr.msg_iov[0].iov_len); + Show("sendmmsg_headers_apart_second", ApartHost[1].msg_hdr.msg_iov[0].iov_len); + SendCalls = 0; + ApartHost[0].msg_len = 11; + Show("sendmmsg_headers_apart_finish", FinishResult(1, &ApartBatch)); + Show("sendmmsg_headers_apart_sent", SentLengths[0]); + Show("sendmmsg_headers_apart_lengths", ApartFirst->msg_len * 0x100 + ApartSecond->msg_len); + + struct iovec MovingVector = {reinterpret_cast(Single + 256), 32}; + const uint64_t Moving = 0x760000000000ULL; + Map(Moving, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t OldHost {}; + TranslateRange(Moving, Page, &OldHost); + auto* MovingHeaders = reinterpret_cast(OldHost); + MovingHeaders[0] = {}; + MovingHeaders[0].msg_hdr.msg_iov = &MovingVector; + MovingHeaders[0].msg_hdr.msg_iovlen = 1; + ArgumentStorage MovingBatch; + uint64_t MovingArgs[6] = {3, Moving, 1, 0, 0, 0}; + Show("moved_result", Call(Sys::SYSCALL_x64_sendmmsg, MovingArgs, &MovingBatch)); + reinterpret_cast(MovingArgs[1])[0].msg_len = 32; + Unmap(Moving, Page); + auto* Unrelated = static_cast(mmap(reinterpret_cast(OldHost), Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0)); + Map(Moving, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t NewHost {}; + TranslateRange(Moving, Page, &NewHost); + Show("moved_finish", FinishResult(1, &MovingBatch)); + Show("moved_unrelated_placed", reinterpret_cast(Unrelated) == OldHost && NewHost != OldHost); + Show("moved_unrelated_length", Unrelated[0].msg_len); + Show("moved_new_length", reinterpret_cast(NewHost)[0].msg_len); + + const uint64_t Sealed = 0x750000000000ULL; + Map(Sealed, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t SealedHost {}; + TranslateRange(Sealed, 2 * Page, &SealedHost); + auto* SealedHeaders = reinterpret_cast(SealedHost + Page - sizeof(struct mmsghdr)); + for (int i = 0; i < 3; ++i) { + SealedHeaders[i] = {}; + SealedHeaders[i].msg_hdr.msg_iov = &MovingVector; + SealedHeaders[i].msg_hdr.msg_iovlen = 1; + } + Protect(Sealed + Page, Page, PROT_READ); + ArgumentStorage SealedBatch; + uint64_t SealedArgs[6] = {static_cast(Peer), Sealed + Page - sizeof(struct mmsghdr), 3, 0, 0, 0}; + Show("sealed_result", Call(Sys::SYSCALL_x64_sendmmsg, SealedArgs, &SealedBatch)); + Show("sealed_submitted", SealedArgs[2]); + auto* SealedCopy = reinterpret_cast(SealedArgs[1]); + SealedCopy[0].msg_len = 32; + SendCalls = 0; + Show("sealed_finish", FinishResult(1, &SealedBatch)); + Show("sealed_later_sends", SendCalls); + Show("sealed_first_length", SealedHeaders[0].msg_len); + Show("sealed_second_length", SealedHeaders[1].msg_len); + Show("sealed_third_length", SealedHeaders[2].msg_len); + ArgumentStorage SealedOnly; + uint64_t SealedOnlyArgs[6] = {3, Sealed + Page, 1, 0, 0, 0}; + Show("sealed_only_result", Call(Sys::SYSCALL_x64_sendmmsg, SealedOnlyArgs, &SealedOnly)); + reinterpret_cast(SealedOnlyArgs[1])[0].msg_len = 32; + Show("sealed_only_finish", FinishResult(1, &SealedOnly)); + + ArgumentStorage Embedded; + uint8_t* SplitEnd = Backing + 3 * Page; + const uint32_t Sizes32[] = {64, 0, 72}; + const char* PerfNames[] = {"perf_attr_fits_result", "perf_attr_default_result", "perf_attr_large_result"}; + for (int i = 0; i < 3; ++i) { + std::memcpy(SplitEnd - 64 + 4, &Sizes32[i], 4); + uint64_t PerfArgs[6] = {Split + Page - 64, 0, static_cast(-1), static_cast(-1), 0, 0}; + Show(PerfNames[i], Call(Sys::SYSCALL_x64_perf_event_open, PerfArgs, &Embedded)); + } + const uint32_t SchedSizes[] = {48, 56}; + const char* SchedNames[] = {"sched_attr_fits_result", "sched_attr_large_result"}; + for (int i = 0; i < 2; ++i) { + std::memcpy(SplitEnd - 48, &SchedSizes[i], 4); + uint64_t SchedArgs[6] = {0, Split + Page - 48, 0, 0, 0, 0}; + Show(SchedNames[i], Call(Sys::SYSCALL_x64_sched_setattr, SchedArgs, &Embedded)); + } + const uint32_t CapHeader1[2] = {0x19980330, 0}; + const uint32_t CapHeader3[2] = {0x20080522, 0}; + uint64_t CapV1[6] = {reinterpret_cast(CapHeader1), Split + Page - 12, 0, 0, 0, 0}; + Show("capget_v1_result", Call(Sys::SYSCALL_x64_capget, CapV1, &Embedded)); + Show("capget_v1_data", CapV1[1] - Base); + uint64_t CapV3[6] = {reinterpret_cast(CapHeader3), Split + Page - 12, 0, 0, 0, 0}; + Show("capget_v3_result", Call(Sys::SYSCALL_x64_capget, CapV3, &Embedded)); + uint64_t CapSetV3[6] = {reinterpret_cast(CapHeader3), Split + Page - 12, 0, 0, 0, 0}; + Show("capset_v3_result", Call(Sys::SYSCALL_x64_capset, CapSetV3, &Embedded)); + uint32_t CapGuest[2] = {0x19980330, 0}; + ArgumentStorage CapCopy; + uint64_t CapCopyArgs[6] = {reinterpret_cast(CapGuest), Split + Page - 12, 0, 0, 0, 0}; + Show("capget_copy_result", Call(Sys::SYSCALL_x64_capget, CapCopyArgs, &CapCopy)); + Show("capget_copy_private", CapCopyArgs[0] != reinterpret_cast(CapGuest)); + CapGuest[0] = 0x20080522; + Show("capget_copy_version", reinterpret_cast(CapCopyArgs[0])[0]); + Show("capget_copy_finish", FinishResult(0, &CapCopy)); + Show("capget_copy_guest_version", CapGuest[0]); + uint32_t CapUnknown[2] = {0x1234, 0}; + ArgumentStorage CapInvalid; + uint64_t CapInvalidArgs[6] = {reinterpret_cast(CapUnknown), Single + 64, 0, 0, 0, 0}; + Show("capget_invalid_result", Call(Sys::SYSCALL_x64_capget, CapInvalidArgs, &CapInvalid)); + reinterpret_cast(CapInvalidArgs[0])[0] = 0x20080522; + Show("capget_invalid_finish", FinishResult(static_cast(-EINVAL), &CapInvalid)); + Show("capget_invalid_version", CapUnknown[0]); + const uint32_t HandleBytes[] = {8, 16}; + const char* HandleNames[] = {"name_to_handle_fits_result", "name_to_handle_large_result"}; + const char* OpenNames[] = {"open_by_handle_fits_result", "open_by_handle_large_result"}; + int MountId = 0; + for (int i = 0; i < 2; ++i) { + std::memcpy(SplitEnd - 16, &HandleBytes[i], 4); + uint64_t HandleArgs[6] = {static_cast(AT_FDCWD), reinterpret_cast("x"), Split + Page - 16, reinterpret_cast(&MountId), 0, 0}; + Show(HandleNames[i], Call(Sys::SYSCALL_x64_name_to_handle_at, HandleArgs, &Embedded)); + uint64_t OpenArgs[6] = {3, Split + Page - 16, 0, 0, 0, 0}; + Show(OpenNames[i], Call(Sys::SYSCALL_x64_open_by_handle_at, OpenArgs, &Embedded)); + } + const uint32_t OversizedHandle = 1000; + std::memcpy(SplitEnd - 4, &OversizedHandle, 4); + uint64_t HandleHeaderSplit[6] = {static_cast(AT_FDCWD), reinterpret_cast("x"), Split + Page - 4, reinterpret_cast(&MountId), 0, 0}; + Show("name_to_handle_header_split_result", Call(Sys::SYSCALL_x64_name_to_handle_at, HandleHeaderSplit, &Embedded)); + uint64_t OpenHeaderSplit[6] = {3, Split + Page - 4, 0, 0, 0, 0}; + Show("open_by_handle_header_split_result", Call(Sys::SYSCALL_x64_open_by_handle_at, OpenHeaderSplit, &Embedded)); + std::memcpy(SplitEnd - 8, &OversizedHandle, 4); + uint64_t OpenHeaderFits[6] = {3, Split + Page - 8, 0, 0, 0, 0}; + Show("open_by_handle_header_fits_result", Call(Sys::SYSCALL_x64_open_by_handle_at, OpenHeaderFits, &Embedded)); + const uint32_t RequestSizes[] = {24, 32}; + const char* RequestNames[] = {"statmount_fits_result", "statmount_large_result"}; + for (int i = 0; i < 2; ++i) { + std::memcpy(SplitEnd - 24, &RequestSizes[i], 4); + uint64_t RequestArgs[6] = {Split + Page - 24, 0, 0, 0, 0, 0}; + Show(RequestNames[i], Call(Sys::SYSCALL_x64_statmount, RequestArgs, &Embedded)); + } + uint64_t PathRule[6] = {3, 1, Split + Page - 12, 0, 0, 0}; + Show("landlock_path_result", Call(Sys::SYSCALL_x64_landlock_add_rule, PathRule, &Embedded)); + uint64_t PortRule[6] = {3, 2, Split + Page - 12, 0, 0, 0}; + Show("landlock_port_result", Call(Sys::SYSCALL_x64_landlock_add_rule, PortRule, &Embedded)); + + const uint64_t Nameless = 0x740000000000ULL; + Map(Nameless, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t NamelessHost {}; + TranslateRange(Nameless, 2 * Page, &NamelessHost); + const uint64_t NamelessGuestHeader = Nameless + Page - 16; + auto* NamelessHeader = reinterpret_cast(NamelessHost + Page - 16); + struct iovec NamelessVector = {reinterpret_cast(Single + 128), 64}; + *NamelessHeader = {}; + NamelessHeader->msg_iov = &NamelessVector; + NamelessHeader->msg_iovlen = 1; + Protect(Nameless, Page, PROT_READ); + ArgumentStorage NamelessReceive; + uint64_t NamelessArgs[6] = {3, NamelessGuestHeader, 0, 0, 0, 0}; + Show("recvmsg_nameless_result", Call(Sys::SYSCALL_x64_recvmsg, NamelessArgs, &NamelessReceive)); + NamelessReceive.Message.msg_flags = MSG_TRUNC; + Show("recvmsg_nameless_finish", FinishResult(64, &NamelessReceive)); + Show("recvmsg_nameless_flags", NamelessHeader->msg_flags); + char NameBuffer[16]; + const uint64_t Named = 0x700000000000ULL; + Map(Named, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t NamedHost {}; + TranslateRange(Named, 2 * Page, &NamedHost); + auto* NamedHeader = reinterpret_cast(NamedHost + Page - 16); + *NamedHeader = {}; + NamedHeader->msg_name = NameBuffer; + NamedHeader->msg_namelen = sizeof(NameBuffer); + NamedHeader->msg_iov = &NamelessVector; + NamedHeader->msg_iovlen = 1; + Protect(Named, Page, PROT_READ); + ArgumentStorage NamedReceive; + uint64_t NamedArgs[6] = {3, Named + Page - 16, 0, 0, 0, 0}; + Show("recvmsg_named_result", Call(Sys::SYSCALL_x64_recvmsg, NamedArgs, &NamedReceive)); + Show("recvmsg_named_private", NamedArgs[1] != NamedHost + Page - 16); + Show("recvmsg_named_name_kept", reinterpret_cast(NamedArgs[1])->msg_name == NameBuffer); + Show("recvmsg_named_finish", FinishResult(64, &NamedReceive)); + + const uint64_t Flagged = 0x730000000000ULL; + Map(Flagged, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t FlaggedHost {}; + TranslateRange(Flagged, 2 * Page, &FlaggedHost); + auto* FlaggedHeader = reinterpret_cast(FlaggedHost + Page - offsetof(struct msghdr, msg_flags)); + *FlaggedHeader = {}; + FlaggedHeader->msg_iov = &NamelessVector; + FlaggedHeader->msg_iovlen = 1; + FlaggedHeader->msg_controllen = 99; + Protect(Flagged + Page, Page, PROT_READ); + ArgumentStorage FlaggedReceive; + uint64_t FlaggedArgs[6] = {3, Flagged + Page - offsetof(struct msghdr, msg_flags), 0, 0, 0, 0}; + Show("recvmsg_flags_first_result", Call(Sys::SYSCALL_x64_recvmsg, FlaggedArgs, &FlaggedReceive)); + FlaggedReceive.Message.msg_controllen = 0; + Show("recvmsg_flags_first_finish", FinishResult(64, &FlaggedReceive)); + Show("recvmsg_flags_first_controllen", FlaggedHeader->msg_controllen); + + const uint64_t Blocks = 0x720000000000ULL; + Map(Blocks, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t BlocksHost {}; + TranslateRange(Blocks, Page, &BlocksHost); + auto* HighIocb = reinterpret_cast(BlocksHost); + *HighIocb = {}; + HighIocb->Data = 0x99; + HighIocb->Opcode = 7; + HighIocb->Buffer = reinterpret_cast(Scatter); + HighIocb->Bytes = 2; + const TestIocb HighExpected = *HighIocb; + uint64_t HighIocbList[1] = {Blocks}; + ArgumentStorage HighCopy; + uint64_t HighCopyArgs[6] = {1, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Show("io_submit_high_copy_result", Call(Sys::SYSCALL_x64_io_submit, HighCopyArgs, &HighCopy)); + const uint64_t HighSent = reinterpret_cast(HighCopyArgs[2])[0]; + Show("io_submit_high_copy_private", HighSent != BlocksHost && FindIoCopyLocked(HighSent) != nullptr); + Show("io_submit_high_copy_vector", reinterpret_cast(reinterpret_cast(HighSent)->Buffer)[0].iov_base == reinterpret_cast(Base + 800)); + Show("io_submit_high_copy_untouched", std::memcmp(HighIocb, &HighExpected, sizeof(TestIocb)) == 0); + ArgumentStorage HighCancel; + uint64_t HighCancelArgs[6] = {1, Blocks, reinterpret_cast(&CancelEvent), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, HighCancelArgs, &HighCancel); + Show("io_cancel_high_private", HighCancelArgs[1] == HighSent); + Show("io_submit_high_copy_hidden", Protect(Blocks, Page, PROT_NONE)); + uint64_t SealedProbe = 0; + auto HiddenRead = [&] { return FEX::HLE::FaultSafeUserMemAccess::CopyFromUser(&SealedProbe, &HighIocb->Buffer, sizeof(SealedProbe)) != 0; }; + auto HiddenWrite = [&] { return FEX::HLE::FaultSafeUserMemAccess::CopyToUser(&HighIocb->Buffer, &SealedProbe, sizeof(SealedProbe)) != 0; }; + ProtectCalls = 0; + FinishSyscallArguments(1, &HighCopy); + Show("io_submit_high_copy_sealed", HiddenRead() && HiddenWrite()); + ArgumentStorage HiddenCancel; + uint64_t HiddenCancelArgs[6] = {1, Blocks, reinterpret_cast(&CancelEvent), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, HiddenCancelArgs, &HiddenCancel); + Show("io_cancel_hidden_native", HiddenCancelArgs[1] == BlocksHost); + TestEvent HighReaped[1] = {{0x99, HighSent, 16, 0}}; + ArgumentStorage HighReap; + uint64_t HighReapArgs[6] = {1, 1, 1, reinterpret_cast(HighReaped), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, HighReapArgs, &HighReap); + Deliver(HighReapArgs, HighReaped, sizeof(HighReaped)); + FinishSyscallArguments(1, &HighReap); + Show("io_getevents_high_object", HighReaped[0].Object - Blocks); + Show("io_getevents_high_sealed", HiddenRead() && HiddenWrite()); + Show("io_getevents_high_protect_calls", ProtectCalls); + Show("io_getevents_high_freed", IoCopyCount.load() - CopiesBefore); + Protect(Blocks, Page, PROT_READ | PROT_WRITE); + Show("io_getevents_high_untouched", std::memcmp(HighIocb, &HighExpected, sizeof(TestIocb)) == 0); + + Protect(Blocks, Page, PROT_READ); + ArgumentStorage SealedSubmit; + uint64_t SealedSubmitArgs[6] = {1, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Show("io_submit_read_only_result", Call(Sys::SYSCALL_x64_io_submit, SealedSubmitArgs, &SealedSubmit)); + Show("io_submit_read_only_count", SealedSubmitArgs[1]); + Show("io_submit_read_only_passed", reinterpret_cast(SealedSubmitArgs[2])[0] == BlocksHost); + Show("io_submit_read_only_copies", IoCopyCount.load() - CopiesBefore); + FinishSyscallArguments(static_cast(-EBADF), &SealedSubmit); + TestIocb Leading = ReadBlock; + uint64_t LeadingList[2] = {reinterpret_cast(&Leading), Blocks}; + ArgumentStorage LeadingSubmit; + uint64_t LeadingSubmitArgs[6] = {5, 2, reinterpret_cast(LeadingList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, LeadingSubmitArgs, &LeadingSubmit); + const auto* LeadingSent = reinterpret_cast(LeadingSubmitArgs[2]); + Show("io_submit_read_only_after_copy", LeadingSubmitArgs[1] == 2 && FindIoCopyLocked(LeadingSent[0]) != nullptr && LeadingSent[1] == BlocksHost); + FinishSyscallArguments(1, &LeadingSubmit); + ArgumentStorage LeadingDestroy; + uint64_t LeadingDestroyArgs[6] = {5, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, LeadingDestroyArgs, &LeadingDestroy); + FinishSyscallArguments(0, &LeadingDestroy); + Show("io_submit_read_only_after_copy_released", IoCopyCount.load() - CopiesBefore); + Show("io_submit_read_only_untouched", std::memcmp(HighIocb, &HighExpected, sizeof(TestIocb)) == 0); + Protect(Blocks, Page, PROT_READ | PROT_WRITE); + HighIocb->Opcode = 1; + HighIocb->Buffer = reinterpret_cast(LowBuffer); + HighIocb->Bytes = sizeof(LowBuffer); + Protect(Blocks, Page, PROT_READ); + ArgumentStorage ReadOnlyNative; + uint64_t ReadOnlyNativeArgs[6] = {1, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Show("io_submit_read_only_native_result", Call(Sys::SYSCALL_x64_io_submit, ReadOnlyNativeArgs, &ReadOnlyNative)); + Show("io_submit_read_only_native_block", reinterpret_cast(ReadOnlyNativeArgs[2])[0] == BlocksHost); + Show("io_submit_read_only_native_copies", IoCopyCount.load() - CopiesBefore); + Protect(Blocks, Page, PROT_READ | PROT_WRITE); + HighIocb->Opcode = 7; + HighIocb->Buffer = reinterpret_cast(Scatter); + HighIocb->Bytes = 2; + HighIocb->Key = 4; + ArgumentStorage KeyedHigh; + uint64_t KeyedHighArgs[6] = {7, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, KeyedHighArgs, &KeyedHigh); + FinishSyscallArguments(1, &KeyedHigh); + Show("io_submit_high_key_accepted", HighIocb->Key); + HighIocb->Key = 4; + ArgumentStorage MovedHigh; + uint64_t MovedHighArgs[6] = {7, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, MovedHighArgs, &MovedHigh); + Unmap(Blocks, Page); + void* ReusedPage = mmap(reinterpret_cast(BlocksHost), Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0); + Show("io_submit_key_reused_mapped", ReusedPage == reinterpret_cast(BlocksHost)); + if (ReusedPage == reinterpret_cast(BlocksHost)) { + static_cast(ReusedPage)->Key = 4; + FinishSyscallArguments(1, &MovedHigh); + Show("io_submit_key_unmapped_skipped", static_cast(ReusedPage)->Key); + munmap(ReusedPage, Page); + } + Map(Blocks, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + static uint64_t RacedHost; + static uint32_t RacedSeen; + static TestIocb* RacedStandIn; + static std::thread RacedSibling; + static std::atomic RacedAttempted; + static bool RacedBlocked; + TranslateRange(Blocks, Page, &RacedHost); + auto* RacedIocb = reinterpret_cast(RacedHost); + *RacedIocb = {}; + RacedIocb->Opcode = 7; + RacedIocb->Buffer = reinterpret_cast(Scatter); + RacedIocb->Bytes = 2; + RacedIocb->Key = 4; + ArgumentStorage RacedHigh; + uint64_t RacedHighArgs[6] = {7, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, RacedHighArgs, &RacedHigh); + FEX::HLE::FaultSafeUserMemAccess::BeforeUserWrite = [] { + RacedSibling = std::thread([] { + std::unique_lock Lock {FEX::HLE::_SyscallHandler->VMATracking.Mutex, std::try_to_lock}; + RacedBlocked = !Lock.owns_lock(); + RacedAttempted = 1; + if (!Lock.owns_lock()) { + Lock.lock(); + } + RacedSeen = reinterpret_cast(RacedHost)->Key; + Unmap(Blocks, Page); + void* StandIn = mmap(reinterpret_cast(RacedHost), Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0); + if (StandIn == reinterpret_cast(RacedHost)) { + RacedStandIn = static_cast(StandIn); + RacedStandIn->Key = 4; + } + }); + while (RacedAttempted.load() == 0) { + std::this_thread::yield(); + } + }; + FinishSyscallArguments(1, &RacedHigh); + RacedSibling.join(); + Show("io_submit_key_store_blocked_writer", RacedBlocked); + Show("io_submit_key_store_before_unmap", RacedSeen); + Show("io_submit_key_store_stand_in", RacedStandIn != nullptr ? RacedStandIn->Key : 0xff); + Show("io_submit_key_store_released", FEX::HLE::TestThread.HighMemoryTrap.Mappings.Held); + if (RacedStandIn != nullptr) { + munmap(RacedStandIn, Page); + } + ArgumentStorage KeyedDestroy; + uint64_t KeyedDestroyArgs[6] = {7, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, KeyedDestroyArgs, &KeyedDestroy); + FinishSyscallArguments(0, &KeyedDestroy); + Show("io_submit_keyed_high_released", IoCopyCount.load() - CopiesBefore); + + auto* LowBlock = static_cast(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + *LowBlock = {}; + LowBlock->Opcode = 7; + LowBlock->Buffer = reinterpret_cast(Scatter); + LowBlock->Bytes = 2; + const TestIocb LowExpected = *LowBlock; + uint64_t LowList[1] = {reinterpret_cast(LowBlock)}; + ArgumentStorage LowCopy; + uint64_t LowCopyArgs[6] = {1, 1, reinterpret_cast(LowList), 0, 0, 0}; + Show("low_iocb_result", Call(Sys::SYSCALL_x64_io_submit, LowCopyArgs, &LowCopy)); + const uint64_t LowSent = reinterpret_cast(LowCopyArgs[2])[0]; + Show("low_iocb_private", LowSent != reinterpret_cast(LowBlock) && FindIoCopyLocked(LowSent) != nullptr); + mprotect(LowBlock, Page, PROT_READ); + ProtectCalls = 0; + FinishSyscallArguments(1, &LowCopy); + Show("low_iocb_untouched", std::memcmp(LowBlock, &LowExpected, sizeof(TestIocb)) == 0); + const auto Regions = Count.load(); + Count.store(0); + ArgumentStorage QuietCancel; + uint64_t QuietCancelArgs[6] = {1, reinterpret_cast(LowBlock), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, QuietCancelArgs, &QuietCancel); + Show("low_iocb_quiet_cancel", QuietCancelArgs[1] == LowSent); + TestEvent QuietReaped[1] = {{0, LowSent, 16, 0}}; + ArgumentStorage QuietReap; + uint64_t QuietReapArgs[6] = {1, 1, 1, reinterpret_cast(QuietReaped), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, QuietReapArgs, &QuietReap); + Show("low_iocb_quiet_host_buffer", QuietReapArgs[3] == reinterpret_cast(QuietReap.EventBuffer.data())); + Deliver(QuietReapArgs, QuietReaped, sizeof(QuietReaped)); + FinishSyscallArguments(1, &QuietReap); + uint32_t QuietRing[8] = {0, 64, 0, 0, 0xa10a10a1, 1, 0, 32}; + uint64_t QuietRingContext = reinterpret_cast(QuietRing); + ArgumentStorage QuietSetup; + uint64_t QuietSetupArgs[6] = {64, reinterpret_cast(&QuietRingContext), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, QuietSetupArgs, &QuietSetup); + FinishSyscallArguments(0, &QuietSetup); + Show("low_quiet_setup_magic", QuietRing[4]); + Count.store(Regions); + Show("low_iocb_quiet_object", QuietReaped[0].Object == reinterpret_cast(LowBlock)); + Show("low_iocb_quiet_freed", IoCopyCount.load() - CopiesBefore); + Show("low_iocb_protect_calls", ProtectCalls); + Show("low_iocb_reaped_untouched", std::memcmp(LowBlock, &LowExpected, sizeof(TestIocb)) == 0); + munmap(LowBlock, Page); + + for (auto& Copy : IoCopies) { + Copy.Used = true; + } + IoCopyCount = MaxIoCopies; + ArgumentStorage Crowded; + uint64_t CrowdedArgs[6] = {1, 2, reinterpret_cast(Submitted), 0, 0, 0}; + Show("io_submit_crowded_result", Call(Sys::SYSCALL_x64_io_submit, CrowdedArgs, &Crowded)); + Show("io_submit_crowded_untouched", GuestBlocksUntouched()); + IoCopies[5].Used = false; + IoCopyCount = MaxIoCopies - 1; + ArgumentStorage LastCopy; + uint64_t LastCopyArgs[6] = {1, 2, reinterpret_cast(Submitted), 0, 0, 0}; + Show("io_submit_last_copy_result", Call(Sys::SYSCALL_x64_io_submit, LastCopyArgs, &LastCopy)); + Show("io_submit_last_copy_count", LastCopyArgs[1]); + Show("io_submit_last_copy_slot", reinterpret_cast(LastCopyArgs[2])[0] == reinterpret_cast(&IoCopies[5])); + for (auto& Copy : IoCopies) { + Copy.Used = false; + } + IoCopyCount = 0; + + auto* CapPage = static_cast(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + CapPage[0] = 0x1234; + ArgumentStorage CapSealed; + uint64_t CapSealedArgs[6] = {reinterpret_cast(CapPage), Single + 64, 0, 0, 0, 0}; + Show("capget_sealed_result", Call(Sys::SYSCALL_x64_capget, CapSealedArgs, &CapSealed)); + reinterpret_cast(CapSealedArgs[0])[0] = 0x20080522; + mprotect(CapPage, Page, PROT_READ); + Show("capget_sealed_finish", FinishResult(static_cast(-EINVAL), &CapSealed)); + Show("capget_sealed_version", CapPage[0]); + + struct iovec ShortVector = {reinterpret_cast(Single + 256), 32}; + struct mmsghdr Shorts[3] {}; + for (auto& Short : Shorts) { + Short.msg_hdr.msg_iov = &ShortVector; + Short.msg_hdr.msg_iovlen = 1; + } + ArgumentStorage ShortFirst; + uint64_t ShortFirstArgs[6] = {static_cast(Peer), reinterpret_cast(Shorts), 3, 0, 0, 0}; + Show("sendmmsg_short_first_result", Call(Sys::SYSCALL_x64_sendmmsg, ShortFirstArgs, &ShortFirst)); + reinterpret_cast(ShortFirstArgs[1])[0].msg_len = 10; + SendCalls = 0; + Show("sendmmsg_short_first_finish", FinishResult(1, &ShortFirst)); + Show("sendmmsg_short_first_sends", SendCalls); + Show("sendmmsg_short_first_lengths", Shorts[0].msg_len * 0x10000 + Shorts[1].msg_len * 0x100 + Shorts[2].msg_len); + for (auto& Short : Shorts) { + Short.msg_len = 0; + } + ArgumentStorage ShortSecond; + uint64_t ShortSecondArgs[6] = {static_cast(Peer), reinterpret_cast(Shorts), 3, 0, 0, 0}; + Show("sendmmsg_short_second_result", Call(Sys::SYSCALL_x64_sendmmsg, ShortSecondArgs, &ShortSecond)); + Show("sendmmsg_short_second_submitted", ShortSecondArgs[2]); + const int Pinned = ShortSecond.Socket; + Show("sendmmsg_pinned_distinct", Pinned >= 0 && Pinned != Peer); + Show("sendmmsg_pinned_dispatched", ShortSecondArgs[0] == static_cast(Pinned)); + reinterpret_cast(ShortSecondArgs[1])[0].msg_len = 32; + SendCalls = 0; + SendLimit = 5; + SentSocket = -1; + Show("sendmmsg_short_second_finish", FinishResult(1, &ShortSecond)); + SendLimit = ~size_t {}; + Show("sendmmsg_short_second_sends", SendCalls); + Show("sendmmsg_short_second_lengths", Shorts[0].msg_len * 0x10000 + Shorts[1].msg_len * 0x100 + Shorts[2].msg_len); + Show("sendmmsg_pinned_used", SentSocket == Pinned); + Show("sendmmsg_pinned_closed", fcntl(Pinned, F_GETFD) == -1 && errno == EBADF && ShortSecond.Socket == -1); + for (auto& Short : Shorts) { + Short.msg_len = 0; + } + ArgumentStorage ShortFailed; + uint64_t ShortFailedArgs[6] = {static_cast(Peer), reinterpret_cast(Shorts), 3, 0, 0, 0}; + Call(Sys::SYSCALL_x64_sendmmsg, ShortFailedArgs, &ShortFailed); + const int FailedPin = ShortFailed.Socket; + Show("sendmmsg_error_finish", FinishResult(static_cast(-EAGAIN), &ShortFailed)); + Show("sendmmsg_error_closed", FailedPin >= 0 && fcntl(FailedPin, F_GETFD) == -1 && errno == EBADF); + int Pair[2]; + if (socketpair(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0, Pair) != 0) { + std::fprintf(stderr, "socketpair: %s\n", std::strerror(errno)); + return 1; + } + struct iovec Payloads[3] = {}; + for (int i = 0; i < 3; ++i) { + std::memset(Backing + 2048 + 16 * i, 'A' + i, 4); + Payloads[i] = {reinterpret_cast(Single + 2048 + 16 * i), 4}; + } + auto Drain = [&] { + uint64_t Packed = 0; + unsigned char Data[16]; + while (recv(Pair[1], Data, sizeof(Data), MSG_DONTWAIT) > 0) { + Packed = Packed * 0x100 + Data[0]; + } + return Packed; + }; + auto Dispatch = [&](uint64_t* Args) { + return static_cast(sendmmsg(static_cast(Args[0]), reinterpret_cast(Args[1]), static_cast(Args[2]), 0)); + }; + auto Lengths = [&](struct mmsghdr* Headers) { + return Headers[0].msg_len * 0x10000 + Headers[1].msg_len * 0x100 + Headers[2].msg_len; + }; + PassSend = true; + + struct mmsghdr Real[3] {}; + for (int i = 0; i < 3; ++i) { + Real[i].msg_hdr.msg_iov = &Payloads[i]; + Real[i].msg_hdr.msg_iovlen = 1; + } + DupFailures = 1; + ArgumentStorage Emfile; + uint64_t EmfileArgs[6] = {static_cast(Pair[0]), reinterpret_cast(Real), 3, 0, 0, 0}; + Show("sendmmsg_emfile_result", Call(Sys::SYSCALL_x64_sendmmsg, EmfileArgs, &Emfile)); + Show("sendmmsg_emfile_submitted", EmfileArgs[2]); + Show("sendmmsg_emfile_original", EmfileArgs[0] == static_cast(Pair[0]) && Emfile.Socket == -1 && DupFailures == 0); + Show("sendmmsg_emfile_first_only", Drain()); + Show("sendmmsg_emfile_finish", FinishResult(Dispatch(EmfileArgs), &Emfile)); + Show("sendmmsg_emfile_received", Drain()); + Show("sendmmsg_emfile_lengths", Lengths(Real)); + + const uint64_t ReadOnly = 0x730000000000ULL; + Map(ReadOnly, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t ReadOnlyHost {}; + TranslateRange(ReadOnly, 2 * Page, &ReadOnlyHost); + auto* ReadOnlyHeaders = reinterpret_cast(ReadOnlyHost + Page - sizeof(struct mmsghdr)); + for (int i = 0; i < 3; ++i) { + ReadOnlyHeaders[i] = {}; + ReadOnlyHeaders[i].msg_hdr.msg_iov = &Payloads[i]; + ReadOnlyHeaders[i].msg_hdr.msg_iovlen = 1; + } + Protect(ReadOnly + Page, Page, PROT_READ); + DupFailures = 1; + ArgumentStorage ReadOnlyBatch; + uint64_t ReadOnlyArgs[6] = {static_cast(Pair[0]), ReadOnly + Page - sizeof(struct mmsghdr), 3, 0, 0, 0}; + Show("sendmmsg_emfile_readonly_result", Call(Sys::SYSCALL_x64_sendmmsg, ReadOnlyArgs, &ReadOnlyBatch)); + Show("sendmmsg_emfile_readonly_submitted", ReadOnlyArgs[2]); + Show("sendmmsg_emfile_readonly_finish", FinishResult(Dispatch(ReadOnlyArgs), &ReadOnlyBatch)); + Show("sendmmsg_emfile_readonly_received", Drain()); + Show("sendmmsg_emfile_readonly_lengths", Lengths(ReadOnlyHeaders)); + + DupFailures = 1; + ArgumentStorage ReadOnlyFirst; + uint64_t ReadOnlyFirstArgs[6] = {static_cast(Pair[0]), ReadOnly + Page, 1, 0, 0, 0}; + Show("sendmmsg_emfile_only_result", Call(Sys::SYSCALL_x64_sendmmsg, ReadOnlyFirstArgs, &ReadOnlyFirst)); + Show("sendmmsg_emfile_only_finish", FinishResult(Dispatch(ReadOnlyFirstArgs), &ReadOnlyFirst)); + Show("sendmmsg_emfile_only_received", Drain()); + DupFailures = 0; + + auto* Unreadable = static_cast(mmap(nullptr, Page, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + struct mmsghdr Middle[3] {}; + for (int i = 0; i < 3; ++i) { + Middle[i].msg_hdr.msg_iov = i == 1 ? Unreadable : &Payloads[i]; + Middle[i].msg_hdr.msg_iovlen = 1; + } + ArgumentStorage MiddleBatch; + uint64_t MiddleArgs[6] = {static_cast(Pair[0]), reinterpret_cast(Middle), 3, 0, 0, 0}; + Show("sendmmsg_unreadable_middle_result", Call(Sys::SYSCALL_x64_sendmmsg, MiddleArgs, &MiddleBatch)); + Show("sendmmsg_unreadable_middle_submitted", MiddleArgs[2]); + Show("sendmmsg_unreadable_middle_queued", MiddleBatch.Messages.size()); + Show("sendmmsg_unreadable_middle_finish", FinishResult(Dispatch(MiddleArgs), &MiddleBatch)); + Show("sendmmsg_unreadable_middle_received", Drain()); + Show("sendmmsg_unreadable_middle_lengths", Lengths(Middle)); + + struct mmsghdr Last[3] {}; + for (int i = 0; i < 3; ++i) { + Last[i].msg_hdr.msg_iov = i == 2 ? Unreadable : &Payloads[i]; + Last[i].msg_hdr.msg_iovlen = 1; + } + ArgumentStorage LastBatch; + uint64_t LastArgs[6] = {static_cast(Pair[0]), reinterpret_cast(Last), 3, 0, 0, 0}; + Show("sendmmsg_unreadable_last_result", Call(Sys::SYSCALL_x64_sendmmsg, LastArgs, &LastBatch)); + Show("sendmmsg_unreadable_last_submitted", LastArgs[2]); + Show("sendmmsg_unreadable_last_queued", LastBatch.Messages.size()); + const int LastPin = LastBatch.Socket; + Show("sendmmsg_unreadable_last_pinned", LastPin >= 0 && LastArgs[0] == static_cast(LastPin)); + Show("sendmmsg_unreadable_last_finish", FinishResult(Dispatch(LastArgs), &LastBatch)); + Show("sendmmsg_unreadable_last_received", Drain()); + Show("sendmmsg_unreadable_last_lengths", Lengths(Last)); + + struct mmsghdr First[3] {}; + for (int i = 0; i < 3; ++i) { + First[i].msg_hdr.msg_iov = i == 0 ? Unreadable : &Payloads[i]; + First[i].msg_hdr.msg_iovlen = 1; + } + ArgumentStorage FirstBatch; + uint64_t FirstArgs[6] = {static_cast(Pair[0]), reinterpret_cast(First), 3, 0, 0, 0}; + Show("sendmmsg_unreadable_first_result", Call(Sys::SYSCALL_x64_sendmmsg, FirstArgs, &FirstBatch)); + Show("sendmmsg_unreadable_first_native", FirstArgs[1] == reinterpret_cast(First) && FirstArgs[2] == 3 && FirstBatch.GuestMessages == 0); + Show("sendmmsg_unreadable_first_error", static_cast(sendmmsg(Pair[0], First, 3, 0)) == static_cast(-1) && errno == EFAULT); + Show("sendmmsg_unreadable_first_received", Drain()); + PassSend = false; + + auto* LowVectors = static_cast(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + char KeptLow[16]; + LowVectors[0] = {KeptLow, sizeof(KeptLow)}; + struct mmsghdr Growing[3] {}; + Growing[0].msg_hdr.msg_iov = &ShortVector; + Growing[0].msg_hdr.msg_iovlen = 1; + for (int i = 1; i < 3; ++i) { + Growing[i].msg_hdr.msg_iov = LowVectors; + Growing[i].msg_hdr.msg_iovlen = 1; + } + ArgumentStorage Grown; + uint64_t GrownArgs[6] = {static_cast(Peer), reinterpret_cast(Growing), 3, 0, 0, 0}; + Show("sendmmsg_grown_result", Call(Sys::SYSCALL_x64_sendmmsg, GrownArgs, &Grown)); + auto* GrownCopy = reinterpret_cast(GrownArgs[1]); + Show("sendmmsg_grown_private", GrownCopy[1].msg_hdr.msg_iov != LowVectors && GrownCopy[1].msg_hdr.msg_iov[0].iov_base == KeptLow); + GrownCopy[0].msg_len = 32; + SendCalls = 0; + GrowAfterSend = LowVectors; + Show("sendmmsg_grown_finish", FinishResult(1, &Grown)); + GrowAfterSend = nullptr; + Show("sendmmsg_grown_sends", SendCalls); + Show("sendmmsg_grown_lengths", Growing[0].msg_len * 0x10000 + Growing[1].msg_len * 0x100 + Growing[2].msg_len); + for (auto& Message : Growing) { + Message.msg_len = 0; + } + LowVectors[0] = {KeptLow, sizeof(KeptLow)}; + ArgumentStorage Vanished; + uint64_t VanishedArgs[6] = {static_cast(Peer), reinterpret_cast(Growing), 3, 0, 0, 0}; + Show("sendmmsg_vanished_result", Call(Sys::SYSCALL_x64_sendmmsg, VanishedArgs, &Vanished)); + reinterpret_cast(VanishedArgs[1])[0].msg_len = 32; + SendCalls = 0; + SendLimit = 5; + UnmapAfterSend = LowVectors; + Show("sendmmsg_vanished_finish", FinishResult(1, &Vanished)); + SendLimit = ~size_t {}; + Show("sendmmsg_vanished_sends", SendCalls); + Show("sendmmsg_vanished_unmapped", UnmapAfterSend == nullptr && msync(LowVectors, Page, MS_ASYNC) == -1 && errno == ENOMEM); + Show("sendmmsg_vanished_lengths", Growing[0].msg_len * 0x10000 + Growing[1].msg_len * 0x100 + Growing[2].msg_len); + + uint64_t AccessRegs[32] {}; + AccessRegs[0] = 0x10000; + AccessRegs[2] = 0xfffffffeULL; + auto Decode = [&](const char* Name, uint32_t Insn) { + uint64_t Address {}; + uint32_t Size {}; + bool Plain {}; + const bool Known = DecodeAccess(Insn, AccessRegs, &Address, &Size, &Plain); + std::printf("decode_%s_known %x\n", Name, Known); + std::printf("decode_%s_offset %llx\n", Name, static_cast(Address - AccessRegs[0])); + std::printf("decode_%s_size %x\n", Name, Size); + std::printf("decode_%s_plain %x\n", Name, Plain); + }; + Decode("str_x_imm", 0xf9000401); + Decode("ldr_x_pre", 0xf85fcc01); + Decode("ldr_x_post", 0xf8408401); + Decode("stur_x", 0xf81fc001); + Decode("ldr_w_lsl", 0xb8627801); + Decode("ldr_w_sxtw", 0xb862c801); + Decode("ldr_w_uxtw", 0xb8624801); + Decode("ldr_w_reserved", 0xb8620801); + Decode("stp_x", 0xa9010c01); + Decode("ldp_w_negative", 0x297f0c01); + Decode("ldp_q_post", 0xacc10c01); + Decode("str_q", 0x3d800401); + Decode("ld1_four", 0x4c402001); + Decode("st1_post", 0x4c9f7c01); + Decode("ld1_lane", 0x0d409001); + Decode("ld4r", 0x4d60e801); + Decode("ldadd", 0xf8210002); + Decode("ldar", 0xc8dffc01); + Decode("casp", 0x48227c04); + Decode("ldxp", 0xc87f0c01); + Decode("ldapur", 0x995fc001); + Decode("ldraa", 0xf8200400); + + auto* Backings = static_cast(mmap(nullptr, 6 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Backed = reinterpret_cast(Backings); + const uint64_t SeparateGuest = 0x6f0000000000ULL; + const uint64_t Adjacent = 0x6f0000100000ULL; + AddEntry(SeparateGuest, Page, Backed, false, PROT_READ | PROT_WRITE); + AddEntry(SeparateGuest + Page, Page, Backed + 2 * Page, false, PROT_READ | PROT_WRITE); + AddEntry(Adjacent, Page, Backed + 4 * Page, false, PROT_READ | PROT_WRITE); + AddEntry(Adjacent + Page, Page, Backed + 5 * Page, false, PROT_READ | PROT_WRITE); + std::memset(Backings + Page, 0xee, Page); + uint64_t StoreRegs[32] {}; + StoreRegs[0] = SeparateGuest + Page - 4; + StoreRegs[1] = 0x1122334455667788ULL; + uint64_t SplitAddress {}; + uint32_t SplitSize {}; + bool SplitPlain {}; + DecodeAccess(0xf9000001, StoreRegs, &SplitAddress, &SplitSize, &SplitPlain); + AccessPiece SplitPieces[MaxAccessPieces] {}; + const auto SplitParts = PlanAccessLocked(SplitAddress, SplitSize, SplitPieces); + Show("split_access_parts", SplitParts); + Show("split_access_first", SplitPieces[0].Host - Backed); + Show("split_access_second", SplitPieces[1].Host - Backed); + Show("split_access_sizes", SplitPieces[0].Size * 0x10 + SplitPieces[1].Size); + Show("split_access_guests", (SplitPieces[0].Guest == SeparateGuest + Page - 4) * 0x10 + (SplitPieces[1].Guest == SeparateGuest + Page)); + Show("split_access_contiguous", HostContiguous(SplitPieces, SplitParts)); + Show("split_access_store_reachable", PiecesReachable(SplitPieces, SplitParts, true)); + alignas(16) uint8_t Window[96] {}; + const auto WindowOffset = SplitAddress & 15; + CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, true); + std::memcpy(Window + WindowOffset, &StoreRegs[1], sizeof(StoreRegs[1])); + CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, false); + uint32_t SplitWords[3] {}; + std::memcpy(&SplitWords[0], Backings + Page - 4, 4); + std::memcpy(&SplitWords[1], Backings + 2 * Page, 4); + std::memcpy(&SplitWords[2], Backings + Page, 4); + Show("split_store_low", SplitWords[0]); + Show("split_store_high", SplitWords[1]); + Show("split_store_neighbour", SplitWords[2]); + std::memset(Window, 0, sizeof(Window)); + CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, true); + uint64_t SplitLoaded {}; + std::memcpy(&SplitLoaded, Window + WindowOffset, sizeof(SplitLoaded)); + Show("split_load_value", SplitLoaded); + SplitPieces[1].Prot = PROT_READ; + Show("split_readonly_store", PiecesReachable(SplitPieces, SplitParts, true)); + Show("split_readonly_load", PiecesReachable(SplitPieces, SplitParts, false)); + SplitPieces[1].Prot = PROT_NONE; + Show("split_none_load", PiecesReachable(SplitPieces, SplitParts, false)); + AccessPiece EdgePieces[MaxAccessPieces] {}; + Show("split_unmapped_parts", PlanAccessLocked(SeparateGuest + 2 * Page - 4, 8, EdgePieces)); + Show("split_inside_parts", PlanAccessLocked(SeparateGuest + 16, 64, EdgePieces)); + Show("split_inside_host", EdgePieces[0].Host - Backed); + AccessPiece JoinedPieces[MaxAccessPieces] {}; + const auto JoinedParts = PlanAccessLocked(Adjacent + Page - 4, 8, JoinedPieces); + Show("joined_access_parts", JoinedParts); + Show("joined_access_contiguous", HostContiguous(JoinedPieces, JoinedParts)); + Show("joined_access_delta", JoinedPieces[0].Host - (Adjacent + Page - 4) == Backed + 4 * Page - Adjacent); + + uint64_t OrderedRegs[32] {}; + Show("ordered_load_parts", EmulateOrdered(0xd9400001, SplitPieces, SplitParts, OrderedRegs)); + Show("ordered_load_value", OrderedRegs[1]); + OrderedRegs[1] = 0xa1a2a3a4b5b6b7b8ULL; + Show("ordered_store_parts", EmulateOrdered(0xd9000001, SplitPieces, SplitParts, OrderedRegs)); + uint32_t OrderedWords[2] {}; + std::memcpy(&OrderedWords[0], Backings + Page - 4, 4); + std::memcpy(&OrderedWords[1], Backings + 2 * Page, 4); + Show("ordered_store_low", OrderedWords[0]); + Show("ordered_store_high", OrderedWords[1]); + AccessPiece WordPieces[MaxAccessPieces] {}; + const auto WordParts = PlanAccessLocked(SeparateGuest + Page - 2, 4, WordPieces); + OrderedRegs[1] = 0; + Show("ordered_signed_parts", EmulateOrdered(0x99800001, WordPieces, WordParts, OrderedRegs) == WordParts && WordParts == 2); + Show("ordered_signed_value", OrderedRegs[1]); + mprotect(Backings + 2 * Page, Page, PROT_NONE); + OrderedRegs[1] = 0x77; + Show("ordered_fault_parts", EmulateOrdered(0xd9400001, SplitPieces, SplitParts, OrderedRegs)); + Show("ordered_fault_untouched", OrderedRegs[1]); + Show("gather_fault_piece", CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, true)); + Show("scatter_fault_piece", CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, false)); + mprotect(Backings + 2 * Page, Page, PROT_READ | PROT_WRITE); + Show("gather_whole", CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, true)); + Show("probe_instruction", ProbeInstruction(16)); + Show("probe_instruction_low", ProbeInstruction(2)); + auto OrderedKind = [](uint32_t Insn) { return static_cast(IsOrderedAccess(Insn)); }; + Show("ordered_kinds", OrderedKind(0xd9400001) << 20 | OrderedKind(0x99800001) << 16 | OrderedKind(0xc8dffc01) << 12 | OrderedKind(0xc89ffc01) << 8 | + OrderedKind(0xf8bfc001) << 4 | OrderedKind(0xf9400001)); + Show("ordered_atomics", OrderedKind(0xf8210002) << 8 | OrderedKind(0x48227c04) << 4 | OrderedKind(0xc87f0c01)); + auto WriteKind = [](uint32_t Insn) { return static_cast(IsWrite(Insn)); }; + Show("write_loads", WriteKind(0xb9800001) << 20 | WriteKind(0x99800001) << 16 | WriteKind(0x39c00001) << 12 | WriteKind(0xf9400001) << 8 | + WriteKind(0x3dc00401) << 4 | WriteKind(0xd9400001)); + Show("write_stores", WriteKind(0xf9000001) << 12 | WriteKind(0xd9000001) << 8 | WriteKind(0x3d800401) << 4 | WriteKind(0x39000001)); + Show("extend_signed_half_w", ExtendOrdered(0x59c00001, 0x8001)); + Show("extend_signed_half_x", ExtendOrdered(0x59800001, 0x8001)); + Show("extend_unsigned_byte", ExtendOrdered(0x19400001, 0x80)); + Show("extend_ldar", ExtendOrdered(0x889ffc01 | (1U << 22), 0x80000000)); + + TestHold Held {}; + std::atomic WriterIn {0}; + uint64_t HoldResults[4] {}; + std::thread Holder([&] { + { + MappingHold Hold {Held}; + Hold.Keep(); + } + HoldResults[0] = Held.Held; + std::thread Writer([&] { + std::unique_lock Exclusive {FEX::HLE::_SyscallHandler->VMATracking.Mutex}; + WriterIn = 1; + }); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + HoldResults[1] = WriterIn.load(); + ReleaseMappings(Held); + Writer.join(); + HoldResults[2] = WriterIn.load() * 0x10 + Held.Held; + { + MappingHold Hold {Held}; + } + HoldResults[3] = ExclusiveFromAnotherThread() * 0x10 + Held.Held; + }); + Holder.join(); + Show("hold_kept_held", HoldResults[0]); + Show("hold_blocks_writer", HoldResults[1]); + Show("hold_released", HoldResults[2]); + Show("hold_scoped", HoldResults[3]); + + struct sigaction TrapAction {}; + TrapAction.sa_sigaction = CountTrap; + TrapAction.sa_flags = SA_SIGINFO; + sigaction(SIGTRAP, &TrapAction, nullptr); + uint64_t DeferResults[12] {}; + std::thread Deferring([&] { + siginfo_t User {}; + User.si_signo = SIGTRAP; + User.si_code = SI_QUEUE; + User.si_pid = getpid(); + User.si_uid = getuid(); + User.si_value.sival_int = 0x1234; + siginfo_t Breakpoint {}; + Breakpoint.si_signo = SIGTRAP; + Breakpoint.si_code = TRAP_BRKPT; + TestHold Deferred {}; + DeferResults[0] = DeferWhileHeld(Deferred, SIGTRAP, &User); + { + MappingHold Hold {Deferred}; + Hold.Keep(); + } + sigset_t Current; + pthread_sigmask(SIG_BLOCK, nullptr, &Current); + DeferResults[1] = sigismember(&Current, SIGTRAP) * 0x100 + sigismember(&Current, SIGSEGV) * 0x10 + sigismember(&Current, SIGILL); + DeferResults[2] = DeferWhileHeld(Deferred, SIGTRAP, &User) * 0x100 + DeferWhileHeld(Deferred, SIGTRAP, &Breakpoint) * 0x10 + + DeferWhileHeld(Deferred, SIGILL, &User); + DeferResults[3] = TrapsSeen.load(); + DeferResults[4] = ReleaseMappings(Deferred); + DeferResults[5] = TrapsSeen.load() * 0x10 + Deferred.Held; + DeferResults[6] = ExclusiveFromAnotherThread(); + sigset_t Trap; + sigemptyset(&Trap); + sigaddset(&Trap, SIGTRAP); + pthread_sigmask(SIG_UNBLOCK, &Trap, nullptr); + DeferResults[7] = TrapsSeen.load(); + DeferResults[8] = static_cast(TrapCode.load()) * 0x10000ULL + static_cast(TrapValue.load()); + { + MappingHold Hold {Deferred}; + User.si_value.sival_int = 0x5678; + DeferWhileHeld(Deferred, SIGTRAP, &User); + } + DeferResults[9] = TrapsSeen.load(); + pthread_sigmask(SIG_BLOCK, nullptr, &Current); + DeferResults[10] = sigismember(&Current, SIGTRAP); + pthread_sigmask(SIG_UNBLOCK, &Trap, nullptr); + DeferResults[11] = TrapsSeen.load() * 0x10000ULL + static_cast(TrapValue.load()); + }); + Deferring.join(); + Show("defer_unheld", DeferResults[0]); + Show("defer_held_mask", DeferResults[1]); + Show("defer_kinds", DeferResults[2]); + Show("defer_not_run_while_held", DeferResults[3]); + Show("defer_requeued", DeferResults[4]); + Show("defer_after_release", DeferResults[5]); + Show("defer_lock_free", DeferResults[6]); + Show("defer_delivered", DeferResults[7]); + Show("defer_info", DeferResults[8]); + Show("defer_scoped_pending", DeferResults[9]); + Show("defer_scoped_blocked", DeferResults[10]); + Show("defer_scoped_delivered", DeferResults[11]); + const uint64_t Delivering = 0x730000000000ULL; + Map(Delivering, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + static int TrapsBefore; + TrapsBefore = TrapsSeen.load(); + FEX::HLE::FaultSafeUserMemAccess::BeforeUserWrite = [] { + siginfo_t User {}; + User.si_signo = SIGTRAP; + User.si_code = SI_QUEUE; + User.si_pid = getpid(); + User.si_uid = getuid(); + DeferWhileHeld(FEX::HLE::TestThread.HighMemoryTrap.Mappings, SIGTRAP, &User); + }; + const uint32_t DeliveringValue = 0x5a; + Show("guest_store_deferred_result", CopyToGuest(Delivering, &DeliveringValue, sizeof(DeliveringValue))); + Show("guest_store_deferred_delivered", TrapsSeen.load() - TrapsBefore); + sigset_t AfterStore; + pthread_sigmask(SIG_BLOCK, nullptr, &AfterStore); + Show("guest_store_deferred_unblocked", !sigismember(&AfterStore, SIGTRAP)); + Unmap(Delivering, Page); + return 0; +} +""" + + +def added_lines(text, path): + lines = [] + inside = False + for line in text.splitlines(): + if line.startswith("diff --git "): + inside = line.endswith(" b/" + path) + continue + if inside and line.startswith("+") and not line.startswith("+++"): + lines.append(line[1:]) + return lines + + +def block(lines, signature): + start = next(i for i, line in enumerate(lines) if line.lstrip().startswith(signature)) + indent = lines[start][: len(lines[start]) - len(lines[start].lstrip())] + if lines[start].rstrip().endswith(";"): + return lines[start] + end = next(i for i in range(start + 1, len(lines)) if lines[i] in (indent + "}", indent + "};")) + return "\n".join(lines[start:end + 1]) + + +def span(lines, first, stop): + start = next(i for i, line in enumerate(lines) if line.startswith(first)) + end = next(i for i in range(start + 1, len(lines)) if lines[i].startswith(stop)) + return "\n".join(lines[start:end]) + + +def syscall_enum(code): + entries = [] + for name in sorted(set(re.findall(r"SYSCALL_x64_(\w+)", code))): + kernel = KERNEL_NAMES.get(name, name) + fallback = NEWER_SYSCALLS.get(name) + if fallback is None: + entries.append(f"SYSCALL_x64_{name} = __NR_{kernel},") + else: + entries.append(f"#ifdef __NR_{kernel}\nSYSCALL_x64_{name} = __NR_{kernel},\n#else\nSYSCALL_x64_{name} = {fallback},\n#endif") + return "enum Syscalls_x64 : int {\n" + "\n".join(entries) + "\n};" + + +def harness(): + text = PATCH.read_text() + source = added_lines(text, SOURCE) + header = [line for line in added_lines(text, HEADER) if not line.startswith(("#pragma", "#include