feat: target Android 14 so Play Protect installs DroidDeck without a warning (#2683)

* fix(proot): ship proot in the APK and run it from the native library directory

* fix(native): start rootfs programs through an APK-shipped exec loader where data files may not be executed

* fix(audio): start PulseAudio through the system linker where data files may not be executed

* feat: target Android 14 (SDK 34) so Play Protect installs DroidDeck without a warning

* fix: ask for all-files access on Android 11+, reject unloadable ELFs before exec, keep checking the proot pack

* fix: hand host scripts to the kernel, skip startup launch while all-files Settings is open

* fix: run proot from its add-on pack through Android's linker, so the APK carries no proot

* fix: declare high sampling rate sensors for controller gyro at target 34

* fix: offer the rootfs proot fallback only where Android lets proot exec its loader

* test: install the runtime's proot pack in GameFileSync fixtures
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-16 09:35:16 -05:00
1 parent 6188c9ac0d
commit dc98b6b96a
28 files changed
+601 -58

No files matched your search

+25 -5
View File
@@ -36,7 +36,12 @@
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.HIGH_SAMPLING_RATE_SENSORS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
@@ -48,7 +53,8 @@
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.vulkan.version" android:version="0x401000" android:required="true" />
@@ -70,6 +76,7 @@
android:hardwareAccelerated="true"
android:largeHeap="true"
android:extractNativeLibs="true"
android:requestLegacyExternalStorage="true"
android:appCategory="game"
android:isGame="true">
@@ -312,7 +319,11 @@
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density"
android:theme="@style/SessionTheme" />
<service android:name=".agent.AgentHostService" android:exported="false" />
<service android:name=".agent.AgentHostService" android:exported="false"
android:foregroundServiceType="specialUse">
<property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Keeps the user's on-device assistant running between screens" />
</service>
<service
android:name=".update.UpdateWatch"
android:permission="android.permission.BIND_JOB_SERVICE"
@@ -320,7 +331,11 @@
<service
android:name=".session.SessionService"
android:exported="false"
android:stopWithTask="false" />
android:stopWithTask="false"
android:foregroundServiceType="specialUse">
<property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Runs the user's Linux gaming session while its window is in the background" />
</service>
<!-- The compositor's native state is one per process, so the bottom-screen desktop's compositor runs in its own. -->
<service
android:name=".wayland.BottomDesktopCompositorService"
@@ -328,10 +343,15 @@
android:exported="false" />
<service
android:name=".runtime.RuntimeInstallService"
android:exported="false" />
android:exported="false"
android:foregroundServiceType="dataSync" />
<service
android:name=".core.WirelessAdbPairingService"
android:exported="false" />
android:exported="false"
android:foregroundServiceType="specialUse">
<property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Waits for the wireless debugging pairing code the user enters" />
</service>
<service
android:name=".stores.download.StoreDownloadService"
android:exported="false"
+6
View File
@@ -40,6 +40,12 @@ add_library(gpuclock SHARED gpuclock/kgsl_clock.c gpuclock/kgsl_busy.c)
add_library(termux SHARED termux/termux.c)
# An executable packaged as a library: the only place a targetSdk 29+ app may execute files from.
add_library(ddexec SHARED ddexec/ddexec.c)
target_compile_options(ddexec PRIVATE -O2 -ffreestanding -fno-builtin -fno-stack-protector -fno-asynchronous-unwind-tables)
target_link_options(ddexec PRIVATE -nostdlib -Wl,-e,_start -Wl,-z,noexecstack -Wl,--no-undefined -Wl,-Bsymbolic
-Wl,-z,max-page-size=16384)
add_library(ddvenc SHARED venc/venc_server.cpp)
target_compile_features(ddvenc PRIVATE cxx_std_17)
target_link_libraries(ddvenc mediandk log)
+274
View File
@@ -0,0 +1,274 @@
// libddexec.so: starts an ELF program from the app's data directory.
//
// usage: libddexec.so <file> <argv0> [args...]
//
// From targetSdk 29, Android refuses execve() of app data files, but still lets the app map them
// executable, and executes the APK's extracted libraries. This executable is one of those libraries:
// it maps <file> (and its PT_INTERP, if it names one) the way the kernel's ELF loader would, builds the
// stack the kernel would have built for "<argv0> [args...]", and jumps to the entry point.
// It is freestanding: no libc, no relocations, so the kernel can run it as a static PIE.
#include <elf.h>
#include <stddef.h>
#include <stdint.h>
#define SYS_faccessat 48
#define SYS_openat 56
#define SYS_close 57
#define SYS_pread64 67
#define SYS_write 64
#define SYS_exit_group 94
#define SYS_munmap 215
#define SYS_mmap 222
#define SYS_mprotect 226
#define AT_FDCWD_ (-100)
#define O_RDONLY_ 0
#define O_CLOEXEC_ 02000000
#define PROT_READ_ 1
#define PROT_WRITE_ 2
#define PROT_EXEC_ 4
#define MAP_PRIVATE_ 0x02
#define MAP_FIXED_ 0x10
#define MAP_ANONYMOUS_ 0x20
#define MAX_PHDRS 64
#define STACK_GAP 65536
static long sys6(long n, long a, long b, long c, long d, long e, long f) {
register long x8 __asm__("x8") = n;
register long x0 __asm__("x0") = a;
register long x1 __asm__("x1") = b;
register long x2 __asm__("x2") = c;
register long x3 __asm__("x3") = d;
register long x4 __asm__("x4") = e;
register long x5 __asm__("x5") = f;
__asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2), "r"(x3), "r"(x4), "r"(x5) : "memory", "cc");
return x0;
}
static size_t slen(const char *s) {
size_t n = 0;
while (s[n]) n++;
return n;
}
static void out(const char *s) { sys6(SYS_write, 2, (long)s, (long)slen(s), 0, 0, 0); }
static void out_num(long v) {
char buf[24];
int i = (int)sizeof(buf) - 1;
buf[i] = 0;
unsigned long u = v < 0 ? (unsigned long)-v : (unsigned long)v;
do {
buf[--i] = (char)('0' + u % 10);
u /= 10;
} while (u && i > 1);
if (v < 0) buf[--i] = '-';
out(buf + i);
}
__attribute__((noreturn)) static void die(const char *what, const char *path, long err) {
out("libddexec: ");
if (path) {
out(path);
out(": ");
}
out(what);
if (err) {
out(" (");
out_num(err);
out(")");
}
out("\n");
sys6(SYS_exit_group, 127, 0, 0, 0, 0, 0);
__builtin_unreachable();
}
static long xpread(int fd, void *buf, size_t len, long off) {
size_t done = 0;
while (done < len) {
long n = sys6(SYS_pread64, fd, (long)((char *)buf + done), (long)(len - done), off + (long)done, 0, 0);
if (n <= 0) return n < 0 ? n : -1;
done += (size_t)n;
}
return (long)done;
}
struct image {
uintptr_t base;
uintptr_t phdr;
uintptr_t entry;
unsigned long phnum;
unsigned long phent;
char interp[256];
};
static uintptr_t trunc_page(uintptr_t v, uintptr_t page) { return v & ~(page - 1); }
static uintptr_t round_page(uintptr_t v, uintptr_t page) { return (v + page - 1) & ~(page - 1); }
static int prot_of(uint32_t flags) {
return ((flags & PF_R) ? PROT_READ_ : 0) | ((flags & PF_W) ? PROT_WRITE_ : 0) | ((flags & PF_X) ? PROT_EXEC_ : 0);
}
static void map_failed(const char *path, long r) { die("cannot map a segment", path, r); }
static void load(const char *path, struct image *im, uintptr_t page) {
int fd = (int)sys6(SYS_openat, AT_FDCWD_, (long)path, O_RDONLY_ | O_CLOEXEC_, 0, 0, 0);
if (fd < 0) die("cannot open", path, fd);
Elf64_Ehdr eh;
if (xpread(fd, &eh, sizeof(eh), 0) != (long)sizeof(eh)) die("not an ELF file", path, 0);
if (eh.e_ident[EI_MAG0] != ELFMAG0 || eh.e_ident[EI_MAG1] != ELFMAG1 || eh.e_ident[EI_MAG2] != ELFMAG2 ||
eh.e_ident[EI_MAG3] != ELFMAG3 || eh.e_ident[EI_CLASS] != ELFCLASS64 || eh.e_machine != EM_AARCH64 ||
(eh.e_type != ET_EXEC && eh.e_type != ET_DYN) || eh.e_phentsize != sizeof(Elf64_Phdr) ||
eh.e_phnum == 0 || eh.e_phnum > MAX_PHDRS)
die("not a 64-bit ARM ELF program", path, 0);
Elf64_Phdr ph[MAX_PHDRS];
long size = (long)eh.e_phnum * (long)sizeof(Elf64_Phdr);
if (xpread(fd, ph, (size_t)size, (long)eh.e_phoff) != size) die("truncated program headers", path, 0);
uintptr_t lo = UINTPTR_MAX, hi = 0;
for (int i = 0; i < eh.e_phnum; i++) {
if (ph[i].p_type != PT_LOAD) continue;
uintptr_t s = trunc_page(ph[i].p_vaddr, page), e = round_page(ph[i].p_vaddr + ph[i].p_memsz, page);
if (s < lo) lo = s;
if (e > hi) hi = e;
}
if (lo >= hi) die("no loadable segments", path, 0);
uintptr_t bias = 0;
if (eh.e_type == ET_DYN) {
long r = sys6(SYS_mmap, 0, (long)(hi - lo), 0, MAP_PRIVATE_ | MAP_ANONYMOUS_, -1, 0);
if (r < 0 && r > -4096) map_failed(path, r);
bias = (uintptr_t)r - lo;
}
for (int i = 0; i < eh.e_phnum; i++) {
Elf64_Phdr *p = &ph[i];
if (p->p_type != PT_LOAD || p->p_memsz == 0) continue;
int prot = prot_of(p->p_flags);
uintptr_t seg = bias + p->p_vaddr;
uintptr_t start = trunc_page(seg, page);
uintptr_t file_end = seg + p->p_filesz;
uintptr_t mem_end = round_page(seg + p->p_memsz, page);
int zero_tail = p->p_memsz > p->p_filesz && (file_end & (page - 1)) != 0;
if (p->p_filesz > 0) {
uintptr_t len = round_page(file_end, page) - start;
long r = sys6(SYS_mmap, (long)start, (long)len, prot | (zero_tail ? PROT_WRITE_ : 0),
MAP_PRIVATE_ | MAP_FIXED_, fd, (long)trunc_page(p->p_offset, page));
if (r < 0 && r > -4096) map_failed(path, r);
if (zero_tail) {
for (volatile char *z = (volatile char *)file_end; (uintptr_t)z < round_page(file_end, page); z++) *z = 0;
if (!(prot & PROT_WRITE_)) sys6(SYS_mprotect, (long)trunc_page(file_end, page), (long)page, prot, 0, 0, 0);
}
}
uintptr_t anon = p->p_filesz > 0 ? round_page(file_end, page) : start;
if (mem_end > anon) {
long r = sys6(SYS_mmap, (long)anon, (long)(mem_end - anon), prot, MAP_PRIVATE_ | MAP_FIXED_ | MAP_ANONYMOUS_, -1, 0);
if (r < 0 && r > -4096) map_failed(path, r);
}
}
im->base = bias;
im->entry = bias + eh.e_entry;
im->phnum = eh.e_phnum;
im->phent = eh.e_phentsize;
im->phdr = 0;
im->interp[0] = 0;
for (int i = 0; i < eh.e_phnum; i++) {
if (ph[i].p_type == PT_PHDR) im->phdr = bias + ph[i].p_vaddr;
if (ph[i].p_type == PT_INTERP) {
if (ph[i].p_filesz == 0 || ph[i].p_filesz >= sizeof(im->interp)) die("bad PT_INTERP", path, 0);
if (xpread(fd, im->interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz)
die("truncated PT_INTERP", path, 0);
im->interp[ph[i].p_filesz] = 0;
}
}
if (!im->phdr) {
for (int i = 0; i < eh.e_phnum; i++) {
Elf64_Phdr *p = &ph[i];
if (p->p_type == PT_LOAD && eh.e_phoff >= p->p_offset && eh.e_phoff < p->p_offset + p->p_filesz) {
im->phdr = bias + p->p_vaddr + (eh.e_phoff - p->p_offset);
break;
}
}
}
if (!im->phdr) die("program headers are not in a loaded segment", path, 0);
sys6(SYS_close, fd, 0, 0, 0, 0, 0);
}
static unsigned long auxv_get(const uintptr_t *auxv, unsigned long type, unsigned long fallback) {
for (; auxv[0] != AT_NULL; auxv += 2)
if (auxv[0] == type) return auxv[1];
return fallback;
}
__attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) {
long argc = (long)sp[0];
char **argv = (char **)(sp + 1);
char **envp = argv + argc + 1;
long nenv = 0;
while (envp[nenv]) nenv++;
uintptr_t *auxv = (uintptr_t *)(envp + nenv + 1);
long naux = 0;
while (auxv[naux * 2] != AT_NULL) naux++;
if (argc < 3) die("usage: libddexec.so <file> <argv0> [args...]", 0, 0);
uintptr_t page = auxv_get(auxv, AT_PAGESZ, 4096);
const char *path = argv[1];
struct image prog, interp;
load(path, &prog, page);
int has_interp = prog.interp[0] != 0;
if (has_interp) load(prog.interp, &interp, page);
// The new stack: argc, argv, envp and auxv as the kernel lays them out, below the current one.
// The strings stay where the kernel put them.
static const unsigned long replaced[] = {AT_PHDR, AT_PHENT, AT_PHNUM, AT_BASE, AT_ENTRY, AT_EXECFN};
long nreplaced = (long)(sizeof(replaced) / sizeof(replaced[0]));
long new_argc = argc - 2;
long words = 1 + (new_argc + 1) + (nenv + 1) + (naux + nreplaced + 1) * 2;
uintptr_t *nsp = (uintptr_t *)(((uintptr_t)sp - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15);
uintptr_t *w = nsp;
*w++ = (uintptr_t)new_argc;
for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)argv[i + 2];
*w++ = 0;
for (long i = 0; i < nenv; i++) *w++ = (uintptr_t)envp[i];
*w++ = 0;
for (long i = 0; i < naux; i++) {
unsigned long type = auxv[i * 2];
int skip = 0;
for (long r = 0; r < nreplaced; r++)
if (type == replaced[r]) skip = 1;
if (skip) continue;
*w++ = type;
*w++ = auxv[i * 2 + 1];
}
*w++ = AT_PHDR;
*w++ = prog.phdr;
*w++ = AT_PHENT;
*w++ = prog.phent;
*w++ = AT_PHNUM;
*w++ = prog.phnum;
*w++ = AT_BASE;
*w++ = has_interp ? interp.base : 0;
*w++ = AT_ENTRY;
*w++ = prog.entry;
*w++ = AT_EXECFN;
*w++ = (uintptr_t)path;
*w++ = AT_NULL;
*w++ = 0;
uintptr_t entry = has_interp ? interp.entry : prog.entry;
__asm__ volatile("mov sp, %0\n"
"mov x0, #0\n"
"br %1\n"
:
: "r"(nsp), "r"(entry)
: "memory");
__builtin_unreachable();
}
__attribute__((naked, noreturn)) void _start(void) {
__asm__ volatile("mov x0, sp\n"
"and sp, x0, #~15\n"
"bl ddexec_main\n");
}
@@ -20,6 +20,7 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
com.droiddeck.launcher.runtime.NativeGuest.init(this)
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
com.droiddeck.launcher.ui.Themes.loadGradient(this)
com.droiddeck.launcher.ui.BuildWatermark.install(this)
@@ -82,7 +83,7 @@ class App : Application() {
Thread({
runCatching {
if (com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app).isDirectory) {
com.droiddeck.launcher.core.AddonPack.PROOT.ensure(app)
if (!com.droiddeck.launcher.runtime.LinuxRuntime.patchedProot(app)) com.droiddeck.launcher.core.AddonPack.PROOT.ensure(app)
com.droiddeck.launcher.core.AddonPack.DIRECTAUDIO.ensure(app)
com.droiddeck.launcher.session.SessionFiles.ensureDirtStandIn(app)
}
@@ -1863,15 +1863,24 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled(cold = true) }
else {
val askAllFiles = Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.files.AllFilesAccess.missing() &&
!SessionPrefs.allFilesAsked(this)
if (savedInstanceState == null) {
if (!askAllFiles) ui.post { startSteamAtStartupIfEnabled(cold = true) }
} else {
restoreCompatLaunch(savedInstanceState)
pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH)
savedIntent(savedInstanceState, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, savedInstanceState.getLong(KEY_SWITCH_DEADLINE)) }
}
val wanted = ArrayList<String>()
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= 30) {
// From targetSdk 30, shared storage outside the app's own folders is all-files access or nothing.
if (askAllFiles) {
SessionPrefs.setAllFilesAsked(this)
com.droiddeck.launcher.files.AllFilesAccess.open(this)
}
} else if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
wanted.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
if (SessionPrefs.micEnabled(this) && !SessionPrefs.micAsked(this)
@@ -850,6 +850,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); refreshControls() } }
steamController = SteamControllerBle(this, inputRouter).also { it.start() }
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(BLUETOOTH_CONNECT) != android.content.pm.PackageManager.PERMISSION_GRANTED &&
!SessionPrefs.bluetoothAsked(this)) {
SessionPrefs.setBluetoothAsked(this)
requestPermissions(arrayOf(BLUETOOTH_CONNECT), REQUEST_BLUETOOTH)
}
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
@Suppress("DEPRECATION")
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
@@ -6354,8 +6359,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
finish()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode != REQUEST_BLUETOOTH || grantResults.firstOrNull() != android.content.pm.PackageManager.PERMISSION_GRANTED) return
steamController?.stop()
steamController = SteamControllerBle(this, inputRouter).also { it.start() }
}
companion object {
const val EXTRA_RETURN_HOME = "returnHome"
private const val BLUETOOTH_CONNECT = "android.permission.BLUETOOTH_CONNECT"
private const val REQUEST_BLUETOOTH = 31
const val EXTRA_LINK_TASK = "linkTask"
const val EXTRA_STEAMVR = "steamVr"
const val EXTRA_PLAYED_GAME = "com.droiddeck.launcher.PLAYED_GAME"
@@ -40,7 +40,11 @@ object AgentProcesses {
val now = SystemClock.elapsedRealtime()
val uptimeTicks = now * HZ / 1000
val elapsed = (now - lastAt).coerceAtLeast(1)
fun isProot(pid: Int) = args[pid].orEmpty().substringBefore(' ').endsWith("proot.so") || args[pid].orEmpty().substringBefore(' ').endsWith("/proot")
fun isProot(pid: Int): Boolean {
val argv = args[pid].orEmpty().split(' ')
val program = if (argv.first().endsWith("/linker64")) argv.getOrElse(1) { "" } else argv.first()
return program.endsWith("proot.so") || program.endsWith("/proot")
}
fun ancestors(pid: Int) = generateSequence(stats[pid]?.ppid) { stats[it]?.ppid }.takeWhile { it > 1 }.take(64)
val out = stats.values.filter { s ->
!isProot(s.pid) && args[s.pid].orEmpty().isNotEmpty() && ancestors(s.pid).any { isProot(it) }
@@ -168,7 +168,7 @@ public class PulseAudioComponent extends SessionPart {
env.add("HOME=" + workingDir);
env.add("TMPDIR=" + workingDir);
String command = workingDir.getAbsolutePath() + "/libpulseaudio.so"
String command = String.join(" ", HostProcess.dataExecutable(workingDir.getAbsolutePath() + "/libpulseaudio.so"))
+ " --system=false --disable-shm=true --fail=false"
+ " -n --file=default.pa --daemonize=false --use-pid-file=false --exit-idle-time=-1"
+ " --log-level=info";
@@ -259,7 +259,7 @@ public class PulseAudioComponent extends SessionPart {
try {
File modules = new File(workingDir, "modules/arm64");
ArrayList<String> cmd = new ArrayList<>();
cmd.add(pactl.getAbsolutePath());
cmd.addAll(HostProcess.dataExecutable(pactl.getAbsolutePath()));
java.util.Collections.addAll(cmd, args);
ProcessBuilder builder = new ProcessBuilder(cmd);
builder.directory(workingDir);
@@ -316,8 +316,9 @@ public class PulseAudioComponent extends SessionPart {
java.lang.Process process = null;
try {
File modules = new File(workingDir, "modules/arm64");
ProcessBuilder builder = new ProcessBuilder(
pactl.getAbsolutePath(), "suspend-" + kind, name, Boolean.toString(suspended));
ArrayList<String> argv = new ArrayList<>(HostProcess.dataExecutable(pactl.getAbsolutePath()));
argv.addAll(java.util.Arrays.asList("suspend-" + kind, name, Boolean.toString(suspended)));
ProcessBuilder builder = new ProcessBuilder(argv);
builder.directory(workingDir);
builder.redirectErrorStream(true);
builder.redirectOutput(new File("/dev/null"));
@@ -6,6 +6,12 @@ import java.util.function.Consumer
object HostProcess {
private const val TAG = "HostProcess"
private const val LINKER = "/system/bin/linker64"
/** Android 10+ refuses to execute app data files for targetSdk 29+; its linker still loads them. */
@JvmStatic
fun dataExecutable(path: String): List<String> =
if (android.os.Build.VERSION.SDK_INT >= 29) listOf(LINKER, path) else listOf(path)
@JvmStatic
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?): Int =
@@ -384,7 +384,7 @@ object BwrapSpawner {
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
return (NativeGuest.execPrefix(program.path) + 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
@@ -411,13 +411,14 @@ object BwrapSpawner {
plan.env.map { (k, v) -> "$k=$v" } + plan.argv
val env = linkedMapOf(
"DDNATV_ROOT" to sandbox,
"DDNATV_EXEC" to NativeGuest.execLoader.orEmpty(),
"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
return (NativeGuest.simulator(rootfs)?.let { it + launch } ?: (NativeGuest.execPrefix(loader.path) + launch)) to env
}
private val runpathDirs = java.util.concurrent.ConcurrentHashMap<String, List<String>>()
@@ -542,7 +543,7 @@ object BwrapSpawner {
.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()) }
if (verbose != null) { cmd.add("-v"); cmd.add(verbose.toString()) }
plan.binds.forEach { cmd.add("-b"); cmd.add(it.spec) }
val envTool = hasEnvTool(plan)
if (envTool) {
@@ -95,10 +95,13 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
permissionNotified = false
context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, observer)
requests.startWatching()
context.registerReceiver(volumeSteps, IntentFilter().apply {
val volumeFilter = IntentFilter().apply {
addAction(VOLUME_CHANGED_ACTION)
addAction(STREAM_MUTE_CHANGED_ACTION)
}, null, handler)
}
if (android.os.Build.VERSION.SDK_INT >= 33)
context.registerReceiver(volumeSteps, volumeFilter, null, handler, Context.RECEIVER_NOT_EXPORTED)
else context.registerReceiver(volumeSteps, volumeFilter, null, handler)
refresh.run()
}
}
@@ -58,7 +58,7 @@ object GuestCommand {
NativeGuest.processBuilder(context, root, binds, guest).redirectErrorStream(true)
} else {
val cmd = LinuxRuntime.prootPrefix(context, root, "/root", fakeRoot)
if (linkDir != null) cmd.add(1, "--link2symlink")
if (linkDir != null) cmd.add("--link2symlink")
binds.forEach { cmd.add("-b"); cmd.add(it) }
cmd += guest
ProcessBuilder(cmd).directory(root).redirectErrorStream(true).also { b ->
@@ -106,13 +106,15 @@ class LinuxNetworkLinkComponent(
synchronized(lock) { writeNetworkState(currentProperties, currentCapabilities) }
}
}
appContext.registerReceiver(receiver, IntentFilter().apply {
val wifiFilter = IntentFilter().apply {
addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
addAction(WifiManager.RSSI_CHANGED_ACTION)
addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION)
addAction(LocationManager.MODE_CHANGED_ACTION)
})
}
if (android.os.Build.VERSION.SDK_INT >= 33) appContext.registerReceiver(receiver, wifiFilter, Context.RECEIVER_NOT_EXPORTED)
else appContext.registerReceiver(receiver, wifiFilter)
wifiReceiver = receiver
scanRequestStamp = File(rootDir, "etc/droiddeck-wifi-scan-request").lastModified()
scanHandler.post(scanRequests)
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.runtime;
import com.droiddeck.launcher.core.AddonPack;
import android.content.Context;
import android.os.Build;
import android.os.Process;
import android.system.ErrnoException;
import android.system.Os;
@@ -77,7 +78,18 @@ public final class LinuxRuntime {
}
private static boolean rootfsProotReady(Context context) {
return rootfsProot(context).isFile() && rootfsLoader(context).isFile();
return Build.VERSION.SDK_INT < 29 && rootfsProot(context).isFile() && rootfsLoader(context).isFile();
}
/** proot execs its loader, and targetSdk 29+ may exec only the APK's libraries, which hold the pack's matching loader. */
public static boolean stockProotAllowed(Context context) {
return Build.VERSION.SDK_INT < 29 && SessionPrefs.allowStockProot(context);
}
/** Android 10+ refuses to execute files from app data for targetSdk 29+, but executes the APK's extracted libraries. */
private static File bundledLoader(Context context) {
File file = new File(context.getApplicationInfo().nativeLibraryDir, "libproot-loader.so");
return file.isFile() ? file : null;
}
public static boolean patchedProot(Context context) {
@@ -86,22 +98,21 @@ public final class LinuxRuntime {
public static File prootBinary(Context context) {
if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot.so");
if (SessionPrefs.allowStockProot(context)) return rootfsProot(context);
if (stockProotAllowed(context)) return rootfsProot(context);
return AddonPack.PROOT.file(context, "libproot.so");
}
public static File prootLoader(Context context) {
if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot-loader.so");
if (SessionPrefs.allowStockProot(context)) return rootfsLoader(context);
return AddonPack.PROOT.file(context, "libproot-loader.so");
File bundled = bundledLoader(context);
if (AddonPack.PROOT.installed(context)) return bundled != null ? bundled : AddonPack.PROOT.file(context, "libproot-loader.so");
if (stockProotAllowed(context)) return rootfsLoader(context);
return bundled != null ? bundled : AddonPack.PROOT.file(context, "libproot-loader.so");
}
public static String prootSource(Context context) {
File bin = prootBinary(context);
if (!bin.isFile()) return PROOT_MISSING;
if (AddonPack.PROOT.installed(context)
&& bin.getPath().equals(AddonPack.PROOT.file(context, "libproot.so").getPath())) return PROOT_PACK;
return PROOT_ROOTFS;
return patchedProot(context) && !bin.equals(rootfsProot(context)) ? PROOT_PACK : PROOT_ROOTFS;
}
public static String prootLibraryPath(Context context) {
@@ -183,13 +194,13 @@ public final class LinuxRuntime {
public static List<String> rootPrefix(Context context, File root, String cwd) {
List<String> cmd = prootPrefix(context, root, cwd, true);
cmd.add(1, "--link2symlink");
cmd.add("--link2symlink");
return cmd;
}
public static List<String> prootPrefix(Context context, File root, String cwd, boolean fakeRoot) {
List<String> cmd = new ArrayList<>();
cmd.add(prootBinary(context).getPath());
cmd.addAll(com.droiddeck.launcher.core.HostProcess.dataExecutable(prootBinary(context).getPath()));
cmd.add("--kill-on-exit");
cmd.add("--kernel-release=" + guestUtsname(SessionPrefs.guestHostname(context)));
int uid = Process.myUid();
@@ -384,7 +384,7 @@ public final class LinuxRuntimeInstaller {
String downloading = context.getString(R.string.rtinst_downloading);
if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0);
if (!LinuxRuntime.patchedProot(context) && !AddonPack.PROOT.await(context, () -> true, packProgress(listener, downloading))
&& !SessionPrefs.allowStockProot(context))
&& !LinuxRuntime.stockProotAllowed(context))
return fail("Cannot download proot", AddonPack.PROOT.getFailure());
if (!AddonPack.DIRECTAUDIO.await(context, () -> true, packProgress(listener, downloading)))
return fail("Cannot download DirectAudio", AddonPack.DIRECTAUDIO.getFailure());
@@ -50,6 +50,21 @@ object NativeGuest {
fun hook(root: File): File = File(root, HOOK)
/**
* libddexec.so, which starts the rootfs loader on Android 10+, where a targetSdk 29+ app may not
* execute its data files; null where the kernel still starts them directly.
*/
@Volatile var execLoader: String? = null
private set
/** What starts the program at [path] from the host: nothing before it, or [execLoader] and the path. */
fun execPrefix(path: String): List<String> = execLoader?.let { listOf(it, path) }.orEmpty()
fun init(context: Context) {
execLoader = File(context.applicationInfo.nativeLibraryDir, "libddexec.so")
.takeIf { android.os.Build.VERSION.SDK_INT >= 29 && it.isFile }?.path
}
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() }
@@ -60,9 +75,10 @@ object NativeGuest {
/** 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,
"DDNATV_EXEC" to execLoader.orEmpty(),
"LD_LIBRARY_PATH" to libraryPath(root),
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
)
).filterValues { it.isNotEmpty() }
/**
* The host command line for the guest program at [program] (an absolute guest path to a real
@@ -72,7 +88,7 @@ object NativeGuest {
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
return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch)
}
/** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */
@@ -80,6 +96,7 @@ object NativeGuest {
val preload = preloadList(root)
return linkedMapOf(
"DDNATV_ROOT" to root.path,
"DDNATV_EXEC" to execLoader.orEmpty(),
"DDNATV_HOSTNAME" to hostname.orEmpty(),
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
"DDNATV_PRELOAD" to preload.joinToString(":"),
@@ -707,6 +707,18 @@ object SessionPrefs {
fun micAsked(context: Context): Boolean = prefs(context).getBoolean("micAsked", false)
fun allFilesAsked(context: Context): Boolean = prefs(context).getBoolean("allFilesAsked", false)
fun setAllFilesAsked(context: Context) {
prefs(context).edit().putBoolean("allFilesAsked", true).apply()
}
fun bluetoothAsked(context: Context): Boolean = prefs(context).getBoolean("bluetoothAsked", false)
fun setBluetoothAsked(context: Context) {
prefs(context).edit().putBoolean("bluetoothAsked", true).apply()
}
fun setMicAsked(context: Context) {
prefs(context).edit().putBoolean("micAsked", true).apply()
}
@@ -540,7 +540,7 @@ class SessionService : Service() {
}
}
if (!LinuxRuntime.patchedProot(this)) {
if (SessionPrefs.allowStockProot(this)) {
if (LinuxRuntime.stockProotAllowed(this)) {
Log.w(TAG, "proot: patched proot missing; droiddeck-stock-proot allows the rootfs copy")
} else {
val message = getString(R.string.session_proot_missing)
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.Assert.*
@@ -16,9 +17,10 @@ class GameFileSyncTest {
@Test fun syncUsesFreshInstalledManifestsAndStopsWhenDisabled() {
val context = RuntimeEnvironment.getApplication()
val root = LinuxRuntime.rootDir(context)
listOf("usr/bin/gamescope", LinuxRuntime.SESSION_SCRIPT.removePrefix("/"), "opt/android-host/proot", "opt/android-host/loader").forEach { path ->
listOf("usr/bin/gamescope", LinuxRuntime.SESSION_SCRIPT.removePrefix("/")).forEach { path ->
File(root, path).apply { parentFile!!.mkdirs(); writeText("") }
}
AddonPack.PROOT.file(context, AddonPack.COMPLETE).apply { parentFile!!.mkdirs(); writeText("") }
SessionPrefs.setGameStorage(context, SessionPrefs.GAME_STORAGE_OFF, "")
SessionPrefs.setAddedGamesDirs(context, emptyList())
val steamapps = File(root, "root/.local/share/Steam/steamapps").apply { mkdirs() }
@@ -51,9 +53,10 @@ class GameFileSyncTest {
@Test fun libraryNotCreatedYetOnPresentStorageIsEmptyNotUnavailable() {
val context = RuntimeEnvironment.getApplication()
val root = LinuxRuntime.rootDir(context)
listOf("usr/bin/gamescope", LinuxRuntime.SESSION_SCRIPT.removePrefix("/"), "opt/android-host/proot", "opt/android-host/loader").forEach { path ->
listOf("usr/bin/gamescope", LinuxRuntime.SESSION_SCRIPT.removePrefix("/")).forEach { path ->
File(root, path).apply { parentFile!!.mkdirs(); writeText("") }
}
AddonPack.PROOT.file(context, AddonPack.COMPLETE).apply { parentFile!!.mkdirs(); writeText("") }
SessionPrefs.setAddedGamesDirs(context, emptyList())
File(root, "root/.local/share/Steam/steamapps").mkdirs()
val volume = File(context.filesDir, "card").apply { mkdirs() }
@@ -80,9 +83,10 @@ class GameFileSyncTest {
@Test fun previousAutomaticLibraryNotCreatedYetKeepsSyncingButRemovedDriveStops() {
val context = RuntimeEnvironment.getApplication()
val root = LinuxRuntime.rootDir(context)
listOf("usr/bin/gamescope", LinuxRuntime.SESSION_SCRIPT.removePrefix("/"), "opt/android-host/proot", "opt/android-host/loader").forEach { path ->
listOf("usr/bin/gamescope", LinuxRuntime.SESSION_SCRIPT.removePrefix("/")).forEach { path ->
File(root, path).apply { parentFile!!.mkdirs(); writeText("") }
}
AddonPack.PROOT.file(context, AddonPack.COMPLETE).apply { parentFile!!.mkdirs(); writeText("") }
SessionPrefs.setAddedGamesDirs(context, emptyList())
SessionPrefs.setGameStorage(context, "", "")
File(root, "root/.local/share/Steam/steamapps").mkdirs()