Merge remote-tracking branch 'origin/main' into frozen-session-disk-spill

This commit is contained in:
Kurt Himebauch committed 2026-12-05 04:08:34 -05:00
commit 088e9994a0
104 files changed
+15184 -317

No files matched your search

+1
View File
@@ -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.
+2
View File
@@ -40,6 +40,8 @@
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_VISUAL_USER_SELECTED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.HIGH_SAMPLING_RATE_SENSORS" />
+24 -10
View File
@@ -329,16 +329,28 @@ static constexpr int kWatchedFds = 1 << 16;
static constexpr int kWatchedBits = sizeof(unsigned long) * 8;
static std::atomic<unsigned long> watched_fds[kWatchedFds / kWatchedBits];
static std::atomic<bool> watched_beyond{false};
static std::atomic<int> 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<decltype(&::poll)>(Next::poll);
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(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<struct pollfd> 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<decltype(&::ppoll)>(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<int>(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<decltype(&::select)>(Next::select);
if (!any_watched())
return my_select ? my_select(nfds, readfds, writefds, exceptfds, timeout) : -1;
fd_set original_readfds;
fd_set original_writefds;
+20 -4
View File
@@ -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;
@@ -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;
@@ -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);
@@ -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;
@@ -661,6 +661,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var effects by mutableStateOf(ScreenEffects.OFF)
private var observedScreenEffectsProfileId by mutableStateOf<String?>(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<SteamVr.Status?>(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())
}
@@ -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()
}
}
@@ -66,11 +66,14 @@ object ProtonExtras {
internal fun installedIn(dir: File, tool: Tool): List<String> =
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
@@ -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 {
@@ -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<android.net.Uri, String>()
val photosCopying = mutableStateMapOf<android.net.Uri, Any>()
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<String
var focused by remember { mutableStateOf(false) }
val field = remember { FocusRequester() }
LaunchedEffect(composer.focusRequests) { if (composer.hasUnconsumedFocusRequest()) runCatching { field.requestFocus() } }
val attach = LocalActivityResultRegistryOwner.current != null
val picks = LocalActivityResultRegistryOwner.current != null
val density = LocalDensity.current
val imeHeight = WindowInsets.ime.getBottom(density)
LaunchedEffect(imeHeight) {
val height = with(density) { imeHeight.toDp() }
if (height > 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<String
Modifier.fillMaxWidth().focusRequester(field).onFocusChanged {
focused = it.isFocused
composer.focused = it.isFocused
if (it.isFocused) composer.tray = false
if (it.isFocused) composer.consumeFocusRequest()
}.testTag("agent-input"),
textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface),
@@ -866,19 +907,22 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
if (stacked) Column {
text(Modifier.fillMaxWidth())
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() }
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() }
AnimatedVisibility(!hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton(composer.tray, toggleTray) }
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp).horizontalScroll(rememberScrollState(), reverseScrolling = true)) { if (controls != null && !focused) controls() }
actions()
}
} else Row(verticalAlignment = Alignment.Bottom) {
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() }
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() }
AnimatedVisibility(!hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton(composer.tray, toggleTray) }
text(Modifier.weight(1f))
if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() }
actions()
}
}
AnimatedVisibility(composer.tray, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
val most = LocalConfiguration.current.screenHeightDp.dp * 0.45f
val height = (if (composer.keyboardHeight > 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
@@ -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<String> = 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<Photo> = 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<Uri>, current: () -> Boolean = { true }, onCopied: (List<Pair<Uri, String>>) -> 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<Uri, String>, copying: SnapshotStateMap<Uri, Any>, onFiles: (() -> Unit)?) {
val context = LocalContext.current
val pal = LocalPalette.current
var access by remember { mutableStateOf(AgentPhotos.access(context)) }
var photos by remember { mutableStateOf<List<AgentPhotos.Photo>?>(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),
)
}
}
@@ -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<Boolean?>(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()
}
}
}
}
@@ -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<Pair<Int, String>>,
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 " ✓")
}
}
}
@@ -706,7 +706,8 @@ private fun TestList(tests: List<Release>, 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),
@@ -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();
+7
View File
@@ -1180,6 +1180,11 @@
<string name="agent_tools_missing">أدوات الوكيل غير مثبتة: %1$s</string>
<string name="agent_unqueue">لا تُرسل</string>
<string name="agent_attach">إرفاق</string>
<string name="agent_attach_files">الملفات</string>
<string name="agent_photos_allow">السماح بالوصول إلى الصور</string>
<string name="agent_photos_more">اختيار المزيد من الصور</string>
<string name="agent_photos_empty">لا توجد صور بعد</string>
<string name="agent_keyboard">لوحة المفاتيح</string>
<string name="agent_remove_attachment">إزالة</string>
<string name="agent_model_default">الافتراضي</string>
<string name="agent_effort">جهد الاستدلال</string>
@@ -4325,4 +4330,6 @@
<string name="glasses_shortcut_group">اختصار داخل اللعبة</string>
<string name="glasses_show_shortcut">إظهار اختصار النظارات الذكية</string>
<string name="glasses_show_shortcut_hint">إظهار زر النظارات الذكية العائم فوق اللعبة.</string>
<string name="display_filter_game_profile">استخدام ملف تعريف %1$s: %2$s</string>
<string name="display_filter_default_profile">استخدام الملف التعريفي الافتراضي: %1$s</string>
</resources>
@@ -1198,6 +1198,11 @@
<string name="agent_tools_missing">Herramientas del agente sin instalar: %1$s</string>
<string name="agent_unqueue">No enviar</string>
<string name="agent_attach">Adjuntar</string>
<string name="agent_attach_files">Archivos</string>
<string name="agent_photos_allow">Permitir acceso a fotos</string>
<string name="agent_photos_more">Elegir más fotos</string>
<string name="agent_photos_empty">Aún no hay fotos</string>
<string name="agent_keyboard">Teclado</string>
<string name="agent_remove_attachment">Quitar</string>
<string name="agent_model_default">Predeterminado</string>
<string name="agent_effort">Esfuerzo de razonamiento</string>
@@ -4203,4 +4208,6 @@
<string name="glasses_shortcut_group">Acceso directo en el juego</string>
<string name="glasses_show_shortcut">Mostrar acceso directo de Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Mostrar el botón flotante de Smart Glasses sobre el juego.</string>
<string name="display_filter_game_profile">Usando el perfil %1$s: %2$s</string>
<string name="display_filter_default_profile">Usando el perfil predeterminado: %1$s</string>
</resources>
+7
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">Инструментите на агента не са инсталирани: %1$s</string>
<string name="agent_unqueue">Не изпращай</string>
<string name="agent_attach">Прикачи</string>
<string name="agent_attach_files">Файлове</string>
<string name="agent_photos_allow">Разрешаване на достъп до снимки</string>
<string name="agent_photos_more">Избор на още снимки</string>
<string name="agent_photos_empty">Все още няма снимки</string>
<string name="agent_keyboard">Клавиатура</string>
<string name="agent_remove_attachment">Премахни</string>
<string name="agent_model_default">По подразбиране</string>
<string name="agent_effort">Усилие за разсъждение</string>
@@ -4165,4 +4170,6 @@
<string name="glasses_shortcut_group">Пряк път в играта</string>
<string name="glasses_show_shortcut">Показване на прекия път за Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Показва плаващия бутон за Smart Glasses върху играта.</string>
<string name="display_filter_game_profile">Използва се профил %1$s: %2$s</string>
<string name="display_filter_default_profile">Използва се профилът по подразбиране: %1$s</string>
</resources>
+7
View File
@@ -1174,6 +1174,11 @@
<string name="agent_tools_missing">Nástroje agenta nejsou nainstalované: %1$s</string>
<string name="agent_unqueue">Neposílat</string>
<string name="agent_attach">Přiložit</string>
<string name="agent_attach_files">Soubory</string>
<string name="agent_photos_allow">Povolit přístup k fotkám</string>
<string name="agent_photos_more">Vybrat další fotky</string>
<string name="agent_photos_empty">Zatím žádné fotky</string>
<string name="agent_keyboard">Klávesnice</string>
<string name="agent_remove_attachment">Odebrat</string>
<string name="agent_model_default">Výchozí</string>
<string name="agent_effort">Náročnost uvažování</string>
@@ -4245,4 +4250,6 @@
<string name="glasses_shortcut_group">Zkratka ve hře</string>
<string name="glasses_show_shortcut">Zobrazit zkratku Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Zobrazit plovoucí tlačítko Smart Glasses nad hrou.</string>
<string name="display_filter_game_profile">Používá se profil %1$s: %2$s</string>
<string name="display_filter_default_profile">Používá se výchozí profil: %1$s</string>
</resources>
+7
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">Agentens værktøjer er ikke installeret: %1$s</string>
<string name="agent_unqueue">Send ikke</string>
<string name="agent_attach">Vedhæft</string>
<string name="agent_attach_files">Filer</string>
<string name="agent_photos_allow">Tillad adgang til billeder</string>
<string name="agent_photos_more">Vælg flere billeder</string>
<string name="agent_photos_empty">Ingen billeder endnu</string>
<string name="agent_keyboard">Tastatur</string>
<string name="agent_remove_attachment">Fjern</string>
<string name="agent_model_default">Standard</string>
<string name="agent_effort">Ræsonneringsindsats</string>
@@ -4165,4 +4170,6 @@
<string name="glasses_shortcut_group">Genvej i spillet</string>
<string name="glasses_show_shortcut">Vis Smart Glasses-genvej</string>
<string name="glasses_show_shortcut_hint">Vis den flydende Smart Glasses-knap oven på spillet.</string>
<string name="display_filter_game_profile">Bruger profilen %1$s: %2$s</string>
<string name="display_filter_default_profile">Bruger standardprofilen: %1$s</string>
</resources>
+7
View File
@@ -1160,6 +1160,11 @@
<string name="agent_tools_missing">Agent-Werkzeuge nicht installiert: %1$s</string>
<string name="agent_unqueue">Nicht senden</string>
<string name="agent_attach">Anhängen</string>
<string name="agent_attach_files">Dateien</string>
<string name="agent_photos_allow">Zugriff auf Fotos erlauben</string>
<string name="agent_photos_more">Weitere Fotos auswählen</string>
<string name="agent_photos_empty">Noch keine Fotos</string>
<string name="agent_keyboard">Tastatur</string>
<string name="agent_remove_attachment">Entfernen</string>
<string name="agent_model_default">Standard</string>
<string name="agent_effort">Denkaufwand</string>
@@ -4165,4 +4170,6 @@
<string name="glasses_shortcut_group">Ingame-Verknüpfung</string>
<string name="glasses_show_shortcut">Smart-Glasses-Verknüpfung anzeigen</string>
<string name="glasses_show_shortcut_hint">Die schwebende Smart-Glasses-Schaltfläche über dem Spiel anzeigen.</string>
<string name="display_filter_game_profile">Profil %1$s wird verwendet: %2$s</string>
<string name="display_filter_default_profile">Standardprofil wird verwendet: %1$s</string>
</resources>
+7
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">Τα εργαλεία του πράκτορα δεν εγκαταστάθηκαν: %1$s</string>
<string name="agent_unqueue">Να μην σταλεί</string>
<string name="agent_attach">Επισύναψη</string>
<string name="agent_attach_files">Αρχεία</string>
<string name="agent_photos_allow">Να επιτρέπεται η πρόσβαση στις φωτογραφίες</string>
<string name="agent_photos_more">Επιλογή περισσότερων φωτογραφιών</string>
<string name="agent_photos_empty">Δεν υπάρχουν φωτογραφίες ακόμα</string>
<string name="agent_keyboard">Πληκτρολόγιο</string>
<string name="agent_remove_attachment">Αφαίρεση</string>
<string name="agent_model_default">Προεπιλογή</string>
<string name="agent_effort">Προσπάθεια συλλογισμού</string>
@@ -4165,4 +4170,6 @@
<string name="glasses_shortcut_group">Συντόμευση μέσα στο παιχνίδι</string>
<string name="glasses_show_shortcut">Εμφάνιση συντόμευσης Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Εμφάνιση του αιωρούμενου κουμπιού Smart Glasses πάνω από το παιχνίδι.</string>
<string name="display_filter_game_profile">Χρήση προφίλ %1$s: %2$s</string>
<string name="display_filter_default_profile">Χρήση προεπιλεγμένου προφίλ: %1$s</string>
</resources>
+7
View File
@@ -1171,6 +1171,11 @@
<string name="agent_tools_missing">Herramientas del agente sin instalar: %1$s</string>
<string name="agent_unqueue">No enviar</string>
<string name="agent_attach">Adjuntar</string>
<string name="agent_attach_files">Archivos</string>
<string name="agent_photos_allow">Permitir acceso a las fotos</string>
<string name="agent_photos_more">Elegir más fotos</string>
<string name="agent_photos_empty">Aún no hay fotos</string>
<string name="agent_keyboard">Teclado</string>
<string name="agent_remove_attachment">Quitar</string>
<string name="agent_model_default">Predeterminado</string>
<string name="agent_effort">Esfuerzo de razonamiento</string>
@@ -4205,4 +4210,6 @@
<string name="glasses_shortcut_group">Acceso directo en el juego</string>
<string name="glasses_show_shortcut">Mostrar acceso directo de Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Mostrar el botón flotante de Smart Glasses sobre el juego.</string>
<string name="display_filter_game_profile">Usando el perfil %1$s: %2$s</string>
<string name="display_filter_default_profile">Usando el perfil predeterminado: %1$s</string>
</resources>
+7
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">Agentin työkaluja ei ole asennettu: %1$s</string>
<string name="agent_unqueue">Älä lähetä</string>
<string name="agent_attach">Liitä</string>
<string name="agent_attach_files">Tiedostot</string>
<string name="agent_photos_allow">Salli kuvien käyttö</string>
<string name="agent_photos_more">Valitse lisää kuvia</string>
<string name="agent_photos_empty">Ei vielä kuvia</string>
<string name="agent_keyboard">Näppäimistö</string>
<string name="agent_remove_attachment">Poista</string>
<string name="agent_model_default">Oletus</string>
<string name="agent_effort">Päättelyteho</string>
@@ -4165,4 +4170,6 @@
<string name="glasses_shortcut_group">Pelin aikainen pikakuvake</string>
<string name="glasses_show_shortcut">Näytä Smart Glasses -pikakuvake</string>
<string name="glasses_show_shortcut_hint">Näytä pelin päällä kelluva Smart Glasses -painike.</string>
<string name="display_filter_game_profile">Käytössä profiili %1$s: %2$s</string>
<string name="display_filter_default_profile">Käytössä oletusprofiili: %1$s</string>
</resources>
+7
View File
@@ -1171,6 +1171,11 @@
<string name="agent_tools_missing">Outils de l’agent non installés : %1$s</string>
<string name="agent_unqueue">Ne pas envoyer</string>
<string name="agent_attach">Joindre</string>
<string name="agent_attach_files">Fichiers</string>
<string name="agent_photos_allow">Autoriser l\'accès aux photos</string>
<string name="agent_photos_more">Choisir d\'autres photos</string>
<string name="agent_photos_empty">Aucune photo pour l\'instant</string>
<string name="agent_keyboard">Clavier</string>
<string name="agent_remove_attachment">Supprimer</string>
<string name="agent_model_default">Par défaut</string>
<string name="agent_effort">Effort de raisonnement</string>
@@ -4204,4 +4209,6 @@
<string name="glasses_shortcut_group">Raccourci en jeu</string>
<string name="glasses_show_shortcut">Afficher le raccourci Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Afficher le bouton flottant Smart Glasses par-dessus le jeu.</string>
<string name="display_filter_game_profile">Profil %1$s utilisé : %2$s</string>
<string name="display_filter_default_profile">Profil par défaut utilisé : %1$s</string>
</resources>
+7
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">एजेंट टूल इंस्टॉल नहीं हुए: %1$s</string>
<string name="agent_unqueue">न भेजें</string>
<string name="agent_attach">संलग्न करें</string>
<string name="agent_attach_files">फ़ाइलें</string>
<string name="agent_photos_allow">फ़ोटो की अनुमति दें</string>
<string name="agent_photos_more">और फ़ोटो चुनें</string>
<string name="agent_photos_empty">अभी कोई फ़ोटो नहीं</string>
<string name="agent_keyboard">कीबोर्ड</string>
<string name="agent_remove_attachment">हटाएँ</string>
<string name="agent_model_default">डिफ़ॉल्ट</string>
<string name="agent_effort">सोचने का स्तर</string>
@@ -4165,4 +4170,6 @@
<string name="glasses_shortcut_group">गेम में शॉर्टकट</string>
<string name="glasses_show_shortcut">Smart Glasses शॉर्टकट दिखाएँ</string>
<string name="glasses_show_shortcut_hint">गेम के ऊपर तैरता हुआ Smart Glasses बटन दिखाएँ।</string>
<string name="display_filter_game_profile">%1$s प्रोफ़ाइल का उपयोग: %2$s</string>
<string name="display_filter_default_profile">डिफ़ॉल्ट प्रोफ़ाइल का उपयोग: %1$s</string>
</resources>
+7
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">Az ügynök eszközei nincsenek telepítve: %1$s</string>
<string name="agent_unqueue">Ne küldd el</string>
<string name="agent_attach">Csatolás</string>
<string name="agent_attach_files">Fájlok</string>
<string name="agent_photos_allow">Fotókhoz való hozzáférés engedélyezése</string>
<string name="agent_photos_more">További fotók kiválasztása</string>
<string name="agent_photos_empty">Még nincsenek fotók</string>
<string name="agent_keyboard">Billentyűzet</string>
<string name="agent_remove_attachment">Eltávolítás</string>
<string name="agent_model_default">Alapértelmezett</string>
<string name="agent_effort">Gondolkodási erőfeszítés</string>
@@ -4165,4 +4170,6 @@
<string name="glasses_shortcut_group">Játékon belüli parancsikon</string>
<string name="glasses_show_shortcut">Smart Glasses parancsikon megjelenítése</string>
<string name="glasses_show_shortcut_hint">A játék fölött lebegő Smart Glasses gomb megjelenítése.</string>
<string name="display_filter_game_profile">Használt profil: %1$s – %2$s</string>
<string name="display_filter_default_profile">Alapértelmezett profil használata: %1$s</string>
</resources>
+7
View File
@@ -1165,6 +1165,11 @@
<string name="agent_tools_missing">Alat agen tidak terpasang: %1$s</string>
<string name="agent_unqueue">Jangan kirim</string>
<string name="agent_attach">Lampirkan</string>
<string name="agent_attach_files">File</string>
<string name="agent_photos_allow">Izinkan akses foto</string>
<string name="agent_photos_more">Pilih foto lainnya</string>
<string name="agent_photos_empty">Belum ada foto</string>
<string name="agent_keyboard">Keyboard</string>
<string name="agent_remove_attachment">Hapus</string>
<string name="agent_model_default">Default</string>
<string name="agent_effort">Upaya penalaran</string>
@@ -4135,4 +4140,6 @@
<string name="glasses_shortcut_group">Pintasan dalam game</string>
<string name="glasses_show_shortcut">Tampilkan pintasan Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Tampilkan tombol Smart Glasses mengambang di atas game.</string>
<string name="display_filter_game_profile">Menggunakan profil %1$s: %2$s</string>
<string name="display_filter_default_profile">Menggunakan profil default: %1$s</string>
</resources>
+7
View File
@@ -1163,6 +1163,11 @@
<string name="agent_tools_missing">Strumenti dell’agente non installati: %1$s</string>
<string name="agent_unqueue">Non inviare</string>
<string name="agent_attach">Allega</string>
<string name="agent_attach_files">File</string>
<string name="agent_photos_allow">Consenti accesso alle foto</string>
<string name="agent_photos_more">Scegli altre foto</string>
<string name="agent_photos_empty">Ancora nessuna foto</string>
<string name="agent_keyboard">Tastiera</string>
<string name="agent_remove_attachment">Rimuovi</string>
<string name="agent_model_default">Predefinito</string>
<string name="agent_effort">Livello di ragionamento</string>
@@ -4204,4 +4209,6 @@
<string name="glasses_shortcut_group">Scorciatoia nel gioco</string>
<string name="glasses_show_shortcut">Mostra scorciatoia Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Mostra il pulsante mobile Smart Glasses sopra il gioco.</string>
<string name="display_filter_game_profile">Profilo %1$s in uso: %2$s</string>
<string name="display_filter_default_profile">Profilo predefinito in uso: %1$s</string>
</resources>
+7
View File
@@ -1165,6 +1165,11 @@
<string name="agent_tools_missing">エージェントのツールが未インストール: %1$s</string>
<string name="agent_unqueue">送信しない</string>
<string name="agent_attach">添付</string>
<string name="agent_attach_files">ファイル</string>
<string name="agent_photos_allow">写真へのアクセスを許可</string>
<string name="agent_photos_more">写真をさらに選択</string>
<string name="agent_photos_empty">まだ写真がありません</string>
<string name="agent_keyboard">キーボード</string>
<string name="agent_remove_attachment">削除</string>
<string name="agent_model_default">デフォルト</string>
<string name="agent_effort">推論レベル</string>
@@ -4135,4 +4140,6 @@
<string name="glasses_shortcut_group">ゲーム内ショートカット</string>
<string name="glasses_show_shortcut">Smart Glasses のショートカットを表示</string>
<string name="glasses_show_shortcut_hint">ゲーム画面上に Smart Glasses のフローティングボタンを表示します。</string>
<string name="display_filter_game_profile">%1$s プロファイルを使用中: %2$s</string>
<string name="display_filter_default_profile">デフォルトプロファイルを使用中: %1$s</string>
</resources>
+7
View File
@@ -1165,6 +1165,11 @@
<string name="agent_tools_missing">에이전트 도구가 설치되지 않음: %1$s</string>
<string name="agent_unqueue">보내지 않기</string>
<string name="agent_attach">첨부</string>
<string name="agent_attach_files">파일</string>
<string name="agent_photos_allow">사진 접근 허용</string>
<string name="agent_photos_more">사진 더 선택</string>
<string name="agent_photos_empty">아직 사진이 없습니다</string>
<string name="agent_keyboard">키보드</string>
<string name="agent_remove_attachment">제거</string>
<string name="agent_model_default">기본</string>
<string name="agent_effort">추론 수준</string>
@@ -4135,4 +4140,6 @@
<string name="glasses_shortcut_group">게임 내 바로가기</string>
<string name="glasses_show_shortcut">Smart Glasses 바로가기 표시</string>
<string name="glasses_show_shortcut_hint">게임 위에 떠 있는 Smart Glasses 버튼을 표시합니다.</string>
<string name="display_filter_game_profile">%1$s 프로필 사용 중: %2$s</string>
<string name="display_filter_default_profile">기본 프로필 사용 중: %1$s</string>
</resources>
+7
View File
@@ -1165,6 +1165,11 @@
<string name="agent_tools_missing">Alat ejen tidak dipasang: %1$s</string>
<string name="agent_unqueue">Jangan hantar</string>
<string name="agent_attach">Lampirkan</string>
<string name="agent_attach_files">Fail</string>
<string name="agent_photos_allow">Benarkan akses foto</string>
<string name="agent_photos_more">Pilih lebih banyak foto</string>
<string name="agent_photos_empty">Belum ada foto</string>
<string name="agent_keyboard">Papan kekunci</string>
<string name="agent_remove_attachment">Alih keluar</string>
<string name="agent_model_default">Lalai</string>
<string name="agent_effort">Usaha penaakulan</string>
@@ -4135,4 +4140,6 @@
<string name="glasses_shortcut_group">Pintasan dalam permainan</string>
<string name="glasses_show_shortcut">Tunjukkan pintasan Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Tunjukkan butang Smart Glasses terapung di atas permainan.</string>
<string name="display_filter_game_profile">Menggunakan profil %1$s: %2$s</string>
<string name="display_filter_default_profile">Menggunakan profil lalai: %1$s</string>
</resources>
+7
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">Agentverktøy er ikke installert: %1$s</string>
<string name="agent_unqueue">Ikke send</string>
<string name="agent_attach">Legg ved</string>
<string name="agent_attach_files">Filer</string>
<string name="agent_photos_allow">Tillat tilgang til bilder</string>
<string name="agent_photos_more">Velg flere bilder</string>
<string name="agent_photos_empty">Ingen bilder ennå</string>
<string name="agent_keyboard">Tastatur</string>
<string name="agent_remove_attachment">Fjern</string>
<string name="agent_model_default">Standard</string>
<string name="agent_effort">Resonneringsinnsats</string>
@@ -4165,4 +4170,6 @@
<string name="glasses_shortcut_group">Snarvei i spillet</string>
<string name="glasses_show_shortcut">Vis Smart Glasses-snarvei</string>
<string name="glasses_show_shortcut_hint">Vis den flytende Smart Glasses-knappen over spillet.</string>
<string name="display_filter_game_profile">Bruker profilen %1$s: %2$s</string>
<string name="display_filter_default_profile">Bruker standardprofilen: %1$s</string>
</resources>
+7
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">Agenttools niet geïnstalleerd: %1$s</string>
<string name="agent_unqueue">Niet verzenden</string>
<string name="agent_attach">Bijvoegen</string>
<string name="agent_attach_files">Bestanden</string>
<string name="agent_photos_allow">Toegang tot foto\'s toestaan</string>
<string name="agent_photos_more">Meer foto\'s kiezen</string>
<string name="agent_photos_empty">Nog geen foto\'s</string>
<string name="agent_keyboard">Toetsenbord</string>
<string name="agent_remove_attachment">Verwijderen</string>
<string name="agent_model_default">Standaard</string>
<string name="agent_effort">Redeneerinspanning</string>
@@ -4165,4 +4170,6 @@
<string name="glasses_shortcut_group">Snelkoppeling in game</string>
<string name="glasses_show_shortcut">Smart Glasses-snelkoppeling tonen</string>
<string name="glasses_show_shortcut_hint">Toon de zwevende Smart Glasses-knop boven het spel.</string>
<string name="display_filter_game_profile">Profiel %1$s in gebruik: %2$s</string>
<string name="display_filter_default_profile">Standaardprofiel in gebruik: %1$s</string>
</resources>
+7
View File
@@ -1174,6 +1174,11 @@
<string name="agent_tools_missing">Narzędzia agenta nie są zainstalowane: %1$s</string>
<string name="agent_unqueue">Nie wysyłaj</string>
<string name="agent_attach">Załącz</string>
<string name="agent_attach_files">Pliki</string>
<string name="agent_photos_allow">Zezwól na dostęp do zdjęć</string>
<string name="agent_photos_more">Wybierz więcej zdjęć</string>
<string name="agent_photos_empty">Brak zdjęć</string>
<string name="agent_keyboard">Klawiatura</string>
<string name="agent_remove_attachment">Usuń</string>
<string name="agent_model_default">Domyślny</string>
<string name="agent_effort">Poziom rozumowania</string>
@@ -4245,4 +4250,6 @@
<string name="glasses_shortcut_group">Skrót w grze</string>
<string name="glasses_show_shortcut">Pokaż skrót Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Pokaż pływający przycisk Smart Glasses nad grą.</string>
<string name="display_filter_game_profile">Używany profil %1$s: %2$s</string>
<string name="display_filter_default_profile">Używany profil domyślny: %1$s</string>
</resources>
@@ -1163,6 +1163,11 @@
<string name="agent_tools_missing">Ferramentas do agente não instaladas: %1$s</string>
<string name="agent_unqueue">Não enviar</string>
<string name="agent_attach">Anexar</string>
<string name="agent_attach_files">Ficheiros</string>
<string name="agent_photos_allow">Permitir acesso às fotos</string>
<string name="agent_photos_more">Escolher mais fotos</string>
<string name="agent_photos_empty">Ainda não há fotos</string>
<string name="agent_keyboard">Teclado</string>
<string name="agent_remove_attachment">Remover</string>
<string name="agent_model_default">Predefinido</string>
<string name="agent_effort">Esforço de raciocínio</string>
@@ -4204,4 +4209,6 @@
<string name="glasses_shortcut_group">Atalho no jogo</string>
<string name="glasses_show_shortcut">Mostrar atalho do Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Mostrar o botão flutuante do Smart Glasses sobre o jogo.</string>
<string name="display_filter_game_profile">Perfil %1$s em utilização: %2$s</string>
<string name="display_filter_default_profile">Perfil predefinido em utilização: %1$s</string>
</resources>
+7
View File
@@ -1170,6 +1170,11 @@
<string name="agent_tools_missing">Ferramentas do agente não instaladas: %1$s</string>
<string name="agent_unqueue">Não enviar</string>
<string name="agent_attach">Anexar</string>
<string name="agent_attach_files">Arquivos</string>
<string name="agent_photos_allow">Permitir acesso às fotos</string>
<string name="agent_photos_more">Escolher mais fotos</string>
<string name="agent_photos_empty">Ainda não há fotos</string>
<string name="agent_keyboard">Teclado</string>
<string name="agent_remove_attachment">Remover</string>
<string name="agent_model_default">Padrão</string>
<string name="agent_effort">Esforço de raciocínio</string>
@@ -4212,4 +4217,6 @@
<string name="glasses_shortcut_group">Atalho durante o jogo</string>
<string name="glasses_show_shortcut">Mostrar atalho do Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Mostrar o botão flutuante do Smart Glasses sobre o jogo.</string>
<string name="display_filter_game_profile">Perfil %1$s em uso: %2$s</string>
<string name="display_filter_default_profile">Perfil predefinido em uso: %1$s</string>
</resources>
+7
View File
@@ -1171,6 +1171,11 @@
<string name="agent_tools_missing">Instrumentele agentului nu sunt instalate: %1$s</string>
<string name="agent_unqueue">Nu trimite</string>
<string name="agent_attach">Atașează</string>
<string name="agent_attach_files">Fișiere</string>
<string name="agent_photos_allow">Permite accesul la fotografii</string>
<string name="agent_photos_more">Alege mai multe fotografii</string>
<string name="agent_photos_empty">Încă nu există fotografii</string>
<string name="agent_keyboard">Tastatură</string>
<string name="agent_remove_attachment">Elimină</string>
<string name="agent_model_default">Implicit</string>
<string name="agent_effort">Efort de raționament</string>
@@ -4205,4 +4210,6 @@
<string name="glasses_shortcut_group">Comandă rapidă în joc</string>
<string name="glasses_show_shortcut">Afișează comanda rapidă Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Afișează butonul plutitor Smart Glasses peste joc.</string>
<string name="display_filter_game_profile">Se folosește profilul %1$s: %2$s</string>
<string name="display_filter_default_profile">Se folosește profilul implicit: %1$s</string>
</resources>
+7
View File
@@ -1174,6 +1174,11 @@
<string name="agent_tools_missing">Инструменты агента не установлены: %1$s</string>
<string name="agent_unqueue">Не отправлять</string>
<string name="agent_attach">Прикрепить</string>
<string name="agent_attach_files">Файлы</string>
<string name="agent_photos_allow">Разрешить доступ к фото</string>
<string name="agent_photos_more">Выбрать ещё фото</string>
<string name="agent_photos_empty">Пока нет фото</string>
<string name="agent_keyboard">Клавиатура</string>
<string name="agent_remove_attachment">Удалить</string>
<string name="agent_model_default">По умолчанию</string>
<string name="agent_effort">Уровень рассуждений</string>
@@ -4246,4 +4251,6 @@
<string name="glasses_shortcut_group">Ярлык в игре</string>
<string name="glasses_show_shortcut">Показывать ярлык Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Показывать плавающую кнопку Smart Glasses поверх игры.</string>
<string name="display_filter_game_profile">Используется профиль %1$s: %2$s</string>
<string name="display_filter_default_profile">Используется профиль по умолчанию: %1$s</string>
</resources>
+7
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">Agentens verktyg är inte installerade: %1$s</string>
<string name="agent_unqueue">Skicka inte</string>
<string name="agent_attach">Bifoga</string>
<string name="agent_attach_files">Filer</string>
<string name="agent_photos_allow">Tillåt åtkomst till bilder</string>
<string name="agent_photos_more">Välj fler bilder</string>
<string name="agent_photos_empty">Inga bilder än</string>
<string name="agent_keyboard">Tangentbord</string>
<string name="agent_remove_attachment">Ta bort</string>
<string name="agent_model_default">Standard</string>
<string name="agent_effort">Resonemangsnivå</string>
@@ -4165,4 +4170,6 @@
<string name="glasses_shortcut_group">Genväg i spelet</string>
<string name="glasses_show_shortcut">Visa Smart Glasses-genväg</string>
<string name="glasses_show_shortcut_hint">Visa den flytande Smart Glasses-knappen ovanpå spelet.</string>
<string name="display_filter_game_profile">Använder profilen %1$s: %2$s</string>
<string name="display_filter_default_profile">Använder standardprofilen: %1$s</string>
</resources>
+7
View File
@@ -1165,6 +1165,11 @@
<string name="agent_tools_missing">ยังไม่ได้ติดตั้งเครื่องมือของเอเจนต์: %1$s</string>
<string name="agent_unqueue">ไม่ต้องส่ง</string>
<string name="agent_attach">แนบ</string>
<string name="agent_attach_files">ไฟล์</string>
<string name="agent_photos_allow">อนุญาตให้เข้าถึงรูปภาพ</string>
<string name="agent_photos_more">เลือกรูปภาพเพิ่ม</string>
<string name="agent_photos_empty">ยังไม่มีรูปภาพ</string>
<string name="agent_keyboard">แป้นพิมพ์</string>
<string name="agent_remove_attachment">นำออก</string>
<string name="agent_model_default">ค่าเริ่มต้น</string>
<string name="agent_effort">ระดับการใช้เหตุผล</string>
@@ -4135,4 +4140,6 @@
<string name="glasses_shortcut_group">ทางลัดในเกม</string>
<string name="glasses_show_shortcut">แสดงทางลัด Smart Glasses</string>
<string name="glasses_show_shortcut_hint">แสดงปุ่ม Smart Glasses แบบลอยทับบนเกม</string>
<string name="display_filter_game_profile">ใช้โปรไฟล์ %1$s: %2$s</string>
<string name="display_filter_default_profile">ใช้โปรไฟล์เริ่มต้น: %1$s</string>
</resources>
+7
View File
@@ -1160,6 +1160,11 @@
<string name="agent_tools_missing">Ajan araçları yüklenmedi: %1$s</string>
<string name="agent_unqueue">Gönderme</string>
<string name="agent_attach">Ekle</string>
<string name="agent_attach_files">Dosyalar</string>
<string name="agent_photos_allow">Fotoğraflara erişime izin ver</string>
<string name="agent_photos_more">Daha fazla fotoğraf seç</string>
<string name="agent_photos_empty">Henüz fotoğraf yok</string>
<string name="agent_keyboard">Klavye</string>
<string name="agent_remove_attachment">Kaldır</string>
<string name="agent_model_default">Varsayılan</string>
<string name="agent_effort">Akıl yürütme çabası</string>
@@ -4165,4 +4170,6 @@
<string name="glasses_shortcut_group">Oyun içi kısayol</string>
<string name="glasses_show_shortcut">Smart Glasses kısayolunu göster</string>
<string name="glasses_show_shortcut_hint">Oyun üzerinde yüzen Smart Glasses düğmesini göster.</string>
<string name="display_filter_game_profile">%1$s profili kullanılıyor: %2$s</string>
<string name="display_filter_default_profile">Varsayılan profil kullanılıyor: %1$s</string>
</resources>
+7
View File
@@ -1174,6 +1174,11 @@
<string name="agent_tools_missing">Інструменти агента не встановлено: %1$s</string>
<string name="agent_unqueue">Не надсилати</string>
<string name="agent_attach">Прикріпити</string>
<string name="agent_attach_files">Файли</string>
<string name="agent_photos_allow">Дозволити доступ до фото</string>
<string name="agent_photos_more">Вибрати ще фото</string>
<string name="agent_photos_empty">Поки немає фото</string>
<string name="agent_keyboard">Клавіатура</string>
<string name="agent_remove_attachment">Видалити</string>
<string name="agent_model_default">За замовчуванням</string>
<string name="agent_effort">Рівень міркувань</string>
@@ -4245,4 +4250,6 @@
<string name="glasses_shortcut_group">Ярлик у грі</string>
<string name="glasses_show_shortcut">Показувати ярлик Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Показувати плаваючу кнопку Smart Glasses поверх гри.</string>
<string name="display_filter_game_profile">Використовується профіль %1$s: %2$s</string>
<string name="display_filter_default_profile">Використовується профіль за замовчуванням: %1$s</string>
</resources>
+7
View File
@@ -1165,6 +1165,11 @@
<string name="agent_tools_missing">Chưa cài công cụ của tác tử: %1$s</string>
<string name="agent_unqueue">Không gửi</string>
<string name="agent_attach">Đính kèm</string>
<string name="agent_attach_files">Tệp</string>
<string name="agent_photos_allow">Cho phép truy cập ảnh</string>
<string name="agent_photos_more">Chọn thêm ảnh</string>
<string name="agent_photos_empty">Chưa có ảnh</string>
<string name="agent_keyboard">Bàn phím</string>
<string name="agent_remove_attachment">Xóa</string>
<string name="agent_model_default">Mặc định</string>
<string name="agent_effort">Mức độ lập luận</string>
@@ -4135,4 +4140,6 @@
<string name="glasses_shortcut_group">Lối tắt trong trò chơi</string>
<string name="glasses_show_shortcut">Hiển thị lối tắt Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Hiển thị nút Smart Glasses nổi phía trên trò chơi.</string>
<string name="display_filter_game_profile">Đang dùng hồ sơ %1$s: %2$s</string>
<string name="display_filter_default_profile">Đang dùng hồ sơ mặc định: %1$s</string>
</resources>
@@ -1248,6 +1248,11 @@
<string name="agent_tools_missing">智能体工具未安装:%1$s</string>
<string name="agent_unqueue">不发送</string>
<string name="agent_attach">添加附件</string>
<string name="agent_attach_files">文件</string>
<string name="agent_photos_allow">允许访问照片</string>
<string name="agent_photos_more">选择更多照片</string>
<string name="agent_photos_empty">还没有照片</string>
<string name="agent_keyboard">键盘</string>
<string name="agent_remove_attachment">移除</string>
<string name="agent_model_default">默认</string>
<string name="agent_effort">推理强度</string>
@@ -4133,4 +4138,6 @@
<string name="glasses_shortcut_group">游戏内快捷方式</string>
<string name="glasses_show_shortcut">显示 Smart Glasses 快捷方式</string>
<string name="glasses_show_shortcut_hint">在游戏画面上显示悬浮的 Smart Glasses 按钮。</string>
<string name="display_filter_game_profile">正在使用 %1$s 配置:%2$s</string>
<string name="display_filter_default_profile">正在使用默认配置:%1$s</string>
</resources>
@@ -1164,6 +1164,11 @@
<string name="agent_tools_missing">智能體工具未安裝:%1$s</string>
<string name="agent_unqueue">不要傳送</string>
<string name="agent_attach">附加</string>
<string name="agent_attach_files">檔案</string>
<string name="agent_photos_allow">允許存取相片</string>
<string name="agent_photos_more">選擇更多相片</string>
<string name="agent_photos_empty">尚未有相片</string>
<string name="agent_keyboard">鍵盤</string>
<string name="agent_remove_attachment">移除</string>
<string name="agent_model_default">預設</string>
<string name="agent_effort">推理強度</string>
@@ -4133,4 +4138,6 @@
<string name="glasses_shortcut_group">遊戲內捷徑</string>
<string name="glasses_show_shortcut">顯示 Smart Glasses 捷徑</string>
<string name="glasses_show_shortcut_hint">在遊戲畫面上顯示浮動的 Smart Glasses 按鈕。</string>
<string name="display_filter_game_profile">正在使用 %1$s 設定檔:%2$s</string>
<string name="display_filter_default_profile">正在使用預設設定檔:%1$s</string>
</resources>
@@ -1164,6 +1164,11 @@
<string name="agent_tools_missing">智慧代理工具未安裝:%1$s</string>
<string name="agent_unqueue">不要傳送</string>
<string name="agent_attach">附加</string>
<string name="agent_attach_files">檔案</string>
<string name="agent_photos_allow">允許存取相片</string>
<string name="agent_photos_more">選擇更多相片</string>
<string name="agent_photos_empty">還沒有相片</string>
<string name="agent_keyboard">鍵盤</string>
<string name="agent_remove_attachment">移除</string>
<string name="agent_model_default">預設</string>
<string name="agent_effort">推理強度</string>
@@ -4133,4 +4138,6 @@
<string name="glasses_shortcut_group">遊戲內捷徑</string>
<string name="glasses_show_shortcut">顯示 Smart Glasses 捷徑</string>
<string name="glasses_show_shortcut_hint">在遊戲畫面上顯示浮動的 Smart Glasses 按鈕。</string>
<string name="display_filter_game_profile">正在使用 %1$s 設定檔:%2$s</string>
<string name="display_filter_default_profile">正在使用預設設定檔:%1$s</string>
</resources>
+7
View File
@@ -1330,6 +1330,11 @@
<string name="agent_tools_missing">Agent tools not installed: %1$s</string>
<string name="agent_unqueue">Don\'t send</string>
<string name="agent_attach">Attach</string>
<string name="agent_attach_files">Files</string>
<string name="agent_photos_allow">Allow photo access</string>
<string name="agent_photos_more">Choose more photos</string>
<string name="agent_photos_empty">No photos yet</string>
<string name="agent_keyboard">Keyboard</string>
<string name="agent_remove_attachment">Remove</string>
<string name="agent_model_default">Default</string>
<string name="agent_effort">Reasoning effort</string>
@@ -2852,6 +2857,8 @@
<string name="display_filter_hint">Shared by Steam and Desktop.</string>
<string name="display_filter_live">Applies live. Shared by Steam and Desktop.</string>
<string name="display_filter_note">FSR, GSR and NIS apply when enlarging the session image. Sharpen only also works without enlargement.</string>
<string name="display_filter_game_profile">Using %1$s profile: %2$s</string>
<string name="display_filter_default_profile">Using Default profile: %1$s</string>
<string name="display_sharpness">Filter sharpness</string>
<string name="display_look_filter">%1$s Sets scaling to %2$s.</string>
<string name="display_match_screen">Match screen (%1$d×%2$d)</string>
@@ -181,6 +181,17 @@ class ProtonExtrasTest {
assertEquals(emptyList<String>(), 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")
@@ -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"))
}
}
+54
View File
@@ -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 <tool>/proton <verb> <args>`: 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/<pid>/mounts` and `/proc/<pid>/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.
+4 -3
View File
@@ -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
+6 -3
View File
@@ -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
+5
View File
@@ -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)
@@ -1,3 +1,4 @@
Fixed-upstream: FEX-2612
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8976588..3ae54f4 100644
--- a/CMakeLists.txt
@@ -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) {
@@ -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<uint64_t*>(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<uint64_t>(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<siginfo_t*>(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 {
@@ -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.
@@ -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<FEXCore::x86_64::ucontext_t*>(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);
}
@@ -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
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,132 @@
From: maxjivi05 <maxjividen@gmail.com>
Subject: [PATCH] List only guest mappings in /proc/<pid>/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 <FEXCore/Config/Config.h>
#include <FEXCore/Core/Context.h>
#include <FEXCore/Core/CPUID.h>
+#include <FEXCore/Utils/Allocator.h>
#include <FEXCore/Utils/LogManager.h>
+#include <FEXCore/Utils/SignalScopeGuards.h>
+#include <FEXCore/fextl/unordered_map.h>
+#include <FEXCore/fextl/vector.h>
#include <FEXCore/fextl/fmt.h>
#include <FEXCore/fextl/string.h>
#include <FEXCore/fextl/sstream.h>
@@ -25,9 +29,13 @@ $end_info$
#include <git_version.h>
+#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <cstring>
+#include <elf.h>
+#include <mutex>
+#include <shared_mutex>
#include <fcntl.h>
#include <filesystem>
#include <ostream>
@@ -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<fextl::string, bool>& 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<ssize_t>(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<std::pair<uint64_t, uint64_t>> GuestRanges;
+ if (HostSharesGuestRange && Self && FEX::HLE::_SyscallHandler) {
+ auto lk = FEXCore::MaskSignalsAndLockMutex<std::shared_lock>(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<uint64_t, uint64_t>& 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<fextl::string, bool> 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;
@@ -0,0 +1,53 @@
From 597bfab6ff068e0f6c08f63d6940486446967b0d Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
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
@@ -0,0 +1,105 @@
From ab6a01db9e93e7f143b9a3da5b40dcb160b960f3 Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
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 <FEXCore/Utils/LogManager.h>
#include <cstdint>
+#include <errno.h>
#include <sched.h>
#include <signal.h>
#include <stdio.h>
@@ -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<long>(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<int>(-x0);
+ return -1;
+ }
+ return static_cast<int32_t>(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<int>(-ret);
+ return -1;
+ }
+ return static_cast<int32_t>(ret);
+#else
+ return static_cast<int32_t>(::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 <FEXHeaderUtils/Syscalls.h>
#include <FEXCore/Config/Config.h>
#include <FEXCore/Core/Context.h>
#include <FEXCore/Core/CPUID.h>
@@ -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 <FEXHeaderUtils/Syscalls.h>
#include <FEXCore/Core/CoreState.h>
#include <FEXCore/Core/X86Enums.h>
@@ -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
@@ -0,0 +1,104 @@
From 38ee3ef08d9bfd8312fccff688290572da82ef2a Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
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<SharedState*>(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
@@ -0,0 +1,78 @@
From 834075bdee10fb0a1c7a7f499a0bb97162370b5d Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
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
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,58 @@
From 0510284085165d39ef0eabb83e7604fe1bb74c76 Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
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<uint8_t*>(map.arg_start);
+ memmove(HostArgs, reinterpret_cast<const void*>(GuestArgStart), ArgSize);
+ memset(HostArgs + ArgSize, 0, map.arg_end - map.arg_start - ArgSize);
+
+ auto ArgumentPointers = reinterpret_cast<uint64_t*>(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
@@ -0,0 +1,310 @@
From fc926d0e9c63a3d5290a5d816029513349de78f6 Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
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/<pid>/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 <elf.h>
#include <mutex>
#include <shared_mutex>
+#include <string_view>
#include <fcntl.h>
#include <filesystem>
#include <ostream>
@@ -649,6 +650,149 @@ static bool IsHostArchModule(const char* Path, fextl::unordered_map<fextl::strin
return Host;
}
+static bool ReadHostFile(const char* Path, fextl::string& Out) {
+ int HostFD = ::open(Path, O_RDONLY | O_CLOEXEC);
+ if (HostFD < 0) {
+ return false;
+ }
+ char Buf[65536];
+ for (;;) {
+ const ssize_t Len = ::read(HostFD, Buf, sizeof(Buf));
+ if (Len > 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<std::string_view> 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<size_t>(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;
};
+92
View File
@@ -0,0 +1,92 @@
#define _GNU_SOURCE
#include <errno.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/uio.h>
#include <unistd.h>
#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;
}
@@ -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())
@@ -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#./}
@@ -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)
+2 -1
View File
@@ -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);
+31
View File
@@ -5,6 +5,7 @@
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
@@ -20,6 +21,9 @@
#include <unistd.h>
#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) {
+1
View File
@@ -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),
+4 -2
View File
@@ -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);
+121 -5
View File
@@ -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;
}
+30 -2
View File
@@ -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";
+22 -1
View File
@@ -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;
+1
View File
@@ -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;
}
+13 -6
View File
@@ -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;
+223
View File
@@ -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()
@@ -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()
+23
View File
@@ -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:
@@ -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()
File diff suppressed because it is too large. Load diff
+22
View File
@@ -117,6 +117,28 @@ class FexInstallTest(unittest.TestCase):
self.assertEqual("old thunk\n", (self.root / "usr/local" / side / name).read_text())
self.assertEqual("stale\n", (self.root / "usr/local" / side / "libwayland-client-thunk.so").read_text())
def test_a_build_without_a_patch_list_drops_the_old_one(self):
marker = self.root / "usr/local/share/fex-emu/.droiddeck-patches"
marker.write_text("fixed-guest-memory-above-host-address-limit\n")
self.assertEqual("OK", self.install(installed_loads=True)[0])
self.assertFalse(marker.exists())
def test_a_failed_install_keeps_the_old_patch_list(self):
marker = self.root / "usr/local/share/fex-emu/.droiddeck-patches"
marker.write_text("fixed-guest-memory-above-host-address-limit\n")
self.assertEqual("FAILED", self.install(installed_loads=False)[0])
self.assertEqual("fixed-guest-memory-above-host-address-limit\n", marker.read_text())
def test_a_build_with_a_patch_list_installs_it(self):
(self.root / "usr/local/share/fex-emu/.droiddeck-patches").write_text("openat2-enosys-fallback\n")
shipped = Path(self.temp.name) / "pkg/usr/local/share/fex-emu"
shipped.mkdir(parents=True)
(shipped / ".droiddeck-patches").write_text("fixed-guest-memory-above-host-address-limit\n")
self.pack()
self.assertEqual("OK", self.install(installed_loads=True)[0])
self.assertEqual("fixed-guest-memory-above-host-address-limit\n",
(self.root / "usr/local/share/fex-emu/.droiddeck-patches").read_text())
def test_an_archive_that_does_not_match_installs_nothing(self):
result, err = self.install(installed_loads=True, sha="0" * 64)
self.assertEqual("FAILED", result)
+157
View File
@@ -0,0 +1,157 @@
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
PATCH = REPO / "tools/fex/patches/0029-proc-mount-tables-describe-the-container-procfs.patch"
EMULATED = "Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles"
HOST_MOUNTS = """/dev/block/dm-28 / ext4 ro,seclabel,relatime,discard 0 0
tmpfs /dev tmpfs rw,seclabel,nosuid,relatime,size=5791196k,nr_inodes=1447799,mode=755 0 0
proc /proc proc rw,relatime,gid=3009,hidepid=invisible 0 0
sysfs /sys sysfs rw,seclabel,relatime 0 0
/dev/fuse /mnt/user/0/emulated fuse rw,lazytime,nosuid,nodev,noexec,noatime,user_id=0,group_id=0,allow_other 0 0
"""
HOST_MOUNTINFO = """9838 9837 254:28 / / ro,relatime master:1 - ext4 /dev/block/dm-28 ro,seclabel,discard
9853 9838 0:20 / /proc rw,relatime master:4 - proc proc rw,gid=3009,hidepid=invisible
9860 9853 0:20 / /proc/sys rw,relatime shared:7 master:4 - proc proc rw,hidepid=2,subset=pid
9871 9838 0:21 / /sys rw,relatime master:5 - sysfs sysfs rw,seclabel
"""
HARNESS = r"""
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <string>
#include <string_view>
#include <vector>
namespace fextl {
using string = std::string;
template<typename T> using vector = std::vector<T>;
}
HELPERS
static std::string Filter(const std::string& In, bool MountInfo) {
std::string Out;
size_t Pos = 0;
while (Pos < In.size()) {
size_t Eol = In.find('\n', Pos);
const size_t LineEnd = Eol == std::string::npos ? In.size() : Eol;
Out += ContainerMountLine(std::string_view(In).substr(Pos, LineEnd - Pos), MountInfo);
if (Eol != std::string::npos) {
Out += '\n';
}
Pos = LineEnd + 1;
}
return Out;
}
int main(int argc, char** argv) {
if (argv[1][0] == 'p') {
for (int i = 2; i < argc; ++i) {
std::printf("%s\n", IsProcMountTablePath(argv[i]) ? "yes" : "no");
}
return 0;
}
std::string In;
char Buf[4096];
size_t Len;
while ((Len = std::fread(Buf, 1, sizeof(Buf), stdin)) > 0) {
In.append(Buf, Len);
}
std::fputs(Filter(In, argv[1][0] == 'i').c_str(), stdout);
return 0;
}
"""
def added():
return [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
def helpers():
body = added()
start = body.index("static const char* ProcFileOfPid(const char* Path) {")
end = body.index("static fextl::string ContainerMountLine(std::string_view Line, bool MountInfo) {")
end = body.index("}", end) + 1
return "\n".join(body[start:end])
class FexProcMountTablesTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.binary = None
compiler = shutil.which("g++") or shutil.which("clang++")
if compiler:
source = Path(cls.tmp.name) / "mounts.cpp"
source.write_text(HARNESS.replace("HELPERS", helpers()))
binary = Path(cls.tmp.name) / "mounts"
subprocess.run([compiler, "-std=c++20", "-O1", "-o", str(binary), str(source)], check=True)
cls.binary = binary
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def run_filter(self, mode, text):
if not self.binary:
self.skipTest("no C++ compiler")
return subprocess.run([str(self.binary), mode], input=text, capture_output=True, text=True, check=True).stdout
def matches(self, *paths):
if not self.binary:
self.skipTest("no C++ compiler")
out = subprocess.run([str(self.binary), "p", *paths], capture_output=True, text=True, check=True).stdout
return out.split()
def test_only_the_emulated_files_change(self):
files = re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M)
self.assertEqual({EMULATED + ".cpp", EMULATED + ".h"}, set(files))
def test_mount_tables_are_routed_to_the_filter_on_open(self):
body = added()
self.assertIn(" if (pathname && IsProcMountTablePath(pathname)) {", body)
self.assertIn(" return ProcMounts(CTX, AT_FDCWD, pathname, flags, mode);", body)
def test_every_path_form_of_the_mount_tables_matches(self):
paths = ["/proc/mounts", "/proc/self/mounts", "/proc/thread-self/mounts", "/proc/self/mountinfo", "/proc/4242/mounts",
"/proc/4242/mountinfo", "/proc/4242/task/4243/mountinfo"]
self.assertEqual(["yes"] * len(paths), self.matches(*paths))
def test_other_proc_files_do_not_match(self):
paths = ["/proc/self/maps", "/proc/self/status", "/proc/self/mountstats", "/proc/4242/task/mounts", "/proc/self/mounts/x",
"/etc/mounts", "/proc/4242x/mounts"]
self.assertEqual(["no"] * len(paths), self.matches(*paths))
def test_only_the_proc_line_of_mounts_changes(self):
out = self.run_filter("m", HOST_MOUNTS).splitlines()
expected = HOST_MOUNTS.splitlines()
expected[2] = "proc /proc proc rw,relatime 0 0"
self.assertEqual(expected, out)
def test_only_proc_super_options_of_mountinfo_change(self):
out = self.run_filter("i", HOST_MOUNTINFO).splitlines()
expected = HOST_MOUNTINFO.splitlines()
expected[1] = "9853 9838 0:20 / /proc rw,relatime master:4 - proc proc rw"
expected[2] = "9860 9853 0:20 / /proc/sys rw,relatime shared:7 master:4 - proc proc rw"
self.assertEqual(expected, out)
def test_tables_without_proc_pass_through_unchanged(self):
text = "".join(line + "\n" for line in HOST_MOUNTS.splitlines() if " proc " not in line)
self.assertEqual(text, self.run_filter("m", text))
def test_malformed_lines_pass_through_unchanged(self):
text = "proc /proc proc\nno dash here proc rw\n\nproc\n"
self.assertEqual(text, self.run_filter("m", text))
self.assertEqual(text, self.run_filter("i", text))
def test_no_comments_are_added(self):
self.assertFalse([line for line in added() if line.strip().startswith(("//", "/*"))])
if __name__ == "__main__":
unittest.main()
+49 -2
View File
@@ -8,14 +8,17 @@ from pathlib import Path
FEX = Path(__file__).resolve().parents[1] / "fex"
PATCH = FEX / "patches/0012-signal-return-applies-guest-registers.patch"
EMULATION = FEX / "patches/0021-anticheat-ptrace-seccomp-and-proc-emulation.patch"
MCONTEXT = "Source/Tools/LinuxEmulation/ArchHelpers/MContext.h"
DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"
PROBE = FEX / "probes/signal-register-update.c"
HEADER = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h"
FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp"
X64_ORDER = ["RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"]
def files():
sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M)
def files(patch=PATCH):
sections = re.split(r"^diff --git a/(\S+) \S+\n", patch.read_text(), flags=re.M)
return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)}
@@ -96,6 +99,50 @@ class SignalRegisterUpdateTest(unittest.TestCase):
self.assertNotIn("Fixed-upstream", PATCH.read_text())
class ClearedSyscallInfoTest(unittest.TestCase):
SOURCE = "ArchHelpers::Context::SavedSyscallInfo(Context)"
def saved_info(self):
lines = [line[1:] for line in files(EMULATION)[MCONTEXT].splitlines() if line.startswith("+") and not line.startswith("+++")]
start = lines.index("template<typename Backup>")
end = lines.index("}", start)
return "\n".join(lines[start:end + 1])
def test_register_writeback_reads_the_same_saved_state_as_the_restore(self):
frames = files(EMULATION)[FRAMES]
self.assertIn("- const uint32_t Spilled = Context->InSyscallInfo & 0xFFFF;", frames)
self.assertIn("+ const uint32_t Spilled = " + self.SOURCE + " & 0xFFFF;", frames)
delegator = added(files(EMULATION)[DELEGATOR])
self.assertIn("Thread->CurrentFrame->InSyscallInfo = " + self.SOURCE + ";", delegator)
self.assertIn("Frame->InSyscallInfo = " + self.SOURCE + ";", delegator)
self.assertIn("Frame->InSyscallInfo = Context->InSyscallInfo;", removed(files(EMULATION)[DELEGATOR]))
self.assertNotIn("Context->ClearedSyscallInfo :", "\n".join(delegator))
@unittest.skipUnless(shutil.which("c++") or shutil.which("g++") or shutil.which("clang++"), "needs a C++ compiler")
def test_cleared_state_is_preferred_only_when_flagged(self):
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
source = "\n".join([
"#include <cstdint>",
"#include <cstdio>",
"enum ContextFlags : uint32_t { CONTEXT_FLAG_INJIT = 1U << 0, CONTEXT_FLAG_SYSCALLINFO_CLEARED = 1U << 1 };",
"struct Backup { uint16_t InSyscallInfo; uint16_t ClearedSyscallInfo; uint32_t Flags; };",
self.saved_info(),
"int main() {",
" const Backup Thunk {0, 0xFFFF, CONTEXT_FLAG_SYSCALLINFO_CLEARED};",
" const Backup Jit {0x0F0F, 0x1234, CONTEXT_FLAG_INJIT};",
" const Backup Idle {0, 0x1234, 0};",
" std::printf(\"%x %x %x\\n\", SavedSyscallInfo(&Thunk), SavedSyscallInfo(&Jit), SavedSyscallInfo(&Idle));",
"}",
])
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "saved.cpp"
binary = Path(tmp) / "saved"
path.write_text(source)
subprocess.run([compiler, "-std=c++20", "-Wall", "-Werror", "-o", str(binary), str(path)], check=True)
output = subprocess.run([str(binary)], capture_output=True, text=True, check=True, timeout=60).stdout
self.assertEqual(output.split(), ["ffff", "f0f", "0"])
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86 code")
class SignalRegisterUpdateProbeTest(unittest.TestCase):
@classmethod
+7 -5
View File
@@ -2664,8 +2664,8 @@ class GameEnvironmentTest(unittest.TestCase):
def test_both_proton_wrappers_call_environment_launcher(self):
self.assertIn('dd_directaudio "$depot" "$@"', COMPAT["LAUNCHER_SH"])
self.assertIn('dd_directaudio "$here" "$@"', COMPAT["EXTRA_WRAPPER_SH"] % "proton")
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
self.assertIn('dd_directaudio "$here" "$@"', COMPAT["extra_wrapper_sh"]("proton"))
for script in (COMPAT["LAUNCHER_SH"], COMPAT["extra_wrapper_sh"]("proton")):
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
self.assertIn('dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env', script)
@@ -2673,9 +2673,11 @@ class GameEnvironmentTest(unittest.TestCase):
scripts = (COMPAT["launcher_sh"](), COMPAT["extra_wrapper_sh"]("proton"))
query = "/root/.local/share/Steam/steamrtarm64/../bin/d3ddriverquery64.exe"
probe = "/root/.local/share/Steam/steamapps/compatdata/0"
for script in scripts:
for script, here in zip(scripts, ("$depot", "$here")):
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
self.assertLess(script.index('case "$verb:${1##*/}:'), script.index("dd_components "))
answered = script.index('case "$verb:${1##*/}:')
self.assertLess(answered, script.index('dd_components "%s"' % here))
self.assertLess(answered, script.index('dd_anticheat "$@"'))
for args, prefix in (([query, "-d3d12"], probe), ([query], probe + "/"),
([query.replace("64.exe", ".exe")], probe)):
result = subprocess.run(["bash", "-s", "run"] + args, input=script, text=True, capture_output=True,
@@ -2744,7 +2746,7 @@ class GameEnvironmentTest(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmp:
for name in ("libddsession.so", "libfakeinput.so"):
(Path(tmp) / name).write_bytes(b"")
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
for script in (COMPAT["LAUNCHER_SH"], COMPAT["extra_wrapper_sh"]("proton")):
start = script.index("for fake in ")
block = script[start:script.index("\ndone\n", start) + 6].replace("/usr/local/lib/", tmp + "/")
for inherited, expected in (
@@ -0,0 +1,229 @@
import errno
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
PROBE = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
#define SIZE 100003
static unsigned long sum_of(int fd) {
unsigned long sum = 0;
unsigned char buf[4096];
ssize_t n;
long total = 0;
while ((n = read(fd, buf, sizeof(buf))) > 0) {
for (ssize_t i = 0; i < n; i++) sum = sum * 31 + buf[i];
total += n;
}
return total == SIZE ? sum : 0;
}
static int open_by(const char *how, const char *path, int flags) {
if (strcmp(how, "open") == 0) return open(path, flags);
if (strcmp(how, "openat") == 0) return openat(AT_FDCWD, path, flags);
return (int)syscall(SYS_openat, AT_FDCWD, path, flags, 0);
}
static void report(const char *label, int fd, int src) {
if (fd < 0) {
printf("%s\terr\t%d\n", label, errno);
return;
}
char link[64], target[256];
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
ssize_t n = readlink(link, target, sizeof(target) - 1);
target[n > 0 ? n : 0] = '\0';
char *deleted = strstr(target, " (deleted)");
if (deleted) *deleted = '\0';
struct stat a, b;
fstat(fd, &a);
fstat(src, &b);
unsigned long sum = sum_of(fd);
int write_errno = pwrite(fd, "x", 1, 0) < 0 ? errno : 0;
int grow_errno = ftruncate(fd, SIZE + 1) < 0 ? errno : 0;
printf("%s\tok\t%lu\t%d\t%s\t%d\t%ld\t%o\t%d\t%d\n", label, sum, fcntl(fd, F_GET_SEALS), target,
(fcntl(fd, F_GETFD) & FD_CLOEXEC) != 0, (long)lseek(src, 0, SEEK_CUR), (unsigned)(a.st_mode & 07777),
write_errno != 0, grow_errno != 0);
close(fd);
}
int main(int argc, char **argv) {
int src = memfd_create("probe-module", MFD_ALLOW_SEALING);
unsigned char *data = malloc(SIZE);
for (long i = 0; i < SIZE; i++) data[i] = (unsigned char)(i * 7 + 3);
if (write(src, data, SIZE) != SIZE) return 3;
unsigned long want = 0;
for (long i = 0; i < SIZE; i++) want = want * 31 + data[i];
printf("want\t%lu\n", want);
fcntl(src, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW);
fchmod(src, 0);
char path[64];
const char *forms[] = {"self", "thread", "pid", "dev"};
const char *hows[] = {"open", "openat", "syscall"};
for (int f = 0; f < 4; f++) {
for (int h = 0; h < 3; h++) {
if (f == 0) snprintf(path, sizeof(path), "/proc/self/fd/%d", src);
if (f == 1) snprintf(path, sizeof(path), "/proc/thread-self/fd/%d", src);
if (f == 2) snprintf(path, sizeof(path), "/proc/%d/fd/%d", getpid(), src);
if (f == 3) snprintf(path, sizeof(path), "/dev/fd/%d", src);
char label[32];
snprintf(label, sizeof(label), "%s-%s", forms[f], hows[h]);
report(label, open_by(hows[h], path, O_RDONLY | O_CLOEXEC), src);
}
}
snprintf(path, sizeof(path), "/proc/self/fd/%d", src);
report("keep-cloexec-off", open(path, O_RDONLY), src);
report("write", open(path, O_RDWR), src);
int foreign = memfd_create("probe-foreign", 0);
fchmod(foreign, 0);
pid_t child = fork();
if (child < 0) return 6;
if (child == 0) {
pause();
_exit(0);
}
snprintf(path, sizeof(path), "/proc/%d/fd/%d", (int)child, foreign);
report("other-pid", open(path, O_RDONLY), src);
kill(child, SIGKILL);
waitpid(child, NULL, 0);
int plain = open(argv[1], O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (write(plain, "x", 1) != 1) return 4;
fchmod(plain, 0);
snprintf(path, sizeof(path), "/proc/self/fd/%d", plain);
report("plain-file", open(path, O_RDONLY | O_CLOEXEC), plain);
int open_mfd = memfd_create("probe-open", 0);
if (write(open_mfd, data, SIZE) != SIZE) return 5;
snprintf(path, sizeof(path), "/proc/self/fd/%d", open_mfd);
int again = open(path, O_RDONLY | O_CLOEXEC);
struct stat a, b;
fstat(again, &a);
fstat(open_mfd, &b);
printf("readable-memfd\t%d\n", again >= 0 && a.st_ino == b.st_ino);
unsigned long long how[3] = {O_RDONLY | O_CLOEXEC, 0, 0};
errno = 0;
long direct = syscall(437, AT_FDCWD, "/", how, sizeof(how));
printf("kernel-openat2\t%d\n", direct >= 0 || errno != ENOSYS);
int (*open2)(int, const char *, void *, size_t) = dlsym(RTLD_DEFAULT, "openat2");
snprintf(path, sizeof(path), "/proc/self/fd/%d", src);
if (open2 && argc > 2) {
errno = 0;
int refused = open2(AT_FDCWD, path, (void *)8, 24);
int refused_errno = errno;
printf("unreadable-how\t%d\t%d\n", refused, refused_errno);
}
return 0;
}
"""
class NativeHookMemfdReopenTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
if os.geteuid() == 0:
raise unittest.SkipTest("root ignores the file mode that stands in for the refused reopen")
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.root = tmp / "root"
cls.root.mkdir()
cls.plain = cls.root / "plain"
cls.bare = cls.run_probe(False)
cls.kernel_openat2 = cls.bare["kernel-openat2"] == ["1"]
cls.hooked = cls.run_probe(True, *(["how"] if cls.kernel_openat2 else []))
@classmethod
def tearDownClass(cls):
os.chmod(cls.plain, 0o600)
cls.tmp.cleanup()
@classmethod
def run_probe(cls, hook, *extra):
if cls.plain.exists():
os.chmod(cls.plain, 0o600)
hook_env = {"DDNATV_ROOT": str(cls.root), "LD_PRELOAD": str(cls.hook)} if hook else {}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
if cls.prefix:
cmd = list(cls.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(cls.probe), str(cls.plain), *extra], env=env, capture_output=True, text=True, timeout=120)
if out.returncode != 0:
raise AssertionError(out.stdout + out.stderr)
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
def test_the_refused_reopen_is_the_condition_without_the_hook(self):
self.assertEqual(["err", str(errno.EACCES)], self.bare["self-open"])
self.assertEqual(["err", str(errno.EACCES)], self.bare["self-syscall"])
def test_a_refused_read_only_reopen_of_an_own_memfd_gets_its_bytes_and_seals(self):
want = self.hooked["want"][0]
for form in ("self", "thread", "pid", "dev"):
for how in ("open", "openat", "syscall"):
with self.subTest(form=form, how=how):
status, total, seals, name, cloexec, offset, mode, unwritable, fixed = self.hooked[f"{form}-{how}"]
self.assertEqual("ok", status)
self.assertEqual(want, total)
self.assertEqual(str(0x2 | 0x4 | 0x8), seals)
self.assertEqual("1", unwritable)
self.assertEqual("1", fixed)
self.assertEqual("/memfd:probe-module", name)
self.assertEqual("1", cloexec)
self.assertEqual("100003", offset)
self.assertEqual("0", mode)
def test_close_on_exec_follows_the_open_flags(self):
self.assertEqual("0", self.hooked["keep-cloexec-off"][4])
def test_an_unreadable_open_how_gets_the_kernel_error(self):
if not self.kernel_openat2:
self.skipTest("the runner has no openat2")
self.assertEqual(["-1", str(errno.EFAULT)], self.hooked["unreadable-how"])
def test_a_writable_reopen_stays_refused(self):
self.assertEqual(["err", str(errno.EACCES)], self.hooked["write"])
def test_another_process_descriptor_is_not_copied(self):
self.assertEqual(["err", str(errno.EACCES)], self.bare["other-pid"])
self.assertEqual(["err", str(errno.EACCES)], self.hooked["other-pid"])
def test_a_refused_regular_file_stays_refused(self):
self.assertEqual(["err", str(errno.EACCES)], self.hooked["plain-file"])
self.assertEqual(self.bare["plain-file"], self.hooked["plain-file"])
def test_a_memfd_the_kernel_reopens_is_the_same_file(self):
self.assertEqual(["1"], self.hooked["readable-memfd"])
self.assertEqual(["1"], self.bare["readable-memfd"])
if __name__ == "__main__":
unittest.main()
+16
View File
@@ -19,6 +19,13 @@ int main(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
char buf[4096];
ssize_t n;
if (strncmp(argv[i], "fill:", 5) == 0 || strncmp(argv[i], "short:", 6) == 0) {
size_t size = argv[i][0] == 'f' ? sizeof(buf) : 256;
memset(buf, '/', sizeof(buf));
n = readlink(strchr(argv[i], ':') + 1, buf, size);
printf("%s\t%s\n", argv[i], n > 0 && (size_t)n < size && buf[n] == 0 ? "ends" : "runs on");
continue;
}
if (strncmp(argv[i], "at:", 3) == 0) {
int dfd = open(argv[i] + 3, O_RDONLY | O_DIRECTORY);
n = dfd >= 0 ? readlinkat(dfd, "exe", buf, sizeof(buf) - 1) : -1;
@@ -57,6 +64,7 @@ class NativeHookProcExeTest(unittest.TestCase):
(cls.root / "usr/bin").mkdir(parents=True)
cls.kwin = cls.root / "usr/bin/kwin_wayland"
shutil.copy(tmp / "sleeper", cls.kwin)
(cls.root / "compositor").symlink_to("usr/bin/kwin_wayland")
cls.runtime = tmp / "runtime"
cls.runtime.mkdir()
cls.bound = cls.runtime / "chrome"
@@ -151,6 +159,14 @@ class NativeHookProcExeTest(unittest.TestCase):
link = f"/proc/{pid}/exe"
self.assertEqual("/usr/bin/kwin_wayland", self.readlink(link)[link])
def test_the_own_program_answer_ends_where_the_name_ends(self):
key = "fill:/proc/self/exe"
self.assertEqual("ends", self.readlink(key)[key])
def test_a_link_read_into_a_short_buffer_ends_where_its_target_ends(self):
key = "short:/compositor"
self.assertEqual("ends", self.readlink(key)[key])
def test_a_loader_without_a_known_program_keeps_the_kernel_link(self):
pid = self.start(loader=True)
link = f"/proc/{pid}/exe"
+87 -2
View File
@@ -45,6 +45,38 @@ int main(int argc, char **argv) {
}
"""
FORMS = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <limits.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv) {
if (chdir(argv[1]) != 0) return 2;
char buf[PATH_MAX];
printf("cwd\t%s\n", getcwd(buf, sizeof(buf)) ? buf : "");
ssize_t n = readlink("/proc/self/cwd", buf, sizeof(buf) - 1);
printf("proc-cwd\t%.*s\n", n > 0 ? (int)n : 0, buf);
n = readlink(argv[2], buf, sizeof(buf) - 1);
printf("relative\t%.*s\n", n > 0 ? (int)n : 0, buf);
char climbing[PATH_MAX];
snprintf(climbing, sizeof(climbing), "../../../../../../../../../../../../etc/alternatives/%s", argv[2]);
n = readlinkat(AT_FDCWD, climbing, buf, sizeof(buf) - 1);
printf("climbing-at\t%.*s\n", n > 0 ? (int)n : 0, buf);
struct stat st;
printf("climbing-size\t%ld\n", fstatat(AT_FDCWD, climbing, &st, AT_SYMLINK_NOFOLLOW) == 0 ? (long)st.st_size : -1L);
for (int i = 3; i < argc; i++) {
char *got = realpath(argv[i], NULL);
printf("realpath:%s\t%s\n", argv[i], got ? got : "");
free(got);
}
return 0;
}
"""
class NativeHookReadlinkTest(unittest.TestCase):
@classmethod
@@ -65,12 +97,20 @@ class NativeHookReadlinkTest(unittest.TestCase):
(cls.root / "bin/nano").write_text("")
os.symlink(cls.root / "bin/nano", cls.root / "etc/alternatives/editor")
os.symlink("/bin/nano", cls.root / "etc/alternatives/guest")
(tmp / "forms.c").write_text(FORMS)
cls.forms = tmp / "forms"
subprocess.run([cls.cc, "-O1", "-o", str(cls.forms), str(tmp / "forms.c")], check=True)
cls.steam = cls.root / "root/.local/share/Steam"
(cls.steam / "steamapps/common/Game").mkdir(parents=True)
(cls.steam / "steamapps/common/Game/Game.exe").write_text("")
(cls.root / "root/pfx/dosdevices").mkdir(parents=True)
os.symlink(cls.steam, cls.root / "root/pfx/dosdevices/s:")
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def read(self, link):
def run_hooked(self, argv):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
if self.prefix:
@@ -78,10 +118,16 @@ class NativeHookReadlinkTest(unittest.TestCase):
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe), link], env=env, capture_output=True, text=True, timeout=120)
out = subprocess.run(cmd + argv, env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(0, out.returncode, out.stdout + out.stderr)
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
def read(self, link):
return self.run_hooked([str(self.probe), link])
def path_forms(self, cwd, relative_link, *paths):
return {key: value[0] for key, value in self.run_hooked([str(self.forms), cwd, relative_link, *paths]).items()}
def test_a_buffer_sized_from_lstat_gets_the_guest_target(self):
result = self.read("/etc/alternatives/editor")
self.assertEqual(["9", "/bin/nano"], result["sized"])
@@ -101,6 +147,45 @@ class NativeHookReadlinkTest(unittest.TestCase):
self.assertEqual(["-1", str(errno.EINVAL)], result["zero"])
self.assertEqual(["-1", str(errno.EINVAL)], result["zero-at"])
def test_a_link_named_by_its_real_path_keeps_a_real_target(self):
steam = str(self.steam)
result = self.read(str(self.root / "root/pfx/dosdevices/s:"))
self.assertEqual([str(len(steam)), steam], result["sized"])
self.assertEqual([str(len(steam)), steam], result["sized-at"])
self.assertEqual([str(len(steam)), steam], result["full"])
def test_a_link_named_by_its_guest_path_keeps_the_guest_target(self):
result = self.read("/root/pfx/dosdevices/s:")
self.assertEqual([str(len("/root/.local/share/Steam")), "/root/.local/share/Steam"], result["full"])
self.assertEqual(["9", "/bin/nano"], self.read("/etc/alternatives/editor")["sized"])
def test_a_link_the_hook_wrote_reads_in_the_form_it_is_named_in(self):
real = str(self.root / "bin/nano")
self.assertEqual([str(len(real)), real], self.read(str(self.root / "etc/alternatives/editor"))["sized"])
self.assertEqual(["9", "/bin/nano"], self.read(str(self.root / "etc/alternatives/guest"))["sized"])
def test_a_game_reached_through_a_drive_link_is_named_like_the_working_directory(self):
game = self.steam / "steamapps/common/Game"
through_drive = str(self.root / "root/pfx/dosdevices/s:/steamapps/common/Game/Game.exe")
result = self.path_forms(str(game), "Game.exe", through_drive, "Game.exe")
self.assertEqual(str(game), result["cwd"])
self.assertEqual(str(game / "Game.exe"), result[f"realpath:{through_drive}"])
self.assertTrue(result[f"realpath:{through_drive}"].startswith(result["cwd"] + "/"))
def test_the_proc_working_directory_link_matches_getcwd(self):
game = str(self.steam / "steamapps/common/Game")
result = self.path_forms(game, "Game.exe")
self.assertEqual(result["cwd"], result["proc-cwd"])
def test_guest_and_relative_names_keep_the_guest_form(self):
guest_drive = "/root/pfx/dosdevices/s:/steamapps/common/Game/Game.exe"
result = self.path_forms(str(self.root / "etc/alternatives"), "editor", guest_drive, "/etc/alternatives/editor")
self.assertEqual("/bin/nano", result["relative"])
self.assertEqual("/bin/nano", result["climbing-at"])
self.assertEqual("9", result["climbing-size"])
self.assertEqual("/root/.local/share/Steam/steamapps/common/Game/Game.exe", result[f"realpath:{guest_drive}"])
self.assertEqual("/bin/nano", result["realpath:/etc/alternatives/editor"])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,81 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
PROBE = r"""
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
static void show(const char *name, int ret) {
struct rlimit now;
if (getrlimit(RLIMIT_RTTIME, &now) != 0) exit(2);
printf("%s\t%d\t%lld\t%lld\n", name, ret, (long long)now.rlim_cur, (long long)now.rlim_max);
}
int main(void) {
struct rlimit zero = {0, 0}, soft_zero = {0, 200000}, usable = {100000, 200000};
show("start", 0);
show("zero", setrlimit(RLIMIT_RTTIME, &zero));
show("soft_zero", setrlimit(RLIMIT_RTTIME, &soft_zero));
show("usable", setrlimit(RLIMIT_RTTIME, &usable));
return 0;
}
"""
class NativeHookRttimeLimitTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.root = tmp / "root"
cls.root.mkdir()
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def limits(self):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe)], env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(0, out.returncode, out.stdout + out.stderr)
return {name: (int(ret), int(cur), int(hard))
for name, ret, cur, hard in (line.split("\t") for line in out.stdout.splitlines())}
def test_a_realtime_limit_of_zero_is_reported_set_and_not_applied(self):
limits = self.limits()
self.assertEqual(0, limits["zero"][0])
self.assertEqual(limits["start"][1:], limits["zero"][1:])
def test_a_soft_realtime_limit_of_zero_is_not_applied(self):
limits = self.limits()
self.assertEqual(0, limits["soft_zero"][0])
self.assertEqual(limits["start"][1:], limits["soft_zero"][1:])
def test_a_usable_realtime_limit_is_applied(self):
self.assertEqual((0, 100000, 200000), self.limits()["usable"])
if __name__ == "__main__":
unittest.main()
+8
View File
@@ -78,6 +78,7 @@ static int g_loop_stub;
static int g_fallback_accept;
static int g_fallback_token;
static int g_hdr_count;
static int g_mirror_count, g_mirror_capture;
int text_input_host_commit(const char *u, size_t n)
{
@@ -143,6 +144,7 @@ void toplevel_icon_init(struct wl_display *d) { (void)d; }
void single_pixel_init(struct wl_display *d) { (void)d; }
void ahb_swapchain_set_mode(int a, int b) { (void)a; (void)b; }
void droiddeck_color_set_output(int a) { (void)a; g_hdr_count++; }
void droiddeck_set_mirror_capture(int on) { g_mirror_capture = on; g_mirror_count++; }
struct wl_display *droiddeck_get_display(void) { return (struct wl_display *)&g_display_stub; }
void wl_display_flush_clients(struct wl_display *d) { (void)d; }
@@ -216,7 +218,10 @@ int main(void)
droiddeck_host_key(29, 0);
droiddeck_host_text_commit("later", 5);
droiddeck_host_hdr_output(1);
droiddeck_host_mirror_capture(1);
CHECK(g_mirror_count == 0);
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
CHECK(g_mirror_count == 1 && g_mirror_capture == 1);
CHECK(g_n == saved);
CHECK(g_hdr_count == 1);
CHECK(g_fallback_token > 0);
@@ -259,7 +264,10 @@ int main(void)
droiddeck_host_key(32, 1);
droiddeck_host_key(32, 0);
droiddeck_host_hdr_output(0);
droiddeck_host_mirror_capture(0);
CHECK(g_mirror_count == 1);
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
CHECK(g_mirror_count == 2 && g_mirror_capture == 0);
CHECK(g_n == saved + 1);
CHECK(g_hdr_count == 2);
CHECK(g_fallback_token > 0);
+83
View File
@@ -1,5 +1,6 @@
import os
from pathlib import Path
import platform
import signal
import shutil
import subprocess
@@ -29,6 +30,7 @@ PROGRAM = r"""
#include <sys/syscall.h>
#include <sys/wait.h>
#include <time.h>
#include <ucontext.h>
#include <unistd.h>
static const char *ctl;
@@ -220,6 +222,45 @@ static void *writer(void *arg) {
return NULL;
}
static volatile unsigned char dispatch_selector;
static int dispatch_traps, dispatch_done, dispatch_ready;
static long dispatch_result = -1;
static void dispatch_trap(int sig, siginfo_t *info, void *context) {
(void)sig;
(void)info;
__atomic_add_fetch(&dispatch_traps, 1, __ATOMIC_RELAXED);
#ifdef __x86_64__
((ucontext_t *)context)->uc_mcontext.gregs[REG_RAX] = -ENOSYS;
#endif
}
static void *dispatch_signaller(void *arg) {
(void)arg;
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGURG);
pthread_sigmask(SIG_BLOCK, &set, NULL);
char ack[256], text[32];
snprintf(ack, sizeof(ack), "%s.trim.%d", ctl, getpid());
unlink(ack);
FILE *f = fopen(ctl, "w");
if (!f) exit(3);
fprintf(f, "2 %ld\n", 1L << 30);
fclose(f);
while (!__atomic_load_n(&dispatch_ready, __ATOMIC_ACQUIRE)) usleep(1000);
kill(getpid(), SIGURG);
for (int i = 0; i < 1200 && dispatch_result < 0; i++) {
f = fopen(ack, "r");
char *line = f ? fgets(text, sizeof(text), f) : NULL;
if (f) fclose(f);
if (line) dispatch_result = atol(text);
else usleep(10000);
}
__atomic_store_n(&dispatch_done, 1, __ATOMIC_RELEASE);
return NULL;
}
int main(int argc, char **argv) {
ctl = argv[1];
size = strtoul(argv[2], NULL, 0) << 20;
@@ -391,6 +432,38 @@ int main(int argc, char **argv) {
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
printf("filtered_trim %ld\n", trim('2', 1L << 30));
return 0;
} else if (!strcmp(argv[4], "dispatch")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
struct sigaction trap;
memset(&trap, 0, sizeof(trap));
trap.sa_sigaction = dispatch_trap;
trap.sa_flags = SA_SIGINFO;
sigemptyset(&trap.sa_mask);
sigaction(SIGSYS, &trap, NULL);
errno = 0;
printf("prctlerr %d\n", prctl(-1, 0, 0, 0, 0) == -1 && errno == EINVAL);
if (prctl(59, 1, (unsigned long)sa.sa_restorer, 16, &dispatch_selector)) {
printf("dispatch 0\n");
return 0;
}
printf("dispatch 1\n");
fflush(stdout);
pthread_t signaller;
pthread_create(&signaller, NULL, dispatch_signaller, NULL);
dispatch_selector = 1;
__atomic_store_n(&dispatch_ready, 1, __ATOMIC_RELEASE);
while (!__atomic_load_n(&dispatch_done, __ATOMIC_ACQUIRE)) {
}
char name[16] = {0};
int named = prctl(PR_GET_NAME, name, 0, 0, 0) == 0 && name[0] != 0;
dispatch_selector = 0;
prctl(59, 0, 0, 0, 0);
pthread_join(signaller, NULL);
printf("traps %d\n", __atomic_load_n(&dispatch_traps, __ATOMIC_RELAXED));
printf("trimmed %d\n", dispatch_result >= 0);
printf("named %d\n", named);
return 0;
} else if (!strcmp(argv[4], "burst")) {
send_request('0');
usleep(10000);
@@ -690,6 +763,16 @@ class ZramPreloadTest(unittest.TestCase):
out = self.run_program(None, 48, 0, "burst")
self.assertEqual([1], out["burstack"])
@unittest.skipUnless(platform.machine() == "x86_64", "selector check is x86-64 only")
def test_requests_are_served_while_syscall_user_dispatch_blocks(self):
out = self.run_program(None, 8, 0, "dispatch")
self.assertEqual([1], out["prctlerr"])
if out["dispatch"] != [1]:
self.skipTest("kernel lacks syscall user dispatch")
self.assertEqual([0], out["traps"], out)
self.assertEqual([1], out["trimmed"], out)
self.assertEqual([1], out["named"], out)
if __name__ == "__main__":
unittest.main()
+4 -4
View File
@@ -7,10 +7,10 @@ Steam on the desktop). The app installs it into `files/linuxfs` and runs it unde
- `build-debs.sh` (run in an `ubuntu:26.04` container on an arm64 runner) rebuilds two Ubuntu source
packages: Mesa with `-Dfreedreno-kmds=msm,kgsl`, so Turnip and freedreno reach Android's
`/dev/kgsl-3d0`, and KWin with `patches/kwin` (nested desktop scale, an explicit render node,
scroll source/discrete forwarding). Both get a `+droiddeck` version. `patches/mesa` adds KGSL
UBWC 5/6 (backported from upstream Mesa) and the KGSL device numbers for WSI (from
[Droid-Deck/Drivers](https://github.com/Droid-Deck/Drivers)). It also carries Icenowy Zheng's upstream
Zink fix that keeps the Imagination depth/stencil swizzle off colour views (Mesa d55418dae7).
scroll source/discrete forwarding). Both get a `+droiddeck` version. `patches/mesa` adds the KGSL
device numbers for WSI (from [Droid-Deck/Drivers](https://github.com/Droid-Deck/Drivers)).
KGSL UBWC 5/6 and Icenowy Zheng's Zink fix that keeps the Imagination depth/stencil swizzle off
colour views (Mesa d55418dae7) are in Ubuntu's Mesa 26.2 and no longer patched.
Zink also reclaims the memory a client freed once it has been idle for a second: otherwise only its
next allocation does, and Steam's UI behind a game held 250 MiB more of unswappable GPU memory.
- The runtime's built-in Vulkan driver is DroidDeck's DD-Turnip Linux build (`DD_TURNIP_URL` and
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff. Show more