Compare commits

..
29 changed files with 198 additions and 539 deletions

No files matched your search

@@ -191,6 +191,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var gamescopeRealtime by mutableStateOf(false)
private var paceCores by mutableStateOf(true)
private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
private var nativeUserland by mutableStateOf(true)
private var desktopAsUser by mutableStateOf(false)
private var cursorComposite by mutableStateOf(true)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
@@ -1328,22 +1331,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
finish()
}
private fun ownsTask(): Boolean = runCatching {
getSystemService(android.app.ActivityManager::class.java)?.appTasks.orEmpty().any { task ->
val info = task.taskInfo
@Suppress("DEPRECATION")
val id = if (Build.VERSION.SDK_INT >= 29) info.taskId else info.persistentId
id == taskId
}
}.getOrDefault(false)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (com.droiddeck.launcher.frontend.LauncherReopen.revealsTask(intent.action, intent.categories, isTaskRoot,
savedInstanceState != null, SessionState.pipActive, ::ownsTask)) {
finish()
return
}
drivers.restartBlocked = ::runtimeChangesBlocked
drivers.loadTpUbwcMode()
val handoff = if (savedInstanceState == null && intent.getBooleanExtra(EXTRA_RESTARTED, false)) LauncherHandoff.take() else null
@@ -3136,7 +3125,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
nativeDesktopAvailable = com.droiddeck.launcher.runtime.NativeGuest.nextSession(this), desktopAsUser = desktopAsUser, cursorComposite = cursorComposite,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, desktopAsUser = desktopAsUser, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
onPaceCores = { on -> SessionPrefs.setPaceCores(this, on); paceCores = on },
@@ -3150,6 +3139,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
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 },
onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on },
onDesktopAsUser = { on -> SessionPrefs.setDesktopAsUser(this, on); desktopAsUser = on },
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
@@ -3472,6 +3464,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
paceCores = SessionPrefs.paceCores(this)
gpuClockPin = SessionPrefs.gpuClockPin(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
nativeUserland = SessionPrefs.nativeUserland(this)
desktopAsUser = SessionPrefs.desktopAsUser(this)
cursorComposite = SessionPrefs.cursorComposite(this)
guestHostname = SessionPrefs.guestHostname(this)
@@ -3862,6 +3862,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
presentationFaultHint()?.let { return it }
if (log == null || !log.isFile) return null
return try {
var enosys = 0
var fexMissing = false
val size = log.length()
val text = java.io.RandomAccessFile(log, "r").use { f ->
@@ -3872,6 +3873,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
String(bytes, Charsets.ISO_8859_1)
}
text.lineSequence().forEach { line ->
if (line.contains("Function not implemented")) enosys++
if (line.contains(FEX_MISSING)) fexMissing = true
}
val steamSetup = com.droiddeck.launcher.session.SteamClientSetupFailure.find(text.lineSequence())
@@ -3893,6 +3895,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} else if (fexMissing) {
val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program)
EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true)
} else if (enosys >= 8) {
EndHint(resources.getQuantityString(R.plurals.session_hint_enosys, enosys, enosys,
getString(R.string.perf_title), getString(R.string.perf_seccomp), getString(R.string.perf_xalia)))
} else null
} catch (e: Exception) {
null
@@ -571,6 +571,7 @@ object AgentHost {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
@@ -14,6 +14,8 @@ object AgentNative {
fun run(context: Context, request: JSONObject, timeoutMs: Long): JSONObject {
val root = LinuxRuntime.rootDir(context)
com.droiddeck.launcher.session.SessionFiles.stage(context, root)
// with the setting off, staging leaves the rootfs as proot wants it
if (!com.droiddeck.launcher.session.SessionPrefs.nativeUserland(context)) NativeGuest.prepare(context, root)
if (!NativeGuest.available(root)) throw AgentException("NATIVE_UNAVAILABLE", "The rootfs has no native hook or glibc loader yet; start a session once")
val argvJson = request.optJSONArray("argv") ?: throw AgentException("INVALID_REQUEST", "argv is required")
val argv = (0 until argvJson.length()).map { argvJson.getString(it) }
@@ -291,12 +291,9 @@ object DeviceReport {
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
k("pace cores", SessionPrefs.paceCores(context))
k("guest runtime policy", "native preferred with PRoot fallback")
k("guest runtime", when (com.droiddeck.launcher.runtime.NativeGuest.sessionMode) {
true -> "native"
false -> "PRoot"
null -> if (com.droiddeck.launcher.runtime.NativeGuest.enabled(context)) "native available" else "native unavailable"
})
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
k("native userland (no proot)", SessionPrefs.nativeUserland(context))
k("proot fast path", SessionPrefs.prootFastPath(context))
k("proot binary", LinuxRuntime.prootSource(context) + " " + LinuxRuntime.prootBinary(context).path)
k("proot fast path (eligible)", com.droiddeck.launcher.runtime.ProotFastPath.enabled(context))
k("Guest host name", SessionPrefs.guestHostname(context))
@@ -1,15 +0,0 @@
package com.droiddeck.launcher.frontend
import android.content.Intent
object LauncherReopen {
fun revealsTask(
action: String?,
categories: Set<String>?,
taskRoot: Boolean,
restored: Boolean,
pipActive: Boolean,
ownTask: () -> Boolean,
): Boolean = action == Intent.ACTION_MAIN && categories?.contains(Intent.CATEGORY_LAUNCHER) == true &&
!taskRoot && !restored && !pipActive && ownTask()
}
@@ -577,15 +577,12 @@ object BwrapSpawner {
private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) {
val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull()
val nativeSession = NativeGuest.forSession(context)
val native = if (nativeSession) nativeLaunch(context, plan) else null
val native = if (NativeGuest.forSession(context)) nativeLaunch(context, plan) else null
val builder = if (native != null) {
ProcessBuilder(native.first).redirectErrorStream(true)
.directory(File(hostPath(plan.binds, plan.root.path, plan.cwd)).takeIf { it.isDirectory } ?: plan.root)
.also { b -> b.environment().apply { clear(); putAll(native.second) } }
} else {
val reason = if (nativeSession) "sandbox native launch unavailable" else "parent guest uses PRoot"
Log.i(TAG, "Flatpak: using PRoot ($reason)")
val cmd = LinuxRuntime.prootPrefix(context, plan.root, plan.cwd)
if (verbose != null) { cmd.add("-v"); cmd.add(verbose.toString()) }
plan.binds.forEach { cmd.add("-b"); cmd.add(it.spec) }
@@ -602,6 +599,7 @@ object BwrapSpawner {
putAll(prootEnvironment(plan, envTool))
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
@@ -6,6 +6,7 @@ import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.session.OrphanReaper
import com.droiddeck.launcher.session.SessionFiles
import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
@@ -66,6 +67,7 @@ object GuestCommand {
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (linkDir != null) put("PROOT_L2S_DIR", linkDir.path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> put(k, v) } }
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
@@ -22,15 +22,15 @@ object NativeGuest {
}
fun enabled(context: Context): Boolean =
available(LinuxRuntime.rootDir(context))
SessionPrefs.nativeUserland(context) && available(LinuxRuntime.rootDir(context))
/**
* Whether the next session will start natively. The session stages the hook from the APK before
* it starts, so the rootfs's loader decides, and a runtime still to be
* it starts, so only the setting and the rootfs's loader decide, and a runtime still to be
* installed will have one.
*/
fun nextSession(context: Context): Boolean =
willRun(LinuxRuntime.rootDir(context), LinuxRuntime.isInstalled(context))
SessionPrefs.nativeUserland(context) && willRun(LinuxRuntime.rootDir(context), LinuxRuntime.isInstalled(context))
internal fun willRun(root: File, installed: Boolean): Boolean = !installed || loader(root) != null
@@ -39,7 +39,7 @@ object NativeGuest {
/**
* Whether a session's helpers (root commands, Flatpak sandboxes, installers) run natively: the
* session's own mode while one runs, as the rootfs is only
* session's own mode while one runs, as the setting can change under it and the rootfs is only
* prepared for native programs at a session's start.
*/
fun forSession(context: Context): Boolean = sessionMode ?: enabled(context)
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.runtime
import android.content.Context
import android.os.Build
import android.util.Log
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.security.MessageDigest
@@ -11,14 +12,17 @@ object ProotFastPath {
const val LIBRARY = "/usr/local/lib/libddfastpath.so"
const val MAX_BINDS = 256
internal fun allows(source: String, native: Boolean): Boolean =
!native && source == LinuxRuntime.PROOT_PACK
fun allows(preference: Boolean, noSeccomp: Boolean, source: String, nativeUserland: Boolean = false): Boolean =
preference && !noSeccomp && !nativeUserland && source == LinuxRuntime.PROOT_PACK
fun enabled(context: Context, native: Boolean = NativeGuest.forSession(context)): Boolean {
if (native) return false
fun enabled(context: Context): Boolean {
val preference = SessionPrefs.prootFastPath(context)
val noSeccomp = SessionPrefs.prootNoSeccomp(context)
val nativeUserland = SessionPrefs.nativeUserland(context)
val source = LinuxRuntime.prootSource(context)
val on = allows(source, native)
if (!on) Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
val on = allows(preference, noSeccomp, source, nativeUserland)
if (preference && !noSeccomp && !nativeUserland && !on)
Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
return on
}
@@ -8,6 +8,7 @@ import android.os.Process
import android.util.Log
import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.session.OrphanReaper
import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject
import java.io.DataInputStream
import java.io.DataOutputStream
@@ -127,6 +128,7 @@ object RootSpawner {
clear()
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
@@ -5,7 +5,6 @@ import android.os.ParcelFileDescriptor
import android.system.Os
import android.system.OsConstants
import com.droiddeck.launcher.core.LogRedactor
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONArray
@@ -26,7 +25,6 @@ import java.nio.channels.SeekableByteChannel
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.StandardOpenOption
@@ -223,7 +221,7 @@ internal object EnhancedSessionLogShare {
Category.values().map { category ->
val budget = budgets.getValue(category)
val records = ArrayList<Record>()
val selected = candidates.filter { it.category == category }.sortedBy(::sharePriority)
val selected = candidates.filter { it.category == category }
val zip = File(out, "DroidDeck-${folder.name}-${category.suffix}.zip")
ZipOutputStream(zip.outputStream().buffered()).use { archive ->
val names = HashSet<String>()
@@ -618,8 +616,7 @@ internal object EnhancedSessionLogShare {
redactionLearningComplete: Boolean,
) {
val entries = JSONArray()
val (discovery, rest) = records.partition { it.origin == "discovery" }
(discovery + rest).take(MAX_MANIFEST_RECORDS).forEach { record ->
records.take(MAX_MANIFEST_RECORDS).forEach { record ->
entries.put(JSONObject().apply {
put("entry", record.entry)
put("origin", record.origin)
@@ -683,15 +680,6 @@ internal object EnhancedSessionLogShare {
categoryCounts[category] = (categoryCounts[category] ?: 0) + 1
}
}
fun addRecentLogs(root: File, entryPrefix: String, origin: String) {
val scan = walk(root, remaining(maxFiles, out.size))
truncated = truncated || scan.truncated
partial = partial || scan.partial
val base = root.toPath().toAbsolutePath().normalize()
scan.files.asSequence().filter { recent(it) && it.name.endsWith(".log", true) }.forEach { file ->
add(file, root, "$entryPrefix/${base.relativize(file.toPath().toAbsolutePath().normalize()).joinToString("/")}", origin)
}
}
CRITICAL_SESSION_FILES.forEach { name ->
File(folder, name).takeIf { it.exists() }?.let { add(it, folder, "${folder.name}/$name", "session-critical") }
}
@@ -725,7 +713,16 @@ internal object EnhancedSessionLogShare {
add(source.file, source.root, source.entry, "battlenet")
}
} else {
battleNetRoots(context).forEach { (prefix, root) -> addRecentLogs(root, "battlenet/$prefix", "battlenet") }
battleNetRoots(context).forEach { (prefix, root) ->
val scan = walk(root, remaining(maxFiles, out.size))
truncated = truncated || scan.truncated
partial = partial || scan.partial
scan.files.asSequence().filter { recent(it) && it.name.endsWith(".log", true) }
.forEach { file ->
val relative = root.toPath().toAbsolutePath().normalize().relativize(file.toPath().toAbsolutePath().normalize()).joinToString("/")
add(file, root, "battlenet/$prefix/$relative", "battlenet")
}
}
}
val sessionScan = walk(folder, remaining(maxFiles, out.size))
truncated = truncated || sessionScan.truncated
@@ -736,9 +733,6 @@ internal object EnhancedSessionLogShare {
if (relative == EnhancedDiagnostics.MANIFEST_FILE) return@forEach
add(file, folder, "${folder.name}/$relative", "session")
}
val antiCheat = antiCheatRoots(context)
partial = partial || antiCheat.partial
antiCheat.roots.forEach { (appId, root) -> addRecentLogs(root, "anticheat/$appId", "anticheat") }
if (SessionPaths.current()?.canonicalFile == folder.canonicalFile && !File(folder, "steam").exists()) {
val steam = File(SessionPrefs.activeSteamRoot(context), "logs")
val scan = directFiles(steam, remaining(maxFiles, out.size))
@@ -754,8 +748,7 @@ internal object EnhancedSessionLogShare {
private fun sharePriority(candidate: Candidate): Int = when {
candidate.origin == "session-critical" -> 0
candidate.origin == "session" && candidate.category == Category.GAMES -> 1
candidate.origin == "anticheat" -> 2
else -> 3
else -> 2
}
private fun remaining(maxFiles: Int, found: Int): Int = (maxFiles - found + 1).coerceAtLeast(0)
@@ -829,39 +822,6 @@ internal object EnhancedSessionLogShare {
return ScanResult(files, truncated, partial)
}
private class AntiCheatRoots(val roots: List<Pair<String, File>>, val partial: Boolean)
private fun antiCheatRoots(context: Context): AntiCheatRoots {
var partial = false
val seen = HashSet<String>()
val dirs = runCatching { Library.compatdataDirs(context) }.getOrElse { partial = true; emptyList() }
val roots = dirs.flatMapIndexed { library, compatdata ->
val prefixes = compatdata.listFiles() ?: run { partial = true; emptyArray() }
prefixes.filter { !Files.isSymbolicLink(it.toPath()) }.mapNotNull { prefix ->
val appId = steamAppId(prefix.name) ?: return@mapNotNull null
val root = File(prefix, EAC_LOG_DIR)
val directory = try {
Files.readAttributes(root.toPath(), BasicFileAttributes::class.java, LinkOption.NOFOLLOW_LINKS).isDirectory
} catch (_: NoSuchFileException) {
false
} catch (_: Exception) {
partial = true
false
}
if (!directory) return@mapNotNull null
val base = "$appId/library${library + 1}"
val key = base.takeIf { seen.add(it) } ?: "$base-${prefix.name}".takeIf { seen.add(it) }
if (key != null) key to root else { partial = true; null }
}
}
return AntiCheatRoots(roots, partial)
}
private fun steamAppId(name: String): String? =
name.takeIf { SIGNED_APP_ID.matches(it) }?.toLongOrNull()
?.takeIf { it in Int.MIN_VALUE.toLong()..0xffffffffL }
?.let { (it and 0xffffffffL).toString() }
private fun battleNetRoots(context: Context): List<Pair<String, File>> {
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
val data = File(drive, "ProgramData/Battle.net")
@@ -968,9 +928,7 @@ internal object EnhancedSessionLogShare {
val normalized = name.replace('\\', '/').trimStart('/')
val parts = normalized.split('/')
if (normalized.isEmpty() || parts.any { it.isEmpty() || it == "." || it == ".." }) return null
return parts.mapIndexed { index, part ->
if (index == 1 && parts[0] == "anticheat" && APP_ID.matches(part)) part else safeComponent(part)
}.joinToString("/")
return parts.joinToString("/") { safeComponent(it) }
}
private fun safeComponent(value: String): String {
@@ -983,7 +941,7 @@ internal object EnhancedSessionLogShare {
private fun category(entry: String): Category {
val value = entry.lowercase(Locale.US)
if (value.startsWith("battlenet/") || value.startsWith("anticheat/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug", "bionic").any(value::contains)) return Category.GAMES
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
@@ -992,7 +950,7 @@ internal object EnhancedSessionLogShare {
private val GAME_LOG = Regex("steam-[0-9]+\\.(log|txt)")
private val KNOWN_COMPONENTS = setOf(
"steam", "graphics", "games", "battlenet", "anticheat", "anticheatlauncher.log", "client", "agent", "setup", "stores", "tools",
"steam", "graphics", "games", "battlenet", "client", "agent", "setup", "stores", "tools",
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
@@ -1003,15 +961,11 @@ internal object EnhancedSessionLogShare {
private val KNOWN_COMPONENT_PATTERNS = listOf(
Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"),
Regex("steam-[0-9]+\\.(?:log|txt)"),
Regex("library[0-9]+(?:--?[0-9]{1,10})?"),
Regex("(?:battle\\.net-[0-9]+|battle\\.net-setup-[0-9]+|Agent-[0-9]+)\\.log"),
Regex("(?:Agent\\.[0-9]+|bna_[0-9]+)"),
Regex("stores-[0-9]{4}-[0-9]{2}-[0-9]{2}\\.log"),
Regex("library[0-9]{1,3}"),
Regex("entry-[0-9a-f]{16}(?:\\.[a-z0-9]{1,8})?"),
)
private val APP_ID = Regex("[0-9]{1,10}")
private val SIGNED_APP_ID = Regex("-?[0-9]{1,10}")
private val SAFE_SUFFIX = Regex("\\.[A-Za-z0-9]{1,8}$")
private val CRITICAL_SESSION_FILES = listOf(
"session.log", "app.log", "wayland.log", "audio.log", "device.txt", "network.txt",
@@ -1019,7 +973,6 @@ internal object EnhancedSessionLogShare {
)
private const val RECENT_MILLIS = 7L * 24 * 60 * 60 * 1000
private const val STORE_LOG_SCAN = 512
private const val EAC_LOG_DIR = "pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat"
private const val COPY_BUFFER_BYTES = 64 * 1024
private const val TRACE_SCAN_BYTES = 16L * 1024 * 1024
private const val LEGACY_LOG_MAX_BYTES = 8L * 1024 * 1024
@@ -367,17 +367,16 @@ object SessionFiles {
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
preload.append("/usr/local/lib/libfakeinput.so\n")
}
com.droiddeck.launcher.runtime.NativeGuest.prepare(context, root)
val native = com.droiddeck.launcher.runtime.NativeGuest.available(root)
val nativePreload = preload.toString()
if (ProotFastPath.enabled(context, native)) {
val nativeUserland = SessionPrefs.nativeUserland(context)
if (nativeUserland) com.droiddeck.launcher.runtime.NativeGuest.prepare(context, root)
if (ProotFastPath.enabled(context)) {
val library = com.droiddeck.launcher.agent.AgentEnv.fastPathLibrary(context)
preload.append(library + "\n")
if (startsSession && library != ProotFastPath.LIBRARY) Log.i(TAG, "fast path preload: $library (debugging override)")
}
val etc = File(root, "etc").apply { mkdirs() }
File(etc, "droiddeck").mkdirs()
FileUtils.writeString(File(etc, "droiddeck/native-preload"), nativePreload)
FileUtils.writeString(File(etc, "droiddeck/native-preload"), preload.toString())
val staged = File(etc, "ld.so.preload.staged")
if (!FileUtils.writeString(staged, preload.toString())
|| !staged.renameTo(File(etc, "ld.so.preload"))) {
@@ -1181,9 +1181,21 @@ object SessionPrefs {
prefs(context).edit().putBoolean("mountSharedStorage", on).apply()
}
fun prootNoSeccomp(context: Context): Boolean = prefs(context).getBoolean("prootNoSeccomp", false)
fun setProotNoSeccomp(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
}
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true)
/** The session's long-lived programs run in worker processes Android does not count (GuestWorkers). */
fun childProcessHandoff(context: Context): Boolean = prefs(context).getBoolean("childProcessHandoff", true)
fun setNativeUserland(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("nativeUserland", on).apply()
}
/** Whether the Plasma desktop, and so its apps and shells, runs as an ordinary user instead of root (native userland only). */
fun desktopAsUser(context: Context): Boolean = prefs(context).getBoolean("desktopAsUser", false)
@@ -1191,6 +1203,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("desktopAsUser", on).apply()
}
fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
fun setProotFastPath(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("prootFastPath", on).apply()
}
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", true)
fun setCursorComposite(context: Context, on: Boolean) {
@@ -47,7 +47,6 @@ import com.droiddeck.launcher.input.SteamControllerBle
import com.droiddeck.launcher.runtime.BwrapSpawner
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.NativeGuest
import com.droiddeck.launcher.runtime.ProotFastPath
import com.droiddeck.launcher.runtime.UserApps
import com.droiddeck.launcher.wayland.WaylandCompositor
@@ -785,13 +784,12 @@ class SessionService : Service() {
SessionEvents.step("shm-clear") { FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm")) }
val sharedStorage = LinuxRuntime.sharedStorage(this)
val nativeUserland = NativeGuest.enabled(this)
val fastPath = ProotFastPath.enabled(this, nativeUserland)
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir, sharedStorage, fastPath)
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir, sharedStorage)
val nativeUserland = com.droiddeck.launcher.runtime.NativeGuest.enabled(this)
synchronized(stopLock) {
if (gen == sessionGen && SessionState.running) com.droiddeck.launcher.runtime.NativeGuest.sessionMode = nativeUserland
}
val fastPathKey = if (fastPath) {
val fastPathKey = if (ProotFastPath.enabled(this)) {
val prootBinds = LinuxRuntime.binds(
this, sessionRoot, runtimeDir, sharedStorage, binds,
)
@@ -812,14 +810,16 @@ class SessionService : Service() {
LinuxRuntime.rememberSessionBinds(sessionBindSpecs)
com.droiddeck.launcher.runtime.NativeGuest.command(root, guest.first(), guest.drop(1))
} else {
val reason = if (NativeGuest.loader(root) == null) "missing glibc loader" else "missing native hook"
Log.i(TAG, "guest runtime: using PRoot ($reason)")
LinuxRuntime.command(this, sessionRoot, runtimeDir, sharedStorage, binds, guest)
}
val prootEnv = HostEnvironment()
prootEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
prootEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(this).path
if (SessionPrefs.prootNoSeccomp(this)) {
prootEnv["PROOT_NO_SECCOMP"] = "1"
if (!nativeUserland) Log.i(TAG, "proot: seccomp acceleration off by request")
}
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> prootEnv[k] = v } }
for (key in listOf("PROOT_PROFILE", "PROOT_PROFILE_SLOW_US")) {
guest.lastOrNull { it.startsWith("$key=") }?.substringAfter('=')?.let { prootEnv[key] = it }
@@ -1313,7 +1313,6 @@ class SessionService : Service() {
sessionRoot: File,
runtimeDir: File,
sharedStorage: File?,
fastPath: Boolean,
): ArrayList<String> {
val binds = ArrayList<String>()
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
@@ -1447,7 +1446,7 @@ class SessionService : Service() {
if (storageDiagnosticLibrary != null && library != null) libraries.add(SecondaryLibrary.CARD_GUESTS[0] to library.label)
val gamesLibraries = GameStorage.gamesFolderLibraries(this)
if (gamesLibraries.isNotEmpty()) {
var room = if (fastPath) {
var room = if (ProotFastPath.enabled(this)) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
for (games in gamesLibraries) {
@@ -1489,7 +1488,7 @@ class SessionService : Service() {
continue
}
try {
val room = if (fastPath) {
val room = if (ProotFastPath.enabled(this)) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
val content = SecondaryLibrary.contentPath(entry.host)
@@ -1518,7 +1517,7 @@ class SessionService : Service() {
if (problem != null) {
Log.w(TAG, "x86-64 steam library: $problem")
} else try {
val room = if (fastPath) {
val room = if (ProotFastPath.enabled(this)) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
val extra = SecondaryLibrary.binds(filesDir, x64, listOf(GameStorage.X64_CARD_GUEST)).drop(1)
@@ -1540,7 +1539,7 @@ class SessionService : Service() {
continue
}
try {
val room = if (fastPath) {
val room = if (ProotFastPath.enabled(this)) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
val extra = SecondaryLibrary.binds(filesDir, entry.x64Host, listOf(entry.x64Guest)).drop(1)
@@ -1576,7 +1575,7 @@ class SessionService : Service() {
try {
val listing = File(filesDir, "session/desktop-volumes.json").apply { parentFile?.mkdirs() }
val volumes = org.json.JSONArray()
var room = if (fastPath) {
var room = if (ProotFastPath.enabled(this)) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
for (root in com.droiddeck.launcher.files.StorageRoots.list(this)) {
@@ -8,6 +8,7 @@ import androidx.compose.runtime.setValue
import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionEvents
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.AchievementNotifications
@@ -148,6 +149,7 @@ object GogComet {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
@@ -5,6 +5,7 @@ import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.ProotFastPath
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.StoreInstallRoot
import org.json.JSONObject
import java.io.Closeable
@@ -106,6 +107,7 @@ internal object Xodus {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (key, value) -> put(key, value) } }
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
@@ -46,7 +46,9 @@ fun PerformancePage(
fsyncFirst: Boolean,
gamescopeRealtime: Boolean,
gpuClockPin: Boolean,
nativeDesktopAvailable: Boolean,
prootNoSeccomp: Boolean,
prootFastPath: Boolean,
nativeUserland: Boolean,
desktopAsUser: Boolean,
cursorComposite: Boolean,
guestHostname: String,
@@ -63,6 +65,9 @@ fun PerformancePage(
onFsyncFirst: (Boolean) -> Unit,
onGamescopeRealtime: (Boolean) -> Unit,
onGpuClockPin: (Boolean) -> Unit,
onProotNoSeccomp: (Boolean) -> Unit,
onProotFastPath: (Boolean) -> Unit,
onNativeUserland: (Boolean) -> Unit,
onDesktopAsUser: (Boolean) -> Unit,
onCursorComposite: (Boolean) -> Unit,
onGuestHostname: (String) -> Unit,
@@ -147,6 +152,26 @@ fun PerformancePage(
stringResource(R.string.perf_fastsync_hint),
fastSync, onChange = onFastSync,
)
ToggleRow(
host, "seccomp", stringResource(R.string.perf_seccomp),
stringResource(R.string.perf_seccomp_hint),
prootNoSeccomp, onChange = onProotNoSeccomp,
)
ToggleRow(
host, "fastpath", stringResource(R.string.perf_fastpath),
when {
nativeUserland -> stringResource(R.string.perf_fastpath_needs_proot)
prootNoSeccomp -> stringResource(R.string.perf_fastpath_needs_seccomp)
else -> stringResource(R.string.perf_fastpath_hint)
},
prootFastPath && !prootNoSeccomp && !nativeUserland, enabled = !prootNoSeccomp && !nativeUserland,
onChange = onProotFastPath,
)
ToggleRow(
host, "nativeuserland", stringResource(R.string.perf_native_userland),
stringResource(R.string.perf_native_userland_hint),
nativeUserland, onChange = onNativeUserland,
)
ToggleRow(
host, "cursorcomposite", stringResource(R.string.perf_cursor_composite),
stringResource(R.string.perf_cursor_composite_hint),
@@ -173,8 +198,8 @@ fun PerformancePage(
}
ToggleRow(
host, "desktopasuser", stringResource(R.string.perf_desktop_as_user),
stringResource(R.string.perf_desktop_as_user_hint),
desktopAsUser && nativeDesktopAvailable, enabled = nativeDesktopAvailable,
stringResource(if (nativeUserland) R.string.perf_desktop_as_user_hint else R.string.perf_desktop_as_user_needs_native),
desktopAsUser && nativeUserland, enabled = nativeUserland,
onChange = onDesktopAsUser,
)
}
@@ -85,6 +85,9 @@ internal object SettingsIndex {
s(SettingsSection.PERFORMANCE, R.string.perf_esync, "esync", "sync", "wine"),
s(SettingsSection.PERFORMANCE, R.string.perf_fsync, "fsync", "sync", "wine"),
s(SettingsSection.PERFORMANCE, R.string.perf_fastsync, "ntsync", "sync", "wine"),
s(SettingsSection.PERFORMANCE, R.string.perf_seccomp, "proot"),
s(SettingsSection.PERFORMANCE, R.string.perf_fastpath, "proot"),
s(SettingsSection.PERFORMANCE, R.string.perf_native_userland, "proot"),
s(SettingsSection.PERFORMANCE, R.string.perf_cursor_composite, "mouse", "cursor"),
s(SettingsSection.PERFORMANCE, R.string.perf_hostname, "name"),
s(SettingsSection.PERFORMANCE, R.string.perf_desktop_as_user, "root", "user", "sudo", "fakeroot"),
@@ -1,46 +0,0 @@
package com.droiddeck.launcher.frontend
import android.content.Intent
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class LauncherReopenTest {
private val launcher = setOf(Intent.CATEGORY_LAUNCHER)
private fun reveals(
action: String? = Intent.ACTION_MAIN,
categories: Set<String>? = launcher,
taskRoot: Boolean = false,
restored: Boolean = false,
pipActive: Boolean = false,
ownTask: Boolean = true,
) = LauncherReopen.revealsTask(action, categories, taskRoot, restored, pipActive) { ownTask }
@Test fun launcherIconStackedOnAShortcutTaskShowsThatTask() {
assertTrue(reveals())
}
@Test fun launcherIconStartingTheTaskOpensTheMenu() {
assertFalse(reveals(taskRoot = true))
}
@Test fun shortcutsLinksAndInternalOpensStillOpenTheMenu() {
assertFalse(reveals(action = Intent.ACTION_VIEW, categories = null))
assertFalse(reveals(action = GameLaunchIntent.ACTION, categories = null))
assertFalse(reveals(categories = null))
assertFalse(reveals(categories = setOf(Intent.CATEGORY_HOME, Intent.CATEGORY_DEFAULT)))
}
@Test fun anotherAppsTaskRestoredMenuAndPictureInPictureKeepTheMenu() {
assertFalse(reveals(ownTask = false))
assertFalse(reveals(restored = true))
assertFalse(reveals(pipActive = true))
}
@Test fun taskOwnershipIsOnlyQueriedForAStackedLauncherOpen() {
var asked = false
LauncherReopen.revealsTask(Intent.ACTION_MAIN, launcher, true, false, false) { asked = true; true }
assertFalse(asked)
}
}
@@ -1,38 +0,0 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import java.io.File
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
@RunWith(RobolectricTestRunner::class)
class NativeGuestDefaultsTest {
@Test fun savedRuntimeOverridesDoNotDisableNativeExecution() {
val context = RuntimeEnvironment.getApplication()
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.putBoolean("nativeUserland", false)
.putBoolean("prootFastPath", false)
.putBoolean("prootNoSeccomp", true)
.apply()
val root = LinuxRuntime.rootDir(context)
val hook = NativeGuest.hook(root)
val loader = File(root, "usr/lib/ld-linux-aarch64.so.1")
hook.parentFile?.mkdirs()
loader.writeText("fixture")
try {
assertTrue(NativeGuest.nextSession(context))
assertFalse(NativeGuest.enabled(context))
hook.writeText("fixture")
assertTrue(NativeGuest.enabled(context))
assertFalse(ProotFastPath.enabled(context, native = true))
} finally {
hook.delete()
loader.delete()
}
}
}
@@ -27,12 +27,14 @@ class ProotFastPathTest {
}
@Test fun fastPathStaysOffForTheRootfsProot() {
assertTrue(ProotFastPath.allows(source = LinuxRuntime.PROOT_PACK, native = false))
assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_ROOTFS, native = false))
assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_MISSING, native = false))
assertTrue(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_PACK))
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_ROOTFS))
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_MISSING))
assertFalse(ProotFastPath.allows(preference = false, noSeccomp = false, source = LinuxRuntime.PROOT_PACK))
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = true, source = LinuxRuntime.PROOT_PACK))
}
@Test fun fastPathStaysOffWithoutProot() {
assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_PACK, native = true))
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_PACK, nativeUserland = true))
}
}
@@ -1,6 +1,5 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.assumeFilePermissionsEnforced
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.text.SimpleDateFormat
@@ -9,7 +8,6 @@ import java.util.Date
import java.util.Locale
import java.util.concurrent.TimeUnit
import java.util.zip.ZipFile
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
@@ -146,136 +144,6 @@ class SessionLogShareZipTest {
}
}
@Test fun theEasyAntiCheatLauncherLogsFromGamePrefixesComeAlong() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val session = File(LinuxRuntime.logDir(app), "2026-12-05-09-steam").apply { mkdirs() }
val out = File(app.getExternalFilesDir(null), "agent-logs/anticheat")
val prefix = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata/976730")
val second = File(app.getExternalFilesDir(null), "second-library-${UUID.randomUUID()}").apply { mkdirs() }
val library = SteamLibraries.add(app, second.path) as SteamLibraries.AddResult.Added
try {
File(session, "session.log").writeText("booted\n")
val eac = File(prefix, "pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/4815162342").apply { mkdirs() }
File(eac, "anticheatlauncher.log").writeText("[Error] Launch Error: 261\n")
File(eac, "old.log").apply {
writeText("stale\n")
setLastModified(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30))
}
val secondEac = File(second, "steamapps/compatdata/976730/pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/b1d0a8c3").apply { mkdirs() }
File(secondEac, "anticheatlauncher.log").writeText("[Error] Launch Error: 206\n")
val signedEac = File(prefix.parentFile, "-1768546955/pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/0a1b").apply { mkdirs() }
File(signedEac, "anticheatlauncher.log").writeText("[Error] Launch Error: 30005\n")
val unsignedEac = File(prefix.parentFile, "2526420341/pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/0a1b").apply { mkdirs() }
File(unsignedEac, "anticheatlauncher.log").writeText("[Error] Launch Error: 30007\n")
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
ZipFile(zip).use { archive ->
val logs = archive.entries().toList().filter { it.name.startsWith("anticheat/976730/") }
assertEquals(2, logs.size)
assertTrue(logs.all { it.name.endsWith("/anticheatlauncher.log") && !it.name.contains("4815162342") })
val texts = logs.map { archive.getInputStream(it).bufferedReader().readText() }
assertTrue(texts.any { it.contains("Launch Error: 261") })
assertTrue(texts.any { it.contains("Launch Error: 206") })
val aliases = archive.entries().toList().filter { it.name.startsWith("anticheat/2526420341/") }
assertEquals(2, aliases.size)
assertEquals(2, aliases.map { it.name.split('/')[2] }.filter { it.startsWith("library1") }.toSet().size)
val aliasTexts = aliases.map { archive.getInputStream(it).bufferedReader().readText() }
assertTrue(aliasTexts.any { it.contains("Launch Error: 30005") })
assertTrue(aliasTexts.any { it.contains("Launch Error: 30007") })
}
} finally {
SteamLibraries.remove(app, library.entry.id)
out.deleteRecursively()
session.deleteRecursively()
prefix.deleteRecursively()
File(prefix.parentFile, "-1768546955").deleteRecursively()
File(prefix.parentFile, "2526420341").deleteRecursively()
second.deleteRecursively()
}
}
@Test fun theSessionsGameLogComesAlongWhenManyAntiCheatLogsAreFound() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val session = File(LinuxRuntime.logDir(app), "2026-12-05-11-steam").apply { mkdirs() }
val out = File(app.getExternalFilesDir(null), "agent-logs/anticheat-flood")
val compatdata = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata")
val prefixes = (0 until 300).map { File(compatdata, "${900000 + it}") }
try {
File(session, "session.log").writeText("booted\n")
File(session, "steam-976730.log").writeText("proton: game started\n")
prefixes.forEach { prefix ->
val eac = File(prefix, "pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/0a1b").apply { mkdirs() }
File(eac, "anticheatlauncher.log").writeText("[Error] Launch Error: 206\n" + "x".repeat(64 * 1024))
}
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
ZipFile(zip).use { archive ->
val game = archive.entries().toList().single { it.name.endsWith("/steam-976730.log") }
assertTrue(archive.getInputStream(game).bufferedReader().readText().contains("game started"))
}
} finally {
out.deleteRecursively()
session.deleteRecursively()
prefixes.forEach { it.deleteRecursively() }
}
}
@Test fun aDiscoveryFailureStaysInTheManifestWhenRecordsPassTheLimit() {
assumeFilePermissionsEnforced()
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val session = File(LinuxRuntime.logDir(app), "2026-12-05-10-steam").apply { mkdirs() }
val out = File(app.getExternalFilesDir(null), "agent-logs/manifest-limit")
val compatdata = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata").apply { mkdirs() }
try {
repeat(300) {
File(session, "part-$it.log").writeText("line $it\n")
File(session, "wayland-$it.log").writeText("line $it\n")
File(session, "proton-$it.log").writeText("line $it\n")
}
assertTrue(compatdata.setReadable(false, false))
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
ZipFile(zip).use { archive ->
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json")).bufferedReader().readText())
val entries = manifest.getJSONArray("entries")
val reasons = (0 until entries.length()).map { entries.getJSONObject(it) }
.filter { it.optString("origin") == "discovery" }.map { it.optString("reason") }
assertTrue(entries.length() > 512)
assertTrue(reasons.toString(), "filesystem-error" in reasons)
}
} finally {
compatdata.setReadable(true, false)
out.deleteRecursively()
session.deleteRecursively()
}
}
@Test fun aPrefixThatDeniesTheAntiCheatFolderIsRecordedAsADiscoveryFailure() {
assumeFilePermissionsEnforced()
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val session = File(LinuxRuntime.logDir(app), "2026-12-05-12-steam").apply { mkdirs() }
val out = File(app.getExternalFilesDir(null), "agent-logs/anticheat-denied")
val compatdata = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata")
val prefix = File(compatdata, "976731")
val users = File(prefix, "pfx/drive_c/users").apply { mkdirs() }
try {
File(session, "session.log").writeText("booted\n")
assertTrue(users.setExecutable(false, false))
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
ZipFile(zip).use { archive ->
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json")).bufferedReader().readText())
val entries = manifest.getJSONArray("entries")
val reasons = (0 until entries.length()).map { entries.getJSONObject(it) }
.filter { it.optString("origin") == "discovery" }.map { it.optString("reason") }
assertTrue(reasons.toString(), "filesystem-error" in reasons)
}
} finally {
users.setExecutable(true, false)
out.deleteRecursively()
session.deleteRecursively()
prefix.deleteRecursively()
}
}
@Test fun everyTextFileInTheZipIsScrubbedAndTheStoresAndToolsLogsComeAlong() {
val logs = LinuxRuntime.logDir(app)
val session = File(logs, "2026-10-08-01-steam").apply { mkdirs() }
+6 -8
View File
@@ -252,15 +252,13 @@ self-extractor stops at "Path not found", so the values it installs are applied
`goggame-<id>.info`, and a script's own `setRegistry` entries always win over the built-in table.
The script's `supportData` actions run right after: files and folders from the game folder
(`{app}`) or its support files (`{supportDir}`, `support/<id>/`) are copied to `{userdocs}`,
`{localappdata}` or `{userappdata}` in the prefix, and `type: folder` without a source creates the
folder. Mods such as one-click editions ship their `Plugins.txt` and INI files this way. The
`savePath` action's `savePath` folder is created with the same path rules, including the common
case where a one-click edition names it again as a `supportData` folder. Paths match without regard
(`{app}`) or its support files (`{supportDir}`, `support/<id>/`) are copied to `{userdocs}` and
`{localappdata}` in the prefix, and `type: folder` without a source creates the folder. Mods such
as one-click editions ship their `Plugins.txt` and INI files this way. Paths match without regard
to case, links are copied as links, and a path outside those folders is refused. A file the
player already has is replaced only when the action says `overwrite`. `.droiddeck-gog-support` and
`.droiddeck-gog-save-path` in the prefix hold the actions' hashes, so they run once per script
revision and a player's later edits stay.
player already has is replaced only when the action says `overwrite`. `.droiddeck-gog-support` in
the prefix holds the actions' hash, so they run once per script revision and a player's later
edits stay.
A GOG game's exe comes from its own manifest first: `goggame-<id>.info`'s play task in category
`game` (`isPrimary` first), or a primary `launcher` task for launcher games, whose `path` stays
+2 -1
View File
@@ -14,7 +14,8 @@ after restarting. If no complete copy exists, the pack uses the checkout's pin.
- `tools/agent/dd-lab-build` builds the checkout with Gradle on the device (`processReleaseResources`
and `mergeDexRelease`), packs the linked resources and dex files into `overlay.apk`, writes
`overlay.json`, and stages both in the app's `files/lab/next`. It then recompiles the app without
an app image and restarts DroidDeck.
an app image and restarts DroidDeck. The resource linker uses IDs from the installed APK so
base and overlay code resolve the same resource names.
- Run by the app's own agent (`DD_AGENT` set), it writes `files/agent/lab-request` instead, and the
app runs the build in a process of its own, logging to `~/.cache/dd-lab-build.log`; the agent's
copy follows that log and exits with the build. A turn's processes end with the turn, so a build
+3
View File
@@ -27,6 +27,9 @@ Links of the form `droiddeck://settings/<section>` open a Settings section direc
| droiddeck-esync | Settings › Performance (`droiddeck://settings/performance`) | esync, sync, wine |
| droiddeck-fsync first | Settings › Performance (`droiddeck://settings/performance`) | fsync, sync, wine |
| droiddeck-ntsync | Settings › Performance (`droiddeck://settings/performance`) | ntsync, sync, wine |
| Run proot without seccomp | Settings › Performance (`droiddeck://settings/performance`) | proot |
| proot fast path | Settings › Performance (`droiddeck://settings/performance`) | proot |
| Run without proot (experimental) | Settings › Performance (`droiddeck://settings/performance`) | proot |
| Draw the cursor inside gamescope | Settings › Performance (`droiddeck://settings/performance`) | mouse, cursor |
| Host name | Settings › Performance (`droiddeck://settings/performance`) | name |
| Desktop runs as a user | Settings › Performance (`droiddeck://settings/performance`) | root, user, sudo, fakeroot |
+48
View File
@@ -134,6 +134,54 @@ fi
gradle=(./gradlew :app:processReleaseResources :app:mergeDexRelease --max-workers=2 -PskipRust=true -x buildVkBridgeServer
-Pandroid.aapt2FromMavenOverride=$HOME/aapt2/aapt2 -Pkotlin.compiler.execution.strategy=daemon
-Pkotlin.daemon.jvmargs=-Xmx${kotlin_heap}m -Dorg.gradle.jvmargs=-Xmx${gradle_heap}m --console=plain)
# Release package aliases rewrite the manifest but keep the resource table under the linker package.
resource_package=com.droiddeck.launcher
resource_cache=$cache/dd-lab-resource-ids
mkdir -p "$resource_cache"
resource_key=$(printf '%s\n' "$pkg" "$base" "$apk" | sha256sum | cut -d ' ' -f1)
stable_ids=$resource_cache/$resource_key.txt
if [ ! -s "$stable_ids" ]; then
progress checking 0 "reading the installed APK resource IDs"
if ! (
resource_work=$(mktemp -d "$resource_cache/.extract.XXXXXX") || exit 1
trap 'rm -rf "$resource_work"' EXIT
adb -s "$serial" pull "$apk" "$resource_work/base.apk" >/dev/null &&
"$HOME/aapt2/aapt2" dump resources "$resource_work/base.apk" > "$resource_work/resources.txt" &&
awk -v package="$resource_package" '
$1 == "Package" { in_package = ($2 == "name=" package) }
in_package && $1 == "resource" && $2 ~ /^0x[[:xdigit:]]+$/ {
print package ":" $3 " = " $2
count++
}
END { if (!count) exit 1 }
' "$resource_work/resources.txt" > "$resource_work/ids.txt" &&
mv "$resource_work/ids.txt" "$stable_ids"
); then
fail "could not read resource IDs from the installed APK"
fi
fi
resource_init=$resource_cache/link.gradle
cat > "$resource_init.part.$$" <<'EOF'
gradle.beforeProject { project ->
if (project.path == ':app') {
project.pluginManager.withPlugin('com.android.application') {
project.androidComponents.finalizeDsl { android ->
android.androidResources.additionalParameters.addAll([
'--stable-ids', project.providers.gradleProperty('droiddeckLabStableIds').get()
])
}
}
}
}
EOF
if cmp -s "$resource_init.part.$$" "$resource_init"; then
rm "$resource_init.part.$$"
else
mv "$resource_init.part.$$" "$resource_init"
fi
gradle+=(--init-script "$resource_init" "-PdroiddeckLabStableIds=$stable_ids")
progress planning
plan_file=$cache/dd-lab-build-plan
plan_key=$(
@@ -968,7 +968,6 @@ def prepare_gog(sidecar, compat_data, launch_dir):
GOG_SCRIPTS = "goggame-*.script"
GOG_REGISTRY_MARK = ".droiddeck-gog-registry"
GOG_SUPPORT_MARK = ".droiddeck-gog-support"
GOG_SAVE_PATH_MARK = ".droiddeck-gog-save-path"
GOG_ROOTS = {"HKEY_LOCAL_MACHINE": "HKEY_LOCAL_MACHINE", "HKLM": "HKEY_LOCAL_MACHINE",
"HKEY_CURRENT_USER": "HKEY_CURRENT_USER", "HKCU": "HKEY_CURRENT_USER",
"HKEY_CLASSES_ROOT": "HKEY_CLASSES_ROOT", "HKCR": "HKEY_CLASSES_ROOT"}
@@ -1717,7 +1716,7 @@ def prepare_steam_ea(argv, compat_data, launch_dir):
return REPLACED
def gog_script_actions(folder, name):
def gog_support_actions(folder):
found = []
for script in sorted(Path(folder).glob(GOG_SCRIPTS)):
product = script.name[len("goggame-"):-len(".script")]
@@ -1727,34 +1726,17 @@ def gog_script_actions(folder, name):
continue
for action in actions if isinstance(actions, list) else []:
install = action.get("install") if isinstance(action, dict) else None
if isinstance(install, dict) and install.get("action") == name \
if isinstance(install, dict) and install.get("action") == "supportData" \
and isinstance(install.get("arguments"), dict):
found.append((product, install["arguments"]))
return found
def gog_support_actions(folder):
return gog_script_actions(folder, "supportData")
def gog_case_child(path, part):
exact = path / part
try:
if not exact.exists() and path.is_dir():
return next((child for child in path.iterdir() if child.name.lower() == part.lower()), exact)
except OSError:
pass
return exact
def gog_support_bases(folder, product, pfx):
user = Path(pfx) / "drive_c" / "users" / "steamuser"
support = Path(folder) / "support" / product
appdata = gog_case_child(user, "AppData")
return {"app": Path(folder), "supportdir": support, "support": support,
"userdocs": gog_case_child(user, "Documents"),
"localappdata": gog_case_child(appdata, "Local"),
"userappdata": gog_case_child(appdata, "Roaming")}
"userdocs": user / "Documents", "localappdata": user / "AppData" / "Local"}
def gog_inside(path, base):
@@ -1773,7 +1755,10 @@ def gog_support_path(text, bases):
base = bases[match.group(1).lower()]
path = base
for part in parts:
path = gog_case_child(path, part)
exact = path / part
if not exact.exists() and path.is_dir():
exact = next((child for child in path.iterdir() if child.name.lower() == part.lower()), exact)
path = exact
if path != base and not gog_inside(path.parent, base):
return None
return path, base
@@ -1845,44 +1830,6 @@ def gog_support_data(folder, compat_data, proton):
return "copied=%d%s" % (copied, note)
def gog_save_paths(folder, compat_data, proton):
actions = gog_script_actions(folder, "savePath")
if not actions:
return "none"
pfx = Path(compat_data) / "pfx" if compat_data else None
if not pfx or not (pfx / "drive_c" / "users" / "steamuser").is_dir():
made = create_prefix(compat_data, proton)
if made not in ("present", "created") or not (pfx / "drive_c" / "users" / "steamuser").is_dir():
return "no-prefix"
stamp = hashlib.sha256(json.dumps(actions, sort_keys=True).encode("utf-8")).hexdigest()
marker = pfx / GOG_SAVE_PATH_MARK
try:
if marker.is_file() and marker.read_text() == stamp:
return "ready"
except OSError:
pass
paths = skipped = 0
for product, arguments in actions:
bases = gog_support_bases(folder, product, pfx)
found = gog_support_path(arguments.get("savePath") or arguments.get("target"), bases)
if found is None:
skipped += 1
continue
target, _root = found
try:
target.mkdir(parents=True, exist_ok=True)
paths += 1
except OSError:
skipped += 1
note = " skipped=%d" % skipped if skipped else ""
if not skipped:
try:
marker.write_text(stamp)
except OSError:
pass
return "paths=%d%s" % (paths, note)
def main(argv):
if os.environ.get("DROIDDECK_GOG_MAINTENANCE") == "1":
return 0
@@ -1929,7 +1876,6 @@ def main(argv):
prepare_gog(sidecar, compat_data, launch_dir)
log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
log("gog support data: " + gog_support_data(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
log("gog save paths: " + gog_save_paths(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
if store == "rockstar":
if game not in ROCKSTAR_TITLES and not rockstar_sdk(folder, sidecar):
if compat_data:
-115
View File
@@ -667,10 +667,6 @@ def support_data(**arguments):
return {'install': {'action': 'supportData', 'arguments': arguments}, 'name': 'supportData'}
def save_path(**arguments):
return {'install': {'action': 'savePath', 'arguments': arguments}, 'name': 'saveFolders'}
class GogSupportData(unittest.TestCase):
def prefix(self, root):
user = Path(root) / 'compat/pfx/drive_c/users/steamuser'
@@ -854,117 +850,6 @@ class GogSupportData(unittest.TestCase):
self.assertTrue((Path(root) / 'compat/pfx/drive_c/users/steamuser/Documents/My Games/G').is_dir())
class GogSavePaths(unittest.TestCase):
def prefix(self, root):
user = Path(root) / 'compat/pfx/drive_c/users/steamuser'
user.mkdir(parents=True)
return user
def test_the_london_script_creates_its_save_path_and_keeps_player_settings(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='1897848199')
user = self.prefix(root)
support = folder / 'support/1897848199'
(support / 'docs').mkdir(parents=True)
(folder / '__AppData').mkdir()
(folder / '__AppData/save.dat').write_text('save')
for name in ('Fallout4Prefs.ini', 'Fallout4.ini'):
(support / 'docs' / name).write_text('[Archive]\n')
for name in ('DLCList.txt', 'Plugins.txt', 'UserDownloadedContent.txt'):
(support / name).write_text('*LondonWorldSpace.esm\n')
gog_script(folder, '1897848199', [
save_path(savePath='{userdocs}/My Games/Fallout4', type='folder'),
set_registry(root='HKLM', subkey='Software\\Bethesda Softworks\\Fallout4',
valueName='Installed Path', valueData='{app}\\', valueType='string'),
support_data(type='folder', target='{userdocs}/My Games/Fallout4'),
support_data(type='folder', target='{localappdata}/Fallout4'),
support_data(type='file', overwrite=True, source='{supportDir}/docs/Fallout4Prefs.ini',
target='{userdocs}/My Games/Fallout4/Fallout4Prefs.ini'),
support_data(type='file', overwrite=True, source='{supportDir}/docs/Fallout4.ini',
target='{userdocs}/My Games/Fallout4/Fallout4.ini'),
support_data(type='file', overwrite=True, source='{supportDir}/DLCList.txt',
target='{localappdata}/Fallout4/DLCList.txt'),
support_data(type='file', overwrite=True, source='{supportDir}/Plugins.txt',
target='{localappdata}/Fallout4/Plugins.txt'),
support_data(type='file', overwrite=True, source='{supportDir}/UserDownloadedContent.txt',
target='{localappdata}/Fallout4/UserDownloadedContent.txt'),
support_data(type='folder', overwrite=True, source='{app}/__AppData', target='{localappdata}/Fallout4'),
])
with patch.object(store, 'create_prefix') as create:
self.assertEqual('copied=6', store.gog_support_data(folder, root + '/compat', '/proton'))
self.assertEqual('paths=1', store.gog_save_paths(folder, root + '/compat', '/proton'))
create.assert_not_called()
saves = user / 'Documents/My Games/Fallout4'
self.assertTrue(saves.is_dir())
self.assertEqual('[Archive]\n', (saves / 'Fallout4.ini').read_text())
self.assertEqual('*LondonWorldSpace.esm\n', (user / 'AppData/Local/Fallout4/Plugins.txt').read_text())
self.assertTrue((Path(root) / 'compat/pfx' / store.GOG_SAVE_PATH_MARK).is_file())
(saves / 'my settings.ini').write_text('player')
self.assertEqual('ready', store.gog_save_paths(folder, root + '/compat', '/proton'))
self.assertEqual('player', (saves / 'my settings.ini').read_text())
def test_existing_prefix_base_names_keep_their_actual_case(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
user = self.prefix(root)
(user / 'documents' / 'fixture').mkdir(parents=True)
(user / 'aPPdATA' / 'roaming').mkdir(parents=True)
gog_script(folder, '9', [
save_path(savePath='{UserDocs}/Fixture/Saves'),
save_path(savePath='{UserAppData}/Fixture/Settings'),
])
self.assertEqual('paths=2', store.gog_save_paths(folder, root + '/compat', '/proton'))
self.assertTrue((user / 'documents/fixture/Saves').is_dir())
self.assertTrue((user / 'aPPdATA/roaming/Fixture/Settings').is_dir())
self.assertEqual({'documents', 'aPPdATA'}, {p.name for p in user.iterdir()})
self.assertEqual({'roaming'}, {p.name for p in (user / 'aPPdATA').iterdir()})
def test_only_save_path_actions_create_known_folders(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
user = self.prefix(root)
saves = user / 'Documents/My Games/Fallout4'
saves.mkdir(parents=True)
(saves / 'Fallout4Prefs.ini').write_text('player')
gog_script(folder, '9', [
set_registry(root='HKLM', subkey='Software\\Game', valueName='a', valueData='b', valueType='string'),
{'install': {'action': 'createFolder', 'arguments': {'savePath': '{userdocs}/Other'}}},
save_path(savePath='{windir}/evil'),
save_path(savePath='{userdocs}/../../escape'),
save_path(savePath='{userappdata}/Ubisoft/Anno1404/Config'),
])
self.assertEqual('paths=1 skipped=2', store.gog_save_paths(folder, root + '/compat', '/proton'))
self.assertTrue((user / 'AppData/Roaming/Ubisoft/Anno1404/Config').is_dir())
self.assertFalse((user / 'Documents/Other').exists())
self.assertFalse((Path(root) / 'escape').exists())
self.assertEqual('player', (saves / 'Fallout4Prefs.ini').read_text())
self.assertFalse((Path(root) / 'compat/pfx' / store.GOG_SAVE_PATH_MARK).exists())
def test_without_save_paths_no_prefix_is_made(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
gog_script(folder, '9', [set_registry(root='HKLM', subkey='Software\\Game', valueName='a',
valueData='b', valueType='string')])
with patch.object(store, 'create_prefix') as create:
self.assertEqual('none', store.gog_save_paths(folder, root + '/compat', '/proton'))
create.assert_not_called()
def test_a_missing_prefix_is_made_first(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
gog_script(folder, '9', [save_path(savePath='{userdocs}/My Games/G')])
with patch.object(store, 'create_prefix', return_value='failed') as create:
self.assertEqual('no-prefix', store.gog_save_paths(folder, root + '/compat', '/proton'))
create.assert_called_once_with(root + '/compat', '/proton')
def made(compat_data, proton):
self.prefix(root)
return 'created'
with patch.object(store, 'create_prefix', side_effect=made):
self.assertEqual('paths=1', store.gog_save_paths(folder, root + '/compat', '/proton'))
self.assertTrue((Path(root) / 'compat/pfx/drive_c/users/steamuser/Documents/My Games/G').is_dir())
class GogRegistry(unittest.TestCase):
def test_patch_registration_uses_authentic_build_and_the_prefix_registry_executable(self):
with tempfile.TemporaryDirectory() as root: