Compare commits

..
55 changed files with 79 additions and 4306 deletions

No files matched your search

+2 -10
View File
@@ -157,7 +157,7 @@ jobs:
uses: actions/cache@v4
with:
path: app/src/main/assets/linuxfs
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/mangoapp/*') }}
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/mangoapp/*') }}
- name: Build libfakeinput.so and libblsession.so (glibc aarch64)
if: steps.preloads.outputs.cache-hit != 'true'
@@ -176,9 +176,6 @@ jobs:
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$D/libblsession.so" tools/linuxfs/preload/*.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$D/libblsession.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$D/libblfastpath.so" tools/proot/fastpath/fastpath.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$D/libblfastpath.so"
for script in tools/linuxfs/overlay/usr/local/bin/bannerlator-*; do
install -Dm644 "$script" "$D/usr/local/bin/$(basename "$script")"
done
@@ -211,13 +208,9 @@ jobs:
rm mango-pkgs/pkg.tar.zst
done
install -m644 mango-pkgs/usr/bin/mangoapp "$M/mangoapp"
for so in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do
for so in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1 libtracefs.so.1; do
cp -L "mango-pkgs/usr/lib/$so" "$M/$so"
done
# Ours, not the package's: GPU memory without tracefs (tools/mangoapp/libtracefs-shim.c).
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \
-o "$M/libtracefs.so.1" tools/mangoapp/libtracefs-shim.c
aarch64-linux-gnu-strip --strip-unneeded "$M/libtracefs.so.1"
install -Dm644 tools/mangoapp/mangoapp "$D/usr/local/bin/mangoapp"
rm -rf mango-pkgs
ls -l "$M"
@@ -298,7 +291,6 @@ jobs:
grep -qx "$sym" <<<"$SESSION" || { echo "::error::libblsession.so does not export $sym"; exit 1; }
done
test -f "$D/usr/local/bin/bannerlator-session"
test -f "$D/usr/local/bin/bannerlator-gog"
test -f "$D/usr/local/bin/bannerlator-proton-extra"
- name: Cache the CMake build tree
-4
View File
@@ -132,10 +132,6 @@
<service
android:name=".runtime.RuntimeInstallService"
android:exported="false" />
<!-- Holds the process in the foreground while a GOG game downloads. -->
<service
android:name=".store.gog.GogInstallService"
android:exported="false" />
<service
android:name=".core.WirelessAdbPairingService"
android:exported="false" />
+2 -12
View File
@@ -750,8 +750,6 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
static struct surface *g_hud_surface;
/* When the HUD's window last presented a frame (now_ns), to let a replacement take over. */
static int64_t g_hud_last_ns;
/* That window committed a frame the screen has not drawn yet. */
static int g_hud_fresh;
extern void banner_on_game_surface(const char *window, const char *gpu); /* window NULL = gone */
extern void banner_on_game_frame(void);
/* The program behind that window: its Linux pid (the Wayland client's credentials) and executable name
@@ -854,7 +852,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
* Asking whether the compositor could import it, as this used to, is a question about the
* copy path and not about whether a frame happened: a game whose buffers go straight to
* the display layer draws on screen while the counter sat at 0.0 fps and 1000.0 ms. */
if (s == g_hud_surface) { g_hud_last_ns = now_ns(); g_hud_fresh = 1; banner_on_game_frame(); }
if (s == g_hud_surface) { g_hud_last_ns = now_ns(); banner_on_game_frame(); }
}
/* ---- hooks for ahb_swapchain.c (zero-copy layers) */
@@ -2023,7 +2021,6 @@ static void render_scene(void) {
int copy = 0; /* this scene went through the screen swapchain (the perf line's "copy") */
g_dirty = 0;
g_hud_fresh = 0;
g_hdr_unimported = NULL; /* found again while the scene is built (HDR gate open only) */
wl_list_for_each(s, &g_surfaces, link) s->drawn = 0;
scene_size(&w, &h);
@@ -2239,13 +2236,6 @@ static void schedule_render(void) {
wl_event_source_timer_update(g_fallback_timer, 8);
}
/* With frame generation on, every scene is the engine's next source frame, so one drawn for
* another window (Steam's overlay) counted as a game frame and took its present slots. Such a
* change waits for the game's next frame, unless the game has been still for 100 ms. */
static int scene_waits_for_game(int64_t now) {
return g_hud_surface && !g_hud_fresh && now - g_hud_last_ns < 100000000LL && vkp_framegen_active();
}
/* A screen refresh (Choreographer tick): draw the newest state once. */
static void on_vsync(int64_t frame_time_ns) {
int64_t now = now_ns();
@@ -2261,7 +2251,7 @@ static void on_vsync(int64_t frame_time_ns) {
if (vkp_apply_window_request()) g_dirty = 1;
/* A screen-effect setting changed (JNI, any thread): redraw so it shows on a static scene too. */
if (vkp_effects_sync()) g_dirty = 1;
if (g_dirty && !scene_waits_for_game(now)) render_scene();
if (g_dirty) render_scene();
}
/* ------------------------------------------------------------------ wl_seat */
@@ -137,7 +137,6 @@ class MainActivity : ComponentActivity() {
private var gamescopeRealtime by mutableStateOf(false)
private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
private var phantomWarning by mutableStateOf<String?>(null)
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
@@ -1053,7 +1052,7 @@ class MainActivity : ComponentActivity() {
tuSysmem = tuSysmem, zinkLazy = zinkLazy, glThread = glThread, noGlError = noGlError, noXalia = noXalia,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, guestHostname = guestHostname, phantomWarning = phantomWarning,
prootNoSeccomp = prootNoSeccomp, guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
onTuSysmem = { on -> SessionPrefs.setTuSysmem(this, on); tuSysmem = on },
onZinkLazy = { on -> SessionPrefs.setZinkLazy(this, on); zinkLazy = on },
@@ -1063,7 +1062,6 @@ class MainActivity : ComponentActivity() {
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
onClientCore = { core, on ->
clientCores = if (on) clientCores + core else clientCores - core
@@ -1164,7 +1162,6 @@ class MainActivity : ComponentActivity() {
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
gpuClockPin = SessionPrefs.gpuClockPin(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
guestHostname = SessionPrefs.guestHostname(this)
refreshPhantomStatus()
}
@@ -369,9 +369,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun createSessionOverlay(): ComposeView = ComposeView(this).apply {
isFocusable = true
isFocusableInTouchMode = true
// Compose draws each control's focus ring. Android's default highlight would cover
// this full-screen host and remain as a white veil after the drawer closes.
defaultFocusHighlightEnabled = false
setContent {
DroidDeckTheme {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
@@ -154,7 +154,6 @@ object DeviceReport {
k("Skip xalia", SessionPrefs.noXalia(context))
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
k("proot fast path", SessionPrefs.prootFastPath(context))
k("Guest host name", SessionPrefs.guestHostname(context))
k("DirectAudio for games", SessionPrefs.directAudio(context))
k("Stretch games to fill", SessionPrefs.forceFullscreen(context))
@@ -6,8 +6,6 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.store.gog.GogGameInfo
import com.droiddeck.launcher.store.gog.GogManager
import java.io.File
import java.util.zip.CRC32
@@ -25,10 +23,6 @@ object AddedGames {
val gameId: Long,
val candidates: List<File>,
val steamAppId: Int? = null,
/** Launch arguments the game's store gives (a GOG play task's); empty for most games. */
val args: String = "",
/** The store a game was installed from ("gog"), or null for a folder the user added. */
val store: String? = null,
) {
fun folderName(): String = folder.name
}
@@ -75,9 +69,6 @@ object AddedGames {
GameStorage.effective(context)?.let { lib ->
if (path.startsWith("${lib.path}/")) return "$LIBRARY/" + path.removePrefix("${lib.path}/")
}
// The runtime's own disk (the store's internal GOG folder) is the session's root.
val rootfs = LinuxRuntime.rootDir(context).absolutePath
if (path.startsWith("$rootfs/")) return "/" + path.removePrefix("$rootfs/")
return null
}
@@ -99,38 +90,25 @@ object AddedGames {
fun scan(context: Context): List<Game> {
val out = ArrayList<Game>()
val stores = GogManager.bases(context).map { it.host }
val folders = roots(context).map { it.host } + listOfNotNull(
GameStorage.effective(context)?.let { File(it.path) },
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
) + stores.filter { it.isDirectory }
val storePaths = stores.map { it.absolutePath }.toSet()
)
for (dir in folders.distinctBy { it.absolutePath }) {
if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue }
for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) {
// The store's folder is a folder of games, not one; its games are scanned on their own.
if (folder.absolutePath in storePaths) continue
scanGame(context, folder, out)
}
for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) scanGame(context, folder, out)
}
return out.distinctBy { it.folder.canonicalPath }
}
private fun scanGame(context: Context, folder: File, out: MutableList<Game>) {
run {
// A store download still running (or stopped partway) is not a game yet.
if (GogManager.incomplete(folder)) return
// A game the store installed says which exe it is, where it starts and with what
// arguments. Folders the user added keep the guess: changing their exe would change
// their shortcut id, and with it the prefix their saves are in.
val task = if (File(folder, GogManager.MARKER).isFile) GogGameInfo.read(folder)?.task else null
val candidates = candidates(folder)
val chosen = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
val exe = chosen ?: task?.exe ?: candidates.firstOrNull() ?: return
val exe = chosen ?: candidates.firstOrNull() ?: return
val guestExe = guestPath(context, exe)
if (guestExe == null) { Log.w(TAG, "${folder.name}: the session cannot see ${exe.path}"); return }
val startDir = if (chosen == null && task != null) task.workingDir else exe.parentFile ?: folder
val guestDir = guestPath(context, startDir) ?: return
val guestDir = guestPath(context, exe.parentFile ?: folder) ?: return
val name = folder.name
// Keyed by the pre-rename path so shortcut ids, and the prefixes and saves under them, stay put.
val crc = CRC32().apply { update(("\"${guestExe.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + name).toByteArray()) }.value
@@ -138,8 +116,7 @@ object AddedGames {
val steamRoot = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
val steamId = steamRoute(steamRoot, appId)
out.add(Game(folder, name, exe, guestExe, guestDir, appId,
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId,
args = if (chosen == null) task?.arguments.orEmpty() else "", store = if (task != null) "gog" else null))
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId))
}
}
@@ -162,8 +139,6 @@ object AddedGames {
json.append("{\"name\":").append(quote(g.name)).append(",\"exe\":").append(quote(g.guestExe))
.append(",\"folder\":").append(quote(guestPath(context, g.folder) ?: g.guestDir))
.append(",\"dir\":").append(quote(g.guestDir)).append(",\"appid\":").append(g.appId)
if (g.args.isNotEmpty()) json.append(",\"args\":").append(quote(g.args))
g.store?.let { json.append(",\"store\":").append(quote(it)) }
// The art, as the session sees it: the app's cache is bound at its own path, a file in
// the game's folder at the folder's guest path.
val art = AddedGameArt.resolve(context, g)
@@ -5,7 +5,6 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SecondaryLibrary
import java.io.File
/**
@@ -85,11 +84,7 @@ object Library {
/** Proton keeps each game's prefix below compatdata/<appid>/pfx in a Steam library. */
fun protonPrefix(context: Context, appId: Long, preferredLibrary: File? = null): File? {
val ids = listOf(appId.toString(), java.lang.Integer.toString(appId.toInt())).distinct()
val secondary = GameStorage.effective(context)?.let { File(it.path) }
fun prefixRoot(root: File): File = if (secondary != null && root.canonicalPath == secondary.canonicalPath)
SecondaryLibrary.privateRoot(context.filesDir, root).takeIf { File(it, "steamapps/compatdata").isDirectory } ?: root
else root
val roots = (listOfNotNull(preferredLibrary) + steamLibraries(context).map { it.first }).map(::prefixRoot)
val roots = (listOfNotNull(preferredLibrary) + steamLibraries(context).map { it.first })
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
return roots.asSequence()
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
@@ -89,7 +89,7 @@ object FlatpakManager {
/** Runs [argv] in the runtime, its output also in Download/DroidDeck/flatpak-<verb>.log. */
private fun runGuest(context: Context, argv: List<String>, fakeRoot: Boolean, onLine: (String) -> Unit): Int {
val name = "flatpak-" + (argv.getOrNull(2)?.takeIf { argv.getOrNull(1) == HELPER } ?: "setup")
return GuestCommand.run(context, argv, fakeRoot, name, onLine = onLine)
return GuestCommand.run(context, argv, fakeRoot, name, onLine)
}
private inline fun <T> exclusive(what: String, block: () -> T): T? {
@@ -18,12 +18,9 @@ object GuestCommand {
* Runs [argv] and hands each output line to [onLine]; returns the exit status. [fakeRoot] is
* for the package tools, which refuse any uid but 0. With [logName], everything the command
* says also goes to Download/DroidDeck/tools/<logName>.log beside the session logs, so a problem can
* be handed over like a session's. [extraBinds] are proot binds beyond the usual ones (a game
* library on an SD card), and [onProcess] gets the process as it starts, for a caller that may
* have to stop it.
* be handed over like a session's.
*/
fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null,
extraBinds: List<String> = emptyList(), onProcess: ((Process) -> Unit)? = null,
onLine: (String) -> Unit): Int {
val log = logName?.let {
try {
@@ -32,14 +29,13 @@ object GuestCommand {
}
log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
try {
return runLogged(context, argv, fakeRoot, extraBinds, onProcess) { line -> log?.println(line); log?.flush(); onLine(line) }
return runLogged(context, argv, fakeRoot) { line -> log?.println(line); log?.flush(); onLine(line) }
} finally {
log?.close()
}
}
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, extraBinds: List<String>,
onProcess: ((Process) -> Unit)?, onLine: (String) -> Unit): Int {
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, onLine: (String) -> Unit): Int {
val root = LinuxRuntime.rootDir(context)
LinuxRuntime.writeAccounts(context)
SessionFiles.stage(context, root)
@@ -49,10 +45,9 @@ object GuestCommand {
val cmd = LinuxRuntime.prootPrefix(context, root, "/root", fakeRoot)
LinuxRuntime.binds(context, null, runtimeDir, Environment.getExternalStorageDirectory(), null)
.forEach { cmd.add("-b"); cmd.add(it) }
extraBinds.forEach { cmd.add("-b"); cmd.add(it) }
cmd += listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "LANG=C.UTF-8",
"PATH=/usr/local/bin:/usr/bin:/bin", "XDG_RUNTIME_DIR=${LinuxRuntime.GUEST_RUNTIME_DIR}",
"PATH=/usr/local/bin:/usr/bin:/bin", "XDG_RUNTIME_DIR=${runtimeDir.path}",
"XDG_DATA_HOME=/root/.local/share", "FLATPAK_BWRAP=${FlatpakManager.BWRAP}",
"XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share",
)
@@ -67,7 +62,6 @@ object GuestCommand {
val process = builder.start()
val pid = HostProcess.pidOf(process)
OrphanReaper.keep(pid)
onProcess?.invoke(process)
try {
process.inputStream.bufferedReader().useLines { lines -> lines.forEach(onLine) }
return process.waitFor()
@@ -34,14 +34,6 @@ public final class LinuxRuntime {
/** Shortcut extra naming which of the modes above a Linux entry launches. */
public static final String EXTRA_LINUX_MODE = "linux_mode";
private static final String KGSL_DEVICE = "/dev/kgsl-3d0";
/**
* Where the guest sees a command's XDG_RUNTIME_DIR. A Unix socket's path must fit in 108 bytes,
* and libwayland checks the guest's path before proot ever sees it: with the app on an SD card
* adopted as internal storage the files directory is /mnt/expand/<uuid>/user/0/<package>/files,
* and gamescope-0 under it is one byte over, so gamescope could not open its socket and the
* session ended at once. A long host path behind it is proot's to shorten.
*/
public static final String GUEST_RUNTIME_DIR = "/run/droiddeck";
/** Where every Linux session's debug log lands: public, so a user can just hand the folder over. */
public static final String DEBUG_LOG_DIR = "DroidDeck";
@@ -193,10 +185,7 @@ public final class LinuxRuntime {
bind(cmd, new File(root, "etc/bannerlator/empty").getPath() + ":/sys/fs/selinux");
bind(cmd, context.getFilesDir().getPath());
bind(cmd, context.getCacheDir().getPath());
if (runtimeDir != null) {
bind(cmd, runtimeDir.getPath());
bind(cmd, runtimeDir.getPath() + ":" + GUEST_RUNTIME_DIR);
}
if (runtimeDir != null) bind(cmd, runtimeDir.getPath());
if (sessionRoot != null) bind(cmd, sessionRoot.getPath());
if (externalStorage != null && externalStorage.isDirectory()) {
bind(cmd, externalStorage.getPath());
@@ -242,15 +231,12 @@ public final class LinuxRuntime {
};
for (String[] entry : procFiles) {
File fake = new File(fakeProc, entry[0]);
// A live stand-in the session binds itself (CpuStatComponent's /proc/stat) wins.
boolean live = false;
if (extraBinds != null) for (String spec : extraBinds) live |= spec.endsWith(":" + entry[1]);
if (!live && fake.isFile() && !new File(entry[1]).canRead()) {
if (fake.isFile() && !new File(entry[1]).canRead()) {
bind(cmd, fake.getPath() + ":" + entry[1]);
}
}
bindGpuNode(context, cmd);
bindAdrenoStats(cmd, extraBinds);
bindAdrenoStats(cmd);
bindCpuTemps(cmd, root);
if (extraBinds != null) {
for (String spec : extraBinds) bind(cmd, spec);
@@ -296,71 +282,12 @@ public final class LinuxRuntime {
if (!Files.isSymbolicLink(subsystem.toPath())) {
Os.symlink("/sys/bus/platform", subsystem.getPath());
}
// What MangoHud names a GPU's driver by; msm_drm is how an Adreno's render node reads
// on a mainline kernel, and the driver it reads the load of (bindAdrenoStats).
File driver = new File(device, "driver");
if (!Files.isSymbolicLink(driver.toPath())) {
Os.symlink("/sys/bus/platform/drivers/msm_drm", driver.getPath());
}
} catch (IOException | ErrnoException e) {
return;
}
bind(cmd, new File(base, "sys").getPath() + ":/sys/dev/char");
bind(cmd, dri.getPath() + ":/dev/dri");
bind(cmd, KGSL_DEVICE + ":/dev/dri/" + node);
bindDrmClass(base, cmd, node, major + ":" + minor);
}
/**
* MangoHud (Deck mode's performance overlay, mangoapp) finds the GPU by listing
* {@code /sys/class/drm}, and an exception from that listing ends the process: under an
* enforcing SELinux policy - every retail phone - an app may not list it, so mangoapp died on
* start, gamescope restarted it until the session gave up, and there was no overlay. Where the
* app cannot list it, the session's {@code /sys/class/drm} is ours: the render node above,
* named as an Adreno's is. MangoHud then reads the GPU's stats from KGSL's sysfs, which such a
* device refuses too - SessionService's GpuStatsComponent stands in for that. Where the
* listing is allowed it is left alone.
*/
private static void bindDrmClass(File base, List<String> cmd, String node, String devNumbers) {
if (new File("/sys/class/drm").list() != null) return;
File drmClass = new File(base, "class");
try {
if (!drmClass.isDirectory() && !drmClass.mkdirs()) return;
// Only symlinks are ever made here; deleting them must not follow one into its target.
File[] old = drmClass.listFiles();
if (old != null) for (File f : old) Files.deleteIfExists(f.toPath());
Os.symlink("/sys/dev/char/" + devNumbers, new File(drmClass, node).getPath());
} catch (IOException | ErrnoException e) {
return;
}
bind(cmd, drmClass.getPath() + ":/sys/class/drm");
android.util.Log.i("LinuxRuntime", "hud: /sys/class/drm is not listable here; the session's lists " + node);
// Also refused to list, also asked for by MangoHud twice a second - an error line each
// time in the session log - and holding nothing it reads on an Adreno phone.
if (new File("/sys/class/powercap").list() == null) {
File empty = new File(base, "empty-powercap");
if (empty.isDirectory() || empty.mkdirs()) bind(cmd, empty.getPath() + ":/sys/class/powercap");
}
}
/** The temperature of a CPU zone the app may read (the first by name), or null. */
public static String cpuTempSource() {
for (java.util.Map.Entry<String, File> e : new java.util.TreeMap<>(thermalZones()).entrySet()) {
File temp = new File(e.getValue(), "temp");
if (e.getKey().contains("cpu") && !e.getKey().contains("gpu") && temp.canRead()) return temp.getPath();
}
return null;
}
/** The file the GPU's temperature reads from, or null where the app may read none. */
public static String gpuTempSource() {
String kgsl = "/sys/class/kgsl/kgsl-3d0/";
return firstReadable(kgsl + "temp", kgsl + "devfreq/temp", thermalZone("gpu"));
}
private static String gpuLoadSource() {
String kgsl = "/sys/class/kgsl/kgsl-3d0/";
return firstReadable(kgsl + "gpu_busy_percentage", kgsl + "devfreq/gpu_load");
}
/**
@@ -371,11 +298,11 @@ public final class LinuxRuntime {
* Android PC emulators (GameNative, Winlator forks) read them in. A value found nowhere is left
* alone.
*/
private static void bindAdrenoStats(List<String> cmd, List<String> extraBinds) {
private static void bindAdrenoStats(List<String> cmd) {
String kgsl = "/sys/class/kgsl/kgsl-3d0/";
String gpuTemp = gpuTempSource();
String gpuTemp = firstReadable(kgsl + "temp", kgsl + "devfreq/temp", thermalZone("gpu"));
String[][] stats = {
{gpuLoadSource(), "/sys/kernel/debug/dri/0/perf_now"},
{firstReadable(kgsl + "gpu_busy_percentage", kgsl + "devfreq/gpu_load"), "/sys/kernel/debug/dri/0/perf_now"},
{firstReadable(kgsl + "devfreq/cur_freq", kgsl + "gpuclk"),
"/sys/devices/platform/soc@0/3d00000.gpu/devfreq/3d00000.gpu/cur_freq"},
{gpuTemp, "/sys/class/thermal/thermal_zone28/temp"},
@@ -383,21 +310,8 @@ public final class LinuxRuntime {
{thermalZone("ddr"), "/sys/class/thermal/thermal_zone22/temp"},
};
for (String[] stat : stats) {
// A value the session feeds itself (GpuStatsComponent, where KGSL is refused) wins.
boolean fed = false;
if (extraBinds != null) for (String spec : extraBinds) fed |= spec.endsWith(":" + stat[1]);
if (stat[0] != null && !fed) bind(cmd, stat[0] + ":" + stat[1]);
if (stat[0] != null) bind(cmd, stat[0] + ":" + stat[1]);
}
// Which of the overlay's GPU values this device lets the app read: a phone under an
// enforcing policy refuses some of them, and the overlay then has no line for that value.
android.util.Log.i("LinuxRuntime", "hud sources: gpu load " + orNone(stats[0][0]) + ", gpu clock "
+ orNone(stats[1][0]) + ", gpu temp " + orNone(gpuTemp) + ", ddr temp " + orNone(stats[4][0])
+ ", thermal zones " + thermalZones().size()
+ ", kgsl gpubusy " + (new File(kgsl + "gpubusy").canRead() ? "readable" : "refused"));
}
private static String orNone(String path) {
return path != null ? path : "none";
}
/**
@@ -1,45 +0,0 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.security.MessageDigest
/**
* proot's fast path: the session's path lookups answered inside each process by libblfastpath
* (tools/proot/fastpath), which issues the translated call from a trampoline page proot's seccomp
* filter lets through (tools/proot/patches/0014). A stat or an open costs about a microsecond
* instead of a 15-60 us round trip through the tracer.
*
* The library maps guest paths to host paths itself, so it has to be told the rootfs and the
* binds exactly as proot was given them. Both sides carry a key derived from that view - proot
* PROOT_FASTPATH=<key>, the guest PROOT_FP_KEY=<key> - and the library answers nothing unless the
* process that traces it has the same key: a program that inherited the variables but runs under
* another proot (a Flatpak sandbox, a one-off command) leaves every call to its own proot.
*
* Needs proot's seccomp filter, so "Run proot without seccomp" turns it off as well.
*/
object ProotFastPath {
const val LIBRARY = "/usr/local/lib/libblfastpath.so"
fun enabled(context: Context): Boolean =
SessionPrefs.prootFastPath(context) && !SessionPrefs.prootNoSeccomp(context)
/** The key for this rootfs and these binds, or null when the library cannot be told them. */
fun key(root: File, binds: List<String>): String? {
if (binds.any { it.contains('|') } || root.path.contains('|')) return null
val digest = MessageDigest.getInstance("SHA-256")
.digest((root.path + "\n" + binds.joinToString("\n")).toByteArray())
return digest.take(12).joinToString("") { "%02x".format(it) }
}
/** What proot's own environment carries. */
fun hostEnv(key: String): Pair<String, String> = "PROOT_FASTPATH" to key
/** The guest's assignments (for `env -i`), describing the view proot was given. */
fun guestEnv(root: File, binds: List<String>, key: String): List<String> = listOf(
"PROOT_FP_ROOT=" + root.path,
"PROOT_FP_BINDS=" + binds.joinToString("|"),
"PROOT_FP_KEY=$key",
)
}
@@ -1,110 +0,0 @@
package com.droiddeck.launcher.session
import android.os.SystemClock
import android.util.Log
import com.droiddeck.launcher.core.SessionPart
import java.io.File
/**
* A `/proc/stat` that moves.
*
* Android has refused apps `/proc/stat` since 8.0, and the session's stand-in for it was one
* `cpu0` line of zeros - enough for glibc and Steam to start, but every CPU load in the session
* read 0 % (the performance overlay showed one core, idle). The kernel still lets apps read each
* core's idle residency (`cpuidle/stateN/time`, µs, the same label as the cpufreq files), which is
* how overlays on Android work out CPU load: a core's busy time is the time that passed less the
* time it spent idle. This writes `/proc/stat` from that, one line per core, refreshed twice a
* second. Counters only grow - a sample's idle is never more than the time that passed - so a
* reader taking the difference of two reads never sees a negative. Where `/proc/stat` is readable,
* or the idle times are not, nothing is done.
*/
class CpuStatComponent(val file: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
private val cores = (0 until coreCount()).toList()
private val busy = LongArray(cores.size)
private val idle = LongArray(cores.size)
private val lastIdleUs = LongArray(cores.size)
private var lastMs = 0L
private val bootSeconds = (System.currentTimeMillis() - SystemClock.elapsedRealtime()) / 1000
/** Writes the first sample; true when it should be bound over `/proc/stat`. */
fun prepare(): Boolean {
if (File("/proc/stat").canRead() || cores.isEmpty() || idleUs(0) == null) return false
lastMs = SystemClock.elapsedRealtime()
for (i in cores) lastIdleUs[i] = idleUs(i) ?: 0L
write()
Log.i(TAG, "hud: /proc/stat from the cores' idle times (${cores.size} cores)")
return true
}
override fun start() {
running = true
thread = Thread({
while (running) {
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
if (!running) break
sample()
write()
}
}, "cpu-stat").apply { isDaemon = true; start() }
}
override fun stop() {
running = false
thread?.interrupt()
thread = null
}
private fun sample() {
val now = SystemClock.elapsedRealtime()
val elapsed = (now - lastMs) / MS_PER_TICK
if (elapsed <= 0) return
lastMs += elapsed * MS_PER_TICK
for (i in cores) {
// An offline core has no idle residency to count and runs nothing: all idle.
val us = idleUs(i)
val idleTicks = if (us == null) elapsed else ((us - lastIdleUs[i]) / US_PER_TICK).coerceIn(0, elapsed)
if (us != null) lastIdleUs[i] = us
idle[i] += idleTicks
busy[i] += elapsed - idleTicks
}
}
/** The whole file at once, renamed into place: a reader opens either the last sample or this one. */
private fun write() {
val text = StringBuilder()
text.append("cpu ${busy.sum()} 0 0 ${idle.sum()} 0 0 0 0 0 0\n")
for (i in cores) text.append("cpu$i ${busy[i]} 0 0 ${idle[i]} 0 0 0 0 0 0\n")
text.append("intr 0\nctxt 0\nbtime $bootSeconds\nprocesses 1\nprocs_running 1\nprocs_blocked 0\n")
try {
val tmp = File(file.parentFile, file.name + ".tmp")
tmp.writeText(text.toString())
if (!tmp.renameTo(file)) tmp.delete()
} catch (e: Exception) {
}
}
companion object {
private const val TAG = "SessionService"
private const val PERIOD_MS = 500L
/** /proc/stat counts in USER_HZ, 100 a second on every Linux the guest runs. */
private const val MS_PER_TICK = 10L
private const val US_PER_TICK = 10_000L
private fun coreCount(): Int =
File("/sys/devices/system/cpu").list()?.count { it.matches(Regex("cpu\\d+")) } ?: 0
/** The core's total idle residency in µs, or null when it has none to read (offline). */
private fun idleUs(core: Int): Long? {
val states = File("/sys/devices/system/cpu/cpu$core/cpuidle").listFiles { f -> f.name.startsWith("state") }
?: return null
if (states.isEmpty()) return null
var total = 0L
for (state in states) {
total += runCatching { File(state, "time").readText().trim().toLong() }.getOrNull() ?: return null
}
return total
}
}
}
@@ -1,118 +0,0 @@
package com.droiddeck.launcher.session
import android.util.Log
import com.droiddeck.launcher.core.SessionPart
import java.io.File
/**
* The GPU memory in use, for the performance overlay's VRAM and PVRAM lines.
*
* Valve's mangoapp reads it from the kernel's gpu_mem_total tracepoint, which no Android app may
* reach, so both lines read 0. Our libtracefs for mangoapp (tools/mangoapp/libtracefs-shim.c) hands
* it what this writes to [file] - `/run/droiddeck-hud/gpu-mem` in the guest - every few seconds, in
* bytes, from the best of what KGSL lets the app read:
*
* - `/sys/class/kgsl/kgsl/page_alloc`, every GPU page on the device - what the tracepoint's total
* counts, where the policy allows it;
* - else KGSL's own accounting of each of the session's processes
* (`/sys/class/kgsl/kgsl/proc/<pid>/gpumem_mapped` and `gpumem_unmapped`);
* - else the size of the KGSL mappings in each of the session's processes' `maps` - only the
* buffers the CPU has mapped, so less than the GPU holds (about 40 % of KGSL's own count in a
* game on an AYN Thor), but always readable: every process the app can see in `/proc` is one of
* its own. `maps` rather than `smaps`, which gives the same sizes but walks page tables to do it:
* in a game, 180,000 lines and most of a second of CPU a pass.
*
* Sampled only while the overlay shows (OverlayShown).
*/
class GpuMemComponent(private val file: File, private val root: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
private var source = ""
/** True when there is a source to write from. */
fun prepare(): Boolean {
val bytes = sample() ?: return false
write(bytes)
Log.i(TAG, "hud: gpu memory from $source (${bytes / (1024 * 1024)} MiB now)")
return true
}
override fun start() {
running = true
thread = Thread({
while (running) {
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
if (running && OverlayShown.check(root)) sample()?.let { write(it) }
}
}, "gpu-mem").apply { isDaemon = true; start() }
}
override fun stop() {
running = false
thread?.interrupt()
thread = null
file.delete()
}
private fun sample(): Long? {
readLong("$KGSL_ROOT/page_alloc")?.let { source = "$KGSL_ROOT/page_alloc"; return it }
val pids = sessionPids()
var perProcess = 0L
var anyProcess = false
for (pid in pids) {
val mapped = readLong("$KGSL_ROOT/proc/$pid/gpumem_mapped") ?: continue
perProcess += mapped + (readLong("$KGSL_ROOT/proc/$pid/gpumem_unmapped") ?: 0L)
anyProcess = true
}
if (anyProcess) { source = "$KGSL_ROOT/proc/<pid>/gpumem_*"; return perProcess }
var mappedKb = 0L
var anyMap = false
for (pid in pids) {
val kb = kgslMappedKb(pid) ?: continue
mappedKb += kb
anyMap = true
}
if (anyMap) { source = "/proc/<pid>/maps (KGSL mappings)"; return mappedKb * 1024 }
return null
}
/** The processes this app may see in /proc: Android hides every other uid's. */
private fun sessionPids(): List<String> =
File("/proc").list()?.filter { it.isNotEmpty() && it.all(Char::isDigit) }.orEmpty()
/** Size of a process's mappings of the KGSL device, in kB; null where its maps cannot be read. */
private fun kgslMappedKb(pid: String): Long? = runCatching {
var bytes = 0L
File("/proc/$pid/maps").forEachLine { line ->
if (line.endsWith("kgsl-3d0") || line.contains("/dev/dri/renderD")) {
val dash = line.indexOf('-')
val space = line.indexOf(' ')
if (dash > 0 && space > dash) {
bytes += line.substring(dash + 1, space).toLong(16) - line.substring(0, dash).toLong(16)
}
}
}
bytes / 1024
}.getOrNull()
/** Whole, renamed into place: the reader opens either the last value or this one. */
private fun write(bytes: Long) {
try {
file.parentFile?.mkdirs()
val tmp = File(file.parentFile, file.name + ".tmp")
tmp.writeText("$bytes\n")
if (!tmp.renameTo(file)) tmp.delete()
} catch (e: Exception) {
}
}
companion object {
private const val TAG = "SessionService"
private const val KGSL_ROOT = "/sys/class/kgsl/kgsl"
/** GPU memory moves slowly; a pass over every process's maps is ~40 ms of CPU in a game. */
private const val PERIOD_MS = 5_000L
private fun readLong(path: String): Long? =
runCatching { File(path).readText().trim().toLong() }.getOrNull()
}
}
@@ -1,176 +0,0 @@
package com.droiddeck.launcher.session
import android.util.Log
import com.droiddeck.launcher.core.SessionPart
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.io.RandomAccessFile
/**
* The Adreno's stats as mangoapp (Deck mode's performance overlay) reads them.
*
* MangoHud takes an Adreno's load, clock and temperature from `gpu_busy_percentage`, `clock_mhz`
* and `temp` in `/sys/class/kgsl/kgsl-3d0`, and ends the process on one of them it may not read -
* not on one that is missing, which it skips. An enforcing SELinux policy (every retail phone)
* refuses apps some or all of KGSL's sysfs, each vendor differently, so mangoapp died on start and
* the session ran with no overlay. Where any of the three is refused, a directory of our own is
* bound there instead, each value fed twice a second from the first source this device lets the
* app read - the places other Android overlays (GameNative, WinNative, Bannerlator) read an
* Adreno's numbers from, across Snapdragon generations and vendor kernels. A value with no
* readable source is left out, and the overlay shows no line for it. Where all three are
* readable, nothing is done.
*
* Valve's build also reads load and clock where a mainline msm kernel has them (debugfs
* `perf_now`, the GPU's devfreq `cur_freq` in Hz) - the paths LinuxRuntime.bindAdrenoStats points
* at KGSL's own files when it may - so the same values are fed there too, in the same formats
* ([binds]).
*/
class GpuStatsComponent(val dir: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
private val feeds = ArrayList<Feed>()
/** One of MangoHud's files and where its value comes from. */
private class Feed(
val file: File, val source: String, val read: () -> Long?, val format: String, val percent: Boolean = false,
)
/** Where Valve's msm reader looks, and the feed for it, as host:guest binds. */
fun binds(): List<String> {
val list = mutableListOf(dir.path + ":" + KGSL)
if (File(dir, "perf_now").exists()) list.add(File(dir, "perf_now").path + ":" + MSM_LOAD)
if (File(dir, "cur_freq").exists()) list.add(File(dir, "cur_freq").path + ":" + MSM_CLOCK)
return list
}
/** Writes the directory; true when it should be bound over [KGSL]. */
fun prepare(): Boolean {
if (!File(KGSL).exists() || MANGOHUD_FILES.none { File(KGSL, it).let { f -> f.exists() && !f.canRead() } }) return false
return try {
dir.mkdirs()
dir.listFiles()?.forEach { java.nio.file.Files.deleteIfExists(it.toPath()) }
feeds.clear()
loadFeed()?.let { load ->
feeds.add(load)
// KGSL's gpu_busy_percentage reads "37 %"; padded after, so a shorter value
// written over a longer one leaves no digits behind.
feeds.add(Feed(File(dir, "perf_now"), load.source, load.read, "%-6s\n", percent = true))
}
pick("clock_mhz", clockSources(), "%5d\n") { mhz(it) }?.let { clock ->
feeds.add(clock)
feeds.add(Feed(File(dir, "cur_freq"), clock.source, { clock.read()?.times(1_000_000) }, "%-10d\n"))
}
pick("temp", tempSources(), "%6d\n") { milliCelsius(it) }?.let { feeds.add(it) }
feeds.forEach { feed -> feed.read()?.let { write(feed, it) } }
Log.i(TAG, "hud: kgsl stats from the session's own: " + MANGOHUD_FILES.joinToString { name ->
"$name " + (feeds.firstOrNull { it.file.name == name }?.source ?: "none")
})
true
} catch (e: Exception) {
Log.w(TAG, "hud: could not stand in for kgsl stats: $e")
false
}
}
override fun start() {
if (feeds.isEmpty()) return
running = true
thread = Thread({
while (running) {
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
if (!running) break
for (feed in feeds) feed.read()?.let { write(feed, it) }
}
}, "gpu-stats").apply { isDaemon = true; start() }
}
override fun stop() {
running = false
thread?.interrupt()
thread = null
}
/** Load: a file that states it in percent, else KGSL's busy and total of the last sample. */
private fun loadFeed(): Feed? {
pick("gpu_busy_percentage", LOAD_SOURCES, "%3d %%\n") { it.coerceIn(0, 100) }?.let { return it }
val gpubusy = "$KGSL/gpubusy"
val read = {
runCatching {
val parts = File(gpubusy).readText().trim().split(Regex("\\s+"))
val total = parts[1].toLong()
if (total > 0) (parts[0].toLong() * 100 / total).coerceIn(0, 100) else 0L
}.getOrNull()
}
return if (read() != null) Feed(File(dir, "gpu_busy_percentage"), gpubusy, read, "%3d %%\n") else null
}
/** The first of [sources] that reads as a number, its value put in MangoHud's unit by [unit]. */
private fun pick(name: String, sources: List<String>, format: String, unit: (Long) -> Long?): Feed? {
for (source in sources) {
val read = { firstNumber(source)?.let(unit) }
if (read() != null) return Feed(File(dir, name), source, read, format)
}
return null
}
/** In place and at one length, so a reader that keeps the file open sees each value whole. */
private fun write(feed: Feed, value: Long) {
try {
val text = if (feed.percent) String.format(feed.format, "$value %") else String.format(feed.format, value)
RandomAccessFile(feed.file, "rw").use { it.seek(0); it.write(text.toByteArray()) }
} catch (e: Exception) {
}
}
companion object {
private const val TAG = "SessionService"
const val KGSL = "/sys/class/kgsl/kgsl-3d0"
/** Must match LinuxRuntime.bindAdrenoStats. */
const val MSM_LOAD = "/sys/kernel/debug/dri/0/perf_now"
const val MSM_CLOCK = "/sys/devices/platform/soc@0/3d00000.gpu/devfreq/3d00000.gpu/cur_freq"
private const val PERIOD_MS = 500L
private val MANGOHUD_FILES = listOf("gpu_busy_percentage", "clock_mhz", "temp")
/** Qualcomm's own GPU summary, beside KGSL in vendor kernels, under the plain sysfs label. */
private const val QCOM_GPU = "/sys/kernel/gpu"
private val LOAD_SOURCES = listOf(
"$KGSL/gpu_busy_percentage", "$KGSL/devfreq/gpu_load", "$KGSL/gpuload", "$QCOM_GPU/gpu_busy",
)
/** The GPU's devfreq node is named by its register address, which differs between Snapdragons. */
private val DEVFREQ_NODES = listOf(
"kgsl-3d0", "3d00000.qcom,kgsl-3d0", "2c00000.qcom,kgsl-3d0", "5000000.qcom,kgsl-3d0", "5900000.qcom,kgsl-3d0",
)
private fun clockSources(): List<String> {
val sources = mutableListOf(
"$KGSL/clock_mhz", "$KGSL/gpu_clock", "$KGSL/gpuclk", "$KGSL/devfreq/cur_freq", "$QCOM_GPU/gpu_clock",
)
DEVFREQ_NODES.forEach { sources.add("/sys/class/devfreq/$it/cur_freq") }
File("/sys/class/devfreq").list()?.sorted()?.forEach { node ->
if (node.contains("kgsl") || node.contains("gpu")) sources.add("/sys/class/devfreq/$node/cur_freq")
}
return sources.distinct()
}
private fun tempSources(): List<String> =
listOfNotNull("$KGSL/temp", "$KGSL/devfreq/temp", "$QCOM_GPU/temp", LinuxRuntime.gpuTempSource()).distinct()
/** The first integer in the file ("550", "37 %", "550000000"), or null. */
private fun firstNumber(path: String): Long? =
runCatching { Regex("-?\\d+").find(File(path).readText())?.value?.toLong() }.getOrNull()
/** Hz, kHz or MHz to MHz, as the files differ; a stopped clock reads 0. */
private fun mhz(raw: Long): Long? = when {
raw < 0 -> null
raw > 10_000_000 -> raw / 1_000_000
raw > 10_000 -> raw / 1_000
else -> raw
}
/** °C or m°C to MangoHud's m°C; nothing a GPU reads at is below 1 °C or above 1000. */
private fun milliCelsius(raw: Long): Long? = when {
raw <= 0 -> null
raw < 1000 -> raw * 1000
else -> raw
}
}
}
@@ -1,141 +0,0 @@
package com.droiddeck.launcher.session
import android.os.SystemClock
import android.system.Os
import android.util.Log
import com.droiddeck.launcher.core.SessionPart
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.io.RandomAccessFile
/**
* The session's `/sys/class/hwmon`, as mangoapp (Deck mode's performance overlay) looks there.
*
* MangoHud finds a CPU's temperature by an hwmon sensor named `cpuN_thermal`, and an Adreno's
* temperature, fan and power by one whose name has `gpuss` in it - a mainline Arm kernel's names.
* An Android kernel has neither (its hwmon holds the PMIC's sensors, or nothing), and where the
* app may not list hwmon at all the overlay logged an error twice a second. So the overlay showed
* no CPU temperature and no fan. This is two sensors named so:
*
* - `hwmon0` (`cpu0_thermal`): `temp1_input` linked to a CPU thermal zone the app can read;
* - `hwmon1` (`gpuss0_thermal`): `temp1_input` linked to the GPU's zone, and `fan1_input` with
* the device's fan speed where it has a fan the app can read - an AYN handheld's tachometer
* (`/sys/class/gpio5_pwm2/speed`), or a `fan*_input` in the device's own hwmon;
* - `hwmon2` (`slg4ax46073v`): the same fan, for Valve's own Qualcomm reader (msm.cpp), which
* looks for its fan controller by that name and halves what it reads - that part reports twice
* the real speed - so this one holds twice it.
*
* Nothing in a phone's own hwmon is read by the overlay, so standing in for it loses nothing.
*/
class HwmonComponent(val dir: File, private val root: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
private var fanSource: String? = null
private val fanFile = File(dir, "hwmon1/fan1_input")
private val valveFanFile = File(dir, "hwmon2/fan1_input")
private var lastRpm = 0L
private var lastRpmAt = 0L
/** Writes the sensors; true when the directory should be bound over `/sys/class/hwmon`. */
fun prepare(): Boolean = try {
dir.mkdirs()
clear(dir)
val cpu = LinuxRuntime.cpuTempSource()
if (cpu != null) sensor("hwmon0", "cpu0_thermal").also { link(cpu, File(it, "temp1_input")) }
val gpu = LinuxRuntime.gpuTempSource()
fanSource = FAN_SOURCES().firstOrNull { readNumber(it) != null }
if (gpu != null || fanSource != null) {
val sensor = sensor("hwmon1", "gpuss0_thermal")
if (gpu != null) link(gpu, File(sensor, "temp1_input"))
if (fanSource != null) {
sensor("hwmon2", "slg4ax46073v")
writeFan(sampleFan())
}
}
Log.i(TAG, "hud: hwmon cpu temp ${cpu ?: "none"}, gpu temp ${gpu ?: "none"}, fan ${fanSource ?: "none"}")
cpu != null || gpu != null || fanSource != null
} catch (e: Exception) {
Log.w(TAG, "hud: could not write the session's hwmon: $e")
false
}
override fun start() {
if (fanSource == null) return
running = true
thread = Thread({
while (running) {
try { Thread.sleep(FAN_PERIOD_MS) } catch (e: InterruptedException) { break }
// A tachometer read busy-waits 100 ms in the kernel: only while the overlay shows.
if (running && OverlayShown.check(root)) writeFan(sampleFan())
}
}, "hwmon-fan").apply { isDaemon = true; start() }
}
override fun stop() {
running = false
thread?.interrupt()
thread = null
}
/**
* The fan's speed in RPM. An AYN tachometer counts pulses over a short window per read and
* often catches none, reading 0 while the fan turns; a reading is held until a newer one
* comes or [FAN_HOLD_MS] passes with only zeros, when the fan is taken to have stopped.
*/
private fun sampleFan(): Long {
val now = SystemClock.elapsedRealtime()
val rpm = fanSource?.let { readNumber(it) } ?: 0L
if (rpm > 0) {
lastRpm = rpm
lastRpmAt = now
} else if (now - lastRpmAt > FAN_HOLD_MS) {
lastRpm = 0
}
return lastRpm
}
/** In place and at one length, so a reader that keeps the file open sees each value whole. */
private fun writeFan(rpm: Long) {
for ((file, value) in listOf(fanFile to rpm, valveFanFile to rpm * 2)) {
try {
RandomAccessFile(file, "rw").use { it.seek(0); it.write(String.format("%6d\n", value).toByteArray()) }
} catch (e: Exception) {
}
}
}
private fun sensor(name: String, label: String): File =
File(dir, name).apply { mkdirs(); File(this, "name").writeText("$label\n") }
private fun link(target: String, link: File) {
java.nio.file.Files.deleteIfExists(link.toPath())
Os.symlink(target, link.path)
}
/** Only files and links are made here; deleting a link must not follow it into sysfs. */
private fun clear(root: File) {
root.listFiles()?.forEach { f ->
if (!java.nio.file.Files.isSymbolicLink(f.toPath()) && f.isDirectory) clear(f)
java.nio.file.Files.deleteIfExists(f.toPath())
}
}
companion object {
private const val TAG = "SessionService"
/** The AYN tachometer reads 0 if read again within a couple of seconds. */
private const val FAN_PERIOD_MS = 3_000L
private const val FAN_HOLD_MS = 10_000L
private val FAN_SOURCES = {
val sources = mutableListOf("/sys/class/gpio5_pwm2/speed", "/sys/class/gpio5_pwm/speed")
File("/sys/class/hwmon").listFiles()?.sortedBy { it.name }?.forEach { hwmon ->
hwmon.listFiles { f -> f.name.matches(Regex("fan\\d+_input")) }?.sortedBy { it.name }
?.forEach { sources.add(it.path) }
}
sources
}
private fun readNumber(path: String): Long? =
runCatching { File(path).readText().trim().toLong() }.getOrNull()?.takeIf { it >= 0 }
}
}
@@ -1,17 +0,0 @@
package com.droiddeck.launcher.session
import java.io.File
/**
* Whether Deck mode's performance overlay is on screen. The client sets its level by rewriting
* mangoapp's config (bannerlator-session makes it, `/tmp/mangohud.*`), and `no_display` is the
* level that hides it. The feeds whose reads cost something - the fan's tachometer busy-waits in
* the kernel, GPU memory walks every process's mappings - only run while it shows.
*/
object OverlayShown {
fun check(root: File): Boolean {
val config = File(root, "tmp").listFiles { f -> f.name.startsWith("mangohud.") }
?.maxByOrNull { it.lastModified() } ?: return false
return runCatching { !config.readText().contains("no_display") }.getOrDefault(false)
}
}
@@ -21,9 +21,8 @@ import java.util.concurrent.atomic.AtomicInteger
* is on, what the screen is actually being shown - "60 → 118 fps" is the proof that the engine
* is doing something, and "FG starting" or a reason is the proof that it is not.
*
* The base rate is the game window's own frames, counted here from the compositor's per-frame
* callback with or without an engine - what Steam's overlay counts too. The presented rate comes
* from the engine's telemetry while it generates.
* The base rate is counted here from the compositor's per-frame callback, so it is right with or
* without an engine. The presented rate comes from the engine's own telemetry while it generates.
*/
class PerfHud(context: Context) {
/** Empty when the HUD is off or not yet started. */
@@ -100,7 +99,10 @@ class PerfHud(context: Context) {
return when {
problem == 1 -> context.getString(R.string.hud_fg_unsupported, name)
problem == 2 -> context.getString(R.string.hud_fg_failed, name)
stats != null && stats[3] > 1f -> String.format(Locale.US, "%s %.0f → %.0f fps", label, base, stats[3])
stats != null && stats[3] > 1f -> {
val source = if (stats[2] > 1f) stats[2] else base
String.format(Locale.US, "%s %.0f → %.0f fps", label, source, stats[3])
}
else -> context.getString(R.string.hud_fg_starting, label, fps(base))
}
}
@@ -1,94 +0,0 @@
package com.droiddeck.launcher.session
import java.io.File
import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.nio.file.StandardCopyOption.COPY_ATTRIBUTES
import java.security.MessageDigest
import java.util.Locale
/** Android shared storage cannot create the links in Wine prefixes or native Steam depots. */
object SecondaryLibrary {
private val bootstrapTools = linkedMapOf(
"4185400" to "SteamLinuxRuntime_4-arm64",
"4427310" to "Proton Experimental (ARM64)",
"4628740" to "Proton 11.0 (ARM64)",
)
fun privateRoot(files: File, library: File): File {
val digest = MessageDigest.getInstance("SHA-256").digest(library.canonicalPath.toByteArray())
.joinToString("") { "%02x".format(it.toInt() and 255) }
return File(files, "steam-libraries/$digest")
}
/** Parent binds come first; the more specific private directories override them in PRoot. */
fun binds(files: File, library: File): List<String> {
val private = privateRoot(files, library)
val apps = File(library, "steamapps")
val tools = LinkedHashMap(bootstrapTools)
// Include other installed Proton/runtime versions, without routing ordinary game depots.
apps.listFiles()?.filter { it.name.matches(Regex("appmanifest_\\d+\\.acf")) }?.forEach { manifest ->
val text = manifest.readText()
val id = Regex("\"appid\"\\s+\"(\\d+)\"").find(text)?.groupValues?.get(1)
val dir = Regex("\"installdir\"\\s+\"([^\"]+)\"").find(text)?.groupValues?.get(1)
if (id != null && dir != null && File(dir).name == dir &&
(dir.startsWith("Proton ") || dir.startsWith("SteamLinuxRuntime"))) tools[id] = dir
}
val overrides = ArrayList<Pair<File, String>>()
for (name in listOf("compatdata", "shadercache")) {
val target = File(private, "steamapps/$name")
migrate(File(apps, name), target)
overrides.add(target to "steamapps/$name")
}
for ((id, dir) in tools) {
for (relative in listOf("steamapps/common/$dir", "steamapps/downloading/$id")) {
val target = File(private, relative)
migrate(File(library, relative), target)
// FUSE discarded the executable bits. Steam will restore the depot's exact modes
// on verification; its launchers must already be executable when importing it.
target.walkTopDown().filter { it.isFile }.forEach { it.setExecutable(true, true) }
overrides.add(target to relative)
// Steam normalizes depot install directories to lowercase on Android's
// case-insensitive shared storage. PRoot binds are case-sensitive, so both
// spellings must reach the same private directory during the commit.
val lower = relative.lowercase(Locale.ROOT)
if (lower != relative) overrides.add(target to lower)
}
}
return listOf("/mnt/droiddeck-sd", "/mnt/bannerlator-sd").flatMap { guest ->
listOf("${library.path}:$guest") + overrides.map { (host, relative) -> "${host.path}:$guest/$relative" }
}
}
/** Copy once into a staging directory; retain the source and never merge over a live prefix. */
private fun migrate(source: File, target: File) {
val migrated = File(target.parentFile, ".${target.name}.migrated")
if (target.isDirectory) {
if (!migrated.isFile) migrated.writeText(source.canonicalPath)
return
}
check(target.parentFile!!.isDirectory || target.parentFile!!.mkdirs()) { "cannot create ${target.parent}" }
if (!source.isDirectory || migrated.isFile) {
check(target.mkdirs()) { "cannot create $target" }
if (!migrated.isFile) migrated.writeText(source.canonicalPath)
return
}
val stage = File(target.parentFile, "${target.name}.migrating")
check(!stage.exists() || stage.deleteRecursively()) { "cannot clear $stage" }
check(stage.mkdirs()) { "cannot create $stage" }
try {
Files.walk(source.toPath()).use { paths ->
paths.forEach { path ->
val destination = stage.toPath().resolve(source.toPath().relativize(path))
if (Files.isDirectory(path, NOFOLLOW_LINKS)) Files.createDirectories(destination)
else Files.copy(path, destination, NOFOLLOW_LINKS, COPY_ATTRIBUTES)
}
}
check(stage.renameTo(target)) { "cannot finish migration to $target" }
migrated.writeText(source.canonicalPath)
} catch (e: Exception) {
stage.deleteRecursively()
throw e
}
}
}
@@ -5,7 +5,6 @@ import android.os.Environment
import android.util.Log
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.ProotFastPath
import java.io.File
/** Everything the session needs written into the runtime before it starts. */
@@ -30,7 +29,6 @@ object SessionFiles {
"usr/local/bin/bannerlator-game-env" to "usr/local/bin/bannerlator-game-env",
"libblsession.so" to "usr/local/lib/libblsession.so",
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
"libblfastpath.so" to "usr/local/lib/libblfastpath.so",
"usr/local/bin/bannerlator-session" to "usr/local/bin/bannerlator-session",
"usr/local/bin/bannerlator-steam-compat" to "usr/local/bin/bannerlator-steam-compat",
"usr/local/bin/bannerlator-steam-install" to "usr/local/bin/bannerlator-steam-install",
@@ -44,8 +42,6 @@ object SessionFiles {
"usr/local/bin/bannerlator-steam-shortcuts" to "usr/local/bin/bannerlator-steam-shortcuts",
"usr/local/bin/bannerlator-steam-games" to "usr/local/bin/bannerlator-steam-games",
"usr/local/bin/bannerlator-pad-defaults" to "usr/local/bin/bannerlator-pad-defaults",
// GOG: the store's wrapper around Heroic's gogdl (which the app downloads itself).
"usr/local/bin/bannerlator-gog" to "usr/local/bin/bannerlator-gog",
// Flatpak: the bwrap stand-in, the store's helper and setup, and the front end's launcher.
"usr/local/bin/bannerlator-bwrap" to "usr/local/bin/bannerlator-bwrap",
"usr/local/bin/bannerlator-flatpak" to "usr/local/bin/bannerlator-flatpak",
@@ -155,9 +151,6 @@ object SessionFiles {
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
preload.append("/usr/local/lib/libfakeinput.so\n")
}
// Last, so the others' opens and stats reach it through RTLD_NEXT. It stays idle in any
// process its proot did not describe to it (ProotFastPath).
if (ProotFastPath.enabled(context)) preload.append(ProotFastPath.LIBRARY + "\n")
val etc = File(root, "etc").apply { mkdirs() }
val staged = File(etc, "ld.so.preload.staged")
if (!FileUtils.writeString(staged, preload.toString())
@@ -302,17 +302,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
}
/**
* Whether the session's path lookups take proot's fast path (ProotFastPath): answered inside
* each process instead of a round trip through the tracer. On by default; it needs proot's
* seccomp filter, so it is off whenever proot runs without one.
*/
fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
fun setProotFastPath(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("prootFastPath", on).apply()
}
const val DEFAULT_GUEST_HOSTNAME = "DroidDeck"
@JvmStatic
@@ -36,7 +36,6 @@ import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.input.FakeInputWriter
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.ProotFastPath
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.text.SimpleDateFormat
@@ -278,9 +277,7 @@ class SessionService : Service() {
// The desktop's Steam launchers start the client there (bannerlator-steam-launch), through the
// same set-up as a Steam session: it gets what the client and its games are started with.
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
addClientEnvironment(guest, steamHere)
// Where the fast path's description of proot's view goes, once the binds are known.
val fastPathAt = guest.size
addClientEnvironment(guest, runtimeDir, steamHere)
val pulse = startAudio(guest, sessionDir)
@@ -366,19 +363,6 @@ class SessionService : Service() {
FileUtils.clear(File(cacheDir, "shm"))
val binds = sessionBinds(controllersOn, fakeInputDir)
// The fast path is told exactly the rootfs and binds proot is given (ProotFastPath).
val fastPathKey = if (ProotFastPath.enabled(this)) {
val prootBinds = LinuxRuntime.binds(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds,
)
val root = LinuxRuntime.rootDir(this)
ProotFastPath.key(root, prootBinds)?.also { key ->
val env = ProotFastPath.guestEnv(root, prootBinds, key)
guest.addAll(fastPathAt, env)
shellGuest.addAll(fastPathAt, env)
Log.i(TAG, "proot: fast path on (${prootBinds.size} binds)")
}
} else null
val command = LinuxRuntime.command(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest,
@@ -395,7 +379,6 @@ class SessionService : Service() {
hostEnv["PROOT_NO_SECCOMP"] = "1"
Log.i(TAG, "proot: seccomp acceleration off by request")
}
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> hostEnv[k] = v } }
val prootLibs = LinuxRuntime.prootLibraryPath(this)
if (prootLibs.isNotEmpty()) hostEnv["LD_LIBRARY_PATH"] = prootLibs
@@ -500,7 +483,7 @@ class SessionService : Service() {
}
/** The guest's base environment: paths, the display, the GL/Vulkan stack and the client's switches. */
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean) {
private fun addClientEnvironment(guest: MutableList<String>, runtimeDir: File, steamHere: Boolean) {
guest.add("/usr/bin/env")
guest.add("-i")
guest.add("HOME=/root")
@@ -511,7 +494,7 @@ class SessionService : Service() {
// Without this the session is UTC: the client's clock, its logs and every timestamp in a
// session bundle sit hours off the device's. Bannerlator carries the same line.
guest.add("TZ=" + java.util.TimeZone.getDefault().id)
guest.add("XDG_RUNTIME_DIR=" + LinuxRuntime.GUEST_RUNTIME_DIR)
guest.add("XDG_RUNTIME_DIR=" + runtimeDir.path)
guest.add("XDG_SESSION_TYPE=wayland")
guest.add("WAYLAND_DISPLAY=wayland-0")
guest.add("GAMESCOPE_FORCE_GENERAL_QUEUE=1")
@@ -552,10 +535,6 @@ class SessionService : Service() {
// opened once and read and written with pread/pwrite, which proot never sees. Mesa removes
// the old folder itself once it has gone a week untouched.
guest.add("MESA_DISK_CACHE_DATABASE=1")
// glibc's per-thread rseq registration is refused by Android's app seccomp policy, so
// every thread start paid a SIGSYS that proot answers; the malloc top pad grows the heap
// 16 MB at a time instead of 128 KB, and every brk(2) is a proot stop too.
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAMDECK=" + (if (SessionPrefs.steamDeckMode(this)) "1" else "0"))
if (SessionState.mode == MODE_STEAM) guest.add("BL_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
if (steamHere) guest.add("BL_STEAM_CHANNEL=" + SessionPrefs.steamChannel(this))
@@ -710,33 +689,6 @@ class SessionService : Service() {
battery.attach(this)
components.add(battery)
binds.add(battery.dir.path + ":/sys/class/power_supply")
// The overlay's CPU and GPU temperatures and the fan, as hwmon sensors it knows by name.
val hwmon = HwmonComponent(File(filesDir, "session/sys/hwmon"), LinuxRuntime.rootDir(this))
if (hwmon.prepare()) {
hwmon.attach(this)
components.add(hwmon)
binds.add(hwmon.dir.path + ":/sys/class/hwmon")
}
// CPU load for everything in the session that reads /proc/stat, the overlay among them.
val cpuStat = CpuStatComponent(File(filesDir, "session/proc-stat"))
if (cpuStat.prepare()) {
cpuStat.attach(this)
components.add(cpuStat)
binds.add(cpuStat.file.path + ":/proc/stat")
}
// The GPU memory in use for the overlay's VRAM lines, which it would read from tracefs.
val gpuMem = GpuMemComponent(File(LinuxRuntime.rootDir(this), "run/droiddeck-hud/gpu-mem"), LinuxRuntime.rootDir(this))
if (gpuMem.prepare()) {
gpuMem.attach(this)
components.add(gpuMem)
}
// The GPU's load and temperature for the performance overlay, where KGSL's sysfs is refused.
val gpuStats = GpuStatsComponent(File(filesDir, "session/sys/kgsl-3d0"))
if (gpuStats.prepare()) {
gpuStats.attach(this)
components.add(gpuStats)
binds.addAll(gpuStats.binds())
}
// Rumble for the on-screen pad: the fake evdev layer sends force-feedback effects to this
// listener, which drives the phone's vibrator (see RumbleComponent).
if (controllersOn) components.add(RumbleComponent().also { it.attach(this) })
@@ -757,14 +709,11 @@ class SessionService : Service() {
val problem = GameStorage.prepare(library.path)
if (problem == null) {
File(LinuxRuntime.rootDir(this), "mnt/droiddeck-sd").mkdirs()
binds.add("${library.path}:/mnt/droiddeck-sd")
// Links, prefixes and Steam entries made before the rename still name the old path.
File(LinuxRuntime.rootDir(this), "mnt/bannerlator-sd").mkdirs()
try {
binds.addAll(SecondaryLibrary.binds(filesDir, File(library.path)))
Log.i(TAG, "game storage: ${library.path} -> /mnt/droiddeck-sd (\"${library.label}\"); prefixes and native tools private")
} catch (e: Exception) {
Log.w(TAG, "game storage: private directories could not be prepared; internal only this session", e)
}
binds.add("${library.path}:/mnt/bannerlator-sd")
Log.i(TAG, "game storage: ${library.path} -> /mnt/droiddeck-sd (\"${library.label}\")")
} else {
Log.w(TAG, "game storage: $problem; internal only this session")
}
@@ -1,117 +0,0 @@
package com.droiddeck.launcher.store.gog
import android.util.Log
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
/**
* GOG's web APIs, as Heroic uses them: the signed-in account's games (embed.gog.com, with the
* token gogdl keeps) and a game's art (gamesdb.gog.com, public). Downloads are gogdl's.
*/
object GogApi {
private const val TAG = "GogApi"
private const val TIMEOUT_MS = 20_000
private const val LIBRARY = "https://embed.gog.com/account/getFilteredProducts?mediaType=1&sortBy=title&page="
private const val GAMESDB = "https://gamesdb.gog.com/platforms/gog/external_releases/"
/** An owned game; [image] is the store's wide tile. Only games with a Windows build are listed. */
class Game(val id: String, val title: String, val image: String?)
class Art(val cover: String?, val header: String?, val hero: String?, val logo: String?)
/** Every game the account owns that runs on Windows, by title; null when GOG could not be asked. */
fun library(token: String): List<Game>? {
val games = ArrayList<Game>()
var page = 1
var pages = 1
while (page <= pages) {
val body = get(LIBRARY + page, token) ?: return null
val (items, total) = parseLibraryPage(body) ?: return null
games += items
pages = total.coerceAtMost(100)
page++
}
return games.distinctBy { it.id }.sortedBy { it.title.lowercase() }
}
/** One page: its games and how many pages there are. */
internal fun parseLibraryPage(body: String): Pair<List<Game>, Int>? = runCatching {
val o = JSONObject(body)
val products = o.optJSONArray("products")
val games = (0 until (products?.length() ?: 0)).mapNotNull { i ->
val p = products!!.optJSONObject(i) ?: return@mapNotNull null
val windows = p.optJSONObject("worksOn")?.optBoolean("Windows") ?: false
val id = p.opt("id")?.toString()?.takeIf { it.isNotEmpty() && it != "null" } ?: return@mapNotNull null
if (!windows) return@mapNotNull null
Game(id, p.optString("title").ifEmpty { id }, image(p.optString("image")))
}
games to o.optInt("totalPages", 1).coerceAtLeast(1)
}.getOrNull()
/** The store's image ids come protocol-relative and without a size; 392 is its wide tile. */
internal fun image(raw: String): String? {
if (raw.isBlank()) return null
val url = if (raw.startsWith("//")) "https:$raw" else raw
return if (url.endsWith(".jpg") || url.endsWith(".png")) url else "${url}_392.jpg"
}
/** The game's art from GOG's games database, or null when it has none. */
fun art(id: String): Art? = get(GAMESDB + id, null)?.let(::parseArt)
internal fun parseArt(body: String): Art? = runCatching {
val game = JSONObject(body).optJSONObject("game") ?: return@runCatching null
fun url(key: String, ext: String) = game.optJSONObject(key)?.optString("url_format")
?.takeIf { it.isNotEmpty() }?.replace("{formatter}", "")?.replace("{ext}", ext)
Art(url("vertical_cover", "jpg"), url("horizontal_artwork", "jpg"), url("background", "jpg"), url("logo", "png"))
}.getOrNull()
/**
* Puts the game's art into its folder's .art/ under the names the Added Games art reader looks
* for first (cover, header, hero, logo), so Steam shows GOG's own art for it. Best effort.
*/
fun saveArt(id: String, dir: File) {
val art = art(id) ?: return
val target = File(dir, ".art").apply { mkdirs() }
listOf("cover.jpg" to art.cover, "header.jpg" to art.header, "hero.jpg" to art.hero, "logo.png" to art.logo)
.forEach { (name, url) ->
val file = File(target, name)
if (url != null && !file.isFile) download(url, file)
}
}
private fun download(url: String, file: File) {
var c: HttpURLConnection? = null
try {
c = (URL(url).openConnection() as HttpURLConnection).apply { connectTimeout = TIMEOUT_MS; readTimeout = TIMEOUT_MS }
if (c.responseCode / 100 != 2) return
val part = File(file.path + ".part")
c.inputStream.use { input -> part.outputStream().use { input.copyTo(it) } }
part.renameTo(file)
} catch (e: Exception) {
Log.w(TAG, "$url: $e")
} finally {
c?.disconnect()
}
}
private fun get(url: String, token: String?): String? {
var c: HttpURLConnection? = null
return try {
c = (URL(url).openConnection() as HttpURLConnection).apply {
connectTimeout = TIMEOUT_MS
readTimeout = TIMEOUT_MS
setRequestProperty("Accept", "application/json")
if (token != null) setRequestProperty("Authorization", "Bearer $token")
}
// The URL is logged; the token never is.
if (c.responseCode / 100 != 2) { Log.w(TAG, "${url.substringBefore('?')} -> HTTP ${c.responseCode}"); null }
else c.inputStream.bufferedReader().use { it.readText() }
} catch (e: Exception) {
Log.w(TAG, "${url.substringBefore('?')}: ${e.javaClass.simpleName}"); null
} finally {
c?.disconnect()
}
}
}
@@ -1,56 +0,0 @@
package com.droiddeck.launcher.store.gog
import org.json.JSONObject
import java.io.File
/**
* What an installed GOG game says about itself: goggame-<id>.info in its folder, the file GOG Galaxy
* and Heroic launch from. Its primary play task names the exe, the folder to start in and the
* arguments, so a store-installed game needs no guessing at which .exe is the game.
*/
object GogGameInfo {
class Task(val exe: File, val workingDir: File, val arguments: String)
class Info(val id: String, val name: String, val task: Task?)
/** The root game's info in [folder] (DLCs add their own files beside it), or null. */
fun read(folder: File): Info? {
val files = folder.listFiles { f -> f.isFile && f.name.startsWith("goggame-") && f.name.endsWith(".info") } ?: return null
val parsed = files.sortedBy { it.name }.mapNotNull { f -> runCatching { JSONObject(f.readText()) }.getOrNull() }
val root = parsed.firstOrNull { it.optString("gameId").let { id -> id.isNotEmpty() && id == it.optString("rootGameId") } }
?: parsed.singleOrNull() ?: return null
return parse(folder, root)
}
internal fun parse(folder: File, json: JSONObject): Info? {
val id = json.optString("gameId").ifEmpty { return null }
val name = json.optString("name").ifEmpty { folder.name }
val tasks = json.optJSONArray("playTasks")
val files = (0 until (tasks?.length() ?: 0)).mapNotNull { tasks!!.optJSONObject(it) }
.filter { it.optString("type") == "FileTask" && it.optString("path").isNotEmpty() }
// Galaxy's own choice: the primary game task; else the first game task; else the first at all.
val chosen = files.firstOrNull { it.optBoolean("isPrimary") && it.optString("category", "game") == "game" }
?: files.firstOrNull { it.optString("category", "game") == "game" }
?: files.firstOrNull()
val task = chosen?.let { t ->
val exe = resolve(folder, t.optString("path")) ?: return@let null
val dir = t.optString("workingDir").takeIf { it.isNotBlank() }?.let { resolve(folder, it) } ?: folder
Task(exe, dir, t.optString("arguments").trim())
}
return Info(id, name, task)
}
/**
* [relative] (a Windows path, backslashes and all) under [base], matched case-insensitively as
* Windows would; null when no such file or folder exists.
*/
internal fun resolve(base: File, relative: String): File? {
var at = base
for (part in relative.replace('\\', '/').split('/').filter { it.isNotEmpty() && it != "." }) {
// The name as the folder lists it: a caseless filesystem (an SD card) would accept any
// spelling, but the session sees the game through proot, where only the real one works.
val names = at.listFiles().orEmpty()
at = names.firstOrNull { it.name == part } ?: names.firstOrNull { it.name.equals(part, ignoreCase = true) } ?: return null
}
return at
}
}
@@ -1,99 +0,0 @@
package com.droiddeck.launcher.store.gog
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import com.droiddeck.launcher.MainActivity
import com.droiddeck.launcher.R
/**
* Keeps the process in the foreground while a GOG game downloads: games run to tens of gigabytes,
* and without a foreground service Android may kill the app (and the download's proot with it) the
* moment the user switches away. A killed or stopped download resumes when installed again.
*/
class GogInstallService : Service() {
/** One download: [kind] is "install" or "update"; [base] a [GogManager.Base] id; [dir] the game's folder for an update. */
class Job(val kind: String, val id: String, val title: String, val base: String, val dir: String?)
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == ACTION_CANCEL) {
GogState.cancel()
return START_NOT_STICKY
}
val job = intent?.let(::jobFrom)
startForeground(NOTIFICATION_ID, notification(job?.title ?: "GOG", "Starting…", -1))
if (job == null) {
stopSelf(startId)
return START_NOT_STICKY
}
Thread({
val manager = getSystemService(NotificationManager::class.java)
var shown = Int.MIN_VALUE
GogState.run(applicationContext, job) { stage, percent ->
// Every percent at most once: a notification per line would flood the system.
if (percent != shown) {
shown = percent
manager?.notify(NOTIFICATION_ID, notification(job.title, stage, percent))
}
}
@Suppress("DEPRECATION")
stopForeground(true)
stopSelf(startId)
}, "gog-${job.kind}").start()
return START_NOT_STICKY
}
private fun notification(title: String, stage: String, percent: Int): Notification {
val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, "GOG downloads",
NotificationManager.IMPORTANCE_LOW).apply {
description = "Shows while a GOG game downloads"
setShowBadge(false)
setSound(null, null)
enableVibration(false)
})
val open = PendingIntent.getActivity(this, 0,
Intent(this, MainActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_IMMUTABLE)
val cancel = PendingIntent.getService(this, 1,
Intent(this, GogInstallService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE)
return Notification.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentTitle(title)
.setContentText(stage)
.setProgress(100, percent.coerceIn(0, 100), percent < 0)
.setContentIntent(open)
.addAction(Notification.Action.Builder(null, "Stop", cancel).build())
.setOngoing(true)
.setOnlyAlertOnce(true)
.setShowWhen(false)
.build()
}
companion object {
private const val CHANNEL_ID = "gog-download"
private const val NOTIFICATION_ID = 4
private const val ACTION_CANCEL = "com.droiddeck.launcher.gog.CANCEL"
fun start(context: Context, job: Job) {
val intent = Intent(context, GogInstallService::class.java)
.putExtra("kind", job.kind).putExtra("id", job.id).putExtra("title", job.title)
.putExtra("base", job.base).putExtra("dir", job.dir)
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
}
private fun jobFrom(intent: Intent): Job? {
val kind = intent.getStringExtra("kind") ?: return null
val id = intent.getStringExtra("id") ?: return null
return Job(kind, id, intent.getStringExtra("title") ?: id, intent.getStringExtra("base") ?: "internal", intent.getStringExtra("dir"))
}
}
}
@@ -1,235 +0,0 @@
package com.droiddeck.launcher.store.gog
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.Hashes
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import org.json.JSONObject
import java.io.File
/**
* GOG in the Linux runtime, through Heroic's gogdl (GOG's own download protocol, sign-in tokens,
* resumable installs): putting gogdl there, signing in, and installing, updating and removing
* games. A game lands in a GOG folder the Added Games scan reads, so the session puts it in Steam
* as a shortcut like any other added game - the store only fetches; Steam still launches.
*
* Each command runs in a proot of its own (GuestCommand), so a download carries on whether or
* not a session is up.
*/
object GogManager {
private const val TAG = "GogManager"
/** Heroic's gogdl release the app puts in the runtime: a Python zipapp, so any architecture. */
const val GOGDL_VERSION = "1.3.0"
private const val GOGDL_URL = "https://github.com/Heroic-Games-Launcher/heroic-gogdl/releases/download/v$GOGDL_VERSION/gogdl_linux_arm64"
private const val GOGDL_SHA256 = "c49e1519146523ec94f33e2d21eedcc9a167004d7da218621e6d5fb84a7a0f4c"
/** Where gogdl lives in the runtime (bannerlator-gog runs it from there). */
private const val GOGDL = "opt/droiddeck/gogdl/gogdl"
private const val HELPER = "/usr/local/bin/bannerlator-gog"
/** The folder, in each place games can go, that store installs live under. */
const val FOLDER = "GOG"
/** Written by the helper into a game's folder before its download starts. */
const val MARKER = ".droiddeck-gog.json"
private const val RESUME = ".gogdl-resume"
/** One store operation at a time. */
@Volatile var busy: String? = null
private set
/** One place games can go: internal (the runtime's own disk) or the SD card's game library. */
class Base(val id: String, val label: String, val host: File, val guest: String, val binds: List<String>)
/** A GOG game in one of the [bases]; [complete] is false for a download that stopped partway. */
class Installed(val id: String, val name: String, val dir: File, val base: Base, val complete: Boolean)
/** The sign-in gogdl keeps (tokens), in the app's private files - never on shared storage. */
fun authFile(context: Context) = File(context.filesDir, "gog/auth.json")
private fun gogdl(context: Context) = File(LinuxRuntime.rootDir(context), GOGDL)
private fun stamp(context: Context) = File(LinuxRuntime.rootDir(context), "$GOGDL.version")
fun ready(context: Context): Boolean =
gogdl(context).isFile && runCatching { stamp(context).readText().trim() }.getOrNull() == GOGDL_VERSION
fun signedIn(context: Context): Boolean = authFile(context).isFile
fun bases(context: Context): List<Base> {
val internal = Base("internal", "Internal storage", File(LinuxRuntime.rootDir(context), "root/$FOLDER"), "/root/$FOLDER", emptyList())
val sd = GameStorage.effective(context)?.let { lib ->
Base("sd", lib.label, File(lib.path, FOLDER), "/mnt/droiddeck-sd/$FOLDER", listOf("${lib.path}:/mnt/droiddeck-sd"))
}
return listOfNotNull(internal, sd)
}
fun installed(context: Context): List<Installed> = bases(context).flatMap { base ->
base.host.listFiles { f -> f.isDirectory }.orEmpty().mapNotNull { dir -> installedAt(dir, base) }
}.sortedBy { it.name.lowercase() }
private fun installedAt(dir: File, base: Base): Installed? {
val marker = runCatching { JSONObject(File(dir, MARKER).readText()) }.getOrNull()
val info = GogGameInfo.read(dir)
val id = marker?.optString("id")?.ifEmpty { null } ?: info?.id ?: return null
val complete = info?.task != null && !File(dir, RESUME).exists()
return Installed(id, info?.name ?: dir.name, dir, base, complete)
}
/** True for a folder the store put there and whose download has not finished: not a game yet. */
fun incomplete(dir: File): Boolean =
File(dir, MARKER).isFile && (File(dir, RESUME).exists() || GogGameInfo.read(dir)?.task == null)
private inline fun <T> exclusive(what: String, block: () -> T): T? {
synchronized(this) {
if (busy != null) return null
busy = what
}
try { return block() } finally { busy = null }
}
/** Downloads the pinned gogdl into the runtime and checks it. Null on success, else why not. */
fun setup(context: Context, onProgress: (String, Int) -> Unit): String? {
if (!LinuxRuntime.isInstalled(context)) return "Install the Linux runtime first"
return exclusive("setup") {
val target = gogdl(context)
val part = File(target.path + ".part")
target.parentFile?.mkdirs()
onProgress("Downloading gogdl $GOGDL_VERSION", -1)
if (!Downloader.downloadFile(GOGDL_URL, part, true) { f -> if (f >= 0) onProgress("Downloading gogdl $GOGDL_VERSION", (f * 100).toInt()) }) {
return@exclusive "Could not download gogdl"
}
if (!Hashes.sha256(part).equals(GOGDL_SHA256, ignoreCase = true)) {
part.delete()
return@exclusive "gogdl did not match its checksum"
}
if (!part.renameTo(target)) return@exclusive "Could not put gogdl in place"
target.setExecutable(true, false)
stamp(context).writeText(GOGDL_VERSION)
null
} ?: "Another GOG task is running"
}
/** Runs the helper. Commands that touch tokens pass no [logName]: their output stays off shared storage. */
private fun helper(context: Context, args: List<String>, logName: String?, binds: List<String> = emptyList(),
onProcess: ((Process) -> Unit)? = null, onEvent: (JSONObject) -> Unit): Int {
val argv = listOf("/usr/bin/python3", HELPER, args[0], authFile(context).path) + args.drop(1)
return GuestCommand.run(context, argv, logName = logName, extraBinds = binds, onProcess = onProcess) { line ->
val o = runCatching { JSONObject(line) }.getOrNull()
if (o != null && o.has("e")) onEvent(o) else if (logName != null) Log.i(TAG, line)
}
}
/** Trades the sign-in page's code for gogdl's tokens. Null on success, else why not. */
fun login(context: Context, code: String): String? {
if (!ready(context)) return "Set up GOG first"
authFile(context).parentFile?.mkdirs()
var error: String? = null
var done = false
val status = exclusive("login") {
helper(context, listOf("login", code), logName = null) { o ->
when (o.optString("e")) {
"done" -> done = true
"error" -> error = o.optString("message")
}
}
} ?: return "Another GOG task is running"
return when {
done -> null
error != null -> error
else -> "Signing in failed (exit $status)"
}
}
fun signOut(context: Context) {
authFile(context).delete()
token = null
}
private class Token(val value: String, val userId: String, val expires: Long)
@Volatile private var token: Token? = null
/** A current access token for GOG's APIs, refreshed by gogdl when due; null when signed out. */
fun accessToken(context: Context): String? {
token?.takeIf { it.expires * 1000 > System.currentTimeMillis() + 60_000 }?.let { return it.value }
if (!ready(context) || !signedIn(context)) return null
var fresh: Token? = null
// Not exclusive: a token is wanted while a download runs, and gogdl only rewrites the
// file when it refreshes.
helper(context, listOf("token"), logName = null) { o ->
if (o.optString("e") == "token") fresh = Token(o.optString("access_token"), o.optString("user_id"), o.optLong("expires"))
}
token = fresh
return fresh?.value
}
class Sizes(val download: Long, val disk: Long)
/** The Windows build's download and installed sizes, or null when it cannot be read. */
fun sizes(context: Context, id: String): Sizes? {
if (!ready(context)) return null
var sizes: Sizes? = null
helper(context, listOf("info", id), logName = null) { o ->
if (o.optString("e") == "info") sizes = Sizes(o.optLong("download_size"), o.optLong("disk_size"))
}
return sizes
}
/**
* Downloads [id] into [base]; a stopped download picks up where it left off. [onProcess] gets
* the running command so the caller can stop it. Null on success, else why not.
*/
fun install(context: Context, id: String, base: Base, onProcess: (Process) -> Unit, onProgress: (String, Int) -> Unit): String? =
transfer(context, "install", listOf("install", id, base.guest), base, onProcess, onProgress)
fun update(context: Context, game: Installed, onProcess: (Process) -> Unit, onProgress: (String, Int) -> Unit): String? {
val guest = game.base.guest + "/" + game.dir.name
return transfer(context, "update", listOf("update", game.id, guest), game.base, onProcess, onProgress)
}
private fun transfer(context: Context, verb: String, args: List<String>, base: Base,
onProcess: (Process) -> Unit, onProgress: (String, Int) -> Unit): String? {
if (!ready(context)) return "Set up GOG first"
if (!signedIn(context)) return "Sign in to GOG first"
return exclusive("$verb:${args[1]}") {
base.host.mkdirs()
// proot binds the SD library onto this folder, as a session does.
if (base.binds.isNotEmpty()) File(LinuxRuntime.rootDir(context), "mnt/droiddeck-sd").mkdirs()
var error: String? = null
var done = false
var stage = if (verb == "update") "Updating" else "Downloading"
onProgress("Preparing", -1)
val status = helper(context, args, logName = "gog-$verb", binds = base.binds, onProcess = onProcess) { o ->
when (o.optString("e")) {
"info" -> {
stage = "${if (verb == "update") "Updating" else "Downloading"} ${formatSize(o.optLong("download_size"))}"
onProgress(stage, 0)
}
"progress" -> onProgress(stage, o.optInt("percent"))
"error" -> error = o.optString("message")
"done" -> done = true
}
}
when {
done -> null
error != null -> error
else -> "Stopped (exit $status)"
}
} ?: "Another GOG task is running"
}
/**
* Removes the game's files and gogdl's record of them. The game's Proton prefix (its saves and
* settings) stays where Steam keeps it, as for any added game taken out of the library.
*/
fun uninstall(context: Context, game: Installed): String? = exclusive("uninstall:${game.id}") {
if (!game.dir.deleteRecursively() && game.dir.exists()) return@exclusive "Could not remove ${game.dir.name}"
File(LinuxRuntime.rootDir(context), "root/.config/heroic_gogdl/manifests/${game.id}").delete()
null
} ?: "Another GOG task is running"
fun formatSize(bytes: Long): String = when {
bytes >= 1L shl 30 -> "%.1f GB".format(bytes / (1L shl 30).toDouble())
bytes >= 1L shl 20 -> "%.0f MB".format(bytes / (1L shl 20).toDouble())
else -> "%.0f KB".format(bytes / 1024.0)
}
}
@@ -1,172 +0,0 @@
package com.droiddeck.launcher.store.gog
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
/**
* The GOG store's state for the life of the process, so a download carries on - and its progress
* shows - while the user moves around the launcher or plays something meanwhile. Downloads run in
* [GogInstallService], which keeps the process in the foreground for as long as they take.
*/
object GogState {
private val main = Handler(Looper.getMainLooper())
var ready by mutableStateOf(false)
private set
var signedIn by mutableStateOf(false)
private set
/** The account's Windows games; null until loaded. */
var library by mutableStateOf<List<GogApi.Game>?>(null)
private set
var libraryFailed by mutableStateOf(false)
private set
var loadingLibrary by mutableStateOf(false)
private set
var installed by mutableStateOf<List<GogManager.Installed>>(emptyList())
private set
/** What is running: "setup", "login", or a game id; null when idle. */
var busy by mutableStateOf<String?>(null)
private set
var stage by mutableStateOf<String?>(null)
private set
var percent by mutableStateOf(-1)
private set
/** Download and installed sizes by game id; absent until asked, null while being read. */
val sizes = mutableStateMapOf<String, GogManager.Sizes?>()
@Volatile private var process: Process? = null
@Volatile private var cancelled = false
fun refresh(context: Context) {
val app = context.applicationContext
Thread({
val r = GogManager.ready(app)
val s = GogManager.signedIn(app)
val list = GogManager.installed(app)
main.post { ready = r; signedIn = s; installed = list }
}, "gog-refresh").start()
}
fun loadLibrary(context: Context, force: Boolean = false) {
if (loadingLibrary || (!force && library != null)) return
val app = context.applicationContext
loadingLibrary = true
libraryFailed = false
Thread({
val token = GogManager.accessToken(app)
val games = token?.let { GogApi.library(it) }
main.post {
loadingLibrary = false
if (games != null) library = games else libraryFailed = true
}
}, "gog-library").start()
}
fun loadSizes(context: Context, id: String) {
if (sizes.containsKey(id)) return
val app = context.applicationContext
sizes[id] = null
Thread({
val s = GogManager.sizes(app, id)
main.post { sizes[id] = s; if (s == null) sizes.remove(id) }
}, "gog-sizes").start()
}
private fun background(context: Context, what: String, label: String, work: (Context, (String, Int) -> Unit) -> String?) {
if (busy != null) return
val app = context.applicationContext
busy = what; stage = "Starting…"; percent = -1
Thread({
val problem = try {
work(app) { s, p -> main.post { stage = s; percent = p } }
} catch (e: Exception) {
e.message ?: e.toString()
}
val r = GogManager.ready(app)
val s = GogManager.signedIn(app)
val list = GogManager.installed(app)
main.post {
busy = null; stage = null; percent = -1
ready = r; signedIn = s; installed = list
if (problem != null) Toast.makeText(app, "$label: $problem", Toast.LENGTH_LONG).show()
}
}, "gog-$what").start()
}
fun setup(context: Context) = background(context, "setup", "GOG setup") { c, p -> GogManager.setup(c, p) }
fun login(context: Context, code: String) = background(context, "login", "GOG sign-in") { c, p ->
p("Signing in…", -1)
GogManager.login(c, code).also { if (it == null) main.post { library = null; loadLibrary(c, force = true) } }
}
fun signOut(context: Context) {
GogManager.signOut(context)
library = null
signedIn = false
}
fun uninstall(context: Context, game: GogManager.Installed) =
background(context, game.id, game.name) { c, p -> p("Removing…", -1); GogManager.uninstall(c, game) }
fun install(context: Context, game: GogApi.Game, base: GogManager.Base) {
if (busy != null) return
busy = game.id; stage = "Starting…"; percent = -1
GogInstallService.start(context, GogInstallService.Job("install", game.id, game.title, base.id, null))
}
fun update(context: Context, game: GogManager.Installed) {
if (busy != null) return
busy = game.id; stage = "Starting…"; percent = -1
GogInstallService.start(context, GogInstallService.Job("update", game.id, game.name, game.base.id, game.dir.path))
}
/** Stops the running download; installing again resumes it. */
fun cancel() {
cancelled = true
process?.destroy()
}
/** The service's half of [install] and [update]; runs on the service's thread. */
internal fun run(context: Context, job: GogInstallService.Job, notify: (String, Int) -> Unit) {
val app = context.applicationContext
cancelled = false
main.post { busy = job.id }
val base = GogManager.bases(app).firstOrNull { it.id == job.base }
val problem = try {
when {
base == null -> "That storage is not available"
job.kind == "update" -> {
val game = GogManager.installed(app).firstOrNull { it.dir.path == job.dir }
if (game == null) "The game is no longer installed"
else GogManager.update(app, game, { process = it }) { s, p -> main.post { stage = s; percent = p }; notify(s, p) }
}
else -> GogManager.install(app, job.id, base, { process = it }) { s, p -> main.post { stage = s; percent = p }; notify(s, p) }
}
} catch (e: Exception) {
e.message ?: e.toString()
} finally {
process = null
}
val list = GogManager.installed(app)
// GOG's own art for Steam to show; the Steam store's is the fallback if this finds none.
if (problem == null) list.firstOrNull { it.id == job.id }?.let { runCatching { GogApi.saveArt(job.id, it.dir) } }
main.post {
busy = null; stage = null; percent = -1
installed = list
val message = when {
cancelled -> "${job.title}: stopped. Install again to pick up where it left off."
problem != null -> "${job.title}: $problem"
job.kind == "update" -> "${job.title} is up to date."
else -> "${job.title} is installed. It shows in Steam the next time Steam starts."
}
Toast.makeText(app, message, Toast.LENGTH_LONG).show()
}
}
}
@@ -1,328 +0,0 @@
package com.droiddeck.launcher.ui
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.net.Uri
import android.view.ViewGroup
import android.webkit.CookieManager
import android.webkit.WebResourceRequest
import android.webkit.WebStorage
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.width
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import coil.compose.AsyncImage
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.store.gog.GogApi
import com.droiddeck.launcher.store.gog.GogManager
import com.droiddeck.launcher.store.gog.GogState
// The Store's GOG side: sign in, the account's Windows games, and installing them into a GOG
// folder the Added Games scan reads - so each shows in Steam as a non-Steam game, launched by
// Steam through Proton like any other added game. gogdl (Heroic's) does the downloading.
/** GOG's own sign-in page; it hands back a code on embed.gog.com, which gogdl trades for tokens. */
private const val GOG_LOGIN = "https://auth.gog.com/auth?client_id=46899977096215655" +
"&redirect_uri=https%3A%2F%2Fembed.gog.com%2Fon_login_success%3Forigin%3Dclient&response_type=code&layout=galaxy"
@Composable
internal fun GogStore(s: FrontEndState) {
val ctx = LocalContext.current
var open by rememberSaveable { mutableStateOf<String?>(null) }
var signingIn by remember { mutableStateOf(false) }
LaunchedEffect(s.ready) { GogState.refresh(ctx) }
BackHandler(enabled = open != null) { open = null }
if (signingIn) GogLoginDialog(onCode = { signingIn = false; GogState.login(ctx, it) }, onDismiss = { signingIn = false })
if (!s.ready) {
Rise(1) { Note("Install the Linux runtime from Setup first; GOG games install into it.") }
return
}
val id = open
if (id != null) {
GogDetail(id) { open = null }
return
}
GogBusyBar()
when {
!GogState.ready -> Rise(1) {
GogCard(
"Set up GOG",
"Adds gogdl, the GOG downloader Heroic Games Launcher uses (about 2 MB), to the Linux runtime. " +
"Games you own on GOG then install from here and show in Steam's library as non-Steam games.",
) {
PrimaryButton(if (GogState.busy == "setup") "Setting up…" else "Set up GOG", enabled = GogState.busy == null, main = true) { GogState.setup(ctx) }
}
}
!GogState.signedIn -> Rise(1) {
GogCard("Sign in to GOG", "Sign in with your GOG account to list and install the games you own. The sign-in stays in the app's private storage.") {
PrimaryButton(if (GogState.busy == "login") "Signing in…" else "Sign in", enabled = GogState.busy == null, main = true) { signingIn = true }
}
}
else -> GogLibrary(onOpen = { open = it }, onSignOut = {
GogState.signOut(ctx)
CookieManager.getInstance().removeAllCookies(null)
WebStorage.getInstance().deleteAllData()
})
}
}
@Composable
private fun GogCard(title: String, body: String, actions: @Composable () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(
verticalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().padding(top = 12.dp).clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(16.dp),
) {
Text(title, fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(body, fontSize = 14.sp, color = colors.onSurfaceVariant)
Actions { actions() }
}
}
/** The running setup, sign-in or download, whichever page it was started from. */
@Composable
private fun GogBusyBar() {
val colors = MaterialTheme.colorScheme
val busy = GogState.busy ?: return
val name = GogState.library?.firstOrNull { it.id == busy }?.title ?: GogState.installed.firstOrNull { it.id == busy }?.name
?: when (busy) { "setup" -> "GOG"; "login" -> "GOG"; else -> busy }
Column(modifier = Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 4.dp)) {
val stage = GogState.stage
Text(
"$name · " + (if (stage != null && GogState.percent >= 0) "$stage · ${GogState.percent}%" else stage ?: "Starting…"),
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(bottom = 6.dp),
)
if (GogState.percent >= 0) LinearProgressIndicator(progress = { GogState.percent / 100f }, modifier = Modifier.fillMaxWidth().height(4.dp))
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(4.dp))
}
}
@Composable
private fun GogLibrary(onOpen: (String) -> Unit, onSignOut: () -> Unit) {
val ctx = LocalContext.current
LaunchedEffect(Unit) { GogState.loadLibrary(ctx) }
val library = GogState.library
val installed = GogState.installed
Rise(2) {
Actions {
SecondaryButton(if (GogState.loadingLibrary) "Refreshing…" else "Refresh", enabled = !GogState.loadingLibrary) { GogState.loadLibrary(ctx, force = true) }
SecondaryButton("Sign out", enabled = GogState.busy == null, onClick = onSignOut)
}
}
if (installed.isNotEmpty()) {
Rise(3) { SectionTitle("Installed", installed.size.toString()) }
Rise(3) {
GogGrid(installed.map { i ->
Triple(i.id, i.name, library?.firstOrNull { it.id == i.id }?.image)
}, first = true, status = { gid -> installed.firstOrNull { it.id == gid }?.let { if (it.complete) "Installed · ${it.base.label}" else "Download stopped" } }, onOpen = onOpen)
}
Rise(3) { Note("Installed games show in Steam's library as non-Steam games the next time Steam starts.") }
}
when {
library == null && GogState.libraryFailed -> Rise(4) { Note("GOG could not be reached, or the sign-in has expired. Refresh, or sign out and in again.") }
library == null -> Rise(4) { SectionTitle("Your games", "loading…") }
library.isEmpty() -> Rise(4) { Note("No Windows games on this GOG account yet.") }
else -> {
Rise(4) { SectionTitle("Your games", library.size.toString()) }
Rise(5) {
GogGrid(library.map { Triple(it.id, it.title, it.image) }, first = installed.isEmpty(),
status = { gid -> installed.firstOrNull { it.id == gid }?.let { if (it.complete) "Installed" else "Download stopped" } }, onOpen = onOpen)
}
}
}
}
/** Games as tiles with GOG's wide art: three across, or one on a narrow page. */
@Composable
private fun GogGrid(games: List<Triple<String, String, String?>>, first: Boolean, status: (String) -> String?, onOpen: (String) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val columns = if (LocalNarrowPane.current) 1 else 3
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 8.dp)) {
games.chunked(columns).forEachIndexed { r, row ->
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
row.forEachIndexed { i, (id, title, image) ->
key(id) {
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Column(
modifier = Modifier.weight(1f).paneItem("tile:gog:$id").then(if (first && r == 0 && i == 0) Modifier.firstTile() else Modifier)
.clip(Shape14).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.glideBorder(hot, Shape14, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button) { onOpen(id) },
) {
AsyncImage(
model = image, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxWidth().aspectRatio(16f / 9f).background(colors.surfaceVariant),
)
Column(modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) {
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
val st = status(id)
Text(st ?: "GOG", fontSize = 13.sp, color = if (st != null) pal.good else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
}
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
}
}
}
}
@Composable
private fun GogDetail(id: String, onBack: () -> Unit) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val narrow = LocalNarrowPane.current
val game = GogState.library?.firstOrNull { it.id == id }
val local = GogState.installed.firstOrNull { it.id == id }
val title = game?.title ?: local?.name ?: id
val bases = remember { GogManager.bases(ctx) }
var baseId by rememberSaveable(id) { mutableStateOf(bases.first().id) }
LaunchedEffect(id) { GogState.loadSizes(ctx, id) }
val sizes = GogState.sizes[id]
val busyHere = GogState.busy == id
// Uninstall asks twice: one stray press of A should not cost a download.
var confirmRemove by remember(id) { mutableStateOf(false) }
LaunchedEffect(confirmRemove) { if (confirmRemove) { kotlinx.coroutines.delay(4000); confirmRemove = false } }
Rise(0) { BackLink("GOG", onClick = onBack) }
Rise(1) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier.padding(top = 12.dp, bottom = 8.dp)) {
AsyncImage(
model = game?.image, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.width(if (narrow) 140.dp else 220.dp).aspectRatio(16f / 9f).clip(Shape12).background(colors.surfaceVariant),
)
Column(modifier = Modifier.weight(1f)) {
Text(title, fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
Text(
when {
local?.complete == true -> "Installed on ${local.base.label}"
local != null -> "Download stopped on ${local.base.label}"
else -> "Windows · runs through Proton in Steam"
},
fontSize = 14.sp, color = colors.onSurfaceVariant,
)
}
}
}
if (local == null && bases.size > 1) {
Rise(2) { SectionTitle("Install to", null) }
Rise(2) {
Actions {
bases.forEach { b ->
val label = "${b.label} · ${GameStorage.free(b.host.parentFile ?: b.host)} free"
if (b.id == baseId) PrimaryButton(label, compact = true) {} else SecondaryButton(label, compact = true) { baseId = b.id }
}
}
}
}
Rise(3) {
Actions {
when {
busyHere -> SecondaryButton("Stop") { GogState.cancel() }
local == null || !local.complete -> PrimaryButton(if (local == null) "Install" else "Resume download", main = true, enabled = GogState.busy == null && game != null) {
val base = local?.base ?: bases.first { it.id == baseId }
game?.let { GogState.install(ctx, it, base) }
}
else -> SecondaryButton("Check for update", enabled = GogState.busy == null) { GogState.update(ctx, local) }
}
if (local != null && !busyHere) {
SecondaryButton(if (confirmRemove) "Press again to uninstall" else "Uninstall", enabled = GogState.busy == null) {
if (confirmRemove) { confirmRemove = false; GogState.uninstall(ctx, local) } else confirmRemove = true
}
}
sizes?.let {
ActionChip("${GogManager.formatSize(it.download)} download", ok = false)
ActionChip("${GogManager.formatSize(it.disk)} installed", ok = false)
}
if (local?.complete == true) ActionChip("● Installed", ok = true)
}
}
if (busyHere) GogBusyBar()
Rise(4) {
Box(Modifier.padding(top = 12.dp)) {
Note(
if (local?.complete == true) "It is in Steam's library as a non-Steam game (after Steam next starts). Uninstalling removes the game's files; " +
"its saves and settings stay in its Proton prefix."
else "Installs the Windows build. Once it finishes, the game shows in Steam's library as a non-Steam game the next time Steam starts, " +
"and runs through Proton like the rest of your added games.",
)
}
}
}
/** A sign-in that ends on GOG's success page hands its code to [onCode]; GOG's page does the rest. */
@SuppressLint("SetJavaScriptEnabled")
@Composable
private fun GogLoginDialog(onCode: (String) -> Unit, onDismiss: () -> Unit) {
var done by remember { mutableStateOf(false) }
fun check(url: String?): Boolean {
val uri = url?.let(Uri::parse) ?: return false
if (uri.host != "embed.gog.com" || uri.path?.startsWith("/on_login_success") != true) return false
val code = uri.getQueryParameter("code") ?: return false
if (!done) { done = true; onCode(code) }
return true
}
Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) {
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = { c ->
WebView(c).apply {
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean = check(request.url.toString())
override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {
if (check(url)) view.stopLoading()
}
}
loadUrl(GOG_LOGIN)
}
},
onRelease = { it.destroy() },
)
}
}
@@ -40,7 +40,6 @@ fun PerformancePage(
gamescopeRealtime: Boolean,
gpuClockPin: Boolean,
prootNoSeccomp: Boolean,
prootFastPath: Boolean,
guestHostname: String,
phantomWarning: String?,
onClientOverride: (Boolean) -> Unit,
@@ -52,7 +51,6 @@ fun PerformancePage(
onGamescopeRealtime: (Boolean) -> Unit,
onGpuClockPin: (Boolean) -> Unit,
onProotNoSeccomp: (Boolean) -> Unit,
onProotFastPath: (Boolean) -> Unit,
onGuestHostname: (String) -> Unit,
onClientCore: (Int, Boolean) -> Unit,
onGameCore: (Int, Boolean) -> Unit,
@@ -129,12 +127,6 @@ fun PerformancePage(
"May fix missing syscall errors on some kernels, but can reduce performance.",
prootNoSeccomp, onChange = onProotNoSeccomp,
)
ToggleRow(
host, "fastpath", "proot fast path",
if (prootNoSeccomp) "Needs proot's seccomp filter: off while proot runs without seccomp."
else "Answers file lookups inside each program instead of through proot. Faster loading and less stutter; turn off if a program cannot find its files.",
prootFastPath && !prootNoSeccomp, enabled = !prootNoSeccomp, onChange = onProotFastPath,
)
}
SettingsGroup("Session identity") {
var draft by remember(guestHostname) { mutableStateOf(guestHostname) }
@@ -76,8 +76,6 @@ internal fun StorePage(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
var openApp by rememberSaveable { mutableStateOf<String?>(null) }
var query by rememberSaveable { mutableStateOf("") }
var category by rememberSaveable { mutableStateOf<String?>(null) }
// Which store the page shows: Flathub's apps, or the user's GOG games.
var store by rememberSaveable { mutableStateOf("flathub") }
LaunchedEffect(s.ready) { StoreState.refresh(ctx) }
LaunchedEffect(Unit) { StoreState.loadSections() }
// A pad's focus sits on something the page is about to replace - the tile that opens an app,
@@ -105,8 +103,8 @@ internal fun StorePage(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
}
Column(
modifier = modifier.verticalScroll(scroll).padding(horizontal = padH, vertical = padV)
.bumpers(onPrevious = { if (openApp == null && store == "flathub") switchTab((tab + TABS.size - 1) % TABS.size) },
onNext = { if (openApp == null && store == "flathub") switchTab((tab + 1) % TABS.size) }),
.bumpers(onPrevious = { if (openApp == null) switchTab((tab + TABS.size - 1) % TABS.size) },
onNext = { if (openApp == null) switchTab((tab + 1) % TABS.size) }),
) {
val id = openApp
if (id != null) {
@@ -115,25 +113,10 @@ internal fun StorePage(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
}
Rise(0) {
PageHeader("Store") {
if (store == "gog") {
Chip("GOG · Windows games", ok = false)
if (com.droiddeck.launcher.store.gog.GogState.signedIn) Chip("● Signed in", ok = true)
} else {
Chip("Flathub · ARM64", ok = false)
if (StoreState.ready) Chip("● Flatpak ready", ok = true)
}
Chip("Flathub · ARM64", ok = false)
if (StoreState.ready) Chip("● Flatpak ready", ok = true)
}
}
Rise(0) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(top = 10.dp)) {
PillButton("Flathub", selected = store == "flathub") { store = "flathub" }
PillButton("GOG", selected = store == "gog") { store = "gog" }
}
}
if (store == "gog") {
GogStore(s)
return@Column
}
if (!s.ready) {
Rise(1) { Note("Install the Linux runtime from Setup first; the store installs apps into it.") }
return@Column
@@ -1,76 +0,0 @@
package com.droiddeck.launcher.session
import java.io.File
import java.nio.file.Files
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class SecondaryLibraryTest {
@get:Rule val tmp = TemporaryFolder()
@Test fun gamesStaySharedButPrefixesAndNativeDownloadsArePrivate() {
val files = tmp.newFolder("files")
val library = tmp.newFolder("card")
File(library, "steamapps/common/Game").mkdirs()
val binds = SecondaryLibrary.binds(files, library)
val private = SecondaryLibrary.privateRoot(files, library)
for (guest in listOf("/mnt/droiddeck-sd", "/mnt/bannerlator-sd")) {
assertTrue(binds.contains("${library.path}:$guest"))
assertTrue(binds.contains("$private/steamapps/compatdata:$guest/steamapps/compatdata"))
assertTrue(binds.contains("$private/steamapps/downloading/4185400:$guest/steamapps/downloading/4185400"))
assertTrue(binds.contains("$private/steamapps/common/SteamLinuxRuntime_4-arm64:$guest/steamapps/common/steamlinuxruntime_4-arm64"))
assertFalse(binds.any { it.endsWith(":$guest/steamapps/common/Game") })
}
}
@Test fun migrationPreservesSavesLinksAndOriginalAndNeverOverwritesNewSaves() {
val files = tmp.newFolder("files")
val library = tmp.newFolder("card")
val save = File(library, "steamapps/compatdata/42/pfx/save.dat")
save.parentFile!!.mkdirs()
save.writeText("original")
Files.createSymbolicLink(File(save.parentFile, "link").toPath(), File("save.dat").toPath())
SecondaryLibrary.binds(files, library)
val copied = File(SecondaryLibrary.privateRoot(files, library), "steamapps/compatdata/42/pfx/save.dat")
assertEquals("original", copied.readText())
assertTrue(Files.isSymbolicLink(File(copied.parentFile, "link").toPath()))
copied.writeText("new save")
SecondaryLibrary.binds(files, library)
assertEquals("new save", copied.readText())
assertEquals("original", save.readText())
}
@Test fun changingLibraryUsesADifferentPrivatePrefixDirectory() {
val files = tmp.newFolder("files")
assertNotEquals(SecondaryLibrary.privateRoot(files, tmp.newFolder("one")),
SecondaryLibrary.privateRoot(files, tmp.newFolder("two")))
}
@Test fun installedNativeToolVersionsAlsoGetPrivateStaging() {
val files = tmp.newFolder("files")
val library = tmp.newFolder("card")
val manifest = File(library, "steamapps/appmanifest_123.acf")
manifest.parentFile!!.mkdirs()
manifest.writeText("\"AppState\" { \"appid\" \"123\" \"installdir\" \"Proton 99.0 (ARM64)\" }")
assertTrue(SecondaryLibrary.binds(files, library).any {
it.endsWith(":/mnt/droiddeck-sd/steamapps/downloading/123")
})
}
@Test fun deletingAStagedDepotDoesNotRestoreTheOldSharedDownload() {
val files = tmp.newFolder("files")
val library = tmp.newFolder("card")
val stale = File(library, "steamapps/downloading/4185400/stale")
stale.parentFile!!.mkdirs()
stale.writeText("old download")
SecondaryLibrary.binds(files, library)
val target = File(SecondaryLibrary.privateRoot(files, library), "steamapps/downloading/4185400")
assertTrue(File(target, "stale").isFile)
target.deleteRecursively()
SecondaryLibrary.binds(files, library)
assertFalse(File(target, "stale").exists())
assertTrue(stale.isFile)
}
}
@@ -1,91 +0,0 @@
package com.droiddeck.launcher.store.gog
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class GogTest {
@get:Rule val tmp = TemporaryFolder()
private fun game(): File = tmp.newFolder("Example Game").apply {
File(this, "Bin").mkdirs()
File(this, "Bin/Game.EXE").writeText("x")
File(this, "Launcher.exe").writeText("x")
File(this, "Data").mkdirs()
}
private fun info(vararg tasks: String) =
JSONObject("""{"gameId":"42","rootGameId":"42","name":"Example: The Game","playTasks":[${tasks.joinToString(",")}]}""")
@Test fun primaryGameTaskWinsWithWindowsPathsMatchedCaselessly() {
val dir = game()
val parsed = GogGameInfo.parse(dir, info(
"""{"type":"FileTask","category":"launcher","isPrimary":true,"path":"Launcher.exe"}""",
"""{"type":"URLTask","category":"document","link":"https://example.com"}""",
"""{"type":"FileTask","category":"game","isPrimary":true,"path":"bin\\game.exe","workingDir":"data","arguments":"-windowed -lang \"en\""}""",
))!!
assertEquals("42", parsed.id)
assertEquals("Example: The Game", parsed.name)
assertEquals(File(dir, "Bin/Game.EXE"), parsed.task!!.exe)
assertEquals(File(dir, "Data"), parsed.task!!.workingDir)
assertEquals("-windowed -lang \"en\"", parsed.task!!.arguments)
}
@Test fun noWorkingDirStartsInTheGameFolder() {
val dir = game()
val parsed = GogGameInfo.parse(dir, info("""{"type":"FileTask","category":"game","path":"Bin\\Game.exe"}"""))!!
assertEquals(dir, parsed.task!!.workingDir)
assertEquals("", parsed.task!!.arguments)
}
@Test fun missingExeMeansNoTask() {
val dir = game()
assertNull(GogGameInfo.parse(dir, info("""{"type":"FileTask","category":"game","isPrimary":true,"path":"Missing.exe"}"""))!!.task)
}
@Test fun readPicksTheRootGameOverDlcInfoFiles() {
val dir = game()
File(dir, "goggame-7.info").writeText("""{"gameId":"7","rootGameId":"42","name":"DLC","playTasks":[]}""")
File(dir, "goggame-42.info").writeText(info("""{"type":"FileTask","category":"game","isPrimary":true,"path":"Bin\\Game.exe"}""").toString())
assertEquals("42", GogGameInfo.read(dir)!!.id)
}
@Test fun incompleteUntilTheDownloadFinishes() {
val dir = game()
File(dir, GogManager.MARKER).writeText("""{"id":"42"}""")
assertTrue(GogManager.incomplete(dir))
File(dir, "goggame-42.info").writeText(info("""{"type":"FileTask","category":"game","isPrimary":true,"path":"Bin\\Game.exe"}""").toString())
File(dir, ".gogdl-resume").writeText("")
assertTrue(GogManager.incomplete(dir))
File(dir, ".gogdl-resume").delete()
assertEquals(false, GogManager.incomplete(dir))
}
@Test fun libraryKeepsWindowsGamesAndPageCount() {
val (games, pages) = GogApi.parseLibraryPage("""{"totalPages":3,"products":[
{"id":1207658924,"title":"Unreal Tournament","image":"//images-1.gog-statics.com/abc","worksOn":{"Windows":true,"Mac":false,"Linux":false}},
{"id":2,"title":"Mac Only","image":"//images-1.gog-statics.com/def","worksOn":{"Windows":false,"Mac":true}}
]}""")!!
assertEquals(3, pages)
assertEquals(listOf("1207658924"), games.map { it.id })
assertEquals("https://images-1.gog-statics.com/abc_392.jpg", games[0].image)
}
@Test fun artFillsGamesDbUrlTemplates() {
val art = GogApi.parseArt("""{"game":{"vertical_cover":{"url_format":"https://images.gog.com/v{formatter}.{ext}"},
"logo":{"url_format":"https://images.gog.com/l{formatter}.{ext}"}}}""")!!
assertEquals("https://images.gog.com/v.jpg", art.cover)
assertEquals("https://images.gog.com/l.png", art.logo)
assertNull(art.hero)
}
}
-310
View File
@@ -1,310 +0,0 @@
# proot, glibc and where the time goes
Research notes for `feat/performance-fixes-2` (2026-09-30). The question was whether Steam and the
games should keep running under proot, run directly on glibc, or a mix of the two, and what the
fastest correct setup is. Everything below was measured on a Snapdragon 8 Elite Gen 5 (SM8850, kernel
6.12.38-android16, Android 16) over adb, unless it says otherwise.
## Short answer
- **Don't drop proot.** On Android it does two jobs. It translates paths. It also answers every
syscall that Android's app seccomp policy blocks (`rseq`, `set_robust_list`, `faccessat2`,
`fchmodat2`, `openat2`, the `set*id` family, `futex_waitv`, ...).
- Stock Arch glibc without a tracer is killed by `SIGSYS` on its first `pthread_create`. That
stays true even with an in-process `SIGSYS` handler, because glibc makes those calls with every
signal blocked.
- Going "pure glibc" means building Termux-style glibc (relocated prefix, blocked syscalls
rewritten), an exec shim for every ELF Steam self-updates, a `/proc/self/exe` emulator for
Chromium, path redirects for `/tmp`, `/dev/shm`, `/mnt/*` and the fake `/proc` and `/sys`
files, and Wine's hard-coded `/tmp/.wine-<uid>`.
- That is a project of its own, and its failure mode is a crash instead of a slow call.
- **During gameplay, proot already costs almost nothing**, thanks to patches 0004–0013. GPU submits
(`ioctl`), `futex`, `read`/`write`, `mmap`, `ppoll`/`epoll`, `sendmsg`/`recvmsg` and
`clock_gettime` (via the vDSO) all run at native speed under the filter.
- **What proot still costs** is every *path* syscall, `execve`, `brk`, thread and process creation,
and every Android-blocked syscall: **15–60 µs each**, against ~0.5 µs natively. All of it goes
through **one tracer thread**, which tops out around 75–95k traps/s. Steam start-up, game loading
and asset streaming, Proton's Python, and any burst on several threads at once all hit this.
- **Most of that cost is not proot's code but the two cross-core wake-ups per trap.** Any
out-of-process mechanism pays them: ptrace, and seccomp user-notification too (measured the same).
The only real fix is to not leave the process.
- **Recommendation: proot plus an in-process fast path.** A preloaded library answers the common
path calls inside the process. It sends them through a trampoline page that proot's filter lets
through, and it falls back to proot for anything it can't prove proot would answer the same way.
- The prototype is in this branch: `tools/proot/fastpath/` and `patches/0014`.
- Speed: `stat` 25 µs → 0.6 µs, `open` 25 µs → 0.9 µs, missing-file lookups 23 µs → 1.6 µs.
Eight threads doing `stat` went from 89k/s to 3.6M/s.
- Correctness: an equivalence suite of awkward paths produced byte-identical results.
- It only uses syscalls the app policy allows.
## How a session runs today
```
SessionService ─HostProcess─▶ libproot.so (ONE tracer process, nice -6 after 2 s)
└─ /usr/bin/env -i … bannerlator-session steam
└─ gamescope ─▶ bannerlator-session (BL_INSIDE) ─▶ steamrtarm64/steam (+ steamwebhelper/CEF tree)
└─ reaper ─▶ bannerlator-game-env ─▶ bannerlator-proton ─▶ Valve ARM64 Proton (python)
└─ wine (arm64ec, FEX loaded in-process as a DLL) ─▶ wineserver, game.exe, …
```
- Every process in the tree, from the session script to the game, is a tracee of the same proot.
- The options are `--kill-on-exit`, `--kernel-release=…` (kompat, for the hostname), `-i uid:uid`
(fake_id0, for Xwayland's `setgid`/`setuid`), and about 25 binds: `/dev`, `/proc`, `/sys`, fake
`/proc` and `/sys` files, the GPU node, `/dev/shm`, storage and the game libraries.
- `/etc/ld.so.preload` loads `libblsession.so` (the `tools/linuxfs/preload/*.c` shims) into every
guest process.
- The Flatpak sandboxes (`BwrapSpawner`) already run in **separate** proot instances, started from
the Android side.
### What proot does per traced syscall
The tracee runs into proot's seccomp filter, which returns `SECCOMP_RET_TRACE`. Then:
1. The kernel stops the tracee and wakes the tracer: a cross-core IPI, and possibly an exit from a
deep idle state.
2. The tracer reads the registers (`PTRACE_GETREGSET`) and reads the path (`process_vm_readv`).
3. It canonicalises the path against the rootfs and bindings: an `lstat` per component, or one
`O_PATH` open plus a `/proc/self/fd` readlink with patch 0002.
4. It writes the host path into a scratch area in the tracee (`process_vm_writev`) and updates the
registers.
5. It resumes the tracee, which is another cross-core wake-up.
Calls flagged `FILTER_SYSEXIT` stop a second time on the way out, for example to translate the
result of `readlink` or `getcwd`. Android-blocked syscalls arrive as a `SIGSYS` signal stop instead,
and proot emulates them (`src/tracee/seccomp.c`). Fork, clone, exec and thread exit each add
`PTRACE_EVENT_*` stops.
## Measurements
The tools are in `tools/proot/bench/`; `run-device.sh` explains the device layout.
**Caveat:** `adb shell` is *not* under the app seccomp filter. Mechanism costs are the same, but
syscalls that Android blocks only for apps (see below) can't be reproduced there.
**Caveat:** the phone in Doze (screen off) runs everything about 7× slower. All numbers below were
taken with the screen awake.
### Per call, as a session runs proot today
`sysbench` in the patched (`patched`) and unpatched (`vanilla`) columns, using the session's own
proot options and a similar set of binds.
| call | direct glibc | termux proot (vanilla) | this repo's proot (0001–0013) | + fast path (0014) |
|---|---|---|---|---|
| getppid / futex / ioctl / pread (untraced) | 0.1–0.4 µs | futex **16.6**, fstat **32.8**, ioctl **30.5** µs | 0.2–0.4 µs | 0.2–0.4 µs |
| stat, deep absolute path | 0.8 µs | 41.7 | 25.3 | **0.6** |
| open + close | 1.7 µs | 40.4 | 25.3 | **0.9** |
| access | | 27.2 | 26.2 | **1.0** |
| fstatat relative to a dirfd | | 45.5 | 26.8 | **1.9** |
| stat of a missing file | | 38.9 | 22.9 | **1.6** |
| readlink /proc/self/exe | | 42.8 | 38–43 | (proot) |
| getcwd / uname / brk | | 31–35 | 30–33 | (proot) |
| memfd_create | | 20.4 | 18.6 | (proot) |
| pthread create+join | | 58 | 48 | 48 |
| fork + exec + wait | ~1.1 ms | 1.16 ms | 0.70–0.78 ms | +0.2–0.4 ms (see open items) |
The patches already in the repo pay off: kompat (0011) and fake_id0 (0012) took `futex`, `fstat` and
`sendmsg` off the trap list, and 0013 did the same for `ioctl`.
### What one trap costs, by mechanism (`mechbench`; the handler does nothing)
| mechanism | cost |
|---|---|
| native syscall | 0.1 µs |
| seccomp filter of 0 / 50 / 150 / 300 compares, allowed syscall | **no difference** (kernel ≥5.11 caches constant decisions per syscall number) |
| ptrace + seccomp, tracer and tracee on the **same core** | 6.2 µs (6.7 µs with register get/set) |
| ptrace + seccomp, **unpinned** (as the app runs it) | 15.5 µs |
| ptrace + seccomp, different cores (same cluster / across clusters) | 34–36 / 42–61 µs |
| ptrace with a spinning tracer, different cores | 20 µs (the tracee's side still has to wake) |
| seccomp user-notification (the "modern proot" design) | 5.7 µs same core, 34–58 µs across, 43 µs unpinned; `SYNC_WAKE_UP` doesn't help |
| **in-process SIGSYS** (`SECCOMP_RET_TRAP`) | **0.83 µs** |
| openat2 `RESOLVE_IN_ROOT` (kernel-side chroot lookup) | 1.0 µs, but **blocked in apps** |
Takeaways:
- The tracer's own work is about 8 µs of the ~14 µs same-core trap. Everything above that is
scheduling.
- Moving to seccomp user-notification would be a rewrite for no gain.
- The filter's length doesn't matter. What matters is not breaking the kernel's cache:
- **Any check on an argument or the instruction pointer must come after the syscall-number
dispatch.** The first version of 0014 checked the address first. That made every syscall in
the session run the whole filter, and cost +0.5 ms per exec.
- Patches 0004 and 0013 already follow this rule.
### One tracer for everything (`parstat`: N threads doing `stat`)
| | 1 thread | 4 threads | 8 threads |
|---|---|---|---|
| one proot | 37k/s, 27 µs | 74–95k/s, 42–54 µs | 68–89k/s, **90–118 µs** each |
| two proots, 2 threads each | | 187k/s total, 21 µs | |
| proot + fast path | 1.64M/s, 0.6 µs | 2.76M/s | **3.60M/s, 2.2 µs** |
A burst of path calls on several threads therefore queues behind the single tracer. CEF loading
assets, Proton's Python, a game streaming files on worker threads and the shader-cache threads all
produce such bursts.
### CPU placement
The workload ran with `taskset`; no fast path. Times are per traced call, and the last column is one
fork + exec.
| affinity | stat | exec |
|---|---|---|
| default | 25.8 µs | 750 µs |
| one core | 14.0 µs | 370 µs |
| the two prime cores | 14.6 µs | |
| the six-core cluster | 25.9 µs | |
The scheduler's wake-affine placement helps when it can put the tracer and the tracee together, and
spreading them apart hurts. **Never pin the tracer away from its tracees.** Today `raiseTracer`
only renices it, which is correct.
### Whole programs
Times are in ms, each with proot's ~40 ms start-up already subtracted.
| | direct glibc | vanilla proot | this repo's proot | + fast path |
|---|---|---|---|---|
| python3: 10 stdlib imports | 75–89 | ~130 | ~110 | ~90 (878 of 879 path calls answered in-process) |
| tar of 2.7k files | 10–40 | ~180 | ~80 | ~20 |
| 200 × fork+exec of `true` | 230 | ~600 | ~500 | ~500 |
| find over 2.7k files | 16–23 | noisy | noisy | unchanged: glibc's fts calls internal entry points |
## Android's app seccomp policy decides more than proot does
The app filter is generated from bionic's `SYSCALLS.TXT`, minus the blocklists, plus the
allowlists. It is the same for every app whatever its `targetSdk`, and anything not listed gets
`SECCOMP_RET_TRAP`, a `SIGSYS`. Filters stack, and the strictest one wins: a blocked call never
reaches proot's `RET_TRACE`. It arrives as a `SIGSYS` stop, and proot answers it (usually `ENOSYS`).
Checked against bionic `android16-release`:
| syscall | app policy | who calls it |
|---|---|---|
| `rseq`, `set_robust_list` | **blocked** | glibc, at the start of every thread, while all signals are blocked |
| `faccessat2` | **blocked** | glibc's `faccessat()`, which tries it on **every** call before falling back, so 2 round trips (`access()` calls the plain `faccessat` syscall directly) |
| `fchmodat2`, `openat2` | **blocked** | newer glibc, Flatpak/libglnx |
| `setuid`, `setgid` and the rest of the family | **blocked** | Xwayland (hence `-i`) |
| `futex_waitv`, `io_uring_*`, `landlock_*` | **blocked** | Proton's fsync, some engines |
| `clone3` | blocked before Android 15 | glibc `pthread_create` |
| `close_range` | blocked on Android 12 | |
| `statx`, `process_vm_readv`/`writev`, `memfd_create`, `pidfd_*`, `seccomp` | allowed | |
On top of the ptrace round trips, every one of these costs a signal round trip through proot.
## Every traced syscall: what it needs and whether it can bypass proot
This is the filter of termux proot at `source.env` plus patches 0001–0013. "Fast path" means the
call can be answered in-process with the 0014 design.
| syscalls | why proot traps them | can it bypass proot? |
|---|---|---|
| `openat`/`open`/`creat`, `newfstatat`/`stat`/`lstat`, `statx`, `faccessat`/`access`, `readlinkat` (exit), `mkdirat`, `unlinkat`, `renameat(2)`, `symlinkat`, `linkat`, `fchmodat`, `fchownat`, `utimensat`, `truncate`, `*xattr`, `inotify_add_watch`, `name_to_handle_at` | path translation (guest → host), plus exit fixups for `readlink` and `rename` | **Yes, through libc wrappers.** The prototype covers open, stat, statx, access, readlink, opendir and fopen; the write family is next. Raw `svc` and glibc's internal callers (ld.so, fts, realpath, nss) still go to proot. |
| `chdir`/`fchdir`, `getcwd` (exit) | proot emulates the cwd; until 0014 the kernel's cwd never moved | With 0014 the kernel's cwd follows the guest's. `getcwd` stays in proot (cheap, rare). |
| `execve`/`execveat` | runs the loader, maps `PT_INTERP` inside the rootfs, shebangs, tracks `/proc/self/exe` | **No.** This is the core of what proot is for. Costs 0.4–0.8 ms per exec; the session scripts already avoid exec-heavy loops (`nap`). |
| `brk` (entry and exit) | heap emulation: programs are mapped by proot's loader, so the kernel's brk area is the loader's | No (`PR_SET_MM` needs `CAP_SYS_RESOURCE`). **Fewer calls:** `GLIBC_TUNABLES=glibc.malloc.top_pad=…` grows the heap in larger steps. |
| `bind`, `connect`, `accept(4)`, `getsockname`, `getpeername` | `sun_path` of Unix sockets | Same-path binds (runtime dir, files dir) need no translation, but the filter can't see the address. Possible fast-path candidate. |
| `wait4`/`waitpid`, `ptrace` | ptrace emulation inside the guest (breakpad, gdb) | Could become opt-in; then `wait4` is free (one stop per wait today). |
| `prctl(PR_SET_DUMPABLE)`, `setrlimit`/`prlimit64(RLIMIT_STACK)` | loader and stack fixups | Already narrowed to these arguments (0004). |
| `ioctl(TCSETSF, termios2, FICLONE)` | Android pty policy, FICLONE `EACCES` | Already narrowed to these requests; GPU ioctls are free (0013). |
| `uname`, `sethostname`, `setdomainname` | the `DroidDeck` hostname (kompat) | Rare. Keep. |
| `set*id`, `*setxattr` | fake_id0 identity mode (0012) | Rare. Keep. |
| `memfd_create` | Qt JIT and php workarounds (string argument) | Every Wayland `wl_shm` buffer and Chromium shared memory pays one stop. Could be dropped if the DroidDeck runtime doesn't need those workarounds. |
| `statfs` (exit) | fakes tmpfs for `/dev/shm` | Rare. |
| `open_tree`, `move_mount`, `fspick`, `mount_setattr`, `openat2` | answered `ENOSYS` (0008, 0010) | Fine. |
| Android-blocked calls (previous table) | `SIGSYS` emulation | **Avoidable at the source:** `GLIBC_TUNABLES=glibc.pthread.rseq=0` removes one stop per thread. The rest need a patched glibc. |
| clone/fork/vfork/exec/exit events | tracking tracees | Needed while proot traces. |
## Options weighed
1. **Pure glibc, no proot.** Rejected as the main path, for the reasons in the short answer.
- Closest prior art: huntergdavis/steamclienttermux, which runs `steamrtarm64` on a patched
Termux glibc 2.44 with an exec shim and a `/tmp` and `/dev/shm` redirect preload.
- They report Steam's first window 7× faster and about 5% more FPS, with proot having used 60–65%
of a core.
- **They still run Proton and the games under proot.**
- DroidDeck also has four package names (`tools/release/variants.txt`), so a relocated prefix
would need four builds or Winlator-style padded path rewriting.
2. **Hybrid by process (Steam in proot, game on glibc, or the reverse).** The game side is the
*harder* half. Wine re-execs itself and `wineserver`, which hits `PT_INTERP`. Its server
directory is hard-coded under `/tmp`, and Proton's esync and fsync use `shm_open` (`/dev/shm`)
and `futex_waitv`, which is blocked. A game's steady state is already mostly untraced, so the
gain is in loading. Not worth it before the fast path.
3. **Seccomp user-notification instead of ptrace.** It measures the same as ptrace, and it can't
rewrite arguments, so every call would have to be emulated. No.
4. **In-process `SIGSYS` for everything** (0.8 µs). The kernel resets a blocked `SIGSYS` to the
default action and kills the process (`force_sig_seccomp`, `HANDLER_CURRENT`). glibc and Wine
block all signals around exactly these calls. Unsafe without also trapping `rt_sigprocmask`. No.
5. **proot plus an in-process fast path (this branch).** Recommended. Details below.
6. **A proot-aware glibc**, the follow-up to 5. Rebuild the rootfs's own glibc (same version, same
Arch package) with two changes:
- its internal path entry points (`__open_nocancel`, `__fstatat64`, ld.so's opens) go through the
fast path, which covers ld.so, fts, realpath and nss;
- it never makes the Android-blocked calls, as Termux's `fakesyscall.json` does.
This removes the remaining library-loading traps and all the `SIGSYS` round trips. The rootfs is
versioned (`linuxfs-rN`), so glibc rebuilds stay under control.
7. **On the tracer side, with no in-process changes:**
- **A second proot for the game tree.** Measured 2.5× trap throughput, and Steam/CEF bursts no
longer stall the game. `BwrapSpawner` already shows the pattern: a stand-in process in the
session relays stdio, the exit status and signals to a proot started from the app.
- Leave the tracer unpinned (above).
- Set `GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216` in the session
environment.
## The fast path (prototype)
The code is `tools/proot/fastpath/fastpath.c`, preloaded into every guest process. On the proot side
it needs `patches/0014`, enabled with `PROOT_FASTPATH=1`.
- **Trampoline.** The library maps a 4 KiB executable page at the fixed address `0xffff00000`. It
holds `mov x8,x0 … svc #0; ret`. With `PROOT_FASTPATH`, proot's filter checks the caller's address
just before each `RET_TRACE` and allows syscalls coming from that page.
- **Mapping a path.** The library takes the literal guest path and finds the longest binding whose
guest path is a prefix of it; otherwise the path is under the rootfs.
- It opens the *parent* host directory `O_PATH` and requires `/proc/self/fd` to name exactly that
path. That proves no component on the way was a symlink, so proot would have walked the same
directories.
- The last component is never followed: a symlink there goes to proot.
- **Missing files.** For a missing file, the deepest existing ancestor is verified the same way, and
the next component must not exist even as a symlink. Then `ENOENT` is exact.
- **What always goes to proot:**
- `..`, a trailing `/`, `/proc`, `/dev/fd` and `/dev/std*`;
- `O_TMPFILE`, `AT_EACCESS`, and any flag not handled;
- any doubt at all. "Go to proot" means calling the real libc function, so proot decides.
- **Relative paths.** Patch 0014 keeps the kernel's cwd at the guest cwd's host directory. Relative
and dirfd lookups are mapped through `/proc/self/{cwd,fd/N}`.
- **Verified-parent cache.** Verified parents are cached for 2 s (`PROOT_FP_TTL_MS`). That is the
same trade-off `preload/pathcache.c` already makes for the Steam client. A parent directory turned
into a symlink inside that window would be missed; `PROOT_FP_TTL_MS=0` verifies every call, at
2.0 µs instead of 0.6 µs.
- **Allowed syscalls only.** It uses only `openat`, `newfstatat`, `statx`, `faccessat`, `readlinkat`
and `close`, all allowed for apps. A first version used `openat2 RESOLVE_IN_ROOT`, which the app
policy blocks.
- **Equivalence check.** `bench/equiv.py` runs stat, lstat, readlink, read, listdir and access over
awkward paths, from several working directories and through a dirfd. Its output is byte-identical
with and without the fast path, at TTL 0 and at TTL 2000. The paths include:
- absolute and relative symlinks into binds, `..` symlinks, dangling links and loops;
- files inside binds, nested binds (`/dev/shm` inside `/dev`) and `/proc`;
- missing paths behind symlinks.
### Open items before shipping it
- **Validate inside the app**, not just from adb. Three things to check:
- The app domain allows an anonymous `PROT_EXEC` page (`execmem`). If not, map a page of the
library file itself at the fixed address instead, as proot's loader does for every program.
- Nothing claims `0xffff00000` first.
- The stub's syscalls pass Android's filter. They should: all are allowed.
- **Integrate into `libblsession.so`** rather than a second preload. `opens.c` and `pathcache.c`
already define `open` and `access`, so their "real" call should become the fast path. That also
removes the second library's load cost, about 0.2–0.4 ms per exec that is still unexplained (see
the exec row above).
- **Wire the launcher.** The app already knows the binds (`LinuxRuntime.binds`):
- set `PROOT_FASTPATH=1` in proot's environment;
- pass `PROOT_FP_ROOT` and `PROOT_FP_BINDS` to the guest;
- add a Performance toggle next to "Run proot without seccomp", with the fast path off whenever
seccomp is off.
- **Cover the write family** (mkdir, unlink, rename, symlink, chmod, utimens) and Unix-socket
`connect`/`bind` for same-path binds. Then measure a real Steam start in the app, a game load,
and `PROOT_FP_STATS` hit rates for steam, steamwebhelper, wine and wineserver.
- **FEX**, inside Proton as a DLL, translates x86 path syscalls through glibc's `syscall()`, not the
wrappers, so they still trap. A `syscall()` hook could route `openat` and `newfstatat` there too.
+28
View File
@@ -48,6 +48,34 @@ Device-tested on the AYN Thor (Katamari under Proton Experimental ARM64).
- **Prior art checked**: WinNative and Bannerlator never emulated uinput or hidraw; Bannerlator's
`-steamdeck` mode stopped at "the virtual pad never arrives", which is this missing uinput.
## 2026-09-28 - Cemu's Turnip fix released for every driver; A8xx driver back; proven on the Galaxy Z Fold 8
State: **DroidDeck main unchanged** (`d98c211`); this is driver-side work in `The412Banner/Banners-Turnip`,
released as **`v26.3.0-20260928-r4`** (Latest; r3 is the same code - r4 was the Mesa watcher rebuilding because a
hand-started release does not update `mesa_hash.txt`).
- **The Cemu Vulkan crash is a Mesa bug, now fixed in every Banners-Turnip zip** (Android, Wayland, Linux):
`tu_knl_kgsl.cc` `kgsl_syncobj_merge` converted the wrong syncobj when a timestamp met a sync-file (NULL
dereference; in Mesa since the 2023 KGSL rewrite `9c808043f350`). Cemu waits on both kinds every frame. The fix
moved from `patches/linux/` to `patches/common/` (PR #2) - it is a KGSL bug, not a Linux one. Upstream Mesa MR:
dropped by the user (Mesa's contribution rules need it written and posted by the contributor).
- **A8xx driver building again** (PR #3): it failed on all three legs since 09-27. whitebelyash's
"expose VK1.3 without multiview" is now Mesa's own behaviour (dropped), and Mesa's new `quirks` struct made
fuzz put `gmem_size` in the wrong struct (both hunks re-anchored).
- **Linux zips carry the driconf defaults built in** (PR #4, `-Dxmlconfig=disabled`, from Max's WinNative
Drivers): before, they read `/usr/share/drirc.d` from the rootfs, so vkd3d/DXVK and per-game workarounds
(RDR2, DOOM Eternal, Spider-Man, ...) were whatever Mesa the rootfs ships. Verification now fails any zip
that reads drirc from disk.
- **Adreno 840v2 chip id `0x44050A21`** (PR #1, felipGonzalez; POCO F9 Pro) and **Max's three A8XX hang fixes**
(PR #5: cube-map direction sanitize, bindless invalidate through the A8XX registers - re-targeted because
his mesh-shader patch is not carried - and a KGSL VBO alias for command streams), all A8XX-gated.
- **Device proof - Samsung Galaxy Z Fold 8** (SM-F976U, SM8850, KGSL `Adreno840v2`, Android 17, DroidDeck
0.1.7, rootfs r9): r2 A8xx-Linux imported as the desktop driver ran Cemu Super Mario 3D World at ~36 fps on
Vulkan with sound, empty crash buffer; r3/r4 then "works, no issues" (user). The Fold's GPU matches Mesa's
existing A840 entry, so it did not need the 840v2 id.
- **Backlog:** DroidDeck setup should install the newest Linux driver itself; hand-started Turnip releases
should update `mesa_hash.txt`; Max's mesh-shader/wave32 patches (DX12 Ultimate) not carried.
## 2026-09-25 - main `8cdedbe`: melonDS out of the box, touch in Big Picture, log privacy, Decky
State: **main = `8cdedbe`** (PR #22 merge). Device-tested on the AYANEO Pocket FIT (repacked test builds)
+1 -8
View File
@@ -117,9 +117,6 @@ docker run --rm --platform linux/amd64 \
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$d/libblsession.so" tools/linuxfs/preload/*.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libblsession.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$d/libblfastpath.so" tools/proot/fastpath/fastpath.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libblfastpath.so"
for script in tools/linuxfs/overlay/usr/local/bin/bannerlator-*; do
install -Dm644 "$script" "$d/usr/local/bin/$(basename "$script")"
done
@@ -224,13 +221,9 @@ while read -r package_sha256 package_url; do
zstd -dc "${package_archive}" | tar -xf - -C "${mango_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/mangoapp/packages.txt")
install -m644 "${mango_pkgs}/usr/bin/mangoapp" "${mango_dir}/mangoapp"
for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do
for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1 libtracefs.so.1; do
cp -L "${mango_pkgs}/usr/lib/${library}" "${mango_dir}/${library}"
done
# Ours, not the package's: GPU memory without tracefs (tools/mangoapp/libtracefs-shim.c).
docker run --rm --platform linux/amd64 --user "$(id -u):$(id -g)" -v "${repo_root}:/src" -w /src "${image_name}" \
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \
-o app/src/main/assets/linuxfs/usr/local/lib/mangoapp/libtracefs.so.1 tools/mangoapp/libtracefs-shim.c
mkdir -p "${linuxfs_dir}/usr/local/bin"
install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/bin/mangoapp"
-8
View File
@@ -39,13 +39,5 @@ library list, before anything is published.
then focus is handed over again. `GAMESCOPE_RESTORE_FOCUS_WINDOW` on the root window asks for the
same restore from outside (the session script's resume watcher).
- `0113-steam-overlay-keeps-game-keyboard-focus.patch` - this app: the Steam client opens the Quick
Access Menu and Steam menu over a game with `STEAM_INPUT_FOCUS` 1, which moves X keyboard focus to
its overlay; wine then deactivates the game and a fullscreen game minimizes itself, freezing
behind the menu instead of running on as on a Steam Deck. Steam's own overlay taking input now
keeps keyboard focus on the game, as mode 2 does; its input comes from the controller through
Steam Input, not the X keyboard. The pointer warps gamescope makes as input moves to Steam and
back are skipped around it, since the game - still taking input - saw them as a mouse jump.
Sixteen more of Armada's patches are DRM/lease/HDR-on-KMS work for a native display, which this
app's Wayland-hosted gamescope never reaches, or need a newer gamescope than the runtime has.
@@ -1,104 +0,0 @@
From: DroidDeck
Subject: [PATCH] steamcompmgr: keep the game's keyboard focus under Steam's overlay
The Steam client opens its Quick Access Menu and Steam menu over a game by setting
STEAM_OVERLAY 1 and STEAM_INPUT_FOCUS 1 on its window. Mode 1 moves X keyboard focus to the
overlay, so the game's window gets FocusOut: wine moves the foreground to the desktop, a fullscreen
game deactivates and minimizes itself (WM_CHANGE_STATE IconicState), and it stops rendering behind
the menu - frozen, all threads asleep, until the menu closes (Alan Wake's American Nightmare,
Proton Experimental ARM64). On a Steam Deck the game runs on behind the menu.
Mode 2 already means "input to the overlay, keyboard focus stays on the focus window". Treat
Steam's own overlay taking input in mode 1 the same way at the three places mode 2 is honoured.
The overlay's input does not need X keyboard focus: the controller drives it through Steam Input.
Measured by rewriting the property to 2 by hand: the game kept running behind the menu and the
controller still moved only the menu.
With the game keeping focus, the pointer resets gamescope makes when input moves to Steam (warp
to the centre, park in the corner) and back (warp to the centre) reached it as a sudden mouse
move: a mouse-look camera spun every time the menu opened and closed. Skip them while Steam's
overlay opens over a game that keeps focus, and as it closes - by then the overlay has dropped its
STEAM_INPUT_FOCUS, so whether the opening kept focus is remembered.
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index 372a82c..3fab3c6 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -1321,6 +1321,22 @@ window_is_steam( steamcompmgr_win_t *w )
return w && ( w->isSteamLegacyBigPicture || w->appID == 769 );
}
+// Whether keyboard focus stays on the focus window while this window has input focus.
+// STEAM_INPUT_FOCUS 2 asks for that. The Steam client also opens its Quick Access Menu and Steam
+// menu over a game with 1, which moves X keyboard focus to the overlay: wine then deactivates the
+// game, a fullscreen game minimizes itself, and it froze behind the menu instead of running on as
+// on a Steam Deck. The overlay's own input does not need X keyboard focus (the controller drives
+// it through Steam Input), so Steam's overlay keeps the game's keyboard focus too.
+static bool
+window_keeps_game_keyboard_focus( steamcompmgr_win_t *w )
+{
+ if ( !w )
+ return false;
+ if ( w->inputFocusMode == 2 )
+ return true;
+ return w->inputFocusMode == 1 && w->isOverlay && window_is_steam( w );
+}
+
static bool
window_is_vr_scene_app( steamcompmgr_win_t *w )
{
@@ -4728,7 +4744,7 @@ void xwayland_ctx_t::DetermineAndApplyFocus( const std::vector< steamcompmgr_win
if ( gamescope::VirtualConnectorIsSingleOutput() )
{
- if ( inputFocus && inputFocus->inputFocusMode == 2 )
+ if ( window_keeps_game_keyboard_focus( inputFocus ) )
keyboardFocusWin = ctx->focus.focusWindow;
}
else
@@ -4834,12 +4850,26 @@ void xwayland_ctx_t::DetermineAndApplyFocus( const std::vector< steamcompmgr_win
if ( ctx->focus.inputFocusWindow != inputFocus ||
ctx->focus.inputFocusMode != inputFocus->inputFocusMode )
{
+ // Steam's overlay opening over a game, or closing again, while the game keeps keyboard focus
+ // (window_keeps_game_keyboard_focus): the game is still taking input, so a pointer warp
+ // reaches it as a sudden mouse move - the camera of a mouse-look game spun as the Quick
+ // Access Menu opened and as it closed. The overlay is driven by the controller and the
+ // cursor is hidden, so leave the pointer where it is. Closing, the overlay has already
+ // dropped its STEAM_INPUT_FOCUS, so whether the opening kept focus is remembered.
+ static bool s_bOverlayKeptGameFocus = false;
+ bool bOverlayKeepsGameFocus = window_keeps_game_keyboard_focus( inputFocus ) &&
+ ctx->focus.focusWindow && !window_is_steam( ctx->focus.focusWindow );
+ bool bSkipPointerReset = bOverlayKeepsGameFocus || s_bOverlayKeptGameFocus;
+ s_bOverlayKeptGameFocus = bOverlayKeepsGameFocus;
+
// If the window doesn't want focus when hidden, move it away
// as we are going to hide it straight after.
// otherwise, if we switch from wanting it to not
// (steam -> game)
// put us back in the centre of the screen.
- if (window_wants_no_focus_when_mouse_hidden(inputFocus))
+ if ( bSkipPointerReset )
+ ;
+ else if (window_wants_no_focus_when_mouse_hidden(inputFocus))
ctx->focus.bResetToCorner = true;
else if ( window_wants_no_focus_when_mouse_hidden(inputFocus) != window_wants_no_focus_when_mouse_hidden(ctx->focus.inputFocusWindow) )
ctx->focus.bResetToCenter = true;
@@ -5340,7 +5370,7 @@ determine_and_apply_focus( global_focus_t *pFocus )
pFocus->inputFocusMode = pFocus->inputFocusWindow->inputFocusMode;
if ( gamescope::VirtualConnectorIsSingleOutput() &&
- pFocus->inputFocusMode == 2 )
+ window_keeps_game_keyboard_focus( pFocus->inputFocusWindow ) )
{
pFocus->keyboardFocusWindow = pFocus->overrideWindow
? pFocus->overrideWindow
@@ -6485,7 +6515,7 @@ handle_wl_surface_id(xwayland_ctx_t *ctx, steamcompmgr_win_t *w, uint32_t surfac
steamcompmgr_win_t *keyboardFocusWindow = pCurrentFocus->inputFocusWindow;
if ( gamescope::VirtualConnectorIsSingleOutput() &&
- keyboardFocusWindow && keyboardFocusWindow->inputFocusMode == 2 )
+ window_keeps_game_keyboard_focus( keyboardFocusWindow ) )
keyboardFocusWindow = pCurrentFocus->focusWindow;
if ( w == keyboardFocusWindow )
+2 -2
View File
@@ -1,2 +1,2 @@
GAMESCOPE_TAG=gamescope-3.16.29-p5
GAMESCOPE_SHA256=188144e5564e020d0bc485a1f4f90e1c5fd61d0d1d6dd29db21e8b019036a5c6
GAMESCOPE_TAG=gamescope-3.16.29-p4
GAMESCOPE_SHA256=e750fb34864bc2eb1160aeed29593e402bf9c8153fafd9fd18c77450bdd50574
@@ -1,195 +0,0 @@
#!/usr/bin/python3
"""The app's GOG store talks to Heroic's gogdl through this: one JSON object per line on stdout,
so progress reaches the front end as numbers rather than log lines. The app puts gogdl in the
runtime (GOGDL below) and keeps the sign-in in its own files (the auth path every command takes).
Tokens never leave on stdout except from "token", whose output the app does not log.
bannerlator-gog login <auth> <code> trades the sign-in page's code for tokens
bannerlator-gog token <auth> a current access token (refreshed when due)
bannerlator-gog info <auth> <id> folder name and sizes of the Windows build
bannerlator-gog install <auth> <id> <base> downloads into <base>/<folder name>
bannerlator-gog update <auth> <id> <dir> brings an installed game to the latest build
Lines: {"e":"info",...}, {"e":"progress","percent":45,"written":..,"total":..},
{"e":"error","message":"..."} and {"e":"done",...} at the end. Exit status 0 on success.
"""
import json
import os
import re
import subprocess
import sys
GOGDL = "/opt/droiddeck/gogdl/gogdl"
PLATFORM = "windows"
MARKER = ".droiddeck-gog.json"
PROGRESS = re.compile(r"= Progress: ([\d.]+) (\d+)/(\d+)")
# gogdl's own log lines: "[NAME] LEVEL: message".
LOG = re.compile(r"^\[([^\]]+)\] (\w+): (.*)$")
def emit(**kw):
sys.stdout.write(json.dumps(kw) + "\n")
sys.stdout.flush()
def gogdl(auth, *args):
return [sys.executable or "/usr/bin/python3", GOGDL, "--auth-config-path", auth] + list(args)
def last_json(text):
"""gogdl prints its answer as the last JSON line of stdout, after anything else it says."""
for line in reversed(text.splitlines()):
line = line.strip()
if line.startswith("{") or line == "null":
try:
return json.loads(line)
except ValueError:
continue
return None
def quiet(auth, *args):
"""Runs a gogdl command that answers in JSON; its log (stderr) is dropped, never echoed."""
run = subprocess.run(gogdl(auth, *args), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
return run.returncode, last_json(run.stdout), run.stderr
def login(auth, code):
os.makedirs(os.path.dirname(auth) or ".", exist_ok=True)
status, data, _ = quiet(auth, "auth", "--code", code)
if status != 0 or not isinstance(data, dict) or data.get("error") or not data.get("access_token"):
emit(e="error", message="GOG did not accept the sign-in")
return 1
emit(e="done", user_id=str(data.get("user_id", "")))
return 0
def token(auth):
if not os.path.isfile(auth):
emit(e="error", message="signed out")
return 1
status, data, _ = quiet(auth, "auth")
if status != 0 or not isinstance(data, dict) or not data.get("access_token"):
emit(e="error", message="signed out")
return 1
expires = float(data.get("loginTime", 0)) + float(data.get("expires_in", 0))
emit(e="token", access_token=data["access_token"], user_id=str(data.get("user_id", "")), expires=int(expires))
return 0
def sizes(size, language):
"""Bytes to download and on disk: the depots every language needs ("*") plus one language's."""
pick = [k for k in ("*", language) if k in size]
if language not in size:
pick += [k for k in size if k != "*"][:1]
return (sum(int(size[k].get("download_size") or 0) for k in pick),
sum(int(size[k].get("disk_size") or 0) for k in pick))
def language_of(data):
langs = data.get("languages") or []
for want in ("en-US", "en"):
if want in langs:
return want
return langs[0] if langs else "en-US"
def info(auth, game_id, out=True):
status, data, err = quiet(auth, "info", game_id, "--platform", PLATFORM, "--skip-dlcs")
if status != 0 or not isinstance(data, dict) or not data.get("folder_name"):
reason = failure(err) or "GOG has no Windows build of this game to download"
if out:
emit(e="error", message=reason)
return None, reason
language = language_of(data)
download, disk = sizes(data.get("size") or {}, language)
result = dict(folder=data["folder_name"], language=language, download_size=download, disk_size=disk,
build=str(data.get("buildId", "")))
if out:
emit(e="info", **result)
return result, None
def failure(text):
"""The last error gogdl logged, for the user; None when it logged none."""
errors = [m.group(3) for m in (LOG.match(line) for line in (text or "").splitlines())
if m and m.group(2) in ("ERROR", "CRITICAL")]
return errors[-1] if errors else None
def follow(argv):
"""Runs a download, turning its progress lines into ours. Returns (status, last error)."""
proc = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)
error, last = None, -1
for line in proc.stdout:
line = line.rstrip("\n")
m = PROGRESS.search(line)
if m:
percent = int(float(m.group(1)))
if percent != last:
last = percent
emit(e="progress", percent=percent, written=int(m.group(2)), total=int(m.group(3)))
continue
log = LOG.match(line)
if log and log.group(2) in ("ERROR", "CRITICAL"):
error = log.group(3)
# Everything else goes to the app's log of this command as it is.
sys.stdout.write(line + "\n")
sys.stdout.flush()
return proc.wait(), error
def install(auth, game_id, base):
data, _ = info(auth, game_id)
if data is None:
return 1
target = os.path.join(base, data["folder"])
os.makedirs(target, exist_ok=True)
# Which game a folder is, from the first byte: the app lists a stopped download by it.
with open(os.path.join(target, MARKER), "w", encoding="utf-8") as f:
json.dump(dict(id=game_id, build=data["build"], language=data["language"]), f)
status, error = follow(gogdl(auth, "download", game_id, "--platform", PLATFORM, "--path", base,
"--skip-dlcs", "--lang", data["language"]))
if status != 0 or not os.path.isfile(os.path.join(target, "goggame-%s.info" % game_id)):
emit(e="error", message=error or "the download stopped (gogdl exit %d)" % status)
return 1
emit(e="done", dir=target)
return 0
def update(auth, game_id, target):
data, _ = info(auth, game_id, out=False)
language = data["language"] if data else "en-US"
status, error = follow(gogdl(auth, "update", game_id, "--platform", PLATFORM, "--path", target,
"--skip-dlcs", "--lang", language))
if status != 0:
emit(e="error", message=error or "the update stopped (gogdl exit %d)" % status)
return 1
emit(e="done", dir=target)
return 0
def main(argv):
if len(argv) < 3:
print(__doc__)
return 2
verb, auth, rest = argv[1], argv[2], argv[3:]
if not os.path.isfile(GOGDL):
emit(e="error", message="gogdl is not set up")
return 1
if verb == "login" and len(rest) == 1:
return login(auth, rest[0])
if verb == "token" and not rest:
return token(auth)
if verb == "info" and len(rest) == 1:
return 0 if info(auth, rest[0])[0] else 1
if verb == "install" and len(rest) == 2:
return install(auth, rest[0], rest[1])
if verb == "update" and len(rest) == 2:
return update(auth, rest[0], rest[1])
print(__doc__)
return 2
if __name__ == "__main__":
sys.exit(main(sys.argv))
@@ -172,8 +172,6 @@ if [ -z "${BL_INSIDE:-}" ]; then
# HDR10: the app opened its compositor's colour-management gate for this session (BL_HDR=1);
# gamescope then offers HDR to its clients through the same wp_color_manager_v1 it binds on ours.
[ "${BL_HDR:-0}" = 1 ] && args+=(--hdr-enabled)
# Extra gamescope arguments for an experiment (--debug-focus, say), from Download/droiddeck-env.
[ -n "${BL_GAMESCOPE_ARGS:-}" ] && read -r -a _bl_extra <<<"$BL_GAMESCOPE_ARGS" && args+=("${_bl_extra[@]}")
# Deck mode's performance overlay (Quick Access Menu → Performance → Overlay Level) is drawn by
# mangoapp, which gamescope starts beside the client; the client sets the level by rewriting
# MANGOHUD_CONFIGFILE. The apk stages Valve's aarch64 build (tools/mangoapp) - without it the menu
@@ -254,8 +254,7 @@ fi
depot=
best=0
for name in %s; do
for library in "$steam_root" /mnt/droiddeck-sd; do
candidate="$library/steamapps/common/$name"
candidate="$steam_root/steamapps/common/$name"
[ -d "$candidate/files/bin-arm64" ] && [ -x "$candidate/proton" ] || continue
build=0
read -r build _ 2>/dev/null < "$candidate/version"
@@ -264,7 +263,6 @@ for name in %s; do
depot=$candidate
best=$build
fi
done
done
if [ -n "$depot" ]; then
bl_components "$depot"
@@ -597,10 +595,10 @@ def depot_build(depot):
def find_source(steam_root):
"""The newest ARM64 Proton depot the client has downloaded (the one the launcher runs), or None."""
common = os.path.join(steam_root, "steamapps", "common")
# bin-arm64 is what makes it the native build rather than the x86_64 one.
found = [os.path.join(root, "steamapps", "common", name)
for root in (steam_root, "/mnt/droiddeck-sd") for name in SOURCES
if os.path.isdir(os.path.join(root, "steamapps", "common", name, "files", "bin-arm64"))]
found = [os.path.join(common, name) for name in SOURCES
if os.path.isdir(os.path.join(common, name, "files", "bin-arm64"))]
return max(found, key=depot_build) if found else None
@@ -178,7 +178,7 @@ def unimported(steam_root, snapshot, candidates):
def watch(steam_root, listing):
games = [game for game in read_json(listing, []) if isinstance(game, dict) and not game.get("store")]
games = read_json(listing, [])
if os.environ.get("BL_STEAM_OFFLINE") == "1" or not games:
return
candidates, sources = {}, {}
@@ -344,10 +344,6 @@ def route(steam_root, acct, games):
owned, candidates, sources = {}, {}, {}
shortcuts, routes = [], {}
for game in games:
# A store's copy (GOG) is that store's game, never the Steam title of the same name.
if game.get("store"):
shortcuts.append(game)
continue
folder = game.get("folder", "")
appid = candidates.get(folder, candidates.get(legacy_path(folder)))
stamp = source_stamp(game)
@@ -219,10 +219,9 @@ def main():
for game in games:
if not game.get("exe") or not game.get("name"):
continue
# A store's own launch arguments (a GOG play task's) unless the user has set some in Steam.
entry = shortcut(game, game.get("args") or "")
entry = shortcut(game)
previous = managed.get(entry["appid"])
if previous and isinstance(previous.get("LaunchOptions"), str) and previous["LaunchOptions"]:
if previous and isinstance(previous.get("LaunchOptions"), str):
entry["LaunchOptions"] = previous["LaunchOptions"]
ours.append(entry)
entries = {str(i): v for i, v in enumerate(kept + ours)}
-144
View File
@@ -1,144 +0,0 @@
// libtracefs.so.1 for mangoapp: the GPU memory Valve's overlay reads, without the kernel's tracing.
//
// Valve's mangoapp (msm.cpp, ftrace_gpumem.c) takes the GPU's memory in use - the VRAM and PVRAM
// lines - from the gpu_mem_total tracepoint (pid 0, the device's total) through libtracefs. An
// Android app may not use tracefs at all: the instance could not be made, and both lines read 0.
// This stands in for the libtracefs calls mangoapp makes, and hands its record walker one
// gpu_mem_total record carrying what the app writes to /run/droiddeck-hud/gpu-mem (bytes; the
// session's GpuMemComponent, from KGSL's own accounting). Only mangoapp loads this copy.
//
// The walker reads libtraceevent's structures directly, so the ones below are libtraceevent
// 1.8.2's (event-parse.h), the version tools/mangoapp/packages.txt pins; tep_find_event_by_record
// and tep_read_number are answered here too, ahead of the real libtraceevent in mangoapp's lookup.
#include <sched.h>
#include <stddef.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define EXPORT __attribute__((visibility("default")))
struct tep_handle;
struct tep_event;
struct tep_print_arg;
struct tep_print_parse;
struct tep_format_field {
struct tep_format_field *next;
struct tep_event *event;
char *type;
char *name;
char *alias;
int offset;
int size;
unsigned int arraylen;
unsigned int elementsize;
unsigned long flags;
};
struct tep_format {
int nr_common;
int nr_fields;
struct tep_format_field *common_fields;
struct tep_format_field *fields;
};
struct tep_print_fmt {
char *format;
struct tep_print_arg *args;
struct tep_print_parse *print_cache;
};
struct tep_event {
struct tep_handle *tep;
char *name;
int id;
int flags;
struct tep_format format;
struct tep_print_fmt print_fmt;
char *system;
void *handler;
void *context;
};
struct tep_record {
unsigned long long ts;
unsigned long long offset;
long long missed_events;
int record_size;
int size;
void *data;
int cpu;
int ref_count;
int locked;
void *priv;
};
// gpu_mem_total's record: gpu_id, pid, size - as the kernel lays it out after the common fields.
struct gpu_mem_total {
unsigned int gpu_id;
unsigned int pid;
unsigned long long size;
};
static struct tep_format_field size_field = {
.name = "size", .offset = offsetof(struct gpu_mem_total, size), .size = 8};
static struct tep_format_field pid_field = {
.next = &size_field, .name = "pid", .offset = offsetof(struct gpu_mem_total, pid), .size = 4};
static struct tep_event gpu_mem_event = {
.name = "gpu_mem_total", .system = "gpu_mem", .format = {.nr_fields = 2, .fields = &pid_field}};
// Never dereferenced by mangoapp: they only have to be non-null.
static char handle;
static char instance;
static unsigned long long gpu_mem_bytes(void) {
unsigned long long bytes = 0;
FILE *f = fopen("/run/droiddeck-hud/gpu-mem", "r");
if (f) {
if (fscanf(f, "%llu", &bytes) != 1) bytes = 0;
fclose(f);
}
return bytes;
}
EXPORT void *tracefs_instance_create(const char *name) { (void)name; return &instance; }
EXPORT char *tracefs_instance_get_dir(void *inst) { (void)inst; return strdup("/run/droiddeck-hud"); }
EXPORT void tracefs_put_tracing_file(char *name) { free(name); }
EXPORT struct tep_handle *tracefs_local_events(const char *dir) { (void)dir; return (struct tep_handle *)&handle; }
EXPORT int tracefs_event_enable(void *inst, const char *system, const char *event) { (void)inst; (void)system; (void)event; return 0; }
EXPORT int tracefs_event_disable(void *inst, const char *system, const char *event) { (void)inst; (void)system; (void)event; return 0; }
EXPORT bool tracefs_instance_is_new(void *inst) { (void)inst; return false; }
EXPORT int tracefs_instance_destroy(void *inst) { (void)inst; return 0; }
EXPORT void tracefs_instance_free(void *inst) { (void)inst; }
EXPORT int tracefs_iterate_raw_events(struct tep_handle *tep, void *inst, cpu_set_t *cpus, int cpu_size,
int (*callback)(struct tep_event *, struct tep_record *, int, void *),
void *context) {
(void)tep; (void)inst; (void)cpus; (void)cpu_size;
if (!callback) return -1;
struct gpu_mem_total data = {.gpu_id = 0, .pid = 0, .size = gpu_mem_bytes()};
struct tep_record record = {.size = sizeof(data), .record_size = sizeof(data), .data = &data};
callback(&gpu_mem_event, &record, 0, context);
return 0;
}
EXPORT struct tep_event *tep_find_event_by_record(struct tep_handle *tep, struct tep_record *record) {
(void)tep; (void)record;
return &gpu_mem_event;
}
EXPORT unsigned long long tep_read_number(struct tep_handle *tep, const void *ptr, int size) {
(void)tep;
switch (size) {
case 1: return *(const unsigned char *)ptr;
case 2: return *(const unsigned short *)ptr;
case 4: return *(const unsigned int *)ptr;
case 8: return *(const unsigned long long *)ptr;
default: return 0;
}
}
EXPORT void tep_free(struct tep_handle *tep) { (void)tep; }
+2 -3
View File
@@ -1,4 +1,4 @@
# Valve's aarch64 mangoapp (the Deck performance overlay) and the libraries it needs that the
# Valve's aarch64 mangoapp (the Deck performance overlay) and the five libraries it needs that the
# runtime does not have, at the versions it was built against (its .BUILDINFO: fmt 10.2.0,
# spdlog 1.13.0). CI fetches each, checks the sha256 and stages the files named below into the apk
# under usr/local/lib/mangoapp; SessionFiles copies them into the runtime at every launch.
@@ -7,6 +7,5 @@
ef7411229ea4e9b3ab4e36ac356a85b5072f362ee1de68b28d09c43f0b0ecc44 https://steamdeck-packages.steamos.cloud/archlinux-deckard/archlinux/mash-20240705.2/extra/os/aarch64/fmt-10.2.0-1-aarch64.pkg.tar.zst
c9bfd2c3f15071329d381b9c2061d07503c4787ceb7001b9dfbf72a23c85cb04 https://steamdeck-packages.steamos.cloud/archlinux-deckard/archlinux/mash-20240705.2/extra/os/aarch64/spdlog-1.13.0-1-aarch64.pkg.tar.zst
f9fae6c84a0382188f1cb20761424051593fd09b1456191cc250bd16e0a1d7a5 https://steamdeck-packages.steamos.cloud/archlinux-deckard/archlinux/mash-20240705.2/extra/os/aarch64/glfw-3.4-2-aarch64.pkg.tar.zst
# libtracefs is ours (libtracefs-shim.c), and reads libtraceevent's structures as 1.8.2 lays them
# out: moving libtraceevent off 1.8.2 means checking event-parse.h against the shim.
0cccdc9c92cb3cae1e37ebeb0ed20b93bb3b5000c8f955b63d0e07bd878c7018 https://steamdeck-packages.steamos.cloud/archlinux-deckard/archlinux/mash-20240705.2/extra/os/aarch64/libtraceevent-1%3A1.8.2-2-aarch64.pkg.tar.zst
47ffd6a953959d6a0df44539bef30a67d0b8c95cce0053273908d9d70ef7abc4 https://steamdeck-packages.steamos.cloud/archlinux-deckard/archlinux/mash-20240705.2/extra/os/aarch64/libtracefs-1.8.0-1-aarch64.pkg.tar.zst
-12
View File
@@ -80,15 +80,3 @@ Added by DroidDeck:
The `faccessat2` exit stop (termux 5ba8b95, for glibc's ENOSYS fallback on kernels before 5.8) and
the `statx` one (emulation on kernels before 4.11) are dropped when the running kernel is newer.
Host build: `ioctl` 31.6 -> 0.5 us; `stat`/`statx`/`faccessat2` about 44 -> 28 us (one stop).
Prototype (inert unless `PROOT_FASTPATH` is set; see `docs/development/proot-performance.md`):
- `0014-fastpath-trampoline.patch` - with `PROOT_FASTPATH`, every `SECCOMP_RET_TRACE` in the filter
is preceded by a check of the caller's address, and a syscall made from the fast path's trampoline
page (`fastpath/fastpath.c`, `0xffff00000`) runs without a stop: the tracee already translated it.
The check comes after the syscall-number dispatch, so untraced syscalls stay constant-ALLOW and keep
the kernel's seccomp action cache (checking first cost every syscall the full filter: +0.5 ms an
exec). `chdir`/`fchdir`, still emulated, also move the kernel's cwd to the host directory, and the
first tracee starts at `-w`'s, so relative lookups inside the tracee resolve where proot would.
SM8850 (adb shell): `stat` 25.3 -> 0.6 us, `open+close` 25.3 -> 0.9 us, ENOENT 22.9 -> 1.6 us,
8 threads `stat`ing 89k -> 3.6M/s; equivalence suite (`bench/equiv.py`) byte-identical to proot.
-32
View File
@@ -1,32 +0,0 @@
import os, sys
paths = ["/etc/os-release", "/root/abs-link", "/root/to-bind", "/root/to-bind/inbind.txt", "/root/rel-to-bind",
"/root/rel-to-bind/inbind.txt", "/root/dotdot", "/root/dotdot/libc.so.6", "/root/dangling", "/root/loop",
"/usr/lib/../lib/libc.so.6", "/usr//lib/./libc.so.6", "/lib", "/lib/libc.so.6", "/bin/env", "/nope", "/nope/x",
"/etc/os-release/x", "/mnt/droiddeck-sd", "/mnt/droiddeck-sd/inbind.txt", "/mnt/droiddeck-sd/../bannerlator",
"/dev/null", "/dev/shm", "/dev/shm/inbind.txt", "/dev/random", "/proc/self/exe", "/proc/version", "/proc",
"/sys/class/thermal/thermal_zone28/temp", "/sdcard", "/", "/tmp", "/root/in-root-abs-dir/os-release",
"/data/local/tmp/dd/tmp/inbind.txt", "/data/local/tmp/dd/mini/etc/os-release", "/root/to-bind/missing/x", "/root/to-bind/inbind.txt/x", "/usr/lib/nope/deeper/x.so", "/mnt/droiddeck-sd/nope/x", "/root/dangling/x", "/root/abs-link/x", "/nope/a/b/c", "/sdcard/nope/x"]
rels = ["os-release", "inbind.txt", "../etc/os-release", "abs-link", "to-bind/inbind.txt", "rel-to-bind",
"shm/inbind.txt", "null", "lib/libc.so.6", "mnt/droiddeck-sd/inbind.txt", "proc/version", "nope", "."]
def probe(p):
out = []
for name, fn in [("stat", lambda: (lambda s: (oct(s.st_mode), s.st_size if not os.path.isdir(p) else 0))(os.stat(p))),
("lstat", lambda: oct(os.lstat(p).st_mode)),
("readlink", lambda: os.readlink(p)),
("read", lambda: open(p, "rb").read(12)),
("list", lambda: sorted(x for x in os.listdir(p) if not x.startswith("proot-"))[:6]),
("access", lambda: (os.access(p, os.R_OK), os.access(p, os.W_OK), os.access(p, os.X_OK)))]:
try: out.append(f"{name}={fn()!r}")
except OSError as e: out.append(f"{name}=E{e.errno}")
return " ".join(out)
for p in paths: print(p, probe(p))
for cwd in ["/", "/root", "/etc", "/mnt/droiddeck-sd", "/dev", "/usr/lib", "/data/local/tmp/dd/tmp", "/root/to-bind", "/root/dotdot"]:
try: os.chdir(cwd)
except OSError as e: print("chdir", cwd, e.errno); continue
print("== cwd", cwd, os.getcwd())
for r in rels: print(" ", r, probe(r))
d = os.open(".", os.O_RDONLY)
for r in rels[:6]:
try: print(" at", r, oct(os.stat(r, dir_fd=d).st_mode))
except OSError as e: print(" at", r, "E", e.errno)
os.close(d)
-274
View File
@@ -1,274 +0,0 @@
/* Cost of the syscall-interception mechanisms available to an Android app, measured on the
* trapped call getppid() (the tracer/handler does no work, so this is pure mechanism cost).
*
* mechbench filter <n_linear> allowed syscall through a filter of n JEQs (linear, proot-style)
* mechbench tree allowed syscall through a binary-search filter (~150 entries)
* mechbench ptrace [spin] [regs] seccomp RET_TRACE + ptrace tracer (proot's mechanism)
* mechbench sigsys seccomp RET_TRAP + in-process SIGSYS handler
* mechbench notif [sync] [spin] seccomp RET_USER_NOTIF + supervisor thread
* mechbench openat2 <root> <path> openat2(RESOLVE_IN_ROOT) vs openat on the host path
* Env CPU_T / CPU_S pin the trapped thread / the tracer-supervisor to a cpu.
*/
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <linux/audit.h>
#include <linux/filter.h>
#include <linux/openat2.h>
#include <linux/seccomp.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/prctl.h>
#include <sys/ptrace.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <time.h>
#include <ucontext.h>
#include <unistd.h>
#include <linux/elf.h>
#ifndef SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP
#define SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP (1UL << 0)
#endif
#ifndef SECCOMP_IOCTL_NOTIF_SET_FLAGS
#define SECCOMP_IOCTL_NOTIF_SET_FLAGS SECCOMP_IOW(4, __u64)
#endif
#define TRAPPED SYS_getppid
static int N = 100000;
static double now(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return t.tv_sec * 1e9 + t.tv_nsec;
}
static void pin(const char *env) {
const char *v = getenv(env);
if (!v) return;
cpu_set_t s;
CPU_ZERO(&s);
CPU_SET(atoi(v), &s);
sched_setaffinity(0, sizeof s, &s);
}
static double time_trapped(void) {
for (int i = 0; i < N / 10; i++) syscall(TRAPPED);
double t0 = now();
for (int i = 0; i < N; i++) syscall(TRAPPED);
return (now() - t0) / N;
}
/* A filter: arch check, then `n` JEQs on numbers that never match (like proot's list of ~150
* traced syscalls seen by an allowed syscall), then `action` for TRAPPED, else ALLOW. */
static int install(int n_linear, uint32_t action, unsigned flags) {
struct sock_filter *f = calloc(n_linear + 16, sizeof *f);
int k = 0;
f[k++] = (struct sock_filter)BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, arch));
f[k++] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_AARCH64, 1, 0);
f[k++] = (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW);
f[k++] = (struct sock_filter)BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr));
for (int i = 0; i < n_linear; i++) /* numbers far above any real syscall */
f[k++] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 5000 + i, 0, 0);
f[k++] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TRAPPED, 0, 1);
f[k++] = (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, action);
f[k++] = (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW);
struct sock_fprog p = {.len = k, .filter = f};
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
return syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, flags, &p);
}
/* ~150 traced numbers as a balanced binary search (what libseccomp's optimize=2 emits). */
static int emit_tree(struct sock_filter *f, int *k, int lo, int hi) {
if (lo > hi) { f[(*k)++] = (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW); return 0; }
int mid = (lo + hi) / 2;
f[(*k)++] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 5000 + mid, 0, 1);
f[(*k)++] = (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_TRACE);
f[(*k)++] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JGT | BPF_K, 5000 + mid, 0, 1);
int ja = (*k)++;
int left = *k;
emit_tree(f, k, lo, mid - 1);
f[ja] = (struct sock_filter)BPF_STMT(BPF_JMP | BPF_JA, *k - left);
emit_tree(f, k, mid + 1, hi);
return 0;
}
static void *sigsys_unused;
static void on_sigsys(int sig, siginfo_t *si, void *ctx) {
(void)sig; (void)si;
ucontext_t *uc = ctx;
uc->uc_mcontext.regs[0] = 4242; /* the emulated result */
}
struct notif_arg { int fd; int spin; };
static void *supervisor(void *a) {
struct notif_arg *na = a;
pin("CPU_S");
struct seccomp_notif *req = calloc(1, 256);
struct seccomp_notif_resp *resp = calloc(1, 256);
for (;;) {
memset(req, 0, sizeof *req);
if (ioctl(na->fd, SECCOMP_IOCTL_NOTIF_RECV, req) < 0) {
if (errno == EINTR) continue;
return NULL;
}
resp->id = req->id;
resp->val = 4242;
resp->error = 0;
resp->flags = 0;
ioctl(na->fd, SECCOMP_IOCTL_NOTIF_SEND, resp);
}
}
static int notif_fd;
static int notif_flags_sync;
static void *notified_worker(void *a) {
(void)a;
pin("CPU_T");
notif_fd = install(0, SECCOMP_RET_USER_NOTIF, SECCOMP_FILTER_FLAG_NEW_LISTENER);
return NULL;
}
int main(int argc, char **argv) {
if (getenv("N")) N = atoi(getenv("N"));
const char *mode = argc > 1 ? argv[1] : "filter";
if (!strcmp(mode, "filter")) {
pin("CPU_T");
printf("no filter getppid %6.0f ns\n", time_trapped());
int n = argc > 2 ? atoi(argv[2]) : 150;
if (install(n, SECCOMP_RET_ALLOW, 0) < 0) { perror("seccomp"); return 1; }
printf("linear %4d JEQs getppid %6.0f ns\n", n, time_trapped());
return 0;
}
if (!strcmp(mode, "tree")) {
pin("CPU_T");
printf("no filter getppid %6.0f ns\n", time_trapped());
struct sock_filter f[2048];
int k = 0;
f[k++] = (struct sock_filter)BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr));
emit_tree(f, &k, 0, 149);
struct sock_fprog p = {.len = k, .filter = f};
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
if (syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, 0, &p) < 0) { perror("seccomp"); return 1; }
printf("tree of 150 (%d insns) getppid %6.0f ns\n", k, time_trapped());
return 0;
}
if (!strcmp(mode, "sigsys")) {
pin("CPU_T");
struct sigaction sa = {0};
sa.sa_sigaction = on_sigsys;
sa.sa_flags = SA_SIGINFO;
sigaction(SIGSYS, &sa, NULL);
if (install(0, SECCOMP_RET_TRAP, 0) < 0) { perror("seccomp"); return 1; }
long r = syscall(TRAPPED);
printf("sigsys trap (result %ld) %6.0f ns\n", r, time_trapped());
(void)sigsys_unused;
return 0;
}
if (!strcmp(mode, "notif")) {
int sync = argc > 2 && strstr(argv[2], "sync");
pthread_t w, s;
pthread_create(&w, NULL, notified_worker, NULL);
pthread_join(w, NULL);
if (notif_fd < 0) { perror("NEW_LISTENER"); return 1; }
if (sync) {
if (ioctl(notif_fd, SECCOMP_IOCTL_NOTIF_SET_FLAGS, SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP) < 0) perror("SYNC_WAKE_UP");
else printf("(sync wake-up on)\n");
}
/* The filter lives on thread w, which has exited; install again on a fresh worker that
* does the timing. */
struct notif_arg na = {.fd = -1};
(void)na;
printf("note: user-notif is measured in 'notif2'\n");
return 0;
}
if (!strcmp(mode, "notif2")) {
/* Supervisor = child thread (unfiltered), timed thread = main after installing. */
int sync = argc > 2 && !strcmp(argv[2], "sync");
pin("CPU_T");
int fd = install(0, SECCOMP_RET_USER_NOTIF, SECCOMP_FILTER_FLAG_NEW_LISTENER);
if (fd < 0) { perror("NEW_LISTENER"); return 1; }
if (sync && ioctl(fd, SECCOMP_IOCTL_NOTIF_SET_FLAGS, SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP, 0) < 0) perror("SYNC_WAKE_UP");
/* The supervisor thread is created AFTER the filter, so it inherits it - but it only
* makes ioctl calls, which the filter allows. */
static struct notif_arg na;
na.fd = fd;
pthread_t s;
pthread_create(&s, NULL, supervisor, &na);
long r = syscall(TRAPPED);
printf("user_notif%s (result %ld) %6.0f ns\n", sync ? "+sync" : "", r, time_trapped());
return 0;
}
if (!strcmp(mode, "ptrace")) {
int spin = 0, regs = 0;
for (int i = 2; i < argc; i++) { if (!strcmp(argv[i], "spin")) spin = 1; if (!strcmp(argv[i], "regs")) regs = 1; }
pid_t c = fork();
if (c == 0) {
pin("CPU_T");
ptrace(PTRACE_TRACEME, 0, 0, 0);
raise(SIGSTOP);
if (install(0, SECCOMP_RET_TRACE, 0) < 0) { perror("seccomp"); _exit(1); }
printf("ptrace+seccomp%s%s %6.0f ns\n", spin ? " spin" : "", regs ? " +getregs+setregs" : "", time_trapped());
fflush(stdout);
_exit(0);
}
pin("CPU_S");
int st;
waitpid(c, &st, 0);
ptrace(PTRACE_SETOPTIONS, c, 0, PTRACE_O_TRACESECCOMP | PTRACE_O_EXITKILL);
ptrace(PTRACE_CONT, c, 0, 0);
for (;;) {
pid_t p;
if (spin) { do p = waitpid(c, &st, WNOHANG | __WALL); while (p == 0); }
else p = waitpid(c, &st, __WALL);
if (p < 0 || WIFEXITED(st) || WIFSIGNALED(st)) break;
int sig = 0;
if ((st >> 8) == (SIGTRAP | (PTRACE_EVENT_SECCOMP << 8))) {
if (regs) {
struct user_regs { uint64_t r[31], sp, pc, pstate; } ur;
struct iovec io = {&ur, sizeof ur};
ptrace(PTRACE_GETREGSET, c, NT_PRSTATUS, &io);
ptrace(PTRACE_SETREGSET, c, NT_PRSTATUS, &io);
}
} else if (WIFSTOPPED(st) && WSTOPSIG(st) != SIGTRAP) sig = WSTOPSIG(st);
ptrace(PTRACE_CONT, c, 0, sig);
}
return 0;
}
if (!strcmp(mode, "openat2")) {
const char *root = argv[2], *path = argv[3];
char host[4096];
snprintf(host, sizeof host, "%s%s", root, path);
int rfd = open(root, O_PATH | O_DIRECTORY);
struct open_how how = {.flags = O_RDONLY | O_CLOEXEC, .resolve = RESOLVE_IN_ROOT};
long fd = syscall(SYS_openat2, rfd, path, &how, sizeof how);
if (fd < 0) { perror("openat2 RESOLVE_IN_ROOT"); return 1; }
close(fd);
double t0 = now();
for (int i = 0; i < N; i++) close(open(host, O_RDONLY | O_CLOEXEC));
printf("openat host path %6.0f ns\n", (now() - t0) / N);
t0 = now();
for (int i = 0; i < N; i++) close(syscall(SYS_openat2, rfd, path, &how, sizeof how));
printf("openat2 RESOLVE_IN_ROOT %6.0f ns\n", (now() - t0) / N);
struct stat st;
t0 = now();
for (int i = 0; i < N; i++) stat(host, &st);
printf("stat host path %6.0f ns\n", (now() - t0) / N);
struct open_how ph = {.flags = O_PATH | O_CLOEXEC, .resolve = RESOLVE_IN_ROOT | RESOLVE_NO_MAGICLINKS};
t0 = now();
for (int i = 0; i < N; i++) { int f = syscall(SYS_openat2, rfd, path, &ph, sizeof ph); fstat(f, &st); close(f); }
printf("openat2(O_PATH)+fstat+close %6.0f ns\n", (now() - t0) / N);
return 0;
}
fprintf(stderr, "unknown mode\n");
return 2;
}
-16
View File
@@ -1,16 +0,0 @@
/* T threads each stat()ing a path for D seconds: aggregate trapped-syscall throughput. */
#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <time.h>
static const char *path; static volatile int stop; static long counts[64];
static void *run(void *a) { long i = (long)a, n = 0; struct stat st; while (!stop) { stat(path, &st); n++; } counts[i] = n; return 0; }
int main(int c, char **v) {
path = v[1]; int T = atoi(v[2]); double D = c > 3 ? atof(v[3]) : 2;
pthread_t t[64]; for (long i = 0; i < T; i++) pthread_create(&t[i], 0, run, (void *)i);
struct timespec ts = {(time_t)D, (long)((D - (long)D) * 1e9)}; nanosleep(&ts, 0); stop = 1;
long tot = 0; for (int i = 0; i < T; i++) { pthread_join(t[i], 0); tot += counts[i]; }
printf("threads=%d %8.0f stat/s total %6.1f us/stat per thread\n", T, tot / D, T * D * 1e6 / tot);
return 0; }
-26
View File
@@ -1,26 +0,0 @@
#!/system/bin/sh
# Runs a guest command on an adb-connected device the way a DroidDeck session runs proot (same
# options, a similar number of binds), as the shell user from /data/local/tmp/dd. Layout there:
# mini/ a glibc rootfs subset (glibc, bash, coreutils, python) + the bench binaries
# proot, loader this repo's proot (tools/proot/build.sh) -> variant "patched"
# proot-vanilla termux proot at source.env with no patches -> variant "vanilla"
# proot-fp this repo's proot incl. 0014 -> "fastpath" / "fpoff"
# mini/usr/lib/libfastpath.so tools/proot/fastpath/fastpath.c
# NOTE: adb shell is NOT under the app seccomp policy; see docs/development/proot-performance.md.
#
# run-device.sh <patched|vanilla|noseccomp|bare|fastpath|fpoff|direct> cmd...
D=/data/local/tmp/dd
V=$1; shift
U=$(id -u)
REL="\\Linux\\DroidDeck\\$(uname -r)\\$(uname -v)\\aarch64\\localdomain\\-1\\"
BINDS="-b /dev -b /proc -b /sys -b /dev/urandom:/dev/random -b /proc/self/fd:/dev/fd -b /proc/self/fd/0:/dev/stdin -b /proc/self/fd/1:/dev/stdout -b /proc/self/fd/2:/dev/stderr -b $D/tmp:/dev/shm -b $D -b /sdcard -b /data/local/tmp/dd/mini/etc/os-release:/proc/version -b $D/mini/etc/os-release:/proc/loadavg -b $D/mini/etc/os-release:/proc/uptime -b /sys/class/thermal/thermal_zone0/temp:/sys/class/thermal/thermal_zone28/temp -b $D/tmp:/mnt/droiddeck-sd -b $D/tmp:/mnt/bannerlator"
export PROOT_TMP_DIR=$D/tmp
case $V in
patched) export PROOT_LOADER=$D/loader; exec $D/proot --kill-on-exit --kernel-release="$REL" -i $U:$U -r $D/mini -w /root $BINDS /usr/bin/env -i HOME=/root PATH=/usr/bin LANG=C.UTF-8 "$@" ;;
noseccomp) export PROOT_LOADER=$D/loader PROOT_NO_SECCOMP=1; exec $D/proot --kill-on-exit --kernel-release="$REL" -i $U:$U -r $D/mini -w /root $BINDS /usr/bin/env -i HOME=/root PATH=/usr/bin LANG=C.UTF-8 "$@" ;;
vanilla) export PROOT_LOADER=$D/loader-vanilla; exec $D/proot-vanilla --kill-on-exit --kernel-release="$REL" -i $U:$U -r $D/mini -w /root $BINDS /usr/bin/env -i HOME=/root PATH=/usr/bin LANG=C.UTF-8 "$@" ;;
bare) export PROOT_LOADER=$D/loader; exec $D/proot --kill-on-exit -r $D/mini -w /root $BINDS /usr/bin/env -i HOME=/root PATH=/usr/bin LANG=C.UTF-8 "$@" ;;
fastpath) export PROOT_LOADER=$D/loader-fp PROOT_FASTPATH=bench; FPB=$(echo "$BINDS" | sed 's/-b //g; s/^ *//; s/ *$//; s/ */|/g'); exec $D/proot-fp --kill-on-exit --kernel-release="$REL" -i $U:$U -r $D/mini -w /root $BINDS /usr/bin/env -i HOME=/root PATH=/usr/bin LANG=C.UTF-8 PROOT_FP_ROOT=$D/mini "PROOT_FP_BINDS=$FPB" PROOT_FP_KEY=bench LD_PRELOAD=/usr/lib/libfastpath.so $FPEXTRA "$@" ;;
fpoff) export PROOT_LOADER=$D/loader-fp; exec $D/proot-fp --kill-on-exit --kernel-release="$REL" -i $U:$U -r $D/mini -w /root $BINDS /usr/bin/env -i HOME=/root PATH=/usr/bin LANG=C.UTF-8 "$@" ;;
direct) cd $D/mini/root; exec $D/mini/usr/lib/ld-linux-aarch64.so.1 --library-path $D/mini/usr/lib "$@" ;;
esac
-78
View File
@@ -1,78 +0,0 @@
/* Per-syscall latency under whatever runs this program (native, proot, ...).
* Usage: sysbench <deep-file> [iterations]
* Prints "name ns/op" lines. */
#define _GNU_SOURCE
#include <fcntl.h>
#include <linux/futex.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
static double now(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return t.tv_sec * 1e9 + t.tv_nsec;
}
#define BENCH(name, n, body) \
do { \
for (int _w = 0; _w < (n) / 10 + 1; _w++) { body; } \
double _t0 = now(); \
for (int _i = 0; _i < (n); _i++) { body; } \
printf("%-28s %10.0f ns\n", name, (now() - _t0) / (n)); \
fflush(stdout); \
} while (0)
static void *thread_fn(void *a) { return a; }
int main(int argc, char **argv) {
const char *deep = argc > 1 ? argv[1] : "/usr/lib/python3.14/os.py";
int n = argc > 2 ? atoi(argv[2]) : 20000;
struct stat st;
char buf[4096];
int pfd[2];
pipe(pfd);
int fd = open(deep, O_RDONLY);
if (fd < 0) { perror(deep); return 1; }
int futexword = 0;
char *slash = strrchr(deep, '/');
char dir[1024];
snprintf(dir, sizeof dir, "%.*s", (int)(slash - deep), deep);
int dfd = open(dir, O_RDONLY | O_DIRECTORY);
BENCH("getppid (untraced)", n, syscall(SYS_getppid));
BENCH("futex wake (untraced)", n, syscall(SYS_futex, &futexword, FUTEX_WAKE_PRIVATE, 1, 0, 0, 0));
BENCH("clock_gettime (vdso)", n, { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); });
BENCH("fstat fd (untraced)", n, fstat(fd, &st));
BENCH("pread 4k (untraced)", n, pread(fd, buf, sizeof buf, 0));
BENCH("ioctl FIONREAD (untraced*)", n, { int v; ioctl(pfd[0], FIONREAD, &v); });
BENCH("fstatat relative dirfd", n, fstatat(dfd, slash + 1, &st, 0));
BENCH("stat deep abs path", n, stat(deep, &st));
BENCH("lstat deep abs path", n, lstat(deep, &st));
BENCH("statx deep abs path", n, { struct statx sx; statx(AT_FDCWD, deep, 0, STATX_BASIC_STATS, &sx); });
BENCH("access deep abs path", n, access(deep, R_OK));
BENCH("open+close deep abs", n, close(open(deep, O_RDONLY)));
BENCH("stat ENOENT", n, stat("/usr/lib/does/not/exist.so", &st));
BENCH("readlink /proc/self/exe", n, readlink("/proc/self/exe", buf, sizeof buf));
BENCH("getcwd", n, getcwd(buf, sizeof buf));
BENCH("uname", n, { struct utsname_dummy { char b[65 * 6]; } u; syscall(SYS_uname, &u); });
BENCH("memfd_create+close", n / 4, close(memfd_create("x", MFD_CLOEXEC)));
BENCH("brk(0) query", n, syscall(SYS_brk, 0));
BENCH("mmap+munmap 64k", n, munmap(mmap(0, 65536, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0), 65536));
BENCH("pthread create+join", n / 20, { pthread_t t; pthread_create(&t, 0, thread_fn, 0); pthread_join(t, 0); });
BENCH("fork+_exit+wait", n / 100, { pid_t p = fork(); if (!p) _exit(0); waitpid(p, 0, 0); });
if (argc > 3) {
char *const av[] = {argv[3], NULL};
BENCH("fork+execve true+wait", n / 200, { pid_t p = fork(); if (!p) { execv(argv[3], av); _exit(127); } waitpid(p, 0, 0); });
}
return 0;
}
-26
View File
@@ -1,26 +0,0 @@
#!/system/bin/sh
# workloads: direct glibc (patched PT_INTERP) vs proot variants
D=/data/local/tmp/dd; cd $D
t() { local s=$(date +%s%N); "$@" >/dev/null 2>&1; local e=$(date +%s%N); echo $(( (e - s) / 1000000 )); }
base() { t ./run.sh $1 /usr/bin/true; }
W1='import json,email.parser,http.client,asyncio,decimal,sqlite3,argparse,subprocess,logging,xml.etree.ElementTree'
for v in direct vanilla fpoff fastpath; do
input keyevent KEYCODE_WAKEUP
for rep in 1 2 3; do
if [ $v = direct ]; then
export LD_LIBRARY_PATH=$D/mini/usr/lib PYTHONHOME=$D/mini/usr PYTHONDONTWRITEBYTECODE=1
a=$(t $D/dbin/python3.14 -c "$W1")
b=$(t $D/dbin/find $D/mini/usr/lib/python3.14 -type f)
c=$(t $D/dbin/bash -c "for i in \$($D/dbin/seq 200); do $D/dbin/true; done")
d=$(t $D/dbin/tar cf /dev/null $D/mini/usr/lib/python3.14)
unset LD_LIBRARY_PATH PYTHONHOME
else
a=$(t ./run.sh $v /usr/bin/env PYTHONDONTWRITEBYTECODE=1 /usr/bin/python3.14 -c "$W1")
b=$(t ./run.sh $v /usr/bin/find /usr/lib/python3.14 -type f)
c=$(t ./run.sh $v /usr/bin/bash -c 'for i in $(seq 200); do /usr/bin/true; done')
d=$(t ./run.sh $v /usr/bin/tar cf /dev/null /usr/lib/python3.14)
fi
[ $v = direct ] && z=0 || z=$(base $v)
echo "$v rep$rep: proot-start=${z}ms python-imports=${a}ms find-8k-files=${b}ms 200x-exec=${c}ms tar-80MB=${d}ms"
done
done
-545
View File
@@ -1,545 +0,0 @@
/*
* proot fast path: path syscalls answered inside the process, without a ptrace round trip.
*
* proot traps every path syscall into its tracer: 15-60 us a call on a Snapdragon, most of it
* the two cross-core wake-ups between tracee and tracer. This library, preloaded into every guest
* process, answers the common calls itself and issues the translated syscall from a trampoline
* page at a fixed address, which proot's seccomp filter lets through without a stop
* (PROOT_FASTPATH, tools/proot/patches/0014).
*
* It decides nothing proot would decide differently. The guest path is mapped literally - the
* longest binding whose guest path is a prefix, else the rootfs - and the parent directory is
* opened O_PATH and must come back from /proc/self/fd as exactly that host path, which proves no
* component on the way was a symlink: proot would then have walked the same directories. The
* last component is looked at without following it, and a symlink there goes to proot. So does
* "..", a trailing "/", anything under /proc, any flag not handled here and any failure to
* decide: the real libc call runs, proot traps it and answers as it always has.
*
* Only syscalls Android's app seccomp policy allows are used (openat, newfstatat, statx,
* faccessat, readlinkat, close) - not openat2 or faccessat2, which it answers with SIGSYS.
*
* Verified parents are remembered for PROOT_FP_TTL_MS (default 2000; 0 = verify every call): a
* parent directory replaced by a symlink within that window would be missed, the same trade the
* session's pathcache.c makes for the Steam client.
*
* Config (the launcher sets it): PROOT_FP_ROOT=<host rootfs>, PROOT_FP_BINDS=<host:guest|...>;
* PROOT_FP_KEY=<key>, with PROOT_FASTPATH=<key> in proot's own environment: nothing is answered
* here unless the tracer is that proot (traced_by_match).
* PROOT_FP_OFF=1 disables it; PROOT_FP_STATS=1 reports hits and misses at exit.
*/
#define _GNU_SOURCE
#include <dirent.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#include <time.h>
#include <unistd.h>
#define FP_STUB_ADDR 0xffff00000UL /* must match FASTPATH_STUB_ADDR in proot's seccomp.c */
#define FP_STUB_SIZE 4096UL
#define MAX_BINDS 64
#define FP_SLOW (-100000L)
typedef long (*stub_fn)(long nr, long a, long b, long c, long d, long e, long f);
static stub_fn fp_sys;
static int fp_on;
struct bind { char *host; size_t hlen; char *guest; size_t glen; int canon; };
static struct bind binds[MAX_BINDS];
static int nbinds;
static char root[PATH_MAX];
static size_t rootlen;
static long long ttl_ns = 2000000000LL;
static unsigned long hits, misses;
static long sc(long nr, long a, long b, long c, long d, long e) { return fp_sys(nr, a, b, c, d, e, 0); }
static void fp_init(void);
static pthread_once_t init_once = PTHREAD_ONCE_INIT;
/* Set up on the first call that could use it: a process that only execs on pays nothing. */
static inline int fp_ready(void) {
pthread_once(&init_once, fp_init);
return fp_on;
}
static int under(const char *path, const char *dir, size_t dlen) {
if (dlen == 1 && dir[0] == '/') return path[0] == '/';
return strncmp(path, dir, dlen) == 0 && (path[dlen] == 0 || path[dlen] == '/');
}
/* ---------------------------------------------------------------- setup */
static void stats(void) {
char line[160];
int n = snprintf(line, sizeof line, "fastpath[%d] %s: %lu fast, %lu to proot\n", getpid(),
program_invocation_short_name, hits, misses);
if (write(2, line, n) < 0) {}
}
/* The canonical form of a host path (bindings may name /sdcard, /data/user/0, ...). */
static void canonical(char *path, size_t size) {
long fd = sc(SYS_openat, AT_FDCWD, (long)path, O_PATH | O_CLOEXEC, 0, 0);
if (fd < 0) return;
char link[40], out[PATH_MAX];
snprintf(link, sizeof link, "/proc/self/fd/%ld", fd);
long n = sc(SYS_readlinkat, AT_FDCWD, (long)link, (long)out, sizeof out - 1, 0);
sc(SYS_close, fd, 0, 0, 0, 0);
if (n > 0 && (size_t)n < size) { out[n] = 0; memcpy(path, out, n + 1); }
}
static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t bind_lock;
static void after_fork(void) { pthread_mutex_init(&cache_lock, NULL); pthread_mutex_init(&bind_lock, NULL); }
/*
* The process is traced by a proot that lets the trampoline through and was given the same
* rootfs and bindings: its own environment carries PROOT_FASTPATH=<PROOT_FP_KEY> (the launcher
* derives the key from them) and no PROOT_NO_SECCOMP. A process that inherited the variables but
* runs under another proot, or none, must not translate paths itself: a proot that traps the
* trampoline would translate the host path a second time.
*/
static int traced_by_match(const char *key) {
static char buf[32768]; /* under init_once */
char path[48], want[160];
long fd = sc(SYS_openat, AT_FDCWD, (long)"/proc/self/status", O_RDONLY | O_CLOEXEC, 0, 0);
if (fd < 0) return 0;
long n = sc(SYS_read, fd, (long)buf, 4095, 0, 0);
sc(SYS_close, fd, 0, 0, 0, 0);
if (n <= 0) return 0;
buf[n] = 0;
const char *line = strstr(buf, "\nTracerPid:");
if (!line) return 0;
long tracer = strtol(line + 11, NULL, 10);
if (tracer <= 0) return 0;
snprintf(path, sizeof path, "/proc/%ld/environ", tracer);
if (snprintf(want, sizeof want, "PROOT_FASTPATH=%s", key) >= (int)sizeof want) return 0;
fd = sc(SYS_openat, AT_FDCWD, (long)path, O_RDONLY | O_CLOEXEC, 0, 0);
if (fd < 0) return 0;
size_t have = 0;
for (long r; have < sizeof buf - 1 && (r = sc(SYS_read, fd, (long)buf + have, sizeof buf - 1 - have, 0, 0)) > 0;) have += r;
sc(SYS_close, fd, 0, 0, 0, 0);
buf[have] = 0;
int found = 0;
for (size_t i = 0; i < have; i += strlen(buf + i) + 1) {
if (strcmp(buf + i, want) == 0) found = 1;
if (strncmp(buf + i, "PROOT_NO_SECCOMP=", 17) == 0) return 0;
}
return found;
}
static void fp_init(void) {
const char *r = getenv("PROOT_FP_ROOT"), *b = getenv("PROOT_FP_BINDS"), *t = getenv("PROOT_FP_TTL_MS");
const char *key = getenv("PROOT_FP_KEY");
if (!r || !*r || !key || !*key || getenv("PROOT_FP_OFF")) return;
void *p = mmap((void *)FP_STUB_ADDR, FP_STUB_SIZE, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0);
if (p != (void *)FP_STUB_ADDR) {
if (p != MAP_FAILED) { munmap(p, FP_STUB_SIZE); return; }
if (errno != EEXIST) return; /* mapped already: this library loaded twice */
} else {
static const uint32_t code[] = {
0xAA0003E8, /* mov x8, x0 */ 0xAA0103E0, /* mov x0, x1 */ 0xAA0203E1, /* mov x1, x2 */
0xAA0303E2, /* mov x2, x3 */ 0xAA0403E3, /* mov x3, x4 */ 0xAA0503E4, /* mov x4, x5 */
0xAA0603E5, /* mov x5, x6 */ 0xD4000001, /* svc #0 */ 0xD65F03C0, /* ret */
};
memcpy(p, code, sizeof code);
__builtin___clear_cache((char *)p, (char *)p + sizeof code);
if (mprotect(p, FP_STUB_SIZE, PROT_READ | PROT_EXEC) != 0) { munmap(p, FP_STUB_SIZE); return; }
}
fp_sys = (stub_fn)FP_STUB_ADDR;
if (!traced_by_match(key)) { fp_sys = NULL; return; }
if (t) ttl_ns = atoll(t) * 1000000LL;
snprintf(root, sizeof root, "%s", r);
canonical(root, sizeof root);
rootlen = strlen(root);
for (const char *s = b; s && *s && nbinds < MAX_BINDS;) {
const char *end = strchr(s, '|');
size_t len = end ? (size_t)(end - s) : strlen(s);
char spec[2 * PATH_MAX];
if (len > 0 && len < sizeof spec) {
memcpy(spec, s, len);
spec[len] = 0;
char *colon = strchr(spec, ':');
if (colon) *colon = 0;
struct bind *bd = &binds[nbinds];
/* Canonicalised on first use: some (/sdcard) are FUSE, slow to look up at every exec.
* Static storage: malloc here would grow the heap with brk(2), which proot traps. */
static char hosts[MAX_BINDS][PATH_MAX], guests[MAX_BINDS][512];
const char *g = colon ? colon + 1 : spec;
if (strlen(g) >= sizeof guests[0]) { s = end ? end + 1 : NULL; continue; }
bd->host = hosts[nbinds];
bd->guest = guests[nbinds];
snprintf(bd->guest, sizeof guests[0], "%s", g);
snprintf(bd->host, PATH_MAX, "%.*s", PATH_MAX - 1, spec);
bd->hlen = strlen(bd->host);
bd->glen = strlen(bd->guest);
if (bd->guest[0] == '/' && bd->glen > 1 && bd->hlen > 0) nbinds++;
}
s = end ? end + 1 : NULL;
}
pthread_atfork(NULL, NULL, after_fork); /* registered once per exec */
fp_on = 1;
if (getenv("PROOT_FP_STATS")) atexit(stats);
}
static pthread_mutex_t bind_lock = PTHREAD_MUTEX_INITIALIZER;
static const struct bind *canon(struct bind *bd) {
if (__atomic_load_n(&bd->canon, __ATOMIC_ACQUIRE)) return bd;
if (pthread_mutex_trylock(&bind_lock) != 0) return NULL;
if (!bd->canon) {
canonical(bd->host, PATH_MAX);
bd->hlen = strlen(bd->host);
__atomic_store_n(&bd->canon, 1, __ATOMIC_RELEASE);
}
pthread_mutex_unlock(&bind_lock);
return bd;
}
/* ---------------------------------------------------------------- verified parents */
#define SLOTS 256
#define SLOT_PATH 240 /* longer directories are verified every time */
struct slot { long long stamp; unsigned hash; char path[SLOT_PATH]; };
static struct slot cache[SLOTS];
static long long now_ns(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC_COARSE, &ts);
return ts.tv_sec * 1000000000LL + ts.tv_nsec;
}
static unsigned hash_of(const char *s) {
unsigned h = 2166136261u;
while (*s) h = (h ^ (unsigned char)*s++) * 16777619u;
return h;
}
static int cached(const char *dir, unsigned h) {
if (ttl_ns <= 0 || pthread_mutex_trylock(&cache_lock) != 0) return 0;
struct slot *e = &cache[h % SLOTS];
int hit = e->stamp && e->hash == h && now_ns() - e->stamp < ttl_ns && strcmp(e->path, dir) == 0;
pthread_mutex_unlock(&cache_lock);
return hit;
}
static void remember(const char *dir, unsigned h) {
if (ttl_ns <= 0 || strlen(dir) >= SLOT_PATH || pthread_mutex_trylock(&cache_lock) != 0) return;
struct slot *e = &cache[h % SLOTS];
e->hash = h;
snprintf(e->path, sizeof e->path, "%s", dir);
e->stamp = now_ns();
pthread_mutex_unlock(&cache_lock);
}
/* The host directory `dir` is reached by the kernel without crossing a symlink. */
static long canonical_dir(const char *dir) {
unsigned h = hash_of(dir);
if (cached(dir, h)) return 1;
long fd = sc(SYS_openat, AT_FDCWD, (long)dir, O_PATH | O_DIRECTORY | O_CLOEXEC, 0, 0);
if (fd < 0) return fd;
char link[40], out[PATH_MAX];
snprintf(link, sizeof link, "/proc/self/fd/%ld", fd);
long n = sc(SYS_readlinkat, AT_FDCWD, (long)link, (long)out, sizeof out - 1, 0);
sc(SYS_close, fd, 0, 0, 0, 0);
if (n <= 0) return 0;
out[n] = 0;
if (strcmp(out, dir) != 0) return 0;
remember(dir, h);
return 1;
}
/* ---------------------------------------------------------------- guest -> host */
/* Guest paths never answered here: proot emulates /proc (self, exe, fd and cwd links). */
static int reserved(const char *g) {
return under(g, "/proc", 5) || under(g, "/dev/fd", 7) || under(g, "/dev/stdin", 10)
|| under(g, "/dev/stdout", 11) || under(g, "/dev/stderr", 11);
}
/* The guest path of a host directory (the cwd, a dirfd): the longest host prefix wins. */
static int host_to_guest(const char *h, char *g, size_t size) {
const struct bind *best = NULL;
for (int i = 0; i < nbinds; i++)
if (under(h, binds[i].host, binds[i].hlen) && (!best || binds[i].hlen > best->hlen)) best = &binds[i];
if (under(h, root, rootlen) && (!best || rootlen >= best->hlen))
return snprintf(g, size, "%s", h[rootlen] ? h + rootlen : "/") < (int)size ? 0 : -1;
if (best) return snprintf(g, size, "%s%s", best->guest, h + best->hlen) < (int)size ? 0 : -1;
return -1;
}
/*
* The host path `path` (relative to dirfd, as the guest means it) names, whose parent directory
* is verified; 0, or FP_SLOW when proot must decide.
*/
static long resolve(int dirfd, const char *path, char *host) {
char guest[PATH_MAX], base[PATH_MAX];
if (!path || !path[0] || !fp_ready()) return FP_SLOW;
size_t plen = strlen(path);
if (path[plen - 1] == '/' && plen > 1) return FP_SLOW;
if (path[0] == '/') {
if (plen >= sizeof guest) return FP_SLOW;
memcpy(guest, path, plen + 1);
} else {
char link[40], h[PATH_MAX];
if (dirfd == AT_FDCWD) snprintf(link, sizeof link, "/proc/self/cwd");
else snprintf(link, sizeof link, "/proc/self/fd/%d", dirfd);
long n = sc(SYS_readlinkat, AT_FDCWD, (long)link, (long)h, sizeof h - 1, 0);
if (n <= 0) return FP_SLOW;
h[n] = 0;
if (host_to_guest(h, base, sizeof base) < 0) return FP_SLOW;
if (snprintf(guest, sizeof guest, "%s/%s", strcmp(base, "/") ? base : "", path) >= (int)sizeof guest) return FP_SLOW;
}
/* Normalise "//" and "/./"; ".." goes to proot (it is not lexical once symlinks are involved). */
char norm[PATH_MAX];
size_t o = 0;
for (const char *c = guest; *c;) {
while (*c == '/') c++;
if (!*c) break;
const char *e = strchrnul(c, '/');
size_t len = e - c;
if (len == 1 && c[0] == '.') { c = e; continue; }
if (len == 2 && c[0] == '.' && c[1] == '.') return FP_SLOW;
if (o + len + 2 >= sizeof norm) return FP_SLOW;
norm[o++] = '/';
memcpy(norm + o, c, len);
o += len;
c = e;
}
if (o == 0) norm[o++] = '/';
norm[o] = 0;
if (reserved(norm)) return FP_SLOW;
struct bind *bd = NULL;
for (int i = 0; i < nbinds; i++)
if (under(norm, binds[i].guest, binds[i].glen) && (!bd || binds[i].glen > bd->glen)) bd = &binds[i];
if (bd && !canon(bd)) return FP_SLOW;
size_t base_len = bd ? bd->hlen : rootlen;
int n = bd ? snprintf(host, PATH_MAX, "%s%s", bd->host, norm + bd->glen)
: snprintf(host, PATH_MAX, "%s%s", root, strcmp(norm, "/") ? norm : "");
if (n >= PATH_MAX) return FP_SLOW;
char *slash = strrchr(host, '/');
if (!slash || slash == host) return FP_SLOW;
*slash = 0;
long ok = canonical_dir(host);
*slash = '/';
if (ok == 1) return 0;
if (ok != -ENOENT) return FP_SLOW;
/* The parent is missing. The path is missing for proot too if the deepest directory that does
* exist is canonical and the next component below it is not there at all - not even as a
* symlink proot would follow. Only within the binding (or rootfs) the path was mapped into. */
char probe[PATH_MAX];
memcpy(probe, host, n + 1);
for (char *cut = strrchr(probe, '/'); cut && (size_t)(cut - probe) > base_len; ) {
*cut = 0;
char *up = strrchr(probe, '/');
if (!up || (size_t)(up - probe) < base_len) break;
*up = 0;
long c = canonical_dir(probe[0] ? probe : "/");
*up = '/';
if (c == 1) {
struct stat st;
if (sc(SYS_newfstatat, AT_FDCWD, (long)probe, (long)&st, AT_SYMLINK_NOFOLLOW, 0) == -ENOENT) return -ENOENT;
return FP_SLOW;
}
if (c != -ENOENT) return FP_SLOW;
cut = up;
}
return FP_SLOW;
}
/* The last component, not followed: 0 something that is not a symlink, 1 a symlink, <0 -errno. */
static long kind(const char *host, struct stat *st) {
long r = sc(SYS_newfstatat, AT_FDCWD, (long)host, (long)st, AT_SYMLINK_NOFOLLOW, 0);
if (r < 0) return r;
return S_ISLNK(st->st_mode) ? 1 : 0;
}
static int ret(long r) {
if (r < 0) { errno = (int)-r; return -1; }
return (int)r;
}
#define REAL(name, type) \
static __typeof__(type) real_##name; \
if (!real_##name) real_##name = (type)dlsym(RTLD_NEXT, #name)
/* ---------------------------------------------------------------- open */
static long fp_open(int dirfd, const char *path, int flags, mode_t mode) {
char host[PATH_MAX];
if ((flags & __O_TMPFILE) == __O_TMPFILE) return FP_SLOW;
long rs = resolve(dirfd, path, host);
if (rs != 0) return rs;
/* The last component is never followed here: a symlink there is proot's to resolve. */
long fd = sc(SYS_openat, AT_FDCWD, (long)host, flags | O_NOFOLLOW, (flags & O_CREAT) ? mode : 0, 0);
if (fd == -ELOOP && !(flags & O_NOFOLLOW)) return FP_SLOW;
if (fd >= 0 && (flags & O_PATH) && !(flags & O_NOFOLLOW)) {
struct stat st;
if (sc(SYS_fstat, fd, (long)&st, 0, 0, 0) != 0 || S_ISLNK(st.st_mode)) {
sc(SYS_close, fd, 0, 0, 0, 0);
return FP_SLOW;
}
}
return fd;
}
static int do_openat(int dirfd, const char *path, int flags, mode_t mode, int (*real)(int, const char *, int, ...)) {
long r = fp_open(dirfd, path, flags, mode);
if (r != FP_SLOW) { hits++; return ret(r); }
misses++;
return real(dirfd, path, flags, mode);
}
int openat(int dirfd, const char *path, int flags, ...) {
REAL(openat, int (*)(int, const char *, int, ...));
mode_t mode = 0;
if (flags & (O_CREAT | __O_TMPFILE)) { va_list ap; va_start(ap, flags); mode = va_arg(ap, mode_t); va_end(ap); }
return do_openat(dirfd, path, flags, mode, real_openat);
}
int openat64(int dirfd, const char *path, int flags, ...) __attribute__((alias("openat")));
int open(const char *path, int flags, ...) {
REAL(openat, int (*)(int, const char *, int, ...));
mode_t mode = 0;
if (flags & (O_CREAT | __O_TMPFILE)) { va_list ap; va_start(ap, flags); mode = va_arg(ap, mode_t); va_end(ap); }
return do_openat(AT_FDCWD, path, flags, mode, real_openat);
}
int open64(const char *path, int flags, ...) __attribute__((alias("open")));
int __open_2(const char *path, int flags) { return open(path, flags); }
int __open64_2(const char *path, int flags) { return open(path, flags); }
int __openat_2(int d, const char *path, int flags) { return openat(d, path, flags); }
int __openat64_2(int d, const char *path, int flags) { return openat(d, path, flags); }
/* ---------------------------------------------------------------- stat family */
static long fp_stat(int dirfd, const char *path, int flags, struct stat *st) {
char host[PATH_MAX];
if (flags & ~AT_SYMLINK_NOFOLLOW) return FP_SLOW;
long rs = resolve(dirfd, path, host);
if (rs != 0) return rs;
long k = kind(host, st);
if (k == 1 && !(flags & AT_SYMLINK_NOFOLLOW)) return FP_SLOW;
return k < 0 ? k : 0;
}
static int stat_common(int dirfd, const char *path, struct stat *st, int flags,
int (*real)(int, const char *, struct stat *, int)) {
long r = fp_stat(dirfd, path, flags, st);
if (r != FP_SLOW) { hits++; return ret(r); }
misses++;
return real(dirfd, path, st, flags);
}
int fstatat(int dirfd, const char *path, struct stat *st, int flags) {
REAL(fstatat, int (*)(int, const char *, struct stat *, int));
return stat_common(dirfd, path, st, flags, real_fstatat);
}
int fstatat64(int d, const char *p, struct stat64 *st, int f) { return fstatat(d, p, (struct stat *)st, f); }
int stat(const char *path, struct stat *st) {
REAL(fstatat, int (*)(int, const char *, struct stat *, int));
return stat_common(AT_FDCWD, path, st, 0, real_fstatat);
}
int stat64(const char *p, struct stat64 *st) { return stat(p, (struct stat *)st); }
int lstat(const char *path, struct stat *st) {
REAL(fstatat, int (*)(int, const char *, struct stat *, int));
return stat_common(AT_FDCWD, path, st, AT_SYMLINK_NOFOLLOW, real_fstatat);
}
int lstat64(const char *p, struct stat64 *st) { return lstat(p, (struct stat *)st); }
int statx(int dirfd, const char *path, int flags, unsigned mask, struct statx *out) {
REAL(statx, int (*)(int, const char *, int, unsigned, struct statx *));
char host[PATH_MAX];
long rs = (flags & ~(AT_SYMLINK_NOFOLLOW | AT_NO_AUTOMOUNT | AT_STATX_SYNC_TYPE)) ? FP_SLOW : resolve(dirfd, path, host);
if (rs == -ENOENT) { hits++; return ret(rs); }
if (rs == 0) {
long r = sc(SYS_statx, AT_FDCWD, (long)host, flags | AT_SYMLINK_NOFOLLOW, mask | STATX_TYPE, (long)out);
if (!(r == 0 && S_ISLNK(out->stx_mode) && !(flags & AT_SYMLINK_NOFOLLOW))) { hits++; return ret(r); }
}
misses++;
return real_statx(dirfd, path, flags, mask, out);
}
/* ---------------------------------------------------------------- access */
static int access_common(int dirfd, const char *path, int mode, int flags) {
REAL(faccessat, int (*)(int, const char *, int, int));
char host[PATH_MAX];
struct stat st;
/* faccessat(2) has no flags: AT_EACCESS and AT_SYMLINK_NOFOLLOW stay with glibc and proot. */
long rs = flags == 0 ? resolve(dirfd, path, host) : FP_SLOW;
if (rs == -ENOENT) { hits++; return ret(rs); }
if (rs == 0) {
long k = kind(host, &st);
if (k != 1) {
hits++;
if (k < 0) return ret(k);
return ret(sc(SYS_faccessat, AT_FDCWD, (long)host, mode, 0, 0));
}
}
misses++;
return real_faccessat(dirfd, path, mode, flags);
}
int faccessat(int dirfd, const char *path, int mode, int flags) { return access_common(dirfd, path, mode, flags); }
int access(const char *path, int mode) { return access_common(AT_FDCWD, path, mode, 0); }
/* ---------------------------------------------------------------- readlink */
/* The link's own text needs no translation outside /proc: proot stores and returns it as is. */
static ssize_t readlink_common(int dirfd, const char *path, char *buf, size_t size) {
REAL(readlinkat, ssize_t (*)(int, const char *, char *, size_t));
char host[PATH_MAX];
long rs = resolve(dirfd, path, host);
if (rs == -ENOENT) { hits++; return ret(rs); }
if (rs == 0) {
hits++;
long r = sc(SYS_readlinkat, AT_FDCWD, (long)host, (long)buf, size, 0);
return r < 0 ? ret(r) : r;
}
misses++;
return real_readlinkat(dirfd, path, buf, size);
}
ssize_t readlinkat(int dirfd, const char *path, char *buf, size_t size) { return readlink_common(dirfd, path, buf, size); }
ssize_t readlink(const char *path, char *buf, size_t size) { return readlink_common(AT_FDCWD, path, buf, size); }
/* ---------------------------------------------------------------- libc calls that open internally */
DIR *opendir(const char *path) {
REAL(opendir, DIR *(*)(const char *));
long fd = fp_open(AT_FDCWD, path, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NONBLOCK, 0);
if (fd == FP_SLOW) { misses++; return real_opendir(path); }
hits++;
if (fd < 0) { errno = (int)-fd; return NULL; }
DIR *d = fdopendir((int)fd);
if (!d) close((int)fd);
return d;
}
static FILE *fopen_common(const char *path, const char *m, FILE *(*real)(const char *, const char *)) {
int flags;
switch (m[0]) {
case 'r': flags = strchr(m, '+') ? O_RDWR : O_RDONLY; break;
case 'w': flags = (strchr(m, '+') ? O_RDWR : O_WRONLY) | O_CREAT | O_TRUNC; break;
case 'a': flags = (strchr(m, '+') ? O_RDWR : O_WRONLY) | O_CREAT | O_APPEND; break;
default: return real(path, m);
}
if (strchr(m, 'e')) flags |= O_CLOEXEC;
if (strchr(m, 'x')) flags |= O_EXCL;
long fd = fp_open(AT_FDCWD, path, flags, 0666);
if (fd == FP_SLOW) { misses++; return real(path, m); }
hits++;
if (fd < 0) { errno = (int)-fd; return NULL; }
FILE *f = fdopen((int)fd, m);
if (!f) close((int)fd);
return f;
}
FILE *fopen(const char *path, const char *m) { REAL(fopen, FILE *(*)(const char *, const char *)); return fopen_common(path, m, real_fopen); }
FILE *fopen64(const char *path, const char *m) { REAL(fopen64, FILE *(*)(const char *, const char *)); return fopen_common(path, m, real_fopen64); }
@@ -1,205 +0,0 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: DroidDeck <droiddeck@users.noreply.github.com>
Date: Wed, 30 Sep 2026 00:00:00 +0000
Subject: [PATCH] fastpath: let translated syscalls from the tracee's trampoline
page through, and keep the kernel's cwd at the guest's
With PROOT_FASTPATH set (and only then), every SECCOMP_RET_TRACE in the filter
is preceded by a check of the caller's address: a syscall made from the fast
path's trampoline page (tools/proot/fastpath, FASTPATH_STUB_ADDR) was already
translated inside the tracee and runs without a stop. The check follows the
syscall-number dispatch, so untraced syscalls stay constant-ALLOW and keep the
kernel's seccomp action cache. chdir/fchdir, emulated as before, also move the
kernel's cwd to the host directory (host "/" where the kernel cannot follow),
and the first tracee starts there, so relative lookups made inside the tracee
resolve where proot resolves them. Without PROOT_FASTPATH nothing changes.
---
--- a/src/syscall/enter.c
+++ b/src/syscall/enter.c
@@ -20,7 +20,8 @@
* 02110-1301 USA.
*/
-#include <errno.h> /* errno(3), E* */
+#include <errno.h>
+#include <stdlib.h> /* errno(3), E* */
#include <talloc.h> /* talloc_*, */
#include <sys/un.h> /* struct sockaddr_un, */
#include <linux/net.h> /* SYS_*, */
@@ -198,6 +199,20 @@
if ((statl.st_mode & S_IXUSR) == 0)
return -EACCES;
+ /* With the fast path, the kernel's cwd follows the guest's
+ * (at its host path), so relative lookups made inside the
+ * tracee resolve where proot would resolve them. */
+ if (getenv("PROOT_FASTPATH") != NULL) {
+ int fd = open(path, O_PATH | O_DIRECTORY | O_CLOEXEC);
+
+ /* Where the kernel could not follow, it goes to the
+ * host's "/", which no binding names: the fast path
+ * then sends every relative lookup to proot. */
+ strcpy(oldpath, fd >= 0 ? path : "/");
+ if (fd >= 0)
+ close(fd);
+ }
+
/* Sadly this method doesn't detranslate statefully,
* this means that there's an ambiguity when several
* bindings are from the same host path:
@@ -229,6 +244,14 @@
tracee->fs->cwd = tmp;
talloc_set_name_const(tracee->fs->cwd, "$cwd");
+ if (getenv("PROOT_FASTPATH") != NULL) {
+ /* fchdir(2) runs as it is; chdir(2) on the host path. */
+ status = syscall_number == PR_chdir
+ ? set_sysarg_path(tracee, oldpath, SYSARG_1)
+ : 0;
+ break;
+ }
+
set_sysnum(tracee, PR_void);
status = 0;
break;
--- a/src/syscall/seccomp.c
+++ b/src/syscall/seccomp.c
@@ -35,6 +35,7 @@
#include <talloc.h> /* talloc_*, */
#include <errno.h> /* E*, */
#include <string.h> /* memcpy(3), */
+#include <stdlib.h> /* getenv(3), */
#include <stddef.h> /* offsetof(3), */
#include <stdint.h> /* uint*_t, UINT*_MAX, */
#include <stdbool.h>
@@ -77,9 +78,95 @@
* items). This function returns -errno if an error occurred,
* otherwise 0.
*/
+/* The fast path's trampoline page (tools/proot/fastpath): a traced syscall made from it was
+ * already translated inside the tracee and is let through without a stop. With PROOT_FASTPATH
+ * set, every SECCOMP_RET_TRACE is preceded by a check of the caller's address. The check sits
+ * after the syscall-number dispatch, so syscalls proot never traces stay constant-ALLOW and keep
+ * the kernel's seccomp action cache. FASTPATH_STUB_ADDR must match FP_STUB_ADDR in fastpath.c. */
+#define FASTPATH_STUB_ADDR 0xffff00000ULL
+#define FASTPATH_STUB_SIZE 0x1000ULL
+#define LENGTH_FASTPATH_TAIL 7
+
+static bool fastpath_enabled(void)
+{
+ static int enabled = -1;
+ if (enabled < 0)
+ enabled = getenv("PROOT_FASTPATH") != NULL;
+ return enabled;
+}
+
+static bool is_ret_trace(const struct sock_filter *statement)
+{
+ return statement->code == (BPF_RET + BPF_K)
+ && (statement->k & SECCOMP_RET_ACTION_FULL) == SECCOMP_RET_TRACE;
+}
+
+static int add_statements_raw(struct sock_fprog *program, size_t nb_statements,
+ struct sock_filter *statements);
+
+/* Append @statements, each RET_TRACE expanded into the trampoline check when the fast path is
+ * on, every jump within (or out of) the block adjusted for the expansion. */
static int add_statements(struct sock_fprog *program, size_t nb_statements,
struct sock_filter *statements)
{
+ struct sock_filter out[64];
+ size_t position[33];
+ size_t i, o;
+
+ if (!fastpath_enabled())
+ return add_statements_raw(program, nb_statements, statements);
+
+ assert(nb_statements <= 32);
+ for (i = 0, o = 0; i < nb_statements; i++) {
+ position[i] = o;
+ o += is_ret_trace(&statements[i]) ? LENGTH_FASTPATH_TAIL : 1;
+ }
+ position[nb_statements] = o;
+
+#define NEW_TARGET(index) (((index) <= nb_statements) ? position[(index)] : position[nb_statements] + (index) - nb_statements)
+
+ for (i = 0, o = 0; i < nb_statements; i++) {
+ struct sock_filter statement = statements[i];
+
+ if (BPF_CLASS(statement.code) == BPF_JMP) {
+ if (BPF_OP(statement.code) == BPF_JA)
+ statement.k = NEW_TARGET(i + 1 + statement.k) - position[i] - 1;
+ else {
+ statement.jt = NEW_TARGET(i + 1 + statement.jt) - position[i] - 1;
+ statement.jf = NEW_TARGET(i + 1 + statement.jf) - position[i] - 1;
+ }
+ }
+
+ if (!is_ret_trace(&statement)) {
+ out[o++] = statement;
+ continue;
+ }
+
+ {
+ const size_t ip = offsetof(struct seccomp_data, instruction_pointer);
+ const uint32_t hi = (uint32_t) (FASTPATH_STUB_ADDR >> 32);
+ const uint32_t lo = (uint32_t) FASTPATH_STUB_ADDR;
+ struct sock_filter tail[LENGTH_FASTPATH_TAIL] = {
+ BPF_STMT(BPF_LD + BPF_W + BPF_ABS, ip + sizeof(uint32_t)),
+ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, hi, 0, 4),
+ BPF_STMT(BPF_LD + BPF_W + BPF_ABS, ip),
+ BPF_JUMP(BPF_JMP + BPF_JGE + BPF_K, lo, 0, 2),
+ BPF_JUMP(BPF_JMP + BPF_JGE + BPF_K, lo + (uint32_t) FASTPATH_STUB_SIZE, 1, 0),
+ BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ALLOW),
+ statement,
+ };
+ memcpy(&out[o], tail, sizeof(tail));
+ o += LENGTH_FASTPATH_TAIL;
+ }
+ }
+#undef NEW_TARGET
+
+ return add_statements_raw(program, o, out);
+}
+
+static int add_statements_raw(struct sock_fprog *program, size_t nb_statements,
+ struct sock_filter *statements)
+{
size_t length;
void *tmp;
size_t i;
@@ -211,8 +298,16 @@
return add_statements(program, LENGTH_TRACE_IOCTL, statements);
}
+static size_t trace_length_raw(Sysnum sysnum);
+
static size_t trace_length(Sysnum sysnum)
{
+ /* Each trace block has exactly one RET_TRACE (see add_statements). */
+ return trace_length_raw(sysnum) + (fastpath_enabled() ? LENGTH_FASTPATH_TAIL - 1 : 0);
+}
+
+static size_t trace_length_raw(Sysnum sysnum)
+{
switch (sysnum) {
case PR_prctl:
case PR_setrlimit:
--- a/src/tracee/event.c
+++ b/src/tracee/event.c
@@ -98,6 +98,15 @@
if (getenv("PROOT_NO_SECCOMP") == NULL)
(void) enable_syscall_filtering(tracee);
+ /* The fast path resolves relative paths against the
+ * kernel's cwd: start it at the guest's (see chdir in
+ * syscall/enter.c). */
+ if (getenv("PROOT_FASTPATH") != NULL) {
+ char host_cwd[PATH_MAX];
+ if (translate_path(tracee, host_cwd, AT_FDCWD, tracee->fs->cwd, true) >= 0)
+ (void) chdir(host_cwd);
+ }
+
/* Now process is ptraced, so the current rootfs is already the
* guest rootfs. Note: Valgrind can't handle execve(2) on
* "foreign" binaries (ENOEXEC) but can handle execvp(3) on such
-145
View File
@@ -1,145 +0,0 @@
import io
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
from contextlib import redirect_stdout
from unittest.mock import patch
from test_steam_games import BIN, imports, load, shortcuts
gog = load('bannerlator-gog')
# Stands in for gogdl: answers info/auth like it, and "downloads" by writing the game's info file.
FAKE_GOGDL = r'''
import json, os, sys
args = sys.argv[1:]
auth = args[args.index("--auth-config-path") + 1]
args = args[args.index("--auth-config-path") + 2:]
cmd = args[0]
if cmd == "auth":
if "--code" in args:
print(json.dumps({"error": True}) if args[-1] == "bad" else json.dumps({"access_token": "A", "refresh_token": "R", "user_id": "7", "expires_in": 3600, "loginTime": 1000}))
elif os.path.exists(auth):
print(json.dumps({"access_token": "A", "refresh_token": "R", "user_id": "7", "expires_in": 3600, "loginTime": 1000}))
else:
print("null")
elif cmd == "info":
print("[MAIN] INFO: working", file=sys.stderr)
print(json.dumps({"folder_name": "Example", "languages": ["de-DE", "en-US"], "buildId": "b1",
"size": {"*": {"download_size": 100, "disk_size": 200}, "en-US": {"download_size": 10, "disk_size": 20},
"de-DE": {"download_size": 5, "disk_size": 6}}}))
elif cmd == "download":
base = args[args.index("--path") + 1]
if os.environ.get("FAIL"):
print("[DOWNLOAD] ERROR: disk full", file=sys.stderr)
sys.exit(1)
for p in ("0.00 0/100", "50.10 50/100", "50.90 51/100", "100.00 100/100"):
print("[PROGRESS] INFO: = Progress: %s, Running for: 00:00:01, ETA: 00:00:01" % p, file=sys.stderr)
target = os.path.join(base, "Example")
os.makedirs(target, exist_ok=True)
open(os.path.join(target, "goggame-%s.info" % args[1]), "w").write("{}")
'''
class GogHelperTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
fake = self.root / 'gogdl'
fake.write_text(FAKE_GOGDL)
patcher = patch.object(gog, 'GOGDL', str(fake))
patcher.start()
self.addCleanup(patcher.stop)
self.auth = str(self.root / 'gog/auth.json')
def run_helper(self, *args):
out = io.StringIO()
with redirect_stdout(out):
status = gog.main(['bannerlator-gog'] + list(args))
lines = [json.loads(line) for line in out.getvalue().splitlines() if line.startswith('{')]
return status, lines, out.getvalue()
def test_token_output_never_carries_the_refresh_token(self):
Path(self.auth).parent.mkdir()
Path(self.auth).write_text('{}')
status, lines, raw = self.run_helper('token', self.auth)
self.assertEqual(0, status)
self.assertEqual({'e': 'token', 'access_token': 'A', 'user_id': '7', 'expires': 4600}, lines[0])
self.assertNotIn('"R"', raw)
def test_signed_out_without_the_auth_file(self):
status, lines, _ = self.run_helper('token', self.auth)
self.assertEqual(1, status)
self.assertEqual('error', lines[0]['e'])
def test_login_reports_success_without_tokens(self):
status, lines, raw = self.run_helper('login', self.auth, 'good')
self.assertEqual((0, [{'e': 'done', 'user_id': '7'}]), (status, lines))
self.assertNotIn('access_token', raw)
status, lines, _ = self.run_helper('login', self.auth, 'bad')
self.assertEqual(1, status)
def test_sizes_are_shared_depots_plus_one_language(self):
status, lines, _ = self.run_helper('info', self.auth, '42')
self.assertEqual(0, status)
self.assertEqual(dict(e='info', folder='Example', language='en-US', download_size=110, disk_size=220, build='b1'), lines[0])
def test_install_reports_progress_once_per_percent_and_marks_the_folder(self):
base = self.root / 'GOG'
status, lines, _ = self.run_helper('install', self.auth, '42', str(base))
self.assertEqual(0, status)
self.assertEqual([0, 50, 100], [line['percent'] for line in lines if line['e'] == 'progress'])
self.assertEqual({'e': 'done', 'dir': str(base / 'Example')}, lines[-1])
self.assertEqual('42', json.loads((base / 'Example' / gog.MARKER).read_text())['id'])
def test_failed_download_passes_on_gogdls_error(self):
with patch.dict('os.environ', {'FAIL': '1'}):
status, lines, _ = self.run_helper('install', self.auth, '42', str(self.root / 'GOG'))
self.assertEqual(1, status)
self.assertEqual({'e': 'error', 'message': 'disk full'}, lines[-1])
class StoreShortcutsTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
self.steam = self.root / 'Steam'
self.acct = self.steam / 'userdata/123'
(self.acct / 'config').mkdir(parents=True)
folder = self.root / 'GOG/Example'
folder.mkdir(parents=True)
(folder / 'Example.exe').write_bytes(b'game')
self.game = dict(name='Example', exe=str(folder / 'Example.exe'), folder=str(folder), dir=str(folder),
appid=0x87654321, args='-windowed', store='gog')
def write(self, *games):
listing = self.root / 'games.json'
listing.write_text(json.dumps(list(games)))
subprocess.run(['python3', str(BIN / 'bannerlator-steam-shortcuts'), str(self.steam), str(listing)], check=True, capture_output=True)
return list(shortcuts.parse((self.acct / 'config/shortcuts.vdf').read_bytes())['shortcuts'].values())
def test_store_arguments_become_launch_options(self):
self.assertEqual('-windowed', self.write(self.game)[0]['LaunchOptions'])
def test_launch_options_set_in_steam_are_kept(self):
self.write(self.game)
path = self.acct / 'config/shortcuts.vdf'
entries = shortcuts.parse(path.read_bytes())['shortcuts']
entries['0']['LaunchOptions'] = '-dx11'
path.write_bytes(shortcuts.write({'shortcuts': entries}))
self.assertEqual('-dx11', self.write(self.game)[0]['LaunchOptions'])
def test_store_games_are_never_routed_to_an_owned_steam_title(self):
imports.save_json(self.acct / 'config' / imports.STATE,
dict(account='123', owned={'42': True}, candidates={self.game['folder']: 42},
sources={self.game['folder']: imports.source_stamp(self.game)}))
games, routes = imports.route(self.steam, self.acct, [self.game])
self.assertEqual(([self.game], {}), (games, routes))
if __name__ == '__main__':
unittest.main()