mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 20:36:04 +00:00
feat: fuck proot and proots mama (#2300)
* feat: experimental native userland that runs the Linux side without proot * fix(native): keep the visible name of link2symlink binaries * fix(ci): run the native hook build through bash * fix(native): address review findings in the hook and the ctl fallback * fix(ctl): use the broadcast fallback only when content is missing * fix(native): survive Android's seccomp filter in ld.so, libc and posix_spawn children * docs(native): how to test under Android's seccomp filter * fix(session): hide an unlistable /sys/bus/pci/devices so libpci does not abort Chromium's GPU init * fix(native): nested syscall() redirects no longer loop with libblsession's openat2 * fix(native): controllers reach Steam and the install-script evaluator no longer blocks game moves * fix(native): write the hook's NUL character literals as escapes * fix(native): proot fast path turns off and greys out while running without proot * fix(native): D-Bus logins work and Xwayland still admits root once peers read as root * fix(native): scripts on session mounts outside the rootfs run with the rootfs shell * fix(native): games on the SD card library start in their own folder * fix(native): Wine drive links proot made point at their real places * fix(native): at-calls, uid lookups and relative programs follow the session's mounts * fix(native): close-from in spawned programs covers what is open at the spawn * fix(native): service names resolve and the DNS fallback answers what was asked * build(native): the hook is built with its Go support and tracked by the preload recipe * fix(native): drive links into identity mounts stay, and relink and seccomp patch failures are logged * fix(native): seccomp-sim's filter holds every allowed call * fix(ctl): the broadcast fallback only stands in for a missing content command * fix(native): pre-2.33 glibc stat calls present owners as root too * fix(native): res_init and res_ninit call glibc, so Steam's store resolves names * fix(ci): a preload lock older than a new output rebuilds that group, and generated headers are not hashed * fix(native): a second seccomp patch run leaves other system calls alone * fix(native): the terminal and bottom desktop keep proot's environment in a native session * fix(native): any number of session mounts, and openat2 relative to a mounted folder * fix(agent): a native command's stdin is written beside its timeout * fix(ctl): native rejects --env without = and timeouts outside 0-600 s * fix(native): the resolver fallback has the network's IPv6 servers, and lookups keep the fallback's validation errors * fix(native): a spawn whose dup2 source close-from closed fails with EBADF * fix(native): __getcwd_chk checks its buffer, and seccomp-sim -a takes only call numbers * feat(native): guests see the session hostname from uname and gethostname * feat(native): the terminal and bottom desktop run without proot * fix(components): an origin APK without a newer preload output still proves the rest * fix(native): seccomp-sim -a rejects empty fields * fix(native): gethostbyname no longer answers failed lookups with Ubuntu and Debian addresses * feat(native): store installers, root helpers, Comet and Xodus run without proot * fix(native): the hook finds libraries, preloads and itself through a sandbox's mounts, and ldconfig -C makes its cache * feat(native): Flatpak sandboxes run without proot, and apply_extra runs without a runtime * fix(native): remove, glob and nftw take guest paths, and links in a mount are followed as the guest sees them * fix(native): Flatpak sandboxes get the session's mounts, their libraries' RUNPATHs, and no rootfs-only settings * fix(native): gethostbyname asks the network's DNS servers, nftw of / gives single slashes, and the library path fits mapped directories * fix(native): a native process starts in its working directory's real place * fix(native): the library path given to ld.so holds whole directories only * fix(native): Wine drive links keep their guest paths, so proot finds the library after a native session * fix(native): droiddeckctl native prepares the rootfs with the setting off * fix(native): a SysV segment stays while any process has it attached * fix(native): DNS lookups ask the network's own servers before public ones * fix(native): a program's own seccomp traps reach its own SIGSYS handler * feat(native): run native sessions under a device's own app seccomp filter for testing * fix(native): SysV attaches and collection take a lock, a failed mark fails the attach, and collection closes its directory * fix(native): shmat fails when it cannot take the segment lock * fix(native): the SysV segment lock is retried when a signal interrupts it * fix(native): process tools see the session's processes as root's * fix(native): native processes are named after their program, not ld.so * fix(native): a session's helpers keep the mode the session started in * fix(native): a keyed SysV segment stays until IPC_RMID * fix(native): a rootfs link to an absolute guest path is followed in the guest, so Wine finds its z: drive * fix(native): a sandbox whose loader can't be patched runs under proot * fix(native): creating a private SysV segment also collects stale ones * fix(native): a session stopped during startup forgets its mode * fix(xbox): a native backend is authorized by its process ancestry * fix(native): Wine's drive links are followed in the guest from any prefix * fix(native): only the startup that owns the running session publishes its mode * fix(native): a SysV segment stays until IPC_RMID even after its maker ends * fix(native): a sandbox mount nested in another mount gets its own place * fix(native): a sandbox whose mount places can't be made runs under proot
This commit is contained in:
1 parent
b1a410ccd2
commit
2848484a99
67 files changed
+13157
-113
No files matched your search
@@ -185,6 +185,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var gpuClockPin by mutableStateOf(false)
|
||||
private var prootNoSeccomp by mutableStateOf(false)
|
||||
private var prootFastPath by mutableStateOf(true)
|
||||
private var nativeUserland by mutableStateOf(false)
|
||||
private var cursorComposite by mutableStateOf(false)
|
||||
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
|
||||
private var phantomWarning by mutableStateOf<String?>(null)
|
||||
@@ -2557,7 +2558,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
deviceRamMb = (android.app.ActivityManager.MemoryInfo()
|
||||
.also((getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)::getMemoryInfo).totalMem / (1024 * 1024)).toInt(),
|
||||
ramCapAvailable = com.droiddeck.launcher.core.ZramSupport.supported(),
|
||||
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, cursorComposite = cursorComposite,
|
||||
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite,
|
||||
guestHostname = guestHostname, phantomWarning = phantomWarning,
|
||||
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
|
||||
onTuSysmem = { on -> SessionPrefs.setTuSysmem(this, on); tuSysmem = on },
|
||||
@@ -2575,6 +2576,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
onVramCapMb = { mb -> SessionPrefs.setVramCapMb(this, mb); vramCapMb = mb },
|
||||
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
|
||||
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
|
||||
onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on },
|
||||
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
|
||||
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
|
||||
onClientCore = { core, on ->
|
||||
@@ -2797,6 +2799,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
gpuClockPin = SessionPrefs.gpuClockPin(this)
|
||||
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
|
||||
prootFastPath = SessionPrefs.prootFastPath(this)
|
||||
nativeUserland = SessionPrefs.nativeUserland(this)
|
||||
cursorComposite = SessionPrefs.cursorComposite(this)
|
||||
guestHostname = SessionPrefs.guestHostname(this)
|
||||
refreshPhantomStatus()
|
||||
|
||||
@@ -85,6 +85,10 @@ class AgentBridgeProvider : ContentProvider() {
|
||||
AgentAccess.requireCommands(context)
|
||||
guest(context, JSONObject(request.toString()).put("kind", "exec"), timeoutMs(request, 30.0, 10_000))
|
||||
}
|
||||
"native" -> {
|
||||
AgentAccess.requireCommands(context)
|
||||
AgentNative.run(context, request, timeoutMs(request, 30.0, 0))
|
||||
}
|
||||
"cdp" -> {
|
||||
AgentAccess.requireCommands(context)
|
||||
guest(context, JSONObject(request.toString()).put("kind", "cdp"), timeoutMs(request, 15.0, 5_000))
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.NativeGuest
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/** Runs a guest program without proot (`droiddeckctl native`), for testing the native userland. */
|
||||
object AgentNative {
|
||||
private const val OUTPUT_CAP = 256 * 1024
|
||||
|
||||
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) }
|
||||
if (argv.isEmpty()) throw AgentException("INVALID_REQUEST", "argv is empty")
|
||||
val env = linkedMapOf<String, String>()
|
||||
request.optJSONObject("env")?.let { obj -> obj.keys().forEach { env[it] = obj.getString(it) } }
|
||||
val preload = request.optJSONArray("preload")?.let { a -> (0 until a.length()).map { a.getString(it) } } ?: emptyList()
|
||||
val builder = NativeGuest.builder(root, request.optString("cwd", "/root"), argv, env, preload)
|
||||
val started = System.nanoTime()
|
||||
val process = builder.start()
|
||||
val out = StringBuilder()
|
||||
val err = StringBuilder()
|
||||
val readers = listOf(
|
||||
Thread { drain(process.inputStream, out) },
|
||||
Thread { drain(process.errorStream, err) },
|
||||
).onEach { it.isDaemon = true; it.start() }
|
||||
// written beside the wait: a program that never reads more than a pipe holds would block it
|
||||
val input = request.optString("stdin").toByteArray()
|
||||
Thread {
|
||||
try {
|
||||
process.outputStream.use { stdin -> if (input.isNotEmpty()) stdin.write(input) }
|
||||
} catch (_: java.io.IOException) {
|
||||
}
|
||||
}.apply { isDaemon = true; start() }
|
||||
val finished = process.waitFor(timeoutMs, TimeUnit.MILLISECONDS)
|
||||
if (!finished) process.destroyForcibly().waitFor()
|
||||
readers.forEach { it.join(2000) }
|
||||
val code = if (finished) process.exitValue() else -1
|
||||
return JSONObject().put("ok", true).put("command", "native")
|
||||
.put("exitCode", code).put("timedOut", !finished)
|
||||
.put("ms", (System.nanoTime() - started) / 1_000_000)
|
||||
.put("stdout", JSONObject().put("text", out.toString()))
|
||||
.put("stderr", JSONObject().put("text", err.toString()))
|
||||
.put("argv", JSONArray(argv))
|
||||
}
|
||||
|
||||
private fun drain(input: java.io.InputStream, into: StringBuilder) {
|
||||
val buffer = ByteArray(8192)
|
||||
val text = java.io.ByteArrayOutputStream()
|
||||
while (true) {
|
||||
val n = try { input.read(buffer) } catch (e: java.io.IOException) { -1 }
|
||||
if (n < 0) break
|
||||
if (text.size() < OUTPUT_CAP) text.write(buffer, 0, minOf(n, OUTPUT_CAP - text.size()))
|
||||
}
|
||||
into.append(text.toString(Charsets.UTF_8.name()))
|
||||
}
|
||||
}
|
||||
@@ -278,6 +278,7 @@ object DeviceReport {
|
||||
k("RAM cap", SessionPrefs.ramCapMb(context).let { if (it > 0) "$it MB" else "off" })
|
||||
k("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" })
|
||||
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))
|
||||
|
||||
@@ -182,6 +182,7 @@ object BwrapSpawner {
|
||||
val argv = request.getJSONArray("argv").let { a -> (0 until a.length()).map { a.getString(it) } }
|
||||
val env = LinkedHashMap<String, String>()
|
||||
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } }
|
||||
withoutRootfsSettings(env, rootfs)
|
||||
val envTool = request.optString("envTool").takeIf { it.startsWith("/") }
|
||||
if (envTool == null && binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) }
|
||||
val libc = listOf("/usr/lib/aarch64-linux-gnu/libc.so.6", "/lib/aarch64-linux-gnu/libc.so.6").map { hostPath(binds, root.path, it) }
|
||||
@@ -191,6 +192,24 @@ object BwrapSpawner {
|
||||
return Plan(root, binds, request.optString("cwd", "/").ifEmpty { "/" }, argv, env, envTool ?: "/usr/bin/env")
|
||||
}
|
||||
|
||||
private val ROOTFS_PIPEWIRE = listOf("PIPEWIRE_MODULE_DIR", "SPA_PLUGIN_DIR", "PIPEWIRE_CONFIG_DIR")
|
||||
|
||||
/**
|
||||
* The session's Flatpak passes settings for the session's own root on: the native hook's,
|
||||
* DroidDeck's PipeWire build, which a runtime does not have (its apps found no PipeWire plugins),
|
||||
* and the session's video driver for SDL.
|
||||
*/
|
||||
internal fun withoutRootfsSettings(env: MutableMap<String, String>, rootfs: String) {
|
||||
env.keys.removeAll { it.startsWith("DDNATV_") }
|
||||
for (key in ROOTFS_PIPEWIRE) if (env[key]?.startsWith("/usr/local/lib/droiddeck-pipewire") == true) env.remove(key)
|
||||
// the session's choice of X11 for SDL, in an app that Flatpak gave Wayland and no X display
|
||||
if (env["SDL_VIDEODRIVER"] == "x11" && env["DISPLAY"].isNullOrEmpty() && !env["WAYLAND_DISPLAY"].isNullOrEmpty()) env.remove("SDL_VIDEODRIVER")
|
||||
env["LD_PRELOAD"]?.let { preload ->
|
||||
val kept = preload.split(':').filter { it.isNotEmpty() && it != rootfs && !it.startsWith("$rootfs/") }
|
||||
if (kept.isEmpty()) env.remove("LD_PRELOAD") else env["LD_PRELOAD"] = kept.joinToString(":")
|
||||
}
|
||||
}
|
||||
|
||||
private const val GPU_DIR = "/run/droiddeck-gpu"
|
||||
|
||||
private val LIB_DIRS = listOf("usr/lib/aarch64-linux-gnu", "usr/lib")
|
||||
@@ -347,22 +366,201 @@ object BwrapSpawner {
|
||||
try { Os.chmod(f.path, mode) } catch (e: Exception) { }
|
||||
}
|
||||
|
||||
private val SANDBOX_LOADERS = listOf("/usr/lib/aarch64-linux-gnu/ld-linux-aarch64.so.1", "/usr/lib/ld-linux-aarch64.so.1",
|
||||
"/lib/ld-linux-aarch64.so.1", "/lib64/ld-linux-aarch64.so.1")
|
||||
private val SANDBOX_LIBCS = listOf("/usr/lib/aarch64-linux-gnu/libc.so.6", "/usr/lib/libc.so.6", "/lib/aarch64-linux-gnu/libc.so.6")
|
||||
private val SANDBOX_LIB_DIRS = listOf("/app/lib/aarch64-linux-gnu", "/app/lib", "/usr/lib/aarch64-linux-gnu", "/usr/lib")
|
||||
private val seccompPatched = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
|
||||
|
||||
/**
|
||||
* The sandbox started by the runtime's own glibc loader with the native hook, which maps the
|
||||
* sandbox's mounts; null when the runtime cannot load the hook (older glibc), so proot runs it.
|
||||
*/
|
||||
private fun nativeLaunch(context: Context, plan: Plan): Pair<List<String>, Map<String, String>>? {
|
||||
val rootfs = LinuxRuntime.rootDir(context)
|
||||
val sandbox = plan.root.path
|
||||
fun host(guest: String) = File(hostPath(plan.binds, sandbox, guest))
|
||||
if (!hasEnvTool(plan)) {
|
||||
val program = plan.argv.firstOrNull()?.takeIf { it.startsWith("/") }?.let(::host)?.canonicalFile
|
||||
?.takeIf { it.isFile && isStaticElf(it) } ?: return null
|
||||
if (!linkMounts(plan)) return null
|
||||
return (listOf(program.path) + plan.argv.drop(1)) to plan.env
|
||||
}
|
||||
val loader = SANDBOX_LOADERS.map(::host).firstOrNull { it.isFile }?.canonicalFile ?: return null
|
||||
val libc = SANDBOX_LIBCS.map(::host).firstOrNull { it.isFile }?.canonicalFile ?: return null
|
||||
val hook = NativeGuest.hook(rootfs)
|
||||
val need = glibcMinor(hook, GLIBC_NEED) { it.maxOrNull() } ?: return null
|
||||
val have = glibcMinor(libc, GLIBC_RELEASE) { it.firstOrNull() } ?: return null
|
||||
if (have < need) {
|
||||
Log.i(TAG, "native userland: this runtime's glibc 2.$have cannot load the hook (2.$need); proot runs the sandbox")
|
||||
return null
|
||||
}
|
||||
for (file in listOf(loader, libc)) {
|
||||
val key = "${file.path}:${file.length()}:${file.lastModified()}"
|
||||
if (key in seccompPatched) continue
|
||||
// an unpatched loader or libc dies under Android's filter before the hook loads: proot runs it
|
||||
val patched = runCatching { ElfSeccompPatch.patchFile(file) }
|
||||
.onFailure { Log.e(TAG, "native userland: could not patch $file for Android's seccomp filter; proot runs the sandbox", it) }
|
||||
if (patched.isFailure) return null
|
||||
seccompPatched.add("${file.path}:${file.length()}:${file.lastModified()}")
|
||||
}
|
||||
val program = host(plan.envTool).canonicalFile.takeIf { it.isFile } ?: return null
|
||||
if (!linkMounts(plan)) return null
|
||||
writeRunpathConf(plan, ::host)
|
||||
val launch = listOf(loader.path, "--argv0", program.name, program.path, "-i") +
|
||||
plan.env.map { (k, v) -> "$k=$v" } + plan.argv
|
||||
val env = linkedMapOf(
|
||||
"DDNATV_ROOT" to sandbox,
|
||||
"DDNATV_LINK_ROOT" to rootfs.path,
|
||||
"DDNATV_BINDS" to plan.binds.joinToString("|") { "${it.host}:${it.guest}" },
|
||||
"DDNATV_HOSTNAME" to SessionPrefs.guestHostname(context),
|
||||
"LD_LIBRARY_PATH" to SANDBOX_LIB_DIRS.map(::host).filter { it.isDirectory }.joinToString(":") { it.path },
|
||||
"LD_PRELOAD" to hook.path,
|
||||
).filterValues { it.isNotEmpty() }
|
||||
return (NativeGuest.simulator(rootfs)?.let { it + launch } ?: launch) to env
|
||||
}
|
||||
|
||||
private val runpathDirs = java.util.concurrent.ConcurrentHashMap<String, List<String>>()
|
||||
|
||||
/**
|
||||
* ld.so opens a library's absolute RUNPATH (libpulse's pulseaudio/ directory) without the hook,
|
||||
* on Android's own filesystem, so those directories are listed for the hook in the sandbox's
|
||||
* ld.so.conf too, as [NativeGuest.syncLibraryDirs] does for the rootfs. A checkout never changes.
|
||||
*/
|
||||
private fun writeRunpathConf(plan: Plan, host: (String) -> File) {
|
||||
val confDir = inRoot(plan.root, "/run/flatpak/ld.so.conf.d")?.takeIf { it.isDirectory } ?: return
|
||||
val dirs = sortedSetOf<String>()
|
||||
for (top in listOf("/usr/lib", "/app/lib")) {
|
||||
val real = host(top).takeIf { it.isDirectory }?.canonicalFile ?: continue
|
||||
dirs += runpathDirs.getOrPut(real.path) {
|
||||
real.walkTopDown().maxDepth(4).onEnter { !Files.isSymbolicLink(it.toPath()) }
|
||||
.filter { it.isFile && ".so" in it.name && !Files.isSymbolicLink(it.toPath()) }
|
||||
.flatMap { runCatching { ElfRunpath.read(it) }.getOrDefault(emptyList()) }
|
||||
.filter { it.startsWith("/usr/") || it.startsWith("/app/") || it.startsWith("/lib") }
|
||||
.distinct().toList()
|
||||
}
|
||||
}
|
||||
if (dirs.isEmpty()) return
|
||||
runCatching { File(confDir, "runtime-999-droiddeck-runpath.conf").writeText(dirs.joinToString("\n", postfix = "\n")) }
|
||||
}
|
||||
|
||||
/** A runtime extension's apply_extra runs in a sandbox with nothing but the extension itself. */
|
||||
private fun hasEnvTool(plan: Plan): Boolean =
|
||||
File(hostPath(plan.binds, plan.root.path, plan.envTool)).let { it.exists() || Files.isSymbolicLink(it.toPath()) }
|
||||
|
||||
internal fun isStaticElf(file: File): Boolean = try {
|
||||
java.io.RandomAccessFile(file, "r").use { f ->
|
||||
val head = ByteArray(64).also { f.readFully(it) }
|
||||
if (head[0] != 0x7f.toByte() || head[1] != 'E'.code.toByte() || head[4] != 2.toByte() || head[5] != 1.toByte()) return false
|
||||
val le = java.nio.ByteBuffer.wrap(head).order(java.nio.ByteOrder.LITTLE_ENDIAN)
|
||||
val phoff = le.getLong(32)
|
||||
val phentsize = le.getShort(54).toInt() and 0xffff
|
||||
val phnum = le.getShort(56).toInt() and 0xffff
|
||||
val entry = ByteArray(4)
|
||||
(0 until phnum).none { i ->
|
||||
f.seek(phoff + i.toLong() * phentsize)
|
||||
f.readFully(entry)
|
||||
java.nio.ByteBuffer.wrap(entry).order(java.nio.ByteOrder.LITTLE_ENDIAN).int == 3 // PT_INTERP
|
||||
}
|
||||
}
|
||||
} catch (_: java.io.IOException) {
|
||||
false
|
||||
}
|
||||
|
||||
/**
|
||||
* The kernel follows paths the hook does not see (ld.so, symbolic links), so each top-level
|
||||
* mount of the sandbox is also a link to its source in the sandbox's own root, and the
|
||||
* sandbox's links with absolute guest targets are made relative, which reaches them through those.
|
||||
* False when a mount's place could not be made; proot then runs the sandbox, whose mounts hide
|
||||
* whatever was left at their places.
|
||||
*/
|
||||
private fun linkMounts(plan: Plan): Boolean {
|
||||
val root = plan.root.toPath()
|
||||
plan.root.walkTopDown().onEnter { !Files.isSymbolicLink(it.toPath()) }.map { it.toPath() }
|
||||
.filter { Files.isSymbolicLink(it) }.toList().forEach { link ->
|
||||
runCatching {
|
||||
val target = Files.readSymbolicLink(link).toString()
|
||||
if (!target.startsWith("/")) return@runCatching
|
||||
Files.delete(link)
|
||||
Files.createSymbolicLink(link, link.parent.relativize(root.resolve(target.removePrefix("/"))))
|
||||
}
|
||||
}
|
||||
// a mount inside another mount (a GL extension at /usr/lib/aarch64-linux-gnu/GL) needs its own
|
||||
// place: the links of the mounts it is in become directories of links to their entries
|
||||
val entryLinks = HashSet<java.nio.file.Path>()
|
||||
for (bind in plan.binds.sortedBy { it.guest.length }) {
|
||||
if (bind.guest == "/") continue
|
||||
val at = try {
|
||||
mountPlace(plan.root, bind.guest, entryLinks)?.also { at ->
|
||||
val path = at.toPath()
|
||||
if (path in entryLinks) {
|
||||
Files.delete(path)
|
||||
entryLinks.remove(path)
|
||||
}
|
||||
}
|
||||
} catch (e: java.io.IOException) {
|
||||
Log.e(TAG, "native userland: could not make a place for ${bind.guest}; proot runs the sandbox", e)
|
||||
return false
|
||||
} ?: continue
|
||||
val path = at.toPath()
|
||||
if (at.exists() || Files.isSymbolicLink(path)) continue
|
||||
at.parentFile?.mkdirs()
|
||||
runCatching { Files.createSymbolicLink(path, java.nio.file.Paths.get(bind.host)) }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun mountPlace(root: File, guest: String, entryLinks: MutableSet<java.nio.file.Path>): File? {
|
||||
val parts = guest.split('/').filter { it.isNotEmpty() }
|
||||
var f = root
|
||||
for ((i, part) in parts.withIndex()) {
|
||||
if (part == "..") return null
|
||||
f = File(f, part)
|
||||
val path = f.toPath()
|
||||
if (i == parts.lastIndex || !Files.isSymbolicLink(path)) continue
|
||||
val target = Files.readSymbolicLink(path)
|
||||
// a link of the sandbox's own tree, made relative above, is not a mount
|
||||
if (!target.isAbsolute) return null
|
||||
Files.delete(path)
|
||||
entryLinks.remove(path)
|
||||
Files.createDirectory(path)
|
||||
target.toFile().listFiles()?.forEach { entry ->
|
||||
val link = path.resolve(entry.name)
|
||||
Files.createSymbolicLink(link, entry.toPath())
|
||||
entryLinks.add(link)
|
||||
}
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) {
|
||||
val cmd = LinuxRuntime.prootPrefix(context, plan.root, plan.cwd)
|
||||
val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull()
|
||||
if (verbose != null) { cmd.add(1, "-v"); cmd.add(2, verbose.toString()) }
|
||||
plan.binds.forEach { cmd.add("-b"); cmd.add(it.spec) }
|
||||
cmd.add(plan.envTool)
|
||||
cmd.add("-i")
|
||||
plan.env.forEach { (k, v) -> cmd.add("$k=$v") }
|
||||
cmd.addAll(plan.argv)
|
||||
val builder = ProcessBuilder(cmd).redirectErrorStream(true).directory(plan.root)
|
||||
builder.environment().apply {
|
||||
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) }
|
||||
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 cmd = LinuxRuntime.prootPrefix(context, plan.root, plan.cwd)
|
||||
if (verbose != null) { cmd.add(1, "-v"); cmd.add(2, verbose.toString()) }
|
||||
plan.binds.forEach { cmd.add("-b"); cmd.add(it.spec) }
|
||||
val envTool = hasEnvTool(plan)
|
||||
if (envTool) {
|
||||
cmd.add(plan.envTool)
|
||||
cmd.add("-i")
|
||||
plan.env.forEach { (k, v) -> cmd.add("$k=$v") }
|
||||
}
|
||||
cmd.addAll(plan.argv)
|
||||
ProcessBuilder(cmd).redirectErrorStream(true).directory(plan.root).also { b ->
|
||||
b.environment().apply {
|
||||
clear()
|
||||
if (!envTool) putAll(plan.env)
|
||||
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) }
|
||||
}
|
||||
}
|
||||
}
|
||||
val process = builder.start()
|
||||
val pid = HostProcess.pidOf(process)
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/** The absolute DT_RUNPATH and DT_RPATH directories of a 64-bit little-endian ELF object. */
|
||||
object ElfRunpath {
|
||||
private const val PT_LOAD = 1
|
||||
private const val PT_DYNAMIC = 2
|
||||
private const val DT_STRTAB = 5
|
||||
private const val DT_RPATH = 15
|
||||
private const val DT_RUNPATH = 29
|
||||
|
||||
fun read(file: File): List<String> {
|
||||
if (file.length() < 64) return emptyList()
|
||||
RandomAccessFile(file, "r").use { raf ->
|
||||
val channel = raf.channel
|
||||
val header = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN)
|
||||
channel.read(header, 0)
|
||||
if (header.getInt(0) != 0x464c457f || header.get(4).toInt() != 2 || header.get(5).toInt() != 1) return emptyList()
|
||||
val phoff = header.getLong(32)
|
||||
val phentsize = header.getShort(54).toInt() and 0xffff
|
||||
val phnum = header.getShort(56).toInt() and 0xffff
|
||||
if (phnum == 0 || phnum > 128 || phentsize < 56) return emptyList()
|
||||
val table = ByteBuffer.allocate(phentsize * phnum).order(ByteOrder.LITTLE_ENDIAN)
|
||||
channel.read(table, phoff)
|
||||
class Load(val vaddr: Long, val offset: Long, val size: Long)
|
||||
val loads = ArrayList<Load>()
|
||||
var dynOffset = -1L
|
||||
var dynSize = 0L
|
||||
for (i in 0 until phnum) {
|
||||
val at = i * phentsize
|
||||
val type = table.getInt(at)
|
||||
val offset = table.getLong(at + 8)
|
||||
val vaddr = table.getLong(at + 16)
|
||||
val filesz = table.getLong(at + 32)
|
||||
if (type == PT_LOAD) loads.add(Load(vaddr, offset, filesz))
|
||||
if (type == PT_DYNAMIC) { dynOffset = offset; dynSize = filesz }
|
||||
}
|
||||
if (dynOffset < 0 || dynSize <= 0 || dynSize > 1 shl 20) return emptyList()
|
||||
val dynamic = ByteBuffer.allocate(dynSize.toInt()).order(ByteOrder.LITTLE_ENDIAN)
|
||||
channel.read(dynamic, dynOffset)
|
||||
var strtab = -1L
|
||||
val names = ArrayList<Long>()
|
||||
var at = 0
|
||||
while (at + 16 <= dynamic.capacity()) {
|
||||
val tag = dynamic.getLong(at)
|
||||
val value = dynamic.getLong(at + 8)
|
||||
if (tag == 0L) break
|
||||
if (tag == DT_STRTAB.toLong()) strtab = value
|
||||
if (tag == DT_RPATH.toLong() || tag == DT_RUNPATH.toLong()) names.add(value)
|
||||
at += 16
|
||||
}
|
||||
if (strtab < 0 || names.isEmpty()) return emptyList()
|
||||
val strtabOffset = loads.firstOrNull { strtab >= it.vaddr && strtab < it.vaddr + it.size }
|
||||
?.let { strtab - it.vaddr + it.offset } ?: return emptyList()
|
||||
val result = ArrayList<String>()
|
||||
for (name in names) {
|
||||
val buffer = ByteBuffer.allocate(4096)
|
||||
val n = channel.read(buffer, strtabOffset + name)
|
||||
if (n <= 0) continue
|
||||
val bytes = buffer.array()
|
||||
var end = 0
|
||||
while (end < n && bytes[end].toInt() != 0) end++
|
||||
String(bytes, 0, end, Charsets.UTF_8).split(':').filter { it.startsWith("/") }.forEach { result.add(it.trimEnd('/')) }
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import java.io.File
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/**
|
||||
* Android's app seccomp filter kills a process with SIGSYS for rseq, set_robust_list and clone3. glibc's
|
||||
* dynamic linker makes the first two before any preloaded library (so before the hook's SIGSYS
|
||||
* handler) exists, so the call sites in the rootfs's ld.so and libc answer by themselves instead: the
|
||||
* `svc` after `mov x8, #nr` becomes a no-op for set_robust_list (glibc ignores the result) and
|
||||
* `mov x0, #-ENOSYS` for rseq and clone3 (glibc falls back from both). Under proot the same
|
||||
* answers are what proot gives.
|
||||
*/
|
||||
object ElfSeccompPatch {
|
||||
private const val SVC = 0xd4000001.toInt()
|
||||
private const val NOP = 0xd503201f.toInt()
|
||||
private const val MOV_X0_ENOSYS = 0x928004a0.toInt()
|
||||
private const val MOV_X8_SET_ROBUST_LIST = 0xd2800c68.toInt()
|
||||
private const val MOV_X8_CLONE3 = 0xd2803668.toInt()
|
||||
private const val MOV_X8_RSEQ = 0xd28024a8.toInt()
|
||||
private const val WINDOW = 16
|
||||
|
||||
/** Patches [data] in place and returns the number of call sites changed. */
|
||||
fun patch(data: ByteArray): Int {
|
||||
if (data.size < 64 || data[0] != 0x7f.toByte() || data[1] != 'E'.code.toByte() || data[4].toInt() != 2 || data[5].toInt() != 1) return 0
|
||||
val buffer = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN)
|
||||
if (buffer.getShort(18).toInt() != 183) return 0
|
||||
val phoff = buffer.getLong(32).toInt()
|
||||
val phentsize = buffer.getShort(54).toInt() and 0xffff
|
||||
val phnum = buffer.getShort(56).toInt() and 0xffff
|
||||
var patched = 0
|
||||
for (i in 0 until phnum) {
|
||||
val at = phoff + i * phentsize
|
||||
if (at + 56 > data.size) break
|
||||
if (buffer.getInt(at) != 1 || (buffer.getInt(at + 4) and 1) == 0) continue
|
||||
val start = ((buffer.getLong(at + 8).toInt()) + 3) and 3.inv()
|
||||
val end = minOf(data.size, buffer.getLong(at + 8).toInt() + buffer.getLong(at + 32).toInt()) and 3.inv()
|
||||
var pos = start
|
||||
while (pos + 4 <= end) {
|
||||
val replacement = when (buffer.getInt(pos)) {
|
||||
MOV_X8_SET_ROBUST_LIST -> NOP
|
||||
MOV_X8_CLONE3, MOV_X8_RSEQ -> MOV_X0_ENOSYS
|
||||
else -> null
|
||||
}
|
||||
if (replacement != null) {
|
||||
var next = pos + 4
|
||||
val limit = minOf(end, pos + 4 + WINDOW * 4)
|
||||
while (next < limit) {
|
||||
val insn = buffer.getInt(next)
|
||||
if (insn == SVC) {
|
||||
buffer.putInt(next, replacement)
|
||||
patched++
|
||||
break
|
||||
}
|
||||
// A site patched before, or x8 set again: an svc after it is another call's
|
||||
// (a second run found clone3's thread exit there and turned it into -ENOSYS)
|
||||
if (insn == MOV_X0_ENOSYS || (insn and 0x1f) == 8) break
|
||||
next += 4
|
||||
}
|
||||
}
|
||||
pos += 4
|
||||
}
|
||||
}
|
||||
return patched
|
||||
}
|
||||
|
||||
/** Patches the file behind [path] (symlinks followed) if it still has unpatched call sites. */
|
||||
fun patchFile(path: File): Int {
|
||||
val target = path.canonicalFile
|
||||
if (!target.isFile) return 0
|
||||
val data = target.readBytes()
|
||||
val count = patch(data)
|
||||
if (count == 0) return 0
|
||||
val temp = File(target.parentFile, "." + target.name + ".seccomp")
|
||||
temp.writeBytes(data)
|
||||
temp.setExecutable(true, false)
|
||||
temp.setReadable(true, false)
|
||||
if (!temp.renameTo(target)) {
|
||||
temp.delete()
|
||||
throw java.io.IOException("could not replace ${target.path}")
|
||||
}
|
||||
return count
|
||||
}
|
||||
}
|
||||
@@ -35,12 +35,10 @@ object GuestCommand {
|
||||
SessionFiles.stage(context, root)
|
||||
LinuxNetworkLinkComponent(context, root).publish()
|
||||
val runtimeDir = File(context.filesDir, ".flatpak-rt").apply { mkdirs() }
|
||||
val cmd = LinuxRuntime.prootPrefix(context, root, "/root", fakeRoot)
|
||||
if (linkDir != null) cmd.add(1, "--link2symlink")
|
||||
val binds = LinuxRuntime.binds(context, null, runtimeDir, Environment.getExternalStorageDirectory(), extraBinds)
|
||||
binds.forEach { cmd.add("-b"); cmd.add(it) }
|
||||
val fastPathKey = if (fastPath && !fakeRoot && linkDir == null && ProotFastPath.enabled(context)) ProotFastPath.key(root, binds) else null
|
||||
cmd += listOf(
|
||||
val native = NativeGuest.forSession(context)
|
||||
val fastPathKey = if (!native && fastPath && !fakeRoot && linkDir == null && ProotFastPath.enabled(context)) ProotFastPath.key(root, binds) else null
|
||||
val guest = mutableListOf(
|
||||
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "LANG=C.UTF-8",
|
||||
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games", "XDG_RUNTIME_DIR=${LinuxRuntime.GUEST_RUNTIME_DIR}",
|
||||
"XDG_DATA_HOME=/root/.local/share", "FLATPAK_BWRAP=${FlatpakManager.BWRAP}",
|
||||
@@ -48,22 +46,31 @@ object GuestCommand {
|
||||
"XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share",
|
||||
)
|
||||
DownloadSource.proxyHostPort(context).takeIf { it.isNotEmpty() }?.let { hostPort ->
|
||||
cmd += listOf(
|
||||
guest += listOf(
|
||||
"http_proxy=http://$hostPort", "https_proxy=http://$hostPort",
|
||||
"HTTP_PROXY=http://$hostPort", "HTTPS_PROXY=http://$hostPort",
|
||||
"no_proxy=localhost,127.0.0.1,::1", "NO_PROXY=localhost,127.0.0.1,::1",
|
||||
)
|
||||
}
|
||||
fastPathKey?.let { cmd += ProotFastPath.guestEnv(root, binds, it) }
|
||||
cmd += argv
|
||||
val builder = ProcessBuilder(cmd).directory(root).redirectErrorStream(true)
|
||||
builder.environment().apply {
|
||||
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) }
|
||||
fastPathKey?.let { guest += ProotFastPath.guestEnv(root, binds, it) }
|
||||
guest += argv
|
||||
val builder = if (native) {
|
||||
NativeGuest.processBuilder(context, root, binds, guest).redirectErrorStream(true)
|
||||
} else {
|
||||
val cmd = LinuxRuntime.prootPrefix(context, root, "/root", fakeRoot)
|
||||
if (linkDir != null) cmd.add(1, "--link2symlink")
|
||||
binds.forEach { cmd.add("-b"); cmd.add(it) }
|
||||
cmd += guest
|
||||
ProcessBuilder(cmd).directory(root).redirectErrorStream(true).also { b ->
|
||||
b.environment().apply {
|
||||
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) }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cancelled?.get() == true) return 130
|
||||
val process = builder.start()
|
||||
|
||||
@@ -155,6 +155,11 @@ public final class LinuxRuntime {
|
||||
|
||||
private static volatile List<String> lastBinds;
|
||||
|
||||
/** The mounts of a session started without proot, which sandboxes and root helpers see too. */
|
||||
public static void rememberSessionBinds(List<String> binds) {
|
||||
lastBinds = binds;
|
||||
}
|
||||
|
||||
public static List<String> lastBinds(Context context) {
|
||||
List<String> binds = lastBinds;
|
||||
if (binds != null) return binds;
|
||||
@@ -306,7 +311,17 @@ public final class LinuxRuntime {
|
||||
|
||||
private static boolean unreadablePciDevice() {
|
||||
File[] devices = new File("/sys/bus/pci/devices").listFiles();
|
||||
if (devices == null) return false;
|
||||
if (devices == null) {
|
||||
// The directory is there but the app may not list it (Android 13 on the AYN Thor): libpci then
|
||||
// aborts the whole program with "Cannot open /sys/bus/pci/devices", which Chromium's GPU
|
||||
// initialisation runs into. Not there at all (no PCI bus) is fine as it is.
|
||||
try {
|
||||
android.system.Os.stat("/sys/bus/pci/devices");
|
||||
return true;
|
||||
} catch (android.system.ErrnoException e) {
|
||||
return e.errno == android.system.OsConstants.EACCES;
|
||||
}
|
||||
}
|
||||
for (File device : devices) {
|
||||
if (!new File(device, "vendor").canRead()) return true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
|
||||
/**
|
||||
* Starts guest programs directly on the Android kernel, with no proot: the glibc loader of the
|
||||
* rootfs runs the program and [HOOK] translates the guest's absolute paths, execs and the system
|
||||
* calls Android's seccomp policy blocks, from inside the process.
|
||||
*/
|
||||
object NativeGuest {
|
||||
private const val TAG = "NativeGuest"
|
||||
const val HOOK = "usr/lib/libddnatv-hook.so"
|
||||
private val LIB_DIRS = listOf("usr/lib", "usr/lib/aarch64-linux-gnu", "usr/local/lib", "usr/lib/systemd")
|
||||
|
||||
/** Libraries every native program loads before the hook, as /etc/ld.so.preload does for proot. */
|
||||
fun preloadList(root: File): List<String> {
|
||||
val listed = File(root, "etc/droiddeck/native-preload").takeIf { it.isFile }?.readLines().orEmpty()
|
||||
return listed.map { it.trim() }.filter { it.startsWith("/") && File(root, it.removePrefix("/")).isFile }
|
||||
}
|
||||
|
||||
fun enabled(context: Context): Boolean =
|
||||
SessionPrefs.nativeUserland(context) && available(LinuxRuntime.rootDir(context))
|
||||
|
||||
/** The mode the running session started in; null between sessions. */
|
||||
@Volatile var sessionMode: Boolean? = null
|
||||
|
||||
/**
|
||||
* Whether a session's helpers (root commands, Flatpak sandboxes, installers) run natively: the
|
||||
* 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)
|
||||
|
||||
/**
|
||||
* Development switch: etc/droiddeck/seccomp-sim names a helper (a guest path, then its arguments)
|
||||
* that applies Android's app seccomp filter before the program starts, for devices that run apps
|
||||
* without one (eng builds, or a permissive SELinux, where zygote skips it). Guest paths among the
|
||||
* arguments are given as their places in the rootfs, as the helper runs before the hook.
|
||||
*/
|
||||
fun simulator(root: File): List<String>? {
|
||||
val words = File(root, "etc/droiddeck/seccomp-sim").takeIf { it.isFile }?.readText()?.trim()
|
||||
?.split(Regex("\\s+"))?.filter { it.isNotEmpty() } ?: return null
|
||||
val helper = words.firstOrNull()?.takeIf { it.startsWith("/") }?.let { File(root, it.removePrefix("/")) }
|
||||
?.takeIf { it.isFile } ?: return null
|
||||
return listOf(helper.path) + words.drop(1).map { if (it.startsWith("/")) File(root, it.removePrefix("/")).path else it }
|
||||
}
|
||||
|
||||
fun hook(root: File): File = File(root, HOOK)
|
||||
|
||||
fun loader(root: File): File? =
|
||||
listOf("usr/lib/ld-linux-aarch64.so.1", "lib/ld-linux-aarch64.so.1").map { File(root, it) }.firstOrNull { it.exists() }
|
||||
|
||||
fun available(root: File): Boolean = hook(root).isFile && loader(root) != null
|
||||
|
||||
fun libraryPath(root: File): String = LIB_DIRS.joinToString(":") { File(root, it).path }
|
||||
|
||||
/** Environment every native process starts with; a guest `env -i` is re-seeded by the hook. */
|
||||
fun environment(root: File, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf(
|
||||
"DDNATV_ROOT" to root.path,
|
||||
"LD_LIBRARY_PATH" to libraryPath(root),
|
||||
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
|
||||
)
|
||||
|
||||
/**
|
||||
* The host command line for the guest program at [program] (an absolute guest path to a real
|
||||
* file, not a symlink).
|
||||
*/
|
||||
fun command(root: File, program: String, args: List<String>): List<String> {
|
||||
val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" }
|
||||
val host = File(root, program.removePrefix("/"))
|
||||
val launch = listOf(loader.path, "--argv0", host.name, host.path) + args
|
||||
return simulator(root)?.let { it + launch } ?: launch
|
||||
}
|
||||
|
||||
/** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */
|
||||
fun sessionEnvironment(root: File, binds: List<String>, hostname: String? = null): Map<String, String> {
|
||||
val preload = preloadList(root)
|
||||
return linkedMapOf(
|
||||
"DDNATV_ROOT" to root.path,
|
||||
"DDNATV_HOSTNAME" to hostname.orEmpty(),
|
||||
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
|
||||
"DDNATV_PRELOAD" to preload.joinToString(":"),
|
||||
"LD_LIBRARY_PATH" to libraryPath(root),
|
||||
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
|
||||
).filterValues { it.isNotEmpty() }
|
||||
}
|
||||
|
||||
/** Where guest directory [cwd] is, through the session's mounts ([binds], "src:dst"); the rootfs if it is nowhere. */
|
||||
fun workingDirectory(root: File, binds: List<String>, cwd: String): File =
|
||||
File(BwrapSpawner.hostPath(binds.map { BwrapSpawner.Bind.parse(it) }, root.path, cwd)).takeIf { it.isDirectory } ?: root
|
||||
|
||||
/** A process for [guest] (argv) started as proot would with [binds], in guest directory [cwd]. */
|
||||
fun processBuilder(context: Context, root: File, binds: List<String>, guest: List<String>, cwd: String = "/root"): ProcessBuilder =
|
||||
ProcessBuilder(command(root, guest.first(), guest.drop(1)))
|
||||
.directory(workingDirectory(root, binds, cwd))
|
||||
.also { builder ->
|
||||
builder.environment().apply {
|
||||
remove("LD_AUDIT")
|
||||
putAll(sessionEnvironment(root, binds, SessionPrefs.guestHostname(context)))
|
||||
}
|
||||
}
|
||||
|
||||
private const val RUNPATH_CONF = "etc/ld.so.conf.d/zz-droiddeck-native.conf"
|
||||
private val SCAN_DIRS = listOf("usr/lib", "usr/local/lib", "opt")
|
||||
|
||||
/**
|
||||
* ld.so opens the absolute RUNPATH directories of a library itself, with system calls the hook
|
||||
* cannot translate, so every one of them is also listed in ld.so.conf (which the hook maps).
|
||||
* Rescanned when dpkg's state or a library directory changes.
|
||||
*/
|
||||
fun syncLibraryDirs(root: File) {
|
||||
val conf = File(root, RUNPATH_CONF)
|
||||
val signature = (listOf("var/lib/dpkg/status", "usr/lib", "usr/local/lib", "usr/lib/aarch64-linux-gnu")
|
||||
.joinToString(",") { File(root, it).lastModified().toString() }) + "," + conf.parentFile.list()?.size
|
||||
val stamp = File(root, "etc/droiddeck/native-runpath-signature")
|
||||
if (conf.isFile && stamp.isFile && stamp.readText() == signature) return
|
||||
val dirs = sortedSetOf<String>()
|
||||
for (name in SCAN_DIRS) File(root, name).walkTopDown().maxDepth(6)
|
||||
.onEnter { !Files.isSymbolicLink(it.toPath()) }
|
||||
.filter { it.isFile && !Files.isSymbolicLink(it.toPath()) && ".so" in it.name }
|
||||
.forEach { file -> runCatching { ElfRunpath.read(file) }.getOrNull()?.let { dirs.addAll(it) } }
|
||||
val kept = dirs.filter { it.startsWith("/usr") || it.startsWith("/lib") || it.startsWith("/opt") }
|
||||
conf.parentFile?.mkdirs()
|
||||
conf.writeText(kept.joinToString("\n", postfix = "\n"))
|
||||
stamp.parentFile?.mkdirs()
|
||||
stamp.writeText(signature)
|
||||
}
|
||||
|
||||
/** What a rootfs needs before anything runs in it natively; cheap once done. */
|
||||
fun prepare(context: Context, root: File) {
|
||||
val relinked = relinkAbsoluteSymlinks(context, root)
|
||||
if (relinked > 0) android.util.Log.i(TAG, "native userland: $relinked absolute symlinks made relative")
|
||||
val patched = patchForSeccomp(root)
|
||||
if (patched > 0) android.util.Log.i(TAG, "native userland: $patched system call sites in ld.so and libc answer Android's blocked calls")
|
||||
syncLibraryDirs(root)
|
||||
}
|
||||
|
||||
/** See [ElfSeccompPatch]: the linker and libc must survive Android's seccomp filter before the hook loads. */
|
||||
fun patchForSeccomp(root: File): Int =
|
||||
listOf("usr/lib/ld-linux-aarch64.so.1", "usr/lib/aarch64-linux-gnu/ld-linux-aarch64.so.1",
|
||||
"usr/lib/aarch64-linux-gnu/libc.so.6", "usr/lib/libc.so.6")
|
||||
.map { File(root, it) }.filter { it.exists() }
|
||||
.distinctBy { it.canonicalPath }.sumOf { file ->
|
||||
runCatching { ElfSeccompPatch.patchFile(file) }.getOrElse {
|
||||
android.util.Log.e(TAG, "native userland: could not patch $file for Android's seccomp filter; programs will die with SIGSYS", it)
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
private val HOST_LINK_TARGETS = listOf("/proc", "/dev", "/sys", "/sdcard", "/storage", "/data", "/system", "/vendor", "/apex",
|
||||
"/system_ext", "/product", "/odm", "/linkerconfig", "/mnt")
|
||||
|
||||
/**
|
||||
* Symbolic links the kernel follows by itself (ld.so, Steam, anything that skips the hook) read
|
||||
* their absolute target on Android's own filesystem. The image's links were made for proot,
|
||||
* which reads the target inside the rootfs, so each is rewritten as a relative link, which
|
||||
* resolves the same way under proot and without it. Rerun when the runtime changes.
|
||||
*/
|
||||
fun relinkAbsoluteSymlinks(context: Context, root: File): Int {
|
||||
val stamp = File(root, "etc/droiddeck/native-symlinks")
|
||||
val version = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(context).orEmpty() + "/2"
|
||||
if (stamp.isFile && stamp.readText() == version) return 0
|
||||
val rootPath = root.toPath()
|
||||
var rewritten = 0
|
||||
Files.walkFileTree(rootPath, object : java.nio.file.SimpleFileVisitor<java.nio.file.Path>() {
|
||||
override fun visitFile(file: java.nio.file.Path, attrs: java.nio.file.attribute.BasicFileAttributes): java.nio.file.FileVisitResult {
|
||||
if (attrs.isSymbolicLink) {
|
||||
try {
|
||||
val target = Files.readSymbolicLink(file).toString()
|
||||
if (target.startsWith("/") && HOST_LINK_TARGETS.none { target == it || target.startsWith("$it/") }
|
||||
&& !target.startsWith(root.path)) {
|
||||
val relative = file.parent.relativize(rootPath.resolve(target.removePrefix("/")))
|
||||
val temp = file.resolveSibling(".relink-" + file.fileName)
|
||||
Files.deleteIfExists(temp)
|
||||
Files.createSymbolicLink(temp, relative)
|
||||
Files.move(temp, file, java.nio.file.StandardCopyOption.REPLACE_EXISTING)
|
||||
rewritten++
|
||||
}
|
||||
} catch (_: java.io.IOException) {
|
||||
}
|
||||
}
|
||||
return java.nio.file.FileVisitResult.CONTINUE
|
||||
}
|
||||
|
||||
override fun visitFileFailed(file: java.nio.file.Path, exc: java.io.IOException) = java.nio.file.FileVisitResult.CONTINUE
|
||||
})
|
||||
stamp.parentFile?.mkdirs()
|
||||
stamp.writeText(version)
|
||||
return rewritten
|
||||
}
|
||||
|
||||
/**
|
||||
* The guest path that host path [target] stands for in a session with [binds] ("src:dst"), or null
|
||||
* when it is a guest path already: the rootfs, or the longest mount source holding it (the first
|
||||
* such mount when several share a source).
|
||||
*/
|
||||
fun guestLinkTarget(target: String, root: String, binds: List<String>): String? {
|
||||
if (!target.startsWith("/")) return null
|
||||
fun under(path: String, dir: String) = path == dir || path.startsWith("$dir/")
|
||||
var best: Pair<String, String>? = if (under(target, root)) root to "/" else null
|
||||
for (spec in binds) {
|
||||
val colon = spec.indexOf(':')
|
||||
if (colon < 0) continue
|
||||
val src = spec.substring(0, colon).trimEnd('/')
|
||||
val dst = spec.substring(colon + 1).trimEnd('/').ifEmpty { "/" }
|
||||
if (src.isEmpty() || src == dst || !under(target, src)) continue
|
||||
if (best == null || src.length > best.first.length) best = src to dst
|
||||
}
|
||||
val (src, dst) = best ?: return null
|
||||
val rest = target.removePrefix(src)
|
||||
return if (rest.isEmpty()) dst else dst.trimEnd('/') + rest
|
||||
}
|
||||
|
||||
/**
|
||||
* Wine prefixes' drive links (dosdevices) hold guest paths ("s:" -> /mnt/droiddeck-sd), which
|
||||
* proot follows and the hook follows inside a mount. Earlier native sessions made them point at
|
||||
* their real places, which proot cannot see: those are given their guest paths back.
|
||||
*/
|
||||
fun relinkPrefixDrives(root: File, binds: List<String>): Int {
|
||||
val compatdata = listOf(File(root, "root/.local/share/Steam/steamapps/compatdata")) + binds.mapNotNull { spec ->
|
||||
val colon = spec.indexOf(':')
|
||||
if (colon > 0 && spec.substring(colon + 1).trimEnd('/').endsWith("/steamapps/compatdata")) File(spec.substring(0, colon)) else null
|
||||
}
|
||||
var rewritten = 0
|
||||
for (prefix in compatdata.distinct().flatMap { it.listFiles()?.toList().orEmpty() }) {
|
||||
val devices = File(prefix, "pfx/dosdevices").toPath()
|
||||
val links = try {
|
||||
Files.newDirectoryStream(devices).use { it.toList() }
|
||||
} catch (e: java.nio.file.NoSuchFileException) {
|
||||
continue
|
||||
} catch (e: java.io.IOException) {
|
||||
android.util.Log.w(TAG, "native userland: could not read the drive links of $prefix", e)
|
||||
continue
|
||||
} catch (e: java.nio.file.DirectoryIteratorException) {
|
||||
android.util.Log.w(TAG, "native userland: could not read the drive links of $prefix", e)
|
||||
continue
|
||||
}
|
||||
for (link in links) {
|
||||
try {
|
||||
if (!Files.isSymbolicLink(link)) continue
|
||||
val guest = guestLinkTarget(Files.readSymbolicLink(link).toString(), root.path, binds) ?: continue
|
||||
val temp = link.resolveSibling(".relink-" + link.fileName)
|
||||
Files.deleteIfExists(temp)
|
||||
Files.createSymbolicLink(temp, java.nio.file.Paths.get(guest))
|
||||
Files.move(temp, link, java.nio.file.StandardCopyOption.REPLACE_EXISTING)
|
||||
rewritten++
|
||||
} catch (_: java.io.IOException) {
|
||||
}
|
||||
}
|
||||
}
|
||||
return rewritten
|
||||
}
|
||||
|
||||
fun builder(root: File, cwd: String, argv: List<String>, env: Map<String, String>, preload: List<String> = emptyList()): ProcessBuilder {
|
||||
val program = argv.first()
|
||||
val cmd = command(root, program, argv.drop(1))
|
||||
val builder = ProcessBuilder(cmd).redirectErrorStream(false)
|
||||
builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root)
|
||||
builder.environment().apply {
|
||||
clear()
|
||||
putAll(environment(root, preload))
|
||||
putAll(env)
|
||||
}
|
||||
return builder
|
||||
}
|
||||
}
|
||||
@@ -12,15 +12,16 @@ object ProotFastPath {
|
||||
const val LIBRARY = "/usr/local/lib/libblfastpath.so"
|
||||
const val MAX_BINDS = 256
|
||||
|
||||
fun allows(preference: Boolean, noSeccomp: Boolean, source: String): Boolean =
|
||||
preference && !noSeccomp && 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): Boolean {
|
||||
val preference = SessionPrefs.prootFastPath(context)
|
||||
val noSeccomp = SessionPrefs.prootNoSeccomp(context)
|
||||
val nativeUserland = SessionPrefs.nativeUserland(context)
|
||||
val source = LinuxRuntime.prootSource(context)
|
||||
val on = allows(preference, noSeccomp, source)
|
||||
if (preference && !noSeccomp && !on)
|
||||
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
|
||||
}
|
||||
|
||||
@@ -113,20 +113,26 @@ object RootSpawner {
|
||||
val argv = request.getJSONArray("argv").let { a -> (0 until a.length()).map { a.getString(it) } }
|
||||
if (argv.isEmpty()) throw IOException("no command")
|
||||
val cwd = request.optString("cwd", "/root").ifEmpty { "/root" }
|
||||
val cmd = LinuxRuntime.prootPrefix(context, root, cwd, true)
|
||||
cmd.add(1, "--link2symlink")
|
||||
LinuxRuntime.lastBinds(context).filterNot { it.startsWith("/proc/self/fd/") }.forEach { cmd.add("-b"); cmd.add(it) }
|
||||
cmd.add("/usr/bin/env")
|
||||
cmd.add("-i")
|
||||
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> cmd.add("$k=${e.getString(k)}") } }
|
||||
cmd.addAll(argv)
|
||||
val builder = ProcessBuilder(cmd).directory(root)
|
||||
builder.environment().apply {
|
||||
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) }
|
||||
val binds = LinuxRuntime.lastBinds(context).filterNot { it.startsWith("/proc/self/fd/") }
|
||||
val guest = mutableListOf("/usr/bin/env", "-i")
|
||||
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> guest.add("$k=${e.getString(k)}") } }
|
||||
guest.addAll(argv)
|
||||
val builder = if (NativeGuest.forSession(context)) {
|
||||
NativeGuest.processBuilder(context, root, binds, guest, cwd)
|
||||
} else {
|
||||
val cmd = LinuxRuntime.prootPrefix(context, root, cwd, true)
|
||||
cmd.add(1, "--link2symlink")
|
||||
binds.forEach { cmd.add("-b"); cmd.add(it) }
|
||||
cmd.addAll(guest)
|
||||
ProcessBuilder(cmd).directory(root).also { b ->
|
||||
b.environment().apply {
|
||||
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) }
|
||||
}
|
||||
}
|
||||
}
|
||||
val streams = listOf(stdio(fds.getOrNull(0), false), stdio(fds.getOrNull(1), true), stdio(fds.getOrNull(2), true))
|
||||
try {
|
||||
|
||||
@@ -39,6 +39,7 @@ object BottomDesktop {
|
||||
val sessionDir: File,
|
||||
val generation: Int,
|
||||
val installed: Boolean,
|
||||
val nativeUserland: Boolean,
|
||||
)
|
||||
|
||||
@Volatile private var launch: Launch? = null
|
||||
@@ -89,10 +90,11 @@ object BottomDesktop {
|
||||
root: File,
|
||||
sessionDir: File,
|
||||
generation: Int,
|
||||
nativeUserland: Boolean,
|
||||
stillCurrent: () -> Boolean,
|
||||
) {
|
||||
val prepared = Launch(ArrayList(guest), ArrayList(binds), sessionRoot, hostEnvironment.copyOf(), root, sessionDir, generation,
|
||||
DesktopCatalog.desktopInstalled(root))
|
||||
DesktopCatalog.desktopInstalled(root), nativeUserland)
|
||||
synchronized(launchLock) { if (stillCurrent()) launch = prepared }
|
||||
}
|
||||
|
||||
@@ -320,9 +322,17 @@ object BottomDesktop {
|
||||
add("BL_IME_DIR=" + imeDir.path)
|
||||
add(SCRIPT)
|
||||
}
|
||||
val command = LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
|
||||
val command = if (current.nativeUserland) {
|
||||
com.droiddeck.launcher.runtime.NativeGuest.command(current.root, guest.first(), guest.drop(1))
|
||||
} else {
|
||||
LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
|
||||
}
|
||||
val environment = if (current.nativeUserland) {
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, SessionPrefs.guestHostname(context))
|
||||
.map { (k, v) -> "$k=$v" }.toTypedArray()
|
||||
} else current.hostEnvironment
|
||||
val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
|
||||
val pid = HostProcess.start(line, current.hostEnvironment, current.root, { status ->
|
||||
val pid = HostProcess.start(line, environment, current.root, { status ->
|
||||
main.post {
|
||||
if (generation != guestGeneration) return@post
|
||||
Log.i(TAG, "the desktop ended ($status)")
|
||||
|
||||
@@ -283,14 +283,20 @@ object ProtonExtras {
|
||||
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share",
|
||||
"/usr/local/bin/droiddeck-proton-extra", "/root/.local/share/Steam", archive.absolutePath,
|
||||
)
|
||||
val command = LinuxRuntime.command(context, null, runtimeDir, null, guest)
|
||||
val process = ProcessBuilder(command)
|
||||
.directory(root)
|
||||
.redirectErrorStream(true)
|
||||
val hostEnv = process.environment()
|
||||
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(context).path
|
||||
hostEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(context).path
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { hostEnv["LD_LIBRARY_PATH"] = it }
|
||||
val process = if (com.droiddeck.launcher.runtime.NativeGuest.enabled(context)) {
|
||||
com.droiddeck.launcher.runtime.NativeGuest.processBuilder(context, root,
|
||||
LinuxRuntime.binds(context, null, runtimeDir, null, null), guest).redirectErrorStream(true)
|
||||
} else {
|
||||
ProcessBuilder(LinuxRuntime.command(context, null, runtimeDir, null, guest))
|
||||
.directory(root)
|
||||
.redirectErrorStream(true)
|
||||
.also { builder ->
|
||||
val hostEnv = builder.environment()
|
||||
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(context).path
|
||||
hostEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(context).path
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { hostEnv["LD_LIBRARY_PATH"] = it }
|
||||
}
|
||||
}
|
||||
val child = process.start()
|
||||
var placed: String? = null
|
||||
child.inputStream.bufferedReader().useLines { lines ->
|
||||
|
||||
@@ -83,6 +83,7 @@ object SessionFiles {
|
||||
"libblsession.so" to "usr/local/lib/libblsession.so",
|
||||
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
|
||||
"libblfastpath.so" to "usr/local/lib/libblfastpath.so",
|
||||
"libddnatv-hook.so" to "usr/lib/libddnatv-hook.so",
|
||||
"libblaudit.so" to "usr/local/lib/libblaudit.so",
|
||||
"libssbs.so" to "usr/local/lib/libssbs.so",
|
||||
"usr/local/bin/droiddeck-session" to "usr/local/bin/droiddeck-session",
|
||||
@@ -289,12 +290,16 @@ object SessionFiles {
|
||||
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
|
||||
preload.append("/usr/local/lib/libfakeinput.so\n")
|
||||
}
|
||||
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"), preload.toString())
|
||||
val staged = File(etc, "ld.so.preload.staged")
|
||||
if (!FileUtils.writeString(staged, preload.toString())
|
||||
|| !staged.renameTo(File(etc, "ld.so.preload"))) {
|
||||
|
||||
@@ -752,6 +752,12 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
|
||||
}
|
||||
|
||||
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", false)
|
||||
|
||||
fun setNativeUserland(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("nativeUserland", on).apply()
|
||||
}
|
||||
|
||||
fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
|
||||
|
||||
fun setProotFastPath(context: Context, on: Boolean) {
|
||||
|
||||
@@ -665,6 +665,10 @@ class SessionService : Service() {
|
||||
FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm"))
|
||||
|
||||
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir)
|
||||
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 (ProotFastPath.enabled(this)) {
|
||||
val prootBinds = LinuxRuntime.binds(
|
||||
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds,
|
||||
@@ -681,27 +685,42 @@ class SessionService : Service() {
|
||||
}
|
||||
} else null
|
||||
|
||||
val command = LinuxRuntime.command(
|
||||
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest,
|
||||
)
|
||||
|
||||
val hostEnv = HostEnvironment()
|
||||
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
|
||||
hostEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(this).path
|
||||
if (SessionPrefs.prootNoSeccomp(this)) {
|
||||
hostEnv["PROOT_NO_SECCOMP"] = "1"
|
||||
Log.i(TAG, "proot: seccomp acceleration off by request")
|
||||
val sessionBindSpecs = LinuxRuntime.binds(this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds)
|
||||
val command = if (nativeUserland) {
|
||||
LinuxRuntime.rememberSessionBinds(sessionBindSpecs)
|
||||
com.droiddeck.launcher.runtime.NativeGuest.command(root, guest.first(), guest.drop(1))
|
||||
} else {
|
||||
LinuxRuntime.command(this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest)
|
||||
}
|
||||
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> hostEnv[k] = v } }
|
||||
|
||||
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 { hostEnv[key] = it }
|
||||
guest.lastOrNull { it.startsWith("$key=") }?.substringAfter('=')?.let { prootEnv[key] = it }
|
||||
}
|
||||
val prootLibs = LinuxRuntime.prootLibraryPath(this)
|
||||
if (prootLibs.isNotEmpty()) hostEnv["LD_LIBRARY_PATH"] = prootLibs
|
||||
if (prootLibs.isNotEmpty()) prootEnv["LD_LIBRARY_PATH"] = prootLibs
|
||||
|
||||
val terminalCommand = LinuxRuntime.command(
|
||||
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, shellGuest,
|
||||
)
|
||||
val drives = com.droiddeck.launcher.runtime.NativeGuest.relinkPrefixDrives(root, sessionBindSpecs)
|
||||
if (drives > 0) Log.i(TAG, "$drives Wine drive links given their guest paths back")
|
||||
val hostEnv = if (nativeUserland) HostEnvironment().also { env ->
|
||||
Log.i(TAG, "native userland: no proot (${sessionBindSpecs.size} mounts)")
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, SessionPrefs.guestHostname(this))
|
||||
.forEach { (k, v) -> env[k] = v }
|
||||
} else prootEnv
|
||||
|
||||
// The terminal and the bottom desktop run the way the session does: without proot when it does
|
||||
val terminalCommand = if (nativeUserland) {
|
||||
com.droiddeck.launcher.runtime.NativeGuest.command(root, shellGuest.first(), shellGuest.drop(1))
|
||||
} else {
|
||||
LinuxRuntime.command(this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, shellGuest)
|
||||
}
|
||||
val terminalHostEnvironment = LinkedHashMap(System.getenv())
|
||||
hostEnv.asArray().forEach { entry ->
|
||||
val separator = entry.indexOf('=')
|
||||
@@ -711,7 +730,7 @@ class SessionService : Service() {
|
||||
SessionTerminal.prepare(terminalCommand, terminalHostEnvironment.map { (key, value) -> "$key=$value" }.toTypedArray(), root, gen)
|
||||
val (fastPathName, _) = ProotFastPath.hostEnv("")
|
||||
BottomDesktop.prepare(desktopGuest, binds, sessionRoot,
|
||||
hostEnv.asArray().filterNot { it.startsWith("$fastPathName=") }.toTypedArray(), root, sessionDir, gen,
|
||||
prootEnv.asArray().filterNot { it.startsWith("$fastPathName=") }.toTypedArray(), root, sessionDir, gen, nativeUserland,
|
||||
) { gen == sessionGen && SessionState.running }
|
||||
}
|
||||
|
||||
@@ -2023,6 +2042,8 @@ class SessionService : Service() {
|
||||
if (gen != null && gen != sessionGen) return
|
||||
cancelQueuedSteamGame()
|
||||
gameExitWatchToken++
|
||||
// also when startup stopped before the guest ran
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionMode = null
|
||||
if (!SessionState.running) return
|
||||
if (relaunch) SessionState.confirmRelaunchStop()
|
||||
SessionEvents.record("guest.exited", mapOf("status" to status))
|
||||
|
||||
@@ -22,7 +22,7 @@ object SettingsReset {
|
||||
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
|
||||
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
|
||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite",
|
||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics",
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
|
||||
|
||||
@@ -139,15 +139,21 @@ object GogComet {
|
||||
!File(LinuxRuntime.rootDir(context), BIN.removePrefix("/")).isFile) return reply(false, "not-installed")
|
||||
val data = File(context.filesDir, "gog-achievements").apply { mkdirs() }
|
||||
val ready = CountDownLatch(1)
|
||||
val command = LinuxRuntime.command(context, null, null, Environment.getExternalStorageDirectory(),
|
||||
listOf("/usr/bin/env", "HOME=/root", "XDG_DATA_HOME=${data.path}/data", "XDG_CONFIG_HOME=${data.path}/config", "COMET_LOG=off", "COMET_ALLOWED_CLIENTS=${policy.path}", BIN, "--credentials-stdin"))
|
||||
val pb = ProcessBuilder(command).redirectErrorStream(true)
|
||||
pb.environment().apply {
|
||||
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) }
|
||||
val guest = listOf("/usr/bin/env", "HOME=/root", "XDG_DATA_HOME=${data.path}/data", "XDG_CONFIG_HOME=${data.path}/config", "COMET_LOG=off", "COMET_ALLOWED_CLIENTS=${policy.path}", BIN, "--credentials-stdin")
|
||||
val pb = if (com.droiddeck.launcher.runtime.NativeGuest.forSession(context)) {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
com.droiddeck.launcher.runtime.NativeGuest.processBuilder(context, root,
|
||||
LinuxRuntime.binds(context, null, null, Environment.getExternalStorageDirectory(), null), guest).redirectErrorStream(true)
|
||||
} else {
|
||||
ProcessBuilder(LinuxRuntime.command(context, null, null, Environment.getExternalStorageDirectory(), guest)).redirectErrorStream(true).also {
|
||||
it.environment().apply {
|
||||
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) }
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
val child = pb.start()
|
||||
|
||||
@@ -64,15 +64,32 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
|
||||
if (root <= 0 || pid <= 0) return null
|
||||
val status = java.io.File("/proc/$pid/status").readLines()
|
||||
val tracer = status.first { it.startsWith("TracerPid:") }.substringAfter(':').trim().toInt()
|
||||
val tracerGroup = java.io.File("/proc/$tracer/status").readLines()
|
||||
.first { it.startsWith("Tgid:") }.substringAfter(':').trim().toInt()
|
||||
if (tracerGroup != root) return null
|
||||
if (tracer != 0) {
|
||||
// under proot, every guest process is traced by the proot the app started
|
||||
val tracerGroup = java.io.File("/proc/$tracer/status").readLines()
|
||||
.first { it.startsWith("Tgid:") }.substringAfter(':').trim().toInt()
|
||||
if (tracerGroup != root) return null
|
||||
} else if (!descendsFrom(pid, root)) {
|
||||
// without proot, the process the app started is the backend itself (or its parent)
|
||||
return null
|
||||
}
|
||||
val executable = android.system.Os.stat(binary.path)
|
||||
if (!mapsBackend(java.io.File("/proc/$pid/maps").readText(), binary.path, executable.st_ino))
|
||||
return null
|
||||
return java.io.File("/proc/$pid/stat").readText().substringAfterLast(") ").split(' ')[19] + ":${executable.st_dev}:${executable.st_ino}"
|
||||
}
|
||||
|
||||
private fun descendsFrom(pid: Int, root: Int): Boolean {
|
||||
var current = pid
|
||||
repeat(32) {
|
||||
if (current == root) return true
|
||||
if (current <= 1) return false
|
||||
current = java.io.File("/proc/$current/status").readLines()
|
||||
.firstOrNull { it.startsWith("PPid:") }?.substringAfter(':')?.trim()?.toIntOrNull() ?: return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
fun signalBackend(signal: Int) {
|
||||
val process = backend ?: return
|
||||
if (!process.isAlive) return
|
||||
|
||||
@@ -88,7 +88,8 @@ internal object Xodus {
|
||||
val fastPathPreloaded = runCatching {
|
||||
File(root, "etc/ld.so.preload").useLines { lines -> lines.any { it.trim() == ProotFastPath.LIBRARY } }
|
||||
}.getOrDefault(false)
|
||||
val fastPathKey = if (ProotFastPath.enabled(app) && fastPathPreloaded &&
|
||||
val native = com.droiddeck.launcher.runtime.NativeGuest.forSession(app)
|
||||
val fastPathKey = if (!native && ProotFastPath.enabled(app) && fastPathPreloaded &&
|
||||
File(root, ProotFastPath.LIBRARY.removePrefix("/")).isFile) ProotFastPath.key(root, binds) else null
|
||||
val guestCommand = mutableListOf(
|
||||
"/usr/bin/env", "HOME=/root", "XODUS_LOG=off", "RUST_LOG=off",
|
||||
@@ -98,12 +99,12 @@ internal object Xodus {
|
||||
guestCommand.addAll(guestCommand.lastIndex, ProotFastPath.guestEnv(root, binds, key))
|
||||
}
|
||||
guestCommand.addAll(args)
|
||||
val command = LinuxRuntime.commandWithBinds(app, root, binds, guestCommand)
|
||||
val builder = ProcessBuilder(command).directory(LinuxRuntime.rootDir(app))
|
||||
val builder = if (native) com.droiddeck.launcher.runtime.NativeGuest.processBuilder(app, root, binds, guestCommand)
|
||||
else ProcessBuilder(LinuxRuntime.commandWithBinds(app, root, binds, guestCommand)).directory(LinuxRuntime.rootDir(app))
|
||||
if (launchDirectory != null) builder.environment()["TMPDIR"] = launchDirectory.path
|
||||
builder.environment()["DROIDDECK_XBOX_CREDENTIAL_PORT"] = credentials.port.toString()
|
||||
builder.environment()["DROIDDECK_XBOX_CREDENTIAL_KEY"] = credentials.key
|
||||
builder.environment().apply {
|
||||
if (!native) builder.environment().apply {
|
||||
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)
|
||||
|
||||
@@ -53,6 +53,7 @@ fun PerformancePage(
|
||||
ramCapAvailable: Boolean,
|
||||
prootNoSeccomp: Boolean,
|
||||
prootFastPath: Boolean,
|
||||
nativeUserland: Boolean,
|
||||
cursorComposite: Boolean,
|
||||
guestHostname: String,
|
||||
phantomWarning: String?,
|
||||
@@ -72,6 +73,7 @@ fun PerformancePage(
|
||||
onVramCapMb: (Int) -> Unit,
|
||||
onProotNoSeccomp: (Boolean) -> Unit,
|
||||
onProotFastPath: (Boolean) -> Unit,
|
||||
onNativeUserland: (Boolean) -> Unit,
|
||||
onCursorComposite: (Boolean) -> Unit,
|
||||
onGuestHostname: (String) -> Unit,
|
||||
onClientCore: (Int, Boolean) -> Unit,
|
||||
@@ -187,9 +189,18 @@ fun PerformancePage(
|
||||
)
|
||||
ToggleRow(
|
||||
host, "fastpath", stringResource(R.string.perf_fastpath),
|
||||
if (prootNoSeccomp) stringResource(R.string.perf_fastpath_needs_seccomp)
|
||||
else stringResource(R.string.perf_fastpath_hint),
|
||||
prootFastPath && !prootNoSeccomp, enabled = !prootNoSeccomp, onChange = onProotFastPath,
|
||||
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),
|
||||
|
||||
Reference in new issue
Block a user