mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-28 00:55:40 +00:00
Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6f42e1cf1a | ||
|
|
2ba290c2f1 | ||
|
|
5aac22f277 | ||
|
|
ca1f12ebb4 | ||
|
|
af481e5159 | ||
|
|
ab99c1a3b3 | ||
|
|
f90d91bfa1 | ||
|
|
4e2bfa5cdc | ||
|
|
924ad4e9a3 | ||
|
|
ba9b0b0422 | ||
|
|
ae6863d016 | ||
|
|
e418f99aa0 | ||
|
|
049ded1812 | ||
|
|
a969998075 | ||
|
|
9b673f59fa | ||
|
|
ef1c208ed7 | ||
|
|
bbb4d11bf0 | ||
|
|
27171d8ffd | ||
|
|
cc63b40387 | ||
|
|
592d03f69a | ||
|
|
146b93dd6c | ||
|
|
aedac67f6d | ||
|
|
89ef2f1e90 | ||
|
|
1e022e2430 | ||
|
|
1c20437fe6 | ||
|
|
2e170ae12b |
No files matched your search
@@ -414,5 +414,69 @@
|
||||
android:name="backend:com.google.android.datatransport.cct.CctBackendFactory"
|
||||
tools:node="remove" />
|
||||
</service>
|
||||
<service android:name=".runtime.GuestWorker0" android:exported="false" android:process=":g0" />
|
||||
<service android:name=".runtime.GuestWorker1" android:exported="false" android:process=":g1" />
|
||||
<service android:name=".runtime.GuestWorker2" android:exported="false" android:process=":g2" />
|
||||
<service android:name=".runtime.GuestWorker3" android:exported="false" android:process=":g3" />
|
||||
<service android:name=".runtime.GuestWorker4" android:exported="false" android:process=":g4" />
|
||||
<service android:name=".runtime.GuestWorker5" android:exported="false" android:process=":g5" />
|
||||
<service android:name=".runtime.GuestWorker6" android:exported="false" android:process=":g6" />
|
||||
<service android:name=".runtime.GuestWorker7" android:exported="false" android:process=":g7" />
|
||||
<service android:name=".runtime.GuestWorker8" android:exported="false" android:process=":g8" />
|
||||
<service android:name=".runtime.GuestWorker9" android:exported="false" android:process=":g9" />
|
||||
<service android:name=".runtime.GuestWorker10" android:exported="false" android:process=":g10" />
|
||||
<service android:name=".runtime.GuestWorker11" android:exported="false" android:process=":g11" />
|
||||
<service android:name=".runtime.GuestWorker12" android:exported="false" android:process=":g12" />
|
||||
<service android:name=".runtime.GuestWorker13" android:exported="false" android:process=":g13" />
|
||||
<service android:name=".runtime.GuestWorker14" android:exported="false" android:process=":g14" />
|
||||
<service android:name=".runtime.GuestWorker15" android:exported="false" android:process=":g15" />
|
||||
<service android:name=".runtime.GuestWorker16" android:exported="false" android:process=":g16" />
|
||||
<service android:name=".runtime.GuestWorker17" android:exported="false" android:process=":g17" />
|
||||
<service android:name=".runtime.GuestWorker18" android:exported="false" android:process=":g18" />
|
||||
<service android:name=".runtime.GuestWorker19" android:exported="false" android:process=":g19" />
|
||||
<service android:name=".runtime.GuestWorker20" android:exported="false" android:process=":g20" />
|
||||
<service android:name=".runtime.GuestWorker21" android:exported="false" android:process=":g21" />
|
||||
<service android:name=".runtime.GuestWorker22" android:exported="false" android:process=":g22" />
|
||||
<service android:name=".runtime.GuestWorker23" android:exported="false" android:process=":g23" />
|
||||
<service android:name=".runtime.GuestWorker24" android:exported="false" android:process=":g24" />
|
||||
<service android:name=".runtime.GuestWorker25" android:exported="false" android:process=":g25" />
|
||||
<service android:name=".runtime.GuestWorker26" android:exported="false" android:process=":g26" />
|
||||
<service android:name=".runtime.GuestWorker27" android:exported="false" android:process=":g27" />
|
||||
<service android:name=".runtime.GuestWorker28" android:exported="false" android:process=":g28" />
|
||||
<service android:name=".runtime.GuestWorker29" android:exported="false" android:process=":g29" />
|
||||
<service android:name=".runtime.GuestWorker30" android:exported="false" android:process=":g30" />
|
||||
<service android:name=".runtime.GuestWorker31" android:exported="false" android:process=":g31" />
|
||||
<service android:name=".runtime.GuestWorker32" android:exported="false" android:process=":g32" />
|
||||
<service android:name=".runtime.GuestWorker33" android:exported="false" android:process=":g33" />
|
||||
<service android:name=".runtime.GuestWorker34" android:exported="false" android:process=":g34" />
|
||||
<service android:name=".runtime.GuestWorker35" android:exported="false" android:process=":g35" />
|
||||
<service android:name=".runtime.GuestWorker36" android:exported="false" android:process=":g36" />
|
||||
<service android:name=".runtime.GuestWorker37" android:exported="false" android:process=":g37" />
|
||||
<service android:name=".runtime.GuestWorker38" android:exported="false" android:process=":g38" />
|
||||
<service android:name=".runtime.GuestWorker39" android:exported="false" android:process=":g39" />
|
||||
<service android:name=".runtime.GuestWorker40" android:exported="false" android:process=":g40" />
|
||||
<service android:name=".runtime.GuestWorker41" android:exported="false" android:process=":g41" />
|
||||
<service android:name=".runtime.GuestWorker42" android:exported="false" android:process=":g42" />
|
||||
<service android:name=".runtime.GuestWorker43" android:exported="false" android:process=":g43" />
|
||||
<service android:name=".runtime.GuestWorker44" android:exported="false" android:process=":g44" />
|
||||
<service android:name=".runtime.GuestWorker45" android:exported="false" android:process=":g45" />
|
||||
<service android:name=".runtime.GuestWorker46" android:exported="false" android:process=":g46" />
|
||||
<service android:name=".runtime.GuestWorker47" android:exported="false" android:process=":g47" />
|
||||
<service android:name=".runtime.GuestWorker48" android:exported="false" android:process=":g48" />
|
||||
<service android:name=".runtime.GuestWorker49" android:exported="false" android:process=":g49" />
|
||||
<service android:name=".runtime.GuestWorker50" android:exported="false" android:process=":g50" />
|
||||
<service android:name=".runtime.GuestWorker51" android:exported="false" android:process=":g51" />
|
||||
<service android:name=".runtime.GuestWorker52" android:exported="false" android:process=":g52" />
|
||||
<service android:name=".runtime.GuestWorker53" android:exported="false" android:process=":g53" />
|
||||
<service android:name=".runtime.GuestWorker54" android:exported="false" android:process=":g54" />
|
||||
<service android:name=".runtime.GuestWorker55" android:exported="false" android:process=":g55" />
|
||||
<service android:name=".runtime.GuestWorker56" android:exported="false" android:process=":g56" />
|
||||
<service android:name=".runtime.GuestWorker57" android:exported="false" android:process=":g57" />
|
||||
<service android:name=".runtime.GuestWorker58" android:exported="false" android:process=":g58" />
|
||||
<service android:name=".runtime.GuestWorker59" android:exported="false" android:process=":g59" />
|
||||
<service android:name=".runtime.GuestWorker60" android:exported="false" android:process=":g60" />
|
||||
<service android:name=".runtime.GuestWorker61" android:exported="false" android:process=":g61" />
|
||||
<service android:name=".runtime.GuestWorker62" android:exported="false" android:process=":g62" />
|
||||
<service android:name=".runtime.GuestWorker63" android:exported="false" android:process=":g63" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -25,6 +25,7 @@
|
||||
#include <gnu/lib-names.h>
|
||||
#endif
|
||||
#include <fcntl.h>
|
||||
#include <linux/futex.h>
|
||||
#include <linux/input.h>
|
||||
#include <linux/joystick.h>
|
||||
#include <linux/uinput.h>
|
||||
@@ -711,6 +712,19 @@ ring_header_is_valid(const FakeInputRingHeader *ring) {
|
||||
ring->capacity == FAKE_INPUT_RING_CAPACITY;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static int ring_wait(const FakeInputRingHeader *ring, uint64_t seen, long ns) {
|
||||
struct timespec wait = {0, ns};
|
||||
if (syscall(SYS_futex, &ring->write_seq, FUTEX_WAIT, static_cast<uint32_t>(seen), &wait, nullptr, 0) == 0 ||
|
||||
errno == EAGAIN || errno == ETIMEDOUT)
|
||||
return 0;
|
||||
if (errno == EINTR) return -1;
|
||||
return nanosleep(&wait, nullptr);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static void ring_wake(const FakeInputRingHeader *ring) {
|
||||
syscall(SYS_futex, &ring->write_seq, FUTEX_WAKE, INT_MAX, nullptr, nullptr, 0);
|
||||
}
|
||||
|
||||
struct SnapshotState {
|
||||
uint64_t sequence = 0;
|
||||
uint64_t write_seq = 0;
|
||||
@@ -1167,6 +1181,7 @@ __attribute__((visibility("hidden"))) static void flush_uinput(UinputWriter &w)
|
||||
__atomic_thread_fence(__ATOMIC_RELEASE);
|
||||
__atomic_store_n(&ring->snapshot_seq, sequence + 2, __ATOMIC_RELEASE);
|
||||
__atomic_store_n(&ring->write_seq, write_seq, __ATOMIC_RELEASE);
|
||||
ring_wake(ring);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static ssize_t
|
||||
@@ -1540,6 +1555,12 @@ __attribute__((visibility("hidden"))) static void sleep_us(int us) {
|
||||
nanosleep(&interval, nullptr);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static void
|
||||
report_wait(const FakeInputRingHeader *ring, bool fresh, uint64_t seen, int us) {
|
||||
if (fresh) ring_wait(ring, seen, us * 1000L);
|
||||
else sleep_us(us);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static uint64_t monotonic_us() {
|
||||
struct timespec now;
|
||||
clock_gettime(CLOCK_MONOTONIC, &now);
|
||||
@@ -1712,7 +1733,8 @@ __attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg)
|
||||
int32_t axes[8] = {};
|
||||
DeckExtras extras;
|
||||
while (live_pad_type() == PAD_TYPE_DECK) {
|
||||
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
|
||||
bool fresh = read_snapshot(self->ring, snap);
|
||||
if (fresh && snap.generation == ring_generation(self->ring)) {
|
||||
buttons = snap.buttons;
|
||||
memcpy(axes, snap.axes, sizeof(axes));
|
||||
}
|
||||
@@ -1722,7 +1744,7 @@ __attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg)
|
||||
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
|
||||
errno != EAGAIN && errno != EWOULDBLOCK)
|
||||
break;
|
||||
sleep_us(controller_report_interval_us(DECK_REPORT_INTERVAL_US));
|
||||
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(DECK_REPORT_INTERVAL_US));
|
||||
}
|
||||
syscall(SYS_close, self->peer);
|
||||
munmap(self->ring, self->mapping_size);
|
||||
@@ -1828,7 +1850,8 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
|
||||
SonyTouch touch;
|
||||
const uint64_t start_us = monotonic_us();
|
||||
while (live_pad_type() == type) {
|
||||
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
|
||||
bool fresh = read_snapshot(self->ring, snap);
|
||||
if (fresh && snap.generation == ring_generation(self->ring)) {
|
||||
buttons = snap.buttons;
|
||||
memcpy(axes, snap.axes, sizeof(axes));
|
||||
}
|
||||
@@ -1838,7 +1861,7 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
|
||||
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
|
||||
errno != EAGAIN && errno != EWOULDBLOCK)
|
||||
break;
|
||||
sleep_us(controller_report_interval_us(DECK_REPORT_INTERVAL_US));
|
||||
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(DECK_REPORT_INTERVAL_US));
|
||||
}
|
||||
syscall(SYS_close, self->peer);
|
||||
munmap(self->ring, self->mapping_size);
|
||||
@@ -2037,7 +2060,8 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
|
||||
DeckExtras extras;
|
||||
const uint64_t start_us = monotonic_us();
|
||||
while (live_pad_type() == PAD_TYPE_STEAM) {
|
||||
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
|
||||
bool fresh = read_snapshot(self->ring, snap);
|
||||
if (fresh && snap.generation == ring_generation(self->ring)) {
|
||||
buttons = snap.buttons;
|
||||
memcpy(axes, snap.axes, sizeof(axes));
|
||||
}
|
||||
@@ -2048,7 +2072,7 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
|
||||
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
|
||||
errno != EAGAIN && errno != EWOULDBLOCK)
|
||||
break;
|
||||
sleep_us(controller_report_interval_us(TRITON_REPORT_INTERVAL_US));
|
||||
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(TRITON_REPORT_INTERVAL_US));
|
||||
}
|
||||
syscall(SYS_close, self->peer);
|
||||
munmap(self->ring, self->mapping_size);
|
||||
@@ -4016,6 +4040,7 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
|
||||
errno = ENODEV;
|
||||
return -1;
|
||||
}
|
||||
bool idle = false;
|
||||
for (int attempt = 0; attempt < 8; ++attempt) {
|
||||
size_t requested = count / sizeof(struct input_event);
|
||||
if (fake.keyframe_remaining == 0) {
|
||||
@@ -4037,7 +4062,10 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
|
||||
capture_keyframe(fake, snap);
|
||||
} else {
|
||||
size_t events = std::min<uint64_t>(requested, snap.write_seq - fake.read_seq);
|
||||
if (events == 0) break;
|
||||
if (events == 0) {
|
||||
idle = true;
|
||||
break;
|
||||
}
|
||||
const uint8_t *ring_events = reinterpret_cast<const uint8_t *>(fake.ring) +
|
||||
FAKE_INPUT_RING_HEADER_SIZE;
|
||||
std::vector<struct input_event> input_events(events);
|
||||
@@ -4083,9 +4111,14 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
|
||||
errno = EAGAIN;
|
||||
return -1;
|
||||
}
|
||||
const FakeInputRingHeader *ring = fake.ring;
|
||||
uint64_t seen = fake.read_seq;
|
||||
guard.unlock();
|
||||
#ifdef __GLIBC__
|
||||
pthread_testcancel();
|
||||
#endif
|
||||
struct timespec sleep_time = {0, backoff_ns};
|
||||
int result = nanosleep(&sleep_time, nullptr);
|
||||
int result = idle ? ring_wait(ring, seen, backoff_ns) : nanosleep(&sleep_time, nullptr);
|
||||
guard.lock();
|
||||
if (result < 0) return -1;
|
||||
if (low_latency(LATENCY_CONTROLLER)) backoff_ns = kLowLatencyRingWaitUs * 1000;
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
#include <errno.h>
|
||||
#include <jni.h>
|
||||
#include <limits.h>
|
||||
#include <linux/futex.h>
|
||||
#include <stdatomic.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
@@ -11,6 +14,13 @@ Java_com_droiddeck_launcher_input_FakeInputWriter_nativeStoreFence(JNIEnv *env,
|
||||
atomic_thread_fence(memory_order_release);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_input_FakeInputWriter_nativeWake(JNIEnv *env, jclass clazz, jobject buffer, jint offset) {
|
||||
(void)clazz;
|
||||
uint8_t *base = (*env)->GetDirectBufferAddress(env, buffer);
|
||||
if (base) syscall(SYS_futex, base + offset, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_session_ThreadSignals_tgkill(JNIEnv *env, jclass clazz, jint tgid, jint tid, jint signal) {
|
||||
(void)env;
|
||||
|
||||
@@ -20,6 +20,10 @@ class App : Application() {
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
if (android.os.Build.VERSION.SDK_INT >= 28 &&
|
||||
com.droiddeck.launcher.runtime.GuestWorker.isWorkerProcess(this, Application.getProcessName())) return
|
||||
if (android.os.Build.VERSION.SDK_INT >= 28 && Application.getProcessName() == packageName)
|
||||
com.droiddeck.launcher.runtime.GuestWorkers.attach(this)
|
||||
com.droiddeck.launcher.runtime.NativeGuest.init(this)
|
||||
com.droiddeck.launcher.session.Onboarding.attach(this)
|
||||
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
|
||||
|
||||
@@ -6960,9 +6960,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (!hasFocus && ::padMouse.isInitialized) padMouse.reset()
|
||||
if (runtimeRemovalBlocked) return
|
||||
if (!hasFocus) {
|
||||
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
|
||||
if (::touchpad.isInitialized) touchpad.cancel()
|
||||
if (::scrollTouch.isInitialized) scrollTouch.cancel()
|
||||
cancelTouchGestures()
|
||||
releaseHeldGuestInput()
|
||||
}
|
||||
if (hasFocus && !pipUi) {
|
||||
|
||||
@@ -89,7 +89,7 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
}
|
||||
}
|
||||
final java.io.PrintWriter log = out;
|
||||
pid = HostProcess.start(command.toString(), env.toArray(new String[0]),
|
||||
pid = HostProcess.startUncounted(command.toString(), env.toArray(new String[0]),
|
||||
app().getFilesDir(), null,
|
||||
line -> {
|
||||
Log.i(TAG, line);
|
||||
|
||||
@@ -186,13 +186,16 @@ public class PulseAudioComponent extends SessionPart {
|
||||
env.add("LD_LIBRARY_PATH=/system/lib64:" + modules + ":" + workingDir.getAbsolutePath());
|
||||
env.add("HOME=" + workingDir);
|
||||
env.add("TMPDIR=" + workingDir);
|
||||
// The daemon closes every fd at start but this one; in a worker process it is the binder
|
||||
// fd whose closing Android takes for the process's death.
|
||||
env.add("PULSE_PASSED_FD=" + com.droiddeck.launcher.runtime.GuestWorker.BINDER_FD_TOKEN);
|
||||
|
||||
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";
|
||||
final java.io.PrintWriter out = openLog();
|
||||
if (!host.launch(generation, () -> HostProcess.start(command, env.toArray(new String[0]), workingDir, status -> {
|
||||
if (!host.launch(generation, () -> HostProcess.startUncounted(command, env.toArray(new String[0]), workingDir, status -> {
|
||||
if (host.exited(generation)) {
|
||||
Log.w(TAG, "audio host exited with status " + status + "; restarting");
|
||||
start(generation);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
import java.util.function.Consumer
|
||||
@@ -7,6 +8,9 @@ import java.util.function.Consumer
|
||||
object HostProcess {
|
||||
private const val TAG = "HostProcess"
|
||||
private const val LINKER = "/system/bin/linker64"
|
||||
// sh -c WORKER_CD sh DIR NAME=VALUE... -- PROGRAM ARGS...
|
||||
private const val WORKER_CD = "cd \"\$1\" || exit 126; shift; " +
|
||||
"while [ \$# -gt 0 ] && [ \"\$1\" != -- ]; do export \"\$1\"; shift; done; shift; exec \"\$@\""
|
||||
|
||||
/** Android 10+ refuses to execute app data files for targetSdk 29+; its linker still loads them. */
|
||||
@JvmStatic
|
||||
@@ -65,6 +69,77 @@ object HostProcess {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* As [start], but the program runs as the main process of one of the app's worker processes,
|
||||
* which Android does not count against the app's child processes (docs/phantom-processes.md).
|
||||
* Falls back to [start] when no worker is available. The exit status is the program's exit
|
||||
* code, or 128 plus the signal that ended it, as Process.waitFor() reports it.
|
||||
*/
|
||||
@JvmStatic
|
||||
@JvmOverloads
|
||||
fun startUncounted(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?,
|
||||
outputFile: File? = null, onOutputComplete: Runnable? = null): Int {
|
||||
val context = com.droiddeck.launcher.runtime.GuestWorkers.context
|
||||
val argv = split(command)
|
||||
// A missing working directory fails the launch (start() returns -1 for it), not the program
|
||||
if (context == null || argv.isEmpty() || !com.droiddeck.launcher.runtime.GuestWorkers.enabled(context) ||
|
||||
(dir != null && !dir.isDirectory)) {
|
||||
return start(command, env, dir, onExit, onLine, outputFile, onOutputComplete)
|
||||
}
|
||||
val environment = LinkedHashMap(System.getenv())
|
||||
env?.forEach { line ->
|
||||
val eq = line.indexOf('=')
|
||||
if (eq > 0) environment[line.substring(0, eq)] = line.substring(eq + 1)
|
||||
}
|
||||
val assignments = environment.map { (k, v) -> "$k=$v" }
|
||||
// A worker cannot chdir before its exec, so Android's shell does it. The shell starts with an
|
||||
// environment of its own (the program's LD_PRELOAD of glibc libraries would stop it loading)
|
||||
// and exports the program's before the exec.
|
||||
val launch = if (dir != null) {
|
||||
listOf("/system/bin/sh", "-c", WORKER_CD, "sh", dir.path) + assignments + listOf("--") + argv
|
||||
} else argv
|
||||
val workerEnv = if (dir != null) listOf("PATH=/system/bin") else assignments
|
||||
var input: ParcelFileDescriptor? = null
|
||||
var reader: ParcelFileDescriptor? = null
|
||||
var output: ParcelFileDescriptor? = null
|
||||
val pid = try {
|
||||
input = ParcelFileDescriptor.open(File("/dev/null"), ParcelFileDescriptor.MODE_READ_ONLY)
|
||||
output = when {
|
||||
onLine != null -> ParcelFileDescriptor.createPipe().let { reader = it[0]; it[1] }
|
||||
outputFile != null -> ParcelFileDescriptor.open(outputFile,
|
||||
ParcelFileDescriptor.MODE_WRITE_ONLY or ParcelFileDescriptor.MODE_CREATE or ParcelFileDescriptor.MODE_APPEND)
|
||||
else -> ParcelFileDescriptor.open(File("/dev/null"), ParcelFileDescriptor.MODE_WRITE_ONLY)
|
||||
}
|
||||
com.droiddeck.launcher.runtime.GuestWorkers.start(context, launch, workerEnv, listOf(input, output, output)) { status ->
|
||||
onExit?.accept(if (status < 0) -1 else if (status and 0x7f == 0) (status shr 8) and 0xff else 128 + (status and 0x7f))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "no worker for ${argv.first()}", e)
|
||||
-1
|
||||
} finally {
|
||||
runCatching { input?.close() }
|
||||
runCatching { output?.close() }
|
||||
}
|
||||
if (pid <= 0) {
|
||||
reader?.close()
|
||||
return start(command, env, dir, onExit, onLine, outputFile, onOutputComplete)
|
||||
}
|
||||
Log.i(TAG, "started pid $pid outside the child-process count: ${argv.first()} (${argv.size - 1} arguments)")
|
||||
reader?.let { pipe ->
|
||||
Thread({
|
||||
try {
|
||||
ParcelFileDescriptor.AutoCloseInputStream(pipe).bufferedReader().useLines { lines ->
|
||||
lines.forEach { onLine?.accept(it) }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
} finally {
|
||||
onOutputComplete?.run()
|
||||
}
|
||||
}, "proc-out-$pid").apply { priority = Thread.NORM_PRIORITY - 1; isDaemon = true; start() }
|
||||
}
|
||||
return pid
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun pidOf(process: Process): Int = try {
|
||||
val field = process.javaClass.getDeclaredField("pid")
|
||||
|
||||
@@ -7,6 +7,8 @@ import com.droiddeck.launcher.R
|
||||
|
||||
enum class PhantomProcessStatus {
|
||||
NOT_APPLICABLE,
|
||||
/** The limit is on, but the session keeps its programs out of Android's count (GuestWorkers). */
|
||||
UNCOUNTED,
|
||||
DISABLED,
|
||||
ENABLED,
|
||||
UNSET,
|
||||
@@ -57,6 +59,12 @@ object PhantomProcessLimit {
|
||||
|
||||
fun read(context: Context, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus {
|
||||
if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE
|
||||
val status = readSetting(context, sdk)
|
||||
return if (status != PhantomProcessStatus.DISABLED && com.droiddeck.launcher.runtime.GuestWorkers.limitHandled(context))
|
||||
PhantomProcessStatus.UNCOUNTED else status
|
||||
}
|
||||
|
||||
private fun readSetting(context: Context, sdk: Int): PhantomProcessStatus {
|
||||
if (usesDeviceConfig(sdk)) {
|
||||
val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false)
|
||||
val global = try {
|
||||
@@ -101,7 +109,8 @@ object PhantomProcessLimit {
|
||||
fun hasDeveloperToggle(sdk: Int = Build.VERSION.SDK_INT): Boolean = sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
|
||||
|
||||
fun blocksSteam(status: PhantomProcessStatus): Boolean =
|
||||
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
|
||||
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED &&
|
||||
status != PhantomProcessStatus.UNCOUNTED
|
||||
|
||||
fun title(context: Context, status: PhantomProcessStatus): String = context.getString(when (status) {
|
||||
PhantomProcessStatus.ENABLED -> R.string.phantom_title_on
|
||||
@@ -109,6 +118,7 @@ object PhantomProcessLimit {
|
||||
PhantomProcessStatus.UNREADABLE -> R.string.phantom_title_unreadable
|
||||
PhantomProcessStatus.DISABLED -> R.string.phantom_title_off
|
||||
PhantomProcessStatus.NOT_APPLICABLE -> R.string.phantom_title_not_required
|
||||
PhantomProcessStatus.UNCOUNTED -> R.string.phantom_title_uncounted
|
||||
})
|
||||
|
||||
fun instructions(context: Context, status: PhantomProcessStatus): String = when (status) {
|
||||
@@ -116,6 +126,7 @@ object PhantomProcessLimit {
|
||||
context.getString(R.string.phantom_instructions_fix, fixSentence(context))
|
||||
PhantomProcessStatus.DISABLED -> context.getString(R.string.phantom_instructions_off)
|
||||
PhantomProcessStatus.NOT_APPLICABLE -> context.getString(R.string.phantom_instructions_not_applicable)
|
||||
PhantomProcessStatus.UNCOUNTED -> context.getString(R.string.phantom_instructions_uncounted)
|
||||
}
|
||||
|
||||
fun gateInstructions(context: Context, status: PhantomProcessStatus): String = when (status) {
|
||||
@@ -132,5 +143,6 @@ object PhantomProcessLimit {
|
||||
PhantomProcessStatus.UNSET -> "not set (ROM default applies; DroidDeck requires an explicit disabled value)"
|
||||
PhantomProcessStatus.UNREADABLE -> "unreadable (DroidDeck could not verify the setting)"
|
||||
PhantomProcessStatus.NOT_APPLICABLE -> "not applicable before Android 12"
|
||||
PhantomProcessStatus.UNCOUNTED -> "on, not needed (most of the session's programs run in uncounted worker processes)"
|
||||
}
|
||||
}
|
||||
@@ -28,17 +28,18 @@ object SessionLogCapture {
|
||||
out.flush()
|
||||
writer = out
|
||||
this.target = target
|
||||
pid = HostProcess.start(
|
||||
pid = HostProcess.startUncounted(
|
||||
command(Process.myPid(), sinceMillis),
|
||||
null, target.parentFile, null,
|
||||
) { line ->
|
||||
synchronized(this) {
|
||||
try {
|
||||
writer?.apply { write(line); newLine(); flush() }
|
||||
} catch (e: Exception) {
|
||||
onLine = { line ->
|
||||
synchronized(this) {
|
||||
try {
|
||||
writer?.apply { write(line); newLine(); flush() }
|
||||
} catch (e: Exception) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
if (pid == -1) {
|
||||
out.write("logcat could not be started; this ROM may not hand an app its own entries.\n")
|
||||
out.flush()
|
||||
|
||||
@@ -233,14 +233,14 @@ object AddedGames {
|
||||
if (folder.name.lowercase() in steamInstalls || isSteamLibraryFolder(folder.name)) continue
|
||||
if (folder.path in removed) continue
|
||||
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
|
||||
for (game in expand(folder, entries, reuse = true)) if (game.path !in removed) scanGame(context, game, out, reuse = true)
|
||||
timed(folder) { for (game in expand(folder, entries, reuse = true)) if (game.path !in removed) scanGame(context, game, out, reuse = true) }
|
||||
}
|
||||
}
|
||||
for (entry in AddedExes.list(context)) {
|
||||
val folder = File(entry.folder)
|
||||
if (folder.path in removed || !folder.isDirectory) continue
|
||||
if (StoreGameSidecar.read(folder)?.isInstalled == false) continue
|
||||
scanGame(context, folder, out, single = entry, reuse = true)
|
||||
timed(folder) { scanGame(context, folder, out, single = entry, reuse = true) }
|
||||
}
|
||||
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
|
||||
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out, reuse = true)
|
||||
@@ -250,6 +250,15 @@ object AddedGames {
|
||||
return out.distinctBy { it.folder.canonicalPath }
|
||||
}
|
||||
|
||||
private const val SLOW_FOLDER_MS = 1_000L
|
||||
|
||||
private inline fun timed(folder: File, block: () -> Unit) {
|
||||
val began = android.os.SystemClock.elapsedRealtime()
|
||||
block()
|
||||
val took = android.os.SystemClock.elapsedRealtime() - began
|
||||
if (took >= SLOW_FOLDER_MS) Log.i(TAG, "games: scanning ${folder.path} took ${took}ms")
|
||||
}
|
||||
|
||||
fun single(context: Context, folderPath: String, reuse: Boolean = false): Game? {
|
||||
val folder = File(folderPath)
|
||||
if (!folder.isDirectory || folderPath in SessionPrefs.removedAddedGames(context)) return null
|
||||
@@ -564,8 +573,10 @@ object AddedGames {
|
||||
|
||||
class Listed(val appId: Long, val name: String, val launchOptions: String)
|
||||
|
||||
fun listingFile(context: Context): File = File(context.filesDir, "session/added-games.json")
|
||||
|
||||
fun listed(context: Context): List<Listed>? = runCatching {
|
||||
val file = File(context.filesDir, "session/added-games.json")
|
||||
val file = listingFile(context)
|
||||
if (!file.isFile) return null
|
||||
val entries = org.json.JSONArray(file.readText())
|
||||
(0 until entries.length()).mapNotNull { i ->
|
||||
@@ -575,7 +586,7 @@ object AddedGames {
|
||||
|
||||
fun writeListing(context: Context, games: List<Game>,
|
||||
extra: List<JSONObject> = listOfNotNull(com.droiddeck.launcher.stores.epic.EpicClient.steamListing(context))): File {
|
||||
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
|
||||
val file = listingFile(context).apply { parentFile?.mkdirs() }
|
||||
val json = StringBuilder("[")
|
||||
games.forEachIndexed { i, g ->
|
||||
if (i > 0) json.append(',')
|
||||
@@ -596,10 +607,24 @@ object AddedGames {
|
||||
if (games.isNotEmpty() || i > 0) json.append(',')
|
||||
json.append(entry.toString())
|
||||
}
|
||||
file.writeText(json.append(']').toString())
|
||||
val text = json.append(']').toString()
|
||||
synchronized(listing) {
|
||||
val partial = File(file.parentFile, file.name + ".part")
|
||||
try {
|
||||
partial.writeText(text)
|
||||
java.nio.file.Files.move(partial.toPath(), file.toPath(),
|
||||
java.nio.file.StandardCopyOption.ATOMIC_MOVE, java.nio.file.StandardCopyOption.REPLACE_EXISTING)
|
||||
} catch (e: java.io.IOException) {
|
||||
Log.w(TAG, "games: listing not replaced: ${e.message}")
|
||||
partial.delete()
|
||||
if (!file.isFile) file.writeText(text)
|
||||
}
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
private val listing = Any()
|
||||
|
||||
private fun artGuestPath(context: Context, file: File): String? {
|
||||
val files = context.filesDir.absolutePath
|
||||
if (file.absolutePath.startsWith("$files/")) return file.absolutePath
|
||||
|
||||
@@ -1,17 +1,31 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Context
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import androidx.annotation.VisibleForTesting
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.stores.SteamLiveShortcuts
|
||||
import java.io.File
|
||||
import java.util.concurrent.Callable
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
object AddedGamesPublisher {
|
||||
private const val TAG = "AddedGamesPublisher"
|
||||
private const val CLIENT_WAIT_MS = 600_000L
|
||||
private const val POLL_MS = 1_000L
|
||||
private const val RETRY_MS = 5_000L
|
||||
|
||||
@VisibleForTesting
|
||||
@Volatile
|
||||
internal var now = false
|
||||
|
||||
@VisibleForTesting
|
||||
@Volatile
|
||||
internal var live: (Context, List<AddedGames.Game>, (AddedGames.Game) -> Boolean) -> Boolean = SteamLiveShortcuts::sync
|
||||
|
||||
private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "added-games-publish") }
|
||||
|
||||
fun later(context: Context, live: () -> Unit = {}) {
|
||||
@@ -23,10 +37,56 @@ object AddedGamesPublisher {
|
||||
if (now) work.run() else worker.execute(work)
|
||||
}
|
||||
|
||||
fun republish(context: Context) {
|
||||
fun republish(context: Context): List<AddedGames.Game> {
|
||||
val games = AddedGames.scan(context)
|
||||
AddedGames.writeListing(context, games)
|
||||
val arch = com.droiddeck.launcher.session.SessionPrefs.activeSteamClientArch(context)
|
||||
val arch = SessionPrefs.activeSteamClientArch(context)
|
||||
LibraryCache.save(context, Library.launchableGames(context, added = games, arch = arch), arch == "x86_64")
|
||||
return games
|
||||
}
|
||||
|
||||
fun sessionListing(context: Context): File {
|
||||
val app = context.applicationContext
|
||||
val started = AddedGames.listed(app)?.map { it.appId }?.toSet()
|
||||
?: return AddedGames.writeListing(app, AddedGames.scan(app).also { log(it) })
|
||||
val session = SessionState.sessionId
|
||||
val work = Runnable {
|
||||
try {
|
||||
val began = SystemClock.elapsedRealtime()
|
||||
val games = serial { republish(app) }
|
||||
Log.i(TAG, "session refresh: ${games.size} game(s) in ${SystemClock.elapsedRealtime() - began} ms")
|
||||
log(games)
|
||||
val fresh = games.filter { (it.appId and 0xFFFFFFFFL) !in started }
|
||||
if (fresh.isNotEmpty()) deliver(app, session, fresh)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "session refresh: ${e.message}")
|
||||
}
|
||||
}
|
||||
if (now) work.run() else Thread(work, "added-games-refresh").apply { priority = Thread.MIN_PRIORITY }.start()
|
||||
return AddedGames.listingFile(app)
|
||||
}
|
||||
|
||||
internal fun log(games: List<AddedGames.Game>) {
|
||||
if (games.isNotEmpty()) Log.i(TAG, "added games: " + games.joinToString { "${it.name} (${it.exe.name})" })
|
||||
}
|
||||
|
||||
private fun deliver(app: Context, session: String?, games: List<AddedGames.Game>) {
|
||||
val until = SystemClock.uptimeMillis() + CLIENT_WAIT_MS
|
||||
while (current(session)) {
|
||||
val ready = SessionState.phase == SessionPhase.READY
|
||||
if (ready && serial { !current(session) || (SessionState.phase == SessionPhase.READY && syncUnremoved(app, games)) }) return
|
||||
if (now || SystemClock.uptimeMillis() >= until) return
|
||||
Thread.sleep(if (ready) RETRY_MS else POLL_MS)
|
||||
}
|
||||
}
|
||||
|
||||
private fun current(session: String?): Boolean =
|
||||
SessionState.running && !SessionState.stopRequested && SessionState.sessionId == session
|
||||
|
||||
private fun syncUnremoved(app: Context, games: List<AddedGames.Game>): Boolean {
|
||||
val removed = SessionPrefs.removedAddedGames(app).toSet()
|
||||
return live(app, games) { it.folder.path !in removed }
|
||||
}
|
||||
|
||||
private fun <T> serial(block: () -> T): T = if (now) block() else worker.submit(Callable { block() }).get()
|
||||
}
|
||||
@@ -51,11 +51,12 @@ object GameExePicker {
|
||||
val entries = dir.listFiles()?.sortedBy { it.name.lowercase() } ?: continue
|
||||
for (f in entries) {
|
||||
if (visited >= WALK_BUDGET) break@walk
|
||||
if (isLink(f)) continue
|
||||
if (f.isDirectory) {
|
||||
val attrs = attributes(f) ?: continue
|
||||
if (attrs.isSymbolicLink) continue
|
||||
if (attrs.isDirectory) {
|
||||
visited++
|
||||
if (depth < MAX_DEPTH && !skipDir(f, f.relativeTo(folder).invariantSeparatorsPath)) next.add(f)
|
||||
} else if (f.isFile && f.name.endsWith(".exe", ignoreCase = true)) {
|
||||
} else if (attrs.isRegularFile && f.name.endsWith(".exe", ignoreCase = true)) {
|
||||
visited++
|
||||
if (!JUNK_EXE_RE.matches(f.nameWithoutExtension)) found.add(f to depth)
|
||||
}
|
||||
@@ -98,7 +99,9 @@ object GameExePicker {
|
||||
return SKIP_PATHS.any { rel == it || rel.endsWith("/$it") }
|
||||
}
|
||||
|
||||
private fun isLink(f: File): Boolean = runCatching { java.nio.file.Files.isSymbolicLink(f.toPath()) }.getOrDefault(false)
|
||||
private fun attributes(f: File): java.nio.file.attribute.BasicFileAttributes? = runCatching {
|
||||
java.nio.file.Files.readAttributes(f.toPath(), java.nio.file.attribute.BasicFileAttributes::class.java, java.nio.file.LinkOption.NOFOLLOW_LINKS)
|
||||
}.getOrNull()
|
||||
|
||||
private fun key(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.input
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.view.MotionEvent
|
||||
import kotlin.math.abs
|
||||
|
||||
@@ -24,6 +25,7 @@ class DirectTouchHold(
|
||||
private var delayMs = 0L
|
||||
private var holdBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK
|
||||
private var forwarded = false
|
||||
private var forwardedAt = 0L
|
||||
private var held = false
|
||||
private var pressing = false
|
||||
private var upX = 0f
|
||||
@@ -125,8 +127,11 @@ class DirectTouchHold(
|
||||
upX = event.x
|
||||
upY = event.y
|
||||
liftId = event.getPointerId(event.actionIndex)
|
||||
liftPending = true
|
||||
handler.postDelayed(lift, LIFT_MS)
|
||||
val wait = MIN_PRESS_MS - (SystemClock.uptimeMillis() - forwardedAt)
|
||||
if (wait > 0L) {
|
||||
liftPending = true
|
||||
handler.postDelayed(lift, wait)
|
||||
} else lift.run()
|
||||
}
|
||||
MotionEvent.ACTION_CANCEL -> cancel()
|
||||
}
|
||||
@@ -136,9 +141,10 @@ class DirectTouchHold(
|
||||
private fun forwardDown() {
|
||||
touch.down(downId, downX, downY)
|
||||
forwarded = true
|
||||
forwardedAt = SystemClock.uptimeMillis()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val LIFT_MS = 50L
|
||||
const val MIN_PRESS_MS = 50L
|
||||
}
|
||||
}
|
||||
@@ -149,6 +149,8 @@ public class FakeInputWriter {
|
||||
|
||||
private static native void nativeStoreFence();
|
||||
|
||||
private static native void nativeWake(ByteBuffer ring, int offset);
|
||||
|
||||
public static void storeFence() {
|
||||
nativeStoreFence();
|
||||
}
|
||||
@@ -455,6 +457,7 @@ public class FakeInputWriter {
|
||||
writeSnapshotLocked(ring);
|
||||
nativeStoreFence();
|
||||
ring.putLong(RING_WRITE_SEQ_OFFSET, writeSeq);
|
||||
nativeWake(ring, RING_WRITE_SEQ_OFFSET);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,707 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.app.Service
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.ServiceConnection
|
||||
import android.net.LocalServerSocket
|
||||
import android.net.LocalSocket
|
||||
import android.os.Binder
|
||||
import android.os.Handler
|
||||
import android.os.IBinder
|
||||
import android.os.Looper
|
||||
import android.os.Parcel
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.os.Process
|
||||
import android.system.ErrnoException
|
||||
import android.system.Os
|
||||
import android.system.OsConstants
|
||||
import android.system.StructPollfd
|
||||
import android.util.Log
|
||||
import org.json.JSONObject
|
||||
import java.io.DataInputStream
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* A guest program run as the main process of its own Android process.
|
||||
*
|
||||
* Android counts the processes in an app process's cgroup against its child-process limit, but not
|
||||
* the app processes themselves. The worker execs the program in place; its binder fd stays open
|
||||
* across the exec, so the system keeps the process as a live service process. The program's own
|
||||
* children are still counted. See docs/phantom-processes.md.
|
||||
*/
|
||||
open class GuestWorker : Service() {
|
||||
private val binder = object : Binder() {
|
||||
override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean {
|
||||
if (code != RUN) return super.onTransact(code, data, reply, flags)
|
||||
val argv = data.createStringArray() ?: return false
|
||||
val env = data.createStringArray() ?: return false
|
||||
val fds = List(data.readInt()) { data.readFileDescriptor() }
|
||||
val targets = data.createIntArray() ?: IntArray(fds.size) { it }
|
||||
val fillBinderFd = data.readInt() != 0
|
||||
val go = data.readFileDescriptor()
|
||||
reply?.writeInt(Process.myPid())
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
// The app writes a byte once it has the reply and has taken the launch on: an exec
|
||||
// before then would end this process with the reply undelivered, and with none (the
|
||||
// app gave up and starts the program another way) the program must not run here.
|
||||
var why = ""
|
||||
// poll() with a timeout counts as network I/O to StrictMode on the main thread
|
||||
android.os.StrictMode.setThreadPolicy(android.os.StrictMode.ThreadPolicy.LAX)
|
||||
val committed = runCatching {
|
||||
val poll = StructPollfd().apply { fd = go.fileDescriptor; events = OsConstants.POLLIN.toShort() }
|
||||
val ready = Os.poll(arrayOf(poll), GO_TIMEOUT_MS)
|
||||
val got = if (ready > 0) Os.read(go.fileDescriptor, ByteArray(1), 0, 1) else -1
|
||||
why = "poll $ready revents ${poll.revents} read $got"
|
||||
// and the answer the app waits for before it reports the launch as started
|
||||
got == 1 && Os.write(go.fileDescriptor, byteArrayOf(1), 0, 1) == 1
|
||||
}.getOrElse { why = it.toString(); false }
|
||||
go.close()
|
||||
if (committed) exec(argv, env, fds, targets, fillBinderFd)
|
||||
else {
|
||||
Log.w(TAG, "launch not committed ($why): not running ${argv.firstOrNull()}")
|
||||
Process.killProcess(Process.myPid())
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent): IBinder = binder
|
||||
|
||||
private fun exec(argv: Array<String>, env: Array<String>, fds: List<ParcelFileDescriptor?>, targets: IntArray, fillBinderFd: Boolean) {
|
||||
try {
|
||||
val top = targets.maxOrNull() ?: 2
|
||||
val (binderTop, binderFd) = keepBinderOpen(maxOf(BINDER_FDS, top + 1))
|
||||
// Out of the way first, so that placing one fd cannot overwrite another not yet placed.
|
||||
val above = maxOf(MOVED_FDS, top + 1, binderTop + 1)
|
||||
val moved = fds.map { pfd -> pfd?.let { Os.fcntlInt(it.fileDescriptor, OsConstants.F_DUPFD, above) } }
|
||||
moved.forEachIndexed { i, fd ->
|
||||
if (fd == null || i >= targets.size) return@forEachIndexed
|
||||
val source = ParcelFileDescriptor.adoptFd(fd).also { kept.add(it) }.fileDescriptor
|
||||
Os.dup2(source, targets[i])
|
||||
Os.fcntlInt(source, OsConstants.F_SETFD, OsConstants.FD_CLOEXEC)
|
||||
}
|
||||
// A session of its own: in zygote's process group, a program signalling its group
|
||||
// (kill(0, sig)) would reach every process of the app.
|
||||
runCatching { Os.setsid() }
|
||||
// The native hook closes the binder fds in every other process (hook/handoff.c). Only an
|
||||
// app launch asks for the number (a whole argument or variable value), never a guest's.
|
||||
val fill = { arg: String ->
|
||||
if (!fillBinderFd) arg
|
||||
else if (arg == BINDER_FD_TOKEN) binderFd.toString()
|
||||
else if (arg.endsWith("=$BINDER_FD_TOKEN")) arg.removeSuffix(BINDER_FD_TOKEN) + binderFd
|
||||
else arg
|
||||
}
|
||||
// This thread blocks SIGQUIT, SIGUSR1 and SIGPIPE (Android's runtime), and an exec keeps
|
||||
// that: the program's hook sets DDH_SIGMASK instead (none blocked, unless the request says).
|
||||
val mask = if (env.any { it.startsWith("DDH_SIGMASK=") }) emptyList() else listOf("DDH_SIGMASK=0")
|
||||
Os.execve(argv[0], argv.map(fill).toTypedArray(),
|
||||
env.filterNot { it.startsWith("DDH_WORKER_PID=") }.map(fill).toTypedArray() + mask +
|
||||
"DDH_WORKER_PID=${Process.myPid()}")
|
||||
} catch (e: ErrnoException) {
|
||||
Log.e(TAG, "could not exec ${argv.firstOrNull()}", e)
|
||||
}
|
||||
Process.killProcess(Process.myPid())
|
||||
}
|
||||
|
||||
/**
|
||||
* Binder fds stay open across the exec, at [from] or above, where no fd of the program goes.
|
||||
* Returns the highest fd used and the one on /dev/binder, whose closing Android takes for
|
||||
* the death of this process.
|
||||
*/
|
||||
private fun keepBinderOpen(from: Int): Pair<Int, Int> {
|
||||
var highest = from - 1
|
||||
var binder = -1
|
||||
File("/proc/self/fd").listFiles()?.forEach { link ->
|
||||
val target = runCatching { Os.readlink(link.path) }.getOrNull() ?: return@forEach
|
||||
if (target !in BINDER_DEVICES && !target.startsWith("/dev/binderfs/")) return@forEach
|
||||
// A copy, not adoptFd(): some of these fds are owned (fdsan) by a ParcelFileDescriptor.
|
||||
val copy = runCatching { ParcelFileDescriptor.fromFd(link.name.toIntOrNull() ?: return@forEach) }.getOrNull()
|
||||
?: return@forEach
|
||||
val kept = Os.fcntlInt(copy.fileDescriptor, OsConstants.F_DUPFD, from)
|
||||
highest = maxOf(highest, kept)
|
||||
if (target.substringAfterLast('/') == "binder") binder = kept
|
||||
copy.close()
|
||||
}
|
||||
return highest to binder
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val RUN = IBinder.FIRST_CALL_TRANSACTION
|
||||
/** An argument, or a variable's whole value, in an app launch: replaced by the number of its kept binder fd. */
|
||||
const val BINDER_FD_TOKEN = "@DDH_WORKER_BINDER_FD@"
|
||||
// Longer than the app may wait for the hook's "go" (GuestWorkers.ACK_TIMEOUT_MS) before it commits
|
||||
private const val GO_TIMEOUT_MS = 15000
|
||||
private val BINDER_DEVICES = setOf("/dev/binder", "/dev/hwbinder", "/dev/vndbinder")
|
||||
private const val BINDER_FDS = 900
|
||||
private const val MOVED_FDS = 1200
|
||||
private const val TAG = "GuestWorker"
|
||||
private val kept = ArrayList<ParcelFileDescriptor>()
|
||||
|
||||
fun isWorkerProcess(context: Context, process: String?): Boolean =
|
||||
process != null && process.startsWith(context.packageName + ":g") &&
|
||||
process.substring(context.packageName.length + 2).all { it.isDigit() }
|
||||
}
|
||||
}
|
||||
|
||||
class GuestWorker0 : GuestWorker()
|
||||
class GuestWorker1 : GuestWorker()
|
||||
class GuestWorker2 : GuestWorker()
|
||||
class GuestWorker3 : GuestWorker()
|
||||
class GuestWorker4 : GuestWorker()
|
||||
class GuestWorker5 : GuestWorker()
|
||||
class GuestWorker6 : GuestWorker()
|
||||
class GuestWorker7 : GuestWorker()
|
||||
class GuestWorker8 : GuestWorker()
|
||||
class GuestWorker9 : GuestWorker()
|
||||
class GuestWorker10 : GuestWorker()
|
||||
class GuestWorker11 : GuestWorker()
|
||||
class GuestWorker12 : GuestWorker()
|
||||
class GuestWorker13 : GuestWorker()
|
||||
class GuestWorker14 : GuestWorker()
|
||||
class GuestWorker15 : GuestWorker()
|
||||
class GuestWorker16 : GuestWorker()
|
||||
class GuestWorker17 : GuestWorker()
|
||||
class GuestWorker18 : GuestWorker()
|
||||
class GuestWorker19 : GuestWorker()
|
||||
class GuestWorker20 : GuestWorker()
|
||||
class GuestWorker21 : GuestWorker()
|
||||
class GuestWorker22 : GuestWorker()
|
||||
class GuestWorker23 : GuestWorker()
|
||||
class GuestWorker24 : GuestWorker()
|
||||
class GuestWorker25 : GuestWorker()
|
||||
class GuestWorker26 : GuestWorker()
|
||||
class GuestWorker27 : GuestWorker()
|
||||
class GuestWorker28 : GuestWorker()
|
||||
class GuestWorker29 : GuestWorker()
|
||||
class GuestWorker30 : GuestWorker()
|
||||
class GuestWorker31 : GuestWorker()
|
||||
class GuestWorker32 : GuestWorker()
|
||||
class GuestWorker33 : GuestWorker()
|
||||
class GuestWorker34 : GuestWorker()
|
||||
class GuestWorker35 : GuestWorker()
|
||||
class GuestWorker36 : GuestWorker()
|
||||
class GuestWorker37 : GuestWorker()
|
||||
class GuestWorker38 : GuestWorker()
|
||||
class GuestWorker39 : GuestWorker()
|
||||
class GuestWorker40 : GuestWorker()
|
||||
class GuestWorker41 : GuestWorker()
|
||||
class GuestWorker42 : GuestWorker()
|
||||
class GuestWorker43 : GuestWorker()
|
||||
class GuestWorker44 : GuestWorker()
|
||||
class GuestWorker45 : GuestWorker()
|
||||
class GuestWorker46 : GuestWorker()
|
||||
class GuestWorker47 : GuestWorker()
|
||||
class GuestWorker48 : GuestWorker()
|
||||
class GuestWorker49 : GuestWorker()
|
||||
class GuestWorker50 : GuestWorker()
|
||||
class GuestWorker51 : GuestWorker()
|
||||
class GuestWorker52 : GuestWorker()
|
||||
class GuestWorker53 : GuestWorker()
|
||||
class GuestWorker54 : GuestWorker()
|
||||
class GuestWorker55 : GuestWorker()
|
||||
class GuestWorker56 : GuestWorker()
|
||||
class GuestWorker57 : GuestWorker()
|
||||
class GuestWorker58 : GuestWorker()
|
||||
class GuestWorker59 : GuestWorker()
|
||||
class GuestWorker60 : GuestWorker()
|
||||
class GuestWorker61 : GuestWorker()
|
||||
class GuestWorker62 : GuestWorker()
|
||||
class GuestWorker63 : GuestWorker()
|
||||
|
||||
/** The pool of [GuestWorker] processes, and the socket guests ask it through (`droiddeck-spawn`). */
|
||||
object GuestWorkers {
|
||||
private const val TAG = "GuestWorkers"
|
||||
private val classes: List<Class<out GuestWorker>> = listOf(
|
||||
GuestWorker0::class.java, GuestWorker1::class.java, GuestWorker2::class.java,
|
||||
GuestWorker3::class.java, GuestWorker4::class.java, GuestWorker5::class.java,
|
||||
GuestWorker6::class.java, GuestWorker7::class.java, GuestWorker8::class.java,
|
||||
GuestWorker9::class.java, GuestWorker10::class.java, GuestWorker11::class.java,
|
||||
GuestWorker12::class.java, GuestWorker13::class.java, GuestWorker14::class.java,
|
||||
GuestWorker15::class.java, GuestWorker16::class.java, GuestWorker17::class.java,
|
||||
GuestWorker18::class.java, GuestWorker19::class.java, GuestWorker20::class.java,
|
||||
GuestWorker21::class.java, GuestWorker22::class.java, GuestWorker23::class.java,
|
||||
GuestWorker24::class.java, GuestWorker25::class.java, GuestWorker26::class.java,
|
||||
GuestWorker27::class.java, GuestWorker28::class.java, GuestWorker29::class.java,
|
||||
GuestWorker30::class.java, GuestWorker31::class.java, GuestWorker32::class.java,
|
||||
GuestWorker33::class.java, GuestWorker34::class.java, GuestWorker35::class.java,
|
||||
GuestWorker36::class.java, GuestWorker37::class.java, GuestWorker38::class.java,
|
||||
GuestWorker39::class.java, GuestWorker40::class.java, GuestWorker41::class.java,
|
||||
GuestWorker42::class.java, GuestWorker43::class.java, GuestWorker44::class.java,
|
||||
GuestWorker45::class.java, GuestWorker46::class.java, GuestWorker47::class.java,
|
||||
GuestWorker48::class.java, GuestWorker49::class.java, GuestWorker50::class.java,
|
||||
GuestWorker51::class.java, GuestWorker52::class.java, GuestWorker53::class.java,
|
||||
GuestWorker54::class.java, GuestWorker55::class.java, GuestWorker56::class.java,
|
||||
GuestWorker57::class.java, GuestWorker58::class.java, GuestWorker59::class.java,
|
||||
GuestWorker60::class.java, GuestWorker61::class.java, GuestWorker62::class.java,
|
||||
GuestWorker63::class.java,
|
||||
)
|
||||
|
||||
private class Slot(val index: Int) {
|
||||
lateinit var connection: ServiceConnection
|
||||
val connected = CountDownLatch(1)
|
||||
@Volatile var service: IBinder? = null
|
||||
@Volatile var pid = -1
|
||||
@Volatile var guest = false
|
||||
/** The session it runs a program for ([serve]'s number). */
|
||||
@Volatile var session = 0
|
||||
@Volatile var onExit: ((Int) -> Unit)? = null
|
||||
/** Set once its program was handed over: only then does its end count as the program's. */
|
||||
@Volatile var started = false
|
||||
}
|
||||
|
||||
private val slots = arrayOfNulls<Slot>(classes.size)
|
||||
// Workers bound ahead of need while a session runs: a zygote fork and the bind take about
|
||||
// 60-100 ms, which every program the session starts would otherwise wait for.
|
||||
private val warm = ArrayDeque<Slot>()
|
||||
@Volatile private var warmTarget = 0
|
||||
// Numbers the sessions: an old session's teardown can still be running when the next one starts.
|
||||
@Volatile private var session = 0
|
||||
// The latest session whose teardown has begun
|
||||
@Volatile private var stopped = 0
|
||||
private val warming = java.util.concurrent.atomic.AtomicBoolean(false)
|
||||
private const val WARM_WORKERS = 2
|
||||
private const val ACK_TIMEOUT_MS = 5000
|
||||
private const val ANSWER_TIMEOUT_MS = 5000
|
||||
private val connections = java.util.concurrent.Executors.newSingleThreadExecutor { Thread(it, "guest-worker-binder").apply { isDaemon = true } }
|
||||
@Volatile private var server: Thread? = null
|
||||
|
||||
/** The app, once [attach] or [serve] ran in its main process; null before. */
|
||||
@Volatile var context: Context? = null
|
||||
private set
|
||||
|
||||
/** Whether the session runs its programs in workers: the native userland, and not turned off. */
|
||||
fun enabled(context: Context): Boolean =
|
||||
android.os.Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.session.SessionPrefs.childProcessHandoff(context) &&
|
||||
NativeGuest.enabled(context)
|
||||
|
||||
/** How the running session's root was started: in a worker (true) or counted (false); null with none running. */
|
||||
@Volatile var sessionRootUncounted: Boolean? = null
|
||||
|
||||
/**
|
||||
* Whether Android's child-process limit is out of the session's way: as the running session
|
||||
* started (a proot session, or one whose root fell back to a counted start, is not), else as
|
||||
* the next one would start.
|
||||
*/
|
||||
fun limitHandled(context: Context): Boolean =
|
||||
sessionRootUncounted ?: (NativeGuest.sessionMode != false && enabled(context))
|
||||
|
||||
/** Whether pid is a program running in one of the workers. */
|
||||
fun runsInWorker(pid: Int): Boolean = pid > 0 && synchronized(slots) { slots.any { it != null && it.started && it.pid == pid } }
|
||||
|
||||
fun socketName(context: Context): String = "droiddeck-spawn." + context.packageName + "." + Process.myUid()
|
||||
|
||||
/**
|
||||
* Runs [argv] (a host command line) as the main process of a free worker with [env] and the
|
||||
* fds in [stdio] as its 0, 1 and 2. Returns its pid, or -1. Blocks: not for the main thread.
|
||||
* [onExit] runs once the process is gone.
|
||||
*/
|
||||
fun start(context: Context, argv: List<String>, env: List<String>, stdio: List<ParcelFileDescriptor>, onExit: (Int) -> Unit): Int =
|
||||
start(context, argv, env, stdio, IntArray(stdio.size) { it }, onExit)
|
||||
|
||||
/** As [start], with the fds in [fds] placed at the numbers in [targets]. */
|
||||
fun start(context: Context, argv: List<String>, env: List<String>, fds: List<ParcelFileDescriptor>, targets: IntArray,
|
||||
onExit: (Int) -> Unit): Int = start(context, argv, env, fds, targets, false, onExit)
|
||||
|
||||
/**
|
||||
* [guest]: one of the session's guest programs, which [guestPids] lists and [stopGuests] ends.
|
||||
* [commit] runs with the pid before the worker may run the program; false, and it does not.
|
||||
*/
|
||||
private fun start(context: Context, argv: List<String>, env: List<String>, fds: List<ParcelFileDescriptor>, targets: IntArray,
|
||||
guest: Boolean, onExit: (Int) -> Unit, commit: (Int) -> Boolean = { true }): Int {
|
||||
val app = context.applicationContext
|
||||
// The session asking: a cold bind can take long enough for it to stop and another to start
|
||||
val owner = session
|
||||
if (guest && owner <= stopped) {
|
||||
Log.w(TAG, "session $owner is stopping: not starting ${argv.firstOrNull()}")
|
||||
return -1
|
||||
}
|
||||
val slot = takeWarm() ?: bind(app)?.takeIf { fresh ->
|
||||
fresh.connected.await(10, TimeUnit.SECONDS).also { if (!it) release(app, fresh) }
|
||||
} ?: run {
|
||||
Log.w(TAG, "no worker started for ${argv.firstOrNull()}")
|
||||
return -1
|
||||
}
|
||||
slot.guest = guest
|
||||
slot.session = owner
|
||||
slot.onExit = onExit
|
||||
refill(app)
|
||||
// The worker execs once a byte comes through this socket: after the reply has reached us, so
|
||||
// that its exec does not cut the reply off, and after the slot is marked started. Closed
|
||||
// without one, the worker ends without running the program (the caller starts it another way).
|
||||
// It answers with a byte of its own: without that it gave up waiting, and nothing runs.
|
||||
var go: Array<ParcelFileDescriptor>? = null
|
||||
val data = Parcel.obtain()
|
||||
val reply = Parcel.obtain()
|
||||
try {
|
||||
go = ParcelFileDescriptor.createSocketPair()
|
||||
data.writeStringArray(argv.toTypedArray())
|
||||
data.writeStringArray(env.toTypedArray())
|
||||
data.writeInt(fds.size)
|
||||
fds.forEach { data.writeFileDescriptor(it.fileDescriptor) }
|
||||
data.writeIntArray(targets)
|
||||
data.writeInt(if (guest) 0 else 1)
|
||||
data.writeFileDescriptor(go[0].fileDescriptor)
|
||||
slot.service!!.transact(GuestWorker.RUN, data, reply, 0)
|
||||
val pid = reply.readInt()
|
||||
// Once a session's teardown has begun (stopGuests), none of its programs may start: it
|
||||
// would not find them.
|
||||
val stopping = { guest && owner <= stopped }
|
||||
if (stopping() || !commit(pid)) {
|
||||
Log.w(TAG, "worker ${slot.index}: ${argv.firstOrNull()} was not taken on")
|
||||
release(app, slot)
|
||||
return -1
|
||||
}
|
||||
val live = synchronized(slots) {
|
||||
(slots[slot.index] === slot && !stopping()).also { if (it) { slot.pid = pid; slot.started = true } }
|
||||
}
|
||||
if (!live) {
|
||||
Log.w(TAG, "worker ${slot.index} ended, or its session is stopping, before running ${argv.firstOrNull()}")
|
||||
release(app, slot)
|
||||
return -1
|
||||
}
|
||||
Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1)
|
||||
val answer = StructPollfd().apply { fd = go[1].fileDescriptor; events = OsConstants.POLLIN.toShort() }
|
||||
val accepted = Os.poll(arrayOf(answer), ANSWER_TIMEOUT_MS) > 0 && Os.read(go[1].fileDescriptor, ByteArray(1), 0, 1) == 1
|
||||
if (!accepted) {
|
||||
Log.w(TAG, "worker ${slot.index} did not take ${argv.firstOrNull()} on")
|
||||
slot.started = false
|
||||
release(app, slot)
|
||||
return -1
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "worker ${slot.index} refused ${argv.firstOrNull()}", e)
|
||||
release(app, slot)
|
||||
return -1
|
||||
} finally {
|
||||
data.recycle()
|
||||
reply.recycle()
|
||||
go?.forEach { runCatching { it.close() } }
|
||||
}
|
||||
Log.i(TAG, "worker ${slot.index} (pid ${slot.pid}) runs ${argv.lastOrNull { !it.startsWith("-") }}")
|
||||
return slot.pid
|
||||
}
|
||||
|
||||
/** Binds a free worker; its [Slot.connected] opens once it is up. Null when all are in use. */
|
||||
private fun bind(app: Context): Slot? {
|
||||
val slot = synchronized(slots) {
|
||||
val index = slots.indexOfFirst { it == null }
|
||||
if (index < 0) {
|
||||
Log.w(TAG, "all ${slots.size} workers are busy")
|
||||
return null
|
||||
}
|
||||
Slot(index).also { slots[index] = it }
|
||||
}
|
||||
slot.connection = object : ServiceConnection {
|
||||
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
|
||||
slot.service = binder
|
||||
slot.connected.countDown()
|
||||
}
|
||||
|
||||
override fun onServiceDisconnected(name: ComponentName) = release(app, slot)
|
||||
|
||||
override fun onBindingDied(name: ComponentName) = release(app, slot)
|
||||
}
|
||||
// Callbacks off the main thread: start() waits for onServiceConnected, and a caller holding a
|
||||
// lock the main thread is waiting for (PulseAudio's launch) would otherwise wait out the timeout.
|
||||
val bound = runCatching {
|
||||
app.bindService(Intent(app, classes[slot.index]), Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT,
|
||||
connections, slot.connection)
|
||||
}.onFailure { Log.w(TAG, "worker ${slot.index} could not be bound", it) }.getOrDefault(false)
|
||||
if (!bound) {
|
||||
release(app, slot)
|
||||
return null
|
||||
}
|
||||
return slot
|
||||
}
|
||||
|
||||
private fun takeWarm(): Slot? = synchronized(slots) {
|
||||
while (warm.isNotEmpty()) {
|
||||
val slot = warm.removeFirst()
|
||||
if (slots[slot.index] === slot && slot.service?.isBinderAlive == true) return slot
|
||||
}
|
||||
null
|
||||
}
|
||||
|
||||
/** Brings the warm workers back up to [warmTarget], one at a time, off the caller's thread. */
|
||||
private fun refill(app: Context) {
|
||||
if (warmTarget == 0 || !warming.compareAndSet(false, true)) return
|
||||
Thread({
|
||||
try {
|
||||
while (true) {
|
||||
val missing = warmTarget - synchronized(slots) { warm.size }
|
||||
if (missing <= 0) break
|
||||
// all at once: the zygote forks them in parallel
|
||||
val fresh = (1..missing).mapNotNull { bind(app) }
|
||||
if (fresh.isEmpty()) break
|
||||
for (slot in fresh) {
|
||||
if (!slot.connected.await(10, TimeUnit.SECONDS)) {
|
||||
release(app, slot)
|
||||
continue
|
||||
}
|
||||
// decided once, under the lock: kept warm, or released
|
||||
val kept = synchronized(slots) {
|
||||
(slots[slot.index] === slot && warmTarget > 0).also { if (it) warm.addLast(slot) }
|
||||
}
|
||||
if (!kept) release(app, slot)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
warming.set(false)
|
||||
}
|
||||
}, "guest-worker-warm").apply { isDaemon = true; start() }
|
||||
}
|
||||
|
||||
private fun release(app: Context, slot: Slot) {
|
||||
val removed = synchronized(slots) {
|
||||
warm.remove(slot)
|
||||
(slots[slot.index] === slot).also { if (it) slots[slot.index] = null }
|
||||
}
|
||||
if (!removed) return
|
||||
runCatching { app.unbindService(slot.connection) }
|
||||
val onExit = slot.onExit
|
||||
if (slot.started && onExit != null) Thread({ onExit(exitStatus(app, slot.pid)) }, "guest-worker-exit").start()
|
||||
}
|
||||
|
||||
/** The worker's exit as a wait status (exit code << 8, or the signal), -1 when unknown. */
|
||||
private fun exitStatus(app: Context, pid: Int): Int {
|
||||
if (pid <= 0 || android.os.Build.VERSION.SDK_INT < 30) return -1
|
||||
val am = app.getSystemService(ActivityManager::class.java)
|
||||
var recorded = false
|
||||
repeat(20) {
|
||||
am.getHistoricalProcessExitReasons(app.packageName, pid, 1).firstOrNull()?.let {
|
||||
recorded = true
|
||||
// an exit code only when the process exited itself; a signal number otherwise (a native crash)
|
||||
if (it.reason == android.app.ApplicationExitInfo.REASON_EXIT_SELF) return (it.status and 0xff) shl 8
|
||||
if (it.status in 1..64) return it.status and 0x7f
|
||||
// Android records the death first and the zygote's status later (as UNKNOWN, 0, then
|
||||
// EXIT_SELF): a reason without a status may still be completed
|
||||
if (it.reason != android.app.ApplicationExitInfo.REASON_UNKNOWN) return OsConstants.SIGKILL
|
||||
}
|
||||
Thread.sleep(50)
|
||||
}
|
||||
// killed by Android with no signal recorded, not a clean exit
|
||||
return if (recorded) OsConstants.SIGKILL else -1
|
||||
}
|
||||
|
||||
/** The pids of session [of]'s guest programs running in workers. */
|
||||
fun guestPids(of: Int = session): List<Int> =
|
||||
synchronized(slots) { slots.mapNotNull { s -> s?.takeIf { it.guest && it.session == of }?.pid?.takeIf { it > 0 } } }
|
||||
|
||||
/** Ends session [of]'s guest programs that are still running, and, for the latest session, the warm workers. */
|
||||
fun stopGuests(of: Int = session) {
|
||||
// the check and the reset together: a new session's serve() may be under way
|
||||
val drained = synchronized(slots) {
|
||||
stopped = maxOf(stopped, of)
|
||||
if (of != session) emptyList() else { warmTarget = 0; warm.toList().also { warm.clear() } }
|
||||
}
|
||||
context?.let { app -> drained.forEach { release(app, it) } }
|
||||
val pids = guestPids(of)
|
||||
if (pids.isEmpty()) return
|
||||
pids.forEach { Process.sendSignal(it, OsConstants.SIGTERM) }
|
||||
Thread.sleep(500)
|
||||
pids.forEach { Process.killProcess(it) }
|
||||
}
|
||||
|
||||
/** Listens for `droiddeck-spawn` requests from the session's guests. */
|
||||
fun attach(context: Context) {
|
||||
this.context = context.applicationContext
|
||||
}
|
||||
|
||||
/** Starts a session's use of the workers (and the spawn socket, once); returns its number. */
|
||||
fun serve(context: Context): Int {
|
||||
val app = context.applicationContext
|
||||
this.context = app
|
||||
val number = synchronized(slots) { warmTarget = WARM_WORKERS; ++session }
|
||||
refill(app)
|
||||
synchronized(this) {
|
||||
if (server != null) return number
|
||||
server = Thread({
|
||||
val socket = try {
|
||||
LocalServerSocket(socketName(app))
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "no spawn socket", e)
|
||||
synchronized(this) { server = null }
|
||||
return@Thread
|
||||
}
|
||||
while (true) {
|
||||
val client = runCatching { socket.accept() }.getOrNull()
|
||||
if (client == null) {
|
||||
Thread.sleep(100) // out of fds, for one: do not spin
|
||||
continue
|
||||
}
|
||||
Thread({
|
||||
try {
|
||||
handle(app, client)
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "spawn request failed", e)
|
||||
}
|
||||
}, "guest-spawn").start()
|
||||
}
|
||||
}, "guest-spawn-server").apply { isDaemon = true; start() }
|
||||
}
|
||||
return number
|
||||
}
|
||||
|
||||
private fun handle(app: Context, client: LocalSocket) {
|
||||
client.use {
|
||||
if (client.peerCredentials.uid != Process.myUid()) return
|
||||
val input = DataInputStream(client.inputStream)
|
||||
val payload = ByteArray(input.readInt()).also { input.readFully(it) }
|
||||
val request = JSONObject(String(payload))
|
||||
val fds = ArrayList<ParcelFileDescriptor>()
|
||||
fun take() {
|
||||
val received = client.ancillaryFileDescriptors.orEmpty()
|
||||
try {
|
||||
received.forEach { fds.add(ParcelFileDescriptor.dup(it)) }
|
||||
} finally {
|
||||
received.forEach { runCatching { Os.close(it) } }
|
||||
}
|
||||
}
|
||||
// Until start() has them: closed on every way out before that, from the first chunk on
|
||||
var handedOver = false
|
||||
try {
|
||||
if (request.has("fdchunks")) {
|
||||
// The hook sends its fds after the request, a chunk with each byte (hook/handoff.c)
|
||||
val total = (request.optJSONArray("fds")?.length() ?: 0) + (if (request.has("table")) 1 else 0)
|
||||
while (fds.size < total) {
|
||||
if (input.read() < 0) throw java.io.EOFException("fds ended at ${fds.size} of $total")
|
||||
take()
|
||||
}
|
||||
} else {
|
||||
take()
|
||||
}
|
||||
val argv = request.getJSONArray("argv").let { a -> List(a.length()) { a.getString(it) } }
|
||||
val env = LinkedHashMap<String, String>()
|
||||
request.optJSONObject("env")?.let { o -> o.keys().forEach { env[it] = o.getString(it) } }
|
||||
request.optJSONArray("envlist")?.let { a ->
|
||||
for (i in 0 until a.length()) a.getString(i).split('=', limit = 2).let { if (it.size == 2) env[it[0]] = it[1] }
|
||||
}
|
||||
// What the hook told the program that asked (it may run in a worker itself) is not this one's
|
||||
env.keys.removeAll { it.startsWith("DDH_") }
|
||||
val cwd = request.optString("cwd", "/")
|
||||
val wait = request.optBoolean("wait", false)
|
||||
// A path without a slash names a file in the cwd, as execve() takes it, not one on PATH
|
||||
val file = request.optString("file", "").let { if (it.isNotEmpty() && '/' !in it) "./$it" else it }
|
||||
// The handoff table (the hook's) comes last among the fds; the rest go to these numbers.
|
||||
val tableIndex = request.optInt("table", -1)
|
||||
val numbers = request.optJSONArray("fds")?.let { a -> IntArray(a.length()) { a.getInt(it) } } ?: IntArray(3) { it }
|
||||
val table = fds.getOrNull(tableIndex)?.takeIf { pfd ->
|
||||
runCatching { Os.readlink("/proc/self/fd/${pfd.fd}") }.getOrNull()?.contains("ddnatv-handoff") == true
|
||||
}
|
||||
val slot = request.optInt("slot", -1)
|
||||
val parent = request.optInt("parent", -1)
|
||||
var programFds = fds.filterIndexed { i, _ -> i != tableIndex }
|
||||
var targets = numbers
|
||||
if (table != null && slot >= 0) {
|
||||
// The program reports its own exit status into the table (hook/handoff.c)
|
||||
val tableFd = (numbers.maxOrNull() ?: 2) + 1
|
||||
programFds = programFds + table
|
||||
targets = numbers + tableFd
|
||||
env["DDH_TABLE"] = "$tableFd:$slot:$parent:${request.optInt("child", -1)}"
|
||||
}
|
||||
val root = env["DDNATV_ROOT"]?.let(::File)
|
||||
val out = client.outputStream
|
||||
if (root == null || argv.isEmpty()) {
|
||||
out.write("error no guest root or program\n".toByteArray())
|
||||
return
|
||||
}
|
||||
val shell = listOf("/usr/bin/bash", "/bin/bash").first { File(root, it.removePrefix("/")).isFile }
|
||||
val args = if (file.isNotEmpty()) {
|
||||
listOf("-c", "unset DDH_WRAPPER; cd -- \"\$1\" 2>/dev/null; a=\$2; f=\$3; shift 3; exec -a \"\$a\" \"\$f\" \"\$@\"",
|
||||
"droiddeck-spawn", cwd, argv[0], file) + argv.drop(1)
|
||||
} else {
|
||||
listOf("-c", "unset DDH_WRAPPER; cd -- \"\$1\" 2>/dev/null; shift; exec \"\$@\"", "droiddeck-spawn", cwd) + argv
|
||||
}
|
||||
val command = NativeGuest.command(root, shell, args)
|
||||
env["DDNATV_REAL_EXE"] = File(root, shell.removePrefix("/")).path
|
||||
// The hook restores these in the program (tools/nativeguest/hook/handoff.c).
|
||||
if (request.has("sigign")) env["DDH_SIGIGN"] = request.getLong("sigign").toString()
|
||||
if (request.has("nofile")) env["DDH_NOFILE"] = request.getLong("nofile").toString()
|
||||
if (request.has("umask")) env["DDH_UMASK"] = request.getLong("umask").toString()
|
||||
if (request.has("pgid")) env["DDH_PGID"] = request.getLong("pgid").toString()
|
||||
if (request.has("anchor")) env["DDH_ANCHOR"] = request.getLong("anchor").toString()
|
||||
if (request.has("pstart")) env["DDH_PSTART"] = request.getLong("pstart").toString()
|
||||
if (request.has("astart")) env["DDH_ASTART"] = request.getLong("astart").toString()
|
||||
env["DDH_SIGMASK"] = request.optLong("sigmask", 0L).toString()
|
||||
// The shell above: the hook restores nothing there (bash changes its own signal mask),
|
||||
// only in the program it execs, which no longer has this.
|
||||
env["DDH_WRAPPER"] = "1"
|
||||
val child = request.optInt("child", -1)
|
||||
val exited = CountDownLatch(1)
|
||||
var status = -1
|
||||
var worker = -1
|
||||
// The hook answers the pid with "go" (ack): without it (it died, or gave up and runs the
|
||||
// program itself) the worker must not run it too.
|
||||
val ack = request.optBoolean("ack", false)
|
||||
var answered = false
|
||||
val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, targets, true, { code ->
|
||||
status = code
|
||||
if (table != null && slot >= 0) reportExit(table, slot, code, parent, child, worker)
|
||||
exited.countDown()
|
||||
}) { started ->
|
||||
worker = started
|
||||
if (!ack) return@start true
|
||||
runCatching {
|
||||
out.write("pid $started\n".toByteArray())
|
||||
out.flush()
|
||||
answered = true
|
||||
client.soTimeout = ACK_TIMEOUT_MS
|
||||
// the whole line: a hook whose write stopped short treats it as failed and runs the program itself
|
||||
val line = StringBuilder()
|
||||
var ended = false
|
||||
while (!ended) {
|
||||
val c = input.read()
|
||||
if (c < 0) break
|
||||
if (c == '\n'.code) ended = true else line.append(c.toChar())
|
||||
}
|
||||
ended && line.toString() == "go"
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
handedOver = true
|
||||
programFds.filter { it !== table }.forEach { runCatching { it.close() } }
|
||||
if (pid <= 0) table?.let { runCatching { it.close() } }
|
||||
if (!answered) {
|
||||
out.write(if (pid > 0) "pid $pid\n".toByteArray() else "error no worker\n".toByteArray())
|
||||
out.flush()
|
||||
}
|
||||
if (pid > 0 && wait) {
|
||||
exited.await()
|
||||
// droiddeck-spawn exits with this: an exit code, or 128 plus the signal
|
||||
val code = if (status < 0) 1 else if (status and 0x7f == 0) (status shr 8) and 0xff else 128 + (status and 0x7f)
|
||||
out.write("exit $code\n".toByteArray())
|
||||
out.flush()
|
||||
}
|
||||
} finally {
|
||||
if (!handedOver) fds.forEach { runCatching { it.close() } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Layout of the hook's table (tools/nativeguest/hook/handoff.c): a 64-byte header, then 32-byte
|
||||
// entries of int32 child, real, parent, state, status, ...
|
||||
// Written only while the entry is still this program's (state CLAIMED or HANDED, its child, parent
|
||||
// and worker): the parent may have reaped it and a later handoff taken the entry over meanwhile.
|
||||
private fun reportExit(table: ParcelFileDescriptor, slot: Int, status: Int, parent: Int, child: Int, worker: Int) {
|
||||
runCatching {
|
||||
val entry = 64L + slot * 32L
|
||||
val head = java.nio.ByteBuffer.allocate(16).order(java.nio.ByteOrder.nativeOrder())
|
||||
Os.pread(table.fileDescriptor, head, entry)
|
||||
val real = head.getInt(4)
|
||||
val state = head.getInt(12)
|
||||
if (head.getInt(0) != child || head.getInt(8) != parent || (real != 0 && real != worker) || (state != 1 && state != 3))
|
||||
return@runCatching
|
||||
val word = java.nio.ByteBuffer.allocate(4).order(java.nio.ByteOrder.nativeOrder())
|
||||
// An exit Android has no record of is reported as a failure, not as a signal.
|
||||
Os.pwrite(table.fileDescriptor, word.putInt(0, if (status < 0) 1 shl 8 else status).also { it.rewind() }, entry + 16)
|
||||
Os.pwrite(table.fileDescriptor, word.putInt(0, 2).also { it.rewind() }, entry + 12)
|
||||
if (parent > 0) Process.sendSignal(parent, OsConstants.SIGCHLD)
|
||||
}.onFailure { Log.w(TAG, "could not report an exit to the guest's parent", it) }
|
||||
runCatching { table.close() }
|
||||
}
|
||||
}
|
||||
@@ -129,6 +129,8 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-agent" to "usr/local/bin/droiddeck-agent",
|
||||
"usr/local/bin/steam-compatibility" to "usr/local/bin/steam-compatibility",
|
||||
"usr/local/bin/droiddeck-clipboard" to "usr/local/bin/droiddeck-clipboard",
|
||||
"usr/local/bin/droiddeck-spawn" to "usr/local/bin/droiddeck-spawn",
|
||||
"usr/local/bin/droiddeck-log-writer" to "usr/local/bin/droiddeck-log-writer",
|
||||
"usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard",
|
||||
"usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window",
|
||||
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
|
||||
|
||||
@@ -1098,6 +1098,9 @@ object SessionPrefs {
|
||||
|
||||
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true)
|
||||
|
||||
/** The session's long-lived programs run in worker processes Android does not count (GuestWorkers). */
|
||||
fun childProcessHandoff(context: Context): Boolean = prefs(context).getBoolean("childProcessHandoff", true)
|
||||
|
||||
fun setNativeUserland(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("nativeUserland", on).apply()
|
||||
}
|
||||
@@ -1735,6 +1738,7 @@ object SessionPrefs {
|
||||
signal = p.getInt("customThemeSignal", defaults.signal),
|
||||
good = p.getInt("customThemeGood", defaults.good),
|
||||
error = p.getInt("customThemeError", defaults.error),
|
||||
warning = p.getInt("customThemeWarning", defaults.warning),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1755,6 +1759,7 @@ object SessionPrefs {
|
||||
.putInt("customThemeSignal", colors.signal)
|
||||
.putInt("customThemeGood", colors.good)
|
||||
.putInt("customThemeError", colors.error)
|
||||
.putInt("customThemeWarning", colors.warning)
|
||||
.apply()
|
||||
}
|
||||
|
||||
|
||||
@@ -693,14 +693,27 @@ class SessionService : Service() {
|
||||
.onFailure { Log.w(TAG, "Epic install directory setup failed", it) }
|
||||
}
|
||||
if (steamHere || noSteamGame) {
|
||||
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
|
||||
val listing = SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
|
||||
val listing = if (steamHere) SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGamesPublisher.sessionListing(this) } else {
|
||||
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
|
||||
com.droiddeck.launcher.frontend.AddedGamesPublisher.log(added)
|
||||
SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
|
||||
}
|
||||
guest.add("DD_ADDED_GAMES=" + listing.path)
|
||||
if (OfflineMode.active(this)) guest.add("DD_STEAM_OFFLINE=1")
|
||||
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1")
|
||||
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
|
||||
}
|
||||
guest.add("DD_LAUNCH_DIR=" + sessionRoot.path)
|
||||
// this session's worker number: the shared field may be a newer session's by the time it is used
|
||||
var ownWorkers = 0
|
||||
if (com.droiddeck.launcher.runtime.GuestWorkers.enabled(this)) {
|
||||
// Under the lock a stop takes its number with: a stop either comes first (and this session
|
||||
// starts no workers) or owns them
|
||||
ownWorkers = synchronized(stopLock) {
|
||||
if (gen != sessionGen || !SessionState.running) 0
|
||||
else com.droiddeck.launcher.runtime.GuestWorkers.serve(this).also { guestWorkerSession = it }
|
||||
}
|
||||
if (ownWorkers > 0) guest.add("DD_SPAWN=" + com.droiddeck.launcher.runtime.GuestWorkers.socketName(this))
|
||||
}
|
||||
// Proton builds up to 11.12 report X11 text fields under this name.
|
||||
guest.add("BL_LAUNCH_DIR=" + sessionRoot.path)
|
||||
GameStorage.effective(this)?.let { guest.add("DD_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
|
||||
@@ -858,10 +871,10 @@ class SessionService : Service() {
|
||||
watchLaunchRequests(sessionRoot)
|
||||
watchSyncWanted(root)
|
||||
EsyncPacks.fetchInBackground(this, root)
|
||||
val pid = SessionEvents.step("guest-launch") { HostProcess.start(line, hostEnv.asArray(), root, { status ->
|
||||
val pid = SessionEvents.step("guest-launch") { HostProcess.startUncounted(line, hostEnv.asArray(), root, { status ->
|
||||
if (gen != sessionGen) {
|
||||
Log.i(TAG, "an earlier session's process ended ($status); the current one carries on")
|
||||
return@start
|
||||
return@startUncounted
|
||||
}
|
||||
val program = programStatus(sessionRoot)
|
||||
Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "")
|
||||
@@ -877,10 +890,13 @@ class SessionService : Service() {
|
||||
syncWatcher = null
|
||||
}
|
||||
abandonStart(gen, sessionDir, started)
|
||||
if (pid > 1) Thread({ teardown(pid) }, "session-teardown").start()
|
||||
val workers = ownWorkers
|
||||
if (pid > 1) Thread({ teardown(pid, workerSession = workers) }, "session-teardown").start()
|
||||
else com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers)
|
||||
return
|
||||
}
|
||||
sessionPid = pid
|
||||
com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted = com.droiddeck.launcher.runtime.GuestWorkers.runsInWorker(pid)
|
||||
if (pid > 1) {
|
||||
raiseTracer(pid, gen)
|
||||
SessionEvents.guestStarted(pid)
|
||||
@@ -1519,10 +1535,15 @@ class SessionService : Service() {
|
||||
return binds
|
||||
}
|
||||
|
||||
private fun teardown(prootPid: Int, expectedStartTime: Long? = null) {
|
||||
// The workers' session number of the session running now (GuestWorkers.serve)
|
||||
@Volatile private var guestWorkerSession = 0
|
||||
|
||||
private fun teardown(prootPid: Int, expectedStartTime: Long? = null, workerSession: Int = guestWorkerSession) {
|
||||
fun stillSameProcess(): Boolean = expectedStartTime == null || readStat(prootPid)?.second == expectedStartTime
|
||||
if (!stillSameProcess()) return
|
||||
val tree = descendants(prootPid)
|
||||
// The session's programs that run in worker processes are not descendants of its root.
|
||||
val workers = if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.guestPids(workerSession) else emptyList()
|
||||
val tree = descendants(prootPid) + workers.flatMap { pid -> listOfNotNull(readStat(pid)?.let { Pair(pid, it.second) }) + descendants(pid) }
|
||||
if (!stillSameProcess()) return
|
||||
saveWineRegistries(tree)
|
||||
android.os.Process.sendSignal(prootPid, 15)
|
||||
@@ -1539,6 +1560,7 @@ class SessionService : Service() {
|
||||
killed++
|
||||
}
|
||||
if (killed > 0) Log.i(TAG, "swept $killed process(es) proot left behind")
|
||||
if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workerSession)
|
||||
}
|
||||
|
||||
private fun clearCachedApps() {
|
||||
@@ -2319,12 +2341,16 @@ class SessionService : Service() {
|
||||
return
|
||||
}
|
||||
completeNativeSleep()
|
||||
var workers = 0
|
||||
val (ended, endedArch) = synchronized(stopLock) {
|
||||
if (gen != null && gen != sessionGen) return
|
||||
// as it is when running is cleared: startup registers its workers under this lock too
|
||||
workers = guestWorkerSession
|
||||
cancelQueuedSteamGame()
|
||||
gameExitWatchToken++
|
||||
// also when startup stopped before the guest ran
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionMode = null
|
||||
com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted = null
|
||||
if (!SessionState.running) return
|
||||
if (relaunch) SessionState.confirmRelaunchStop()
|
||||
SessionEvents.record("guest.exited", mapOf("status" to status))
|
||||
@@ -2385,7 +2411,8 @@ class SessionService : Service() {
|
||||
if (prootPid > 1 && steamClientMayRun) askSteamToExit(prootPid)
|
||||
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
|
||||
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
|
||||
if (prootPid > 1) teardown(prootPid)
|
||||
if (prootPid > 1) teardown(prootPid, workerSession = workers)
|
||||
else com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers)
|
||||
killGuestLeftovers()
|
||||
pruneSystemVulkanRuntime()
|
||||
finishSessionStop(status, stoppedGen, collectEnded)
|
||||
@@ -2394,6 +2421,7 @@ class SessionService : Service() {
|
||||
} else {
|
||||
Thread({ pruneSystemVulkanRuntime() }, "system-vulkan-prune").start()
|
||||
Thread({
|
||||
com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers)
|
||||
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
|
||||
finishSessionStop(status, stoppedGen, collectEnded)
|
||||
if (launcherEnded) importLauncherGames()
|
||||
|
||||
@@ -19,25 +19,33 @@ object SteamLiveShortcuts {
|
||||
private const val EVAL_TIMEOUT_MS = 20_000L
|
||||
private const val THAW_WAIT_MS = 15_000L
|
||||
|
||||
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }) {
|
||||
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }): Boolean {
|
||||
val wanted = games.filter(include)
|
||||
if (wanted.isEmpty() || !clientRunning()) return
|
||||
if (wanted.isEmpty()) return true
|
||||
if (!clientRunning()) return false
|
||||
val list = JSONArray()
|
||||
for (g in wanted) list.put(JSONObject().put("name", g.name).put("exe", g.guestExe).put("dir", g.guestDir).put("appid", g.appId and 0xFFFFFFFFL).put("launch", g.launchOptions))
|
||||
val js = """
|
||||
(async () => {
|
||||
const want = ${list};
|
||||
let added = 0;
|
||||
let added = 0, missed = 0;
|
||||
for (const w of want) {
|
||||
if (await ${KNOWN}(w.appid, w.name, w.exe)) continue;
|
||||
if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))}, w.launch)) added++;
|
||||
if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))}, w.launch)) added++; else missed++;
|
||||
}
|
||||
return added;
|
||||
return JSON.stringify({ added, missed });
|
||||
})()
|
||||
""".trimIndent()
|
||||
val result = evaluate(context, js) ?: return
|
||||
Log.i(TAG, "live shortcuts: $result added")
|
||||
if (result != "0") StoresState.logLine("Steam: $result shortcut(s) added to the running client")
|
||||
return synced(evaluate(context, js))
|
||||
}
|
||||
|
||||
internal fun synced(result: String?): Boolean {
|
||||
val counts = result?.let { runCatching { JSONObject(it) }.getOrNull() } ?: return false
|
||||
val added = counts.optInt("added")
|
||||
val missed = counts.optInt("missed")
|
||||
Log.i(TAG, "live shortcuts: $added added" + if (missed > 0) ", $missed not added" else "")
|
||||
if (added > 0) StoresState.logLine("Steam: $added shortcut(s) added to the running client")
|
||||
return missed == 0
|
||||
}
|
||||
|
||||
fun ensure(context: Context, name: String, exe: String, dir: String, compat: Boolean, appId: Long? = null): Long? {
|
||||
|
||||
@@ -15,7 +15,7 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.withFrameMillis
|
||||
import androidx.compose.runtime.withFrameNanos
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
@@ -99,7 +99,7 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
||||
var vx = speed * 0.8f
|
||||
var vy = -speed * 0.6f
|
||||
while (true) {
|
||||
if (clock.page == Size.Zero) { withFrameMillis { }; continue }
|
||||
if (clock.page == Size.Zero) { withFrameNanos { }; continue }
|
||||
val f = MarkFrame(clock.page, Offset.Zero)
|
||||
if (clock.at == Offset.Unspecified) clock.at = Offset(clock.page.width * 0.64f, clock.page.height * 0.42f)
|
||||
if (Motion.scale == 0f) {
|
||||
@@ -108,8 +108,13 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
||||
clock.wall = 0f
|
||||
return@LaunchedEffect
|
||||
}
|
||||
withFrameMillis { now ->
|
||||
val dt = if (last < 0) 0f else min(50f, (now - last) / Motion.scale)
|
||||
withFrameNanos { nanos ->
|
||||
val scale = Motion.scale
|
||||
if (scale == 0f) return@withFrameNanos
|
||||
val settled = clock.intro >= END && clock.ball >= IMPACT + REVEAL_MS && !clock.poked
|
||||
if (settled && last >= 0 && !IdleFrames.due(nanos)) return@withFrameNanos
|
||||
val now = nanos / 1_000_000L
|
||||
val dt = if (last < 0) 0f else min(50f, (now - last).toFloat()) / scale.coerceAtLeast(0.01f)
|
||||
last = now
|
||||
clock.intro += dt
|
||||
clock.wall += dt
|
||||
@@ -117,34 +122,41 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
||||
val before = clock.ball
|
||||
clock.ball += dt
|
||||
|
||||
var x = clock.at.x + vx * dt / 1000f
|
||||
var y = clock.at.y + vy * dt / 1000f
|
||||
var x = clock.at.x
|
||||
var y = clock.at.y
|
||||
val hw = f.ball
|
||||
val hh = f.ball
|
||||
if (x - hw < 0f) { x = hw; vx = abs(vx) }
|
||||
if (x + hw > clock.page.width) { x = clock.page.width - hw; vx = -abs(vx) }
|
||||
if (y - hh < 0f) { y = hh; vy = abs(vy) }
|
||||
if (y + hh > clock.page.height) { y = clock.page.height - hh; vy = -abs(vy) }
|
||||
keepOff?.inflate(clearance)?.let { r ->
|
||||
val nearX = x.coerceIn(r.left, r.right)
|
||||
val nearY = y.coerceIn(r.top, r.bottom)
|
||||
val gapX = x - nearX
|
||||
val gapY = y - nearY
|
||||
val gap = hypot(gapX, gapY)
|
||||
if (gap in 0.0001f..f.ball) {
|
||||
val nx = gapX / gap
|
||||
val ny = gapY / gap
|
||||
x = nearX + nx * f.ball
|
||||
y = nearY + ny * f.ball
|
||||
val into = vx * nx + vy * ny
|
||||
if (into < 0f) { vx -= 2f * into * nx; vy -= 2f * into * ny }
|
||||
} else if (gap <= 0.0001f) {
|
||||
val outX = if (x < r.center.x) r.left - f.ball - x else r.right + f.ball - x
|
||||
val outY = if (y < r.center.y) r.top - f.ball - y else r.bottom + f.ball - y
|
||||
if (abs(outX) < abs(outY)) { x += outX; vx = if (outX < 0) -abs(vx) else abs(vx) }
|
||||
else { y += outY; vy = if (outY < 0) -abs(vy) else abs(vy) }
|
||||
var left = dt
|
||||
do {
|
||||
val step = min(50f, left)
|
||||
left -= step
|
||||
x += vx * step / 1000f
|
||||
y += vy * step / 1000f
|
||||
if (x - hw < 0f) { x = hw; vx = abs(vx) }
|
||||
if (x + hw > clock.page.width) { x = clock.page.width - hw; vx = -abs(vx) }
|
||||
if (y - hh < 0f) { y = hh; vy = abs(vy) }
|
||||
if (y + hh > clock.page.height) { y = clock.page.height - hh; vy = -abs(vy) }
|
||||
keepOff?.inflate(clearance)?.let { r ->
|
||||
val nearX = x.coerceIn(r.left, r.right)
|
||||
val nearY = y.coerceIn(r.top, r.bottom)
|
||||
val gapX = x - nearX
|
||||
val gapY = y - nearY
|
||||
val gap = hypot(gapX, gapY)
|
||||
if (gap in 0.0001f..f.ball) {
|
||||
val nx = gapX / gap
|
||||
val ny = gapY / gap
|
||||
x = nearX + nx * f.ball
|
||||
y = nearY + ny * f.ball
|
||||
val into = vx * nx + vy * ny
|
||||
if (into < 0f) { vx -= 2f * into * nx; vy -= 2f * into * ny }
|
||||
} else if (gap <= 0.0001f) {
|
||||
val outX = if (x < r.center.x) r.left - f.ball - x else r.right + f.ball - x
|
||||
val outY = if (y < r.center.y) r.top - f.ball - y else r.bottom + f.ball - y
|
||||
if (abs(outX) < abs(outY)) { x += outX; vx = if (outX < 0) -abs(vx) else abs(vx) }
|
||||
else { y += outY; vy = if (outY < 0) -abs(vy) else abs(vy) }
|
||||
}
|
||||
}
|
||||
}
|
||||
} while (left > 0f)
|
||||
clock.at = Offset(x, y)
|
||||
|
||||
if (before < IMPACT && clock.ball >= IMPACT) {
|
||||
|
||||
@@ -96,8 +96,7 @@ import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.onPlaced
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
|
||||
|
||||
internal val AttentionAmber = Color(0xFFFFB547)
|
||||
internal val AttentionAmber: Color @Composable get() = LocalPalette.current.warning
|
||||
|
||||
@Composable
|
||||
internal fun BottomBar(
|
||||
@@ -308,7 +307,7 @@ private fun RailItem(
|
||||
}
|
||||
if (badge) Box(
|
||||
modifier = Modifier.align(Alignment.TopEnd).padding(top = if (iconOnly) 7.dp else 8.dp, end = if (iconOnly) 9.dp else 18.dp)
|
||||
.size(8.dp).clip(CircleShape).background(AttentionAmber),
|
||||
.size(8.dp).clip(CircleShape).background(pal.warning),
|
||||
)
|
||||
if (count > 0) Text(
|
||||
if (count > 9) "9+" else count.toString(),
|
||||
|
||||
@@ -393,7 +393,8 @@ internal fun SetupPanel(
|
||||
listOfNotNull(
|
||||
gpu.displayName(ctx),
|
||||
s.installed?.let { stringResource(R.string.setup_ready_runtime, it) },
|
||||
stringResource(R.string.setup_ready_limit_off).takeIf { !limitBlocks },
|
||||
stringResource(R.string.setup_ready_limit_off)
|
||||
.takeIf { !limitBlocks && s.phantomProcessStatus != PhantomProcessStatus.UNCOUNTED },
|
||||
s.offlineAccount?.takeIf { it.isNotEmpty() }?.let { stringResource(R.string.setup_ready_signed_in, it) },
|
||||
).joinToString(" · "),
|
||||
open = showChecks, onDetails = { showChecks = !showChecks },
|
||||
@@ -1254,6 +1255,7 @@ private fun CustomColorRows() {
|
||||
Triple("signal", stringResource(R.string.theme_custom_signal), colors.signal),
|
||||
Triple("good", stringResource(R.string.theme_custom_good), colors.good),
|
||||
Triple("error", stringResource(R.string.theme_custom_error), colors.error),
|
||||
Triple("warning", stringResource(R.string.theme_custom_warning), colors.warning),
|
||||
)
|
||||
|
||||
rows.forEach { (key, label, argb) ->
|
||||
|
||||
@@ -82,7 +82,18 @@ import kotlinx.coroutines.withContext
|
||||
private const val WALL_MIN_GAMES = 4
|
||||
private const val WALL_DISTINCT = 40
|
||||
|
||||
private const val DRIFT_STEP_NS = 15_000_000L
|
||||
private const val IDLE_FRAME_NS = 30_000_000L
|
||||
|
||||
internal object IdleFrames {
|
||||
private var shown = 0L
|
||||
|
||||
fun due(nanos: Long): Boolean {
|
||||
if (nanos == shown) return true
|
||||
if (nanos - shown < IDLE_FRAME_NS) return false
|
||||
shown = nanos
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) {
|
||||
@@ -281,7 +292,7 @@ internal fun TiltedWall(
|
||||
var shown = 0L
|
||||
while (true) withFrameNanos { now ->
|
||||
if (shown == 0L) shown = now
|
||||
else if (now - shown >= DRIFT_STEP_NS) {
|
||||
else if (IdleFrames.due(now)) {
|
||||
drift.floatValue = ((drift.floatValue + (now - shown) / (period.value * 1_000_000.0 * Motion.scale)) % 1.0).toFloat()
|
||||
shown = now
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ class Palette(
|
||||
val background: Color, val surface: Color, val surfaceVariant: Color, val line: Color, val line2: Color,
|
||||
val onBackground: Color, val onSurfaceVariant: Color,
|
||||
val primary: Color, val primary2: Color, val onPrimary: Color, val signal: Color,
|
||||
val good: Color, val error: Color = Color(0xFFFF8A80),
|
||||
val good: Color, val error: Color = Color(0xFFFF8A80), val warning: Color = Color(0xFFFFB547),
|
||||
)
|
||||
|
||||
data class CustomThemeColors(
|
||||
@@ -54,6 +54,7 @@ data class CustomThemeColors(
|
||||
val signal: Int = 0xFF1A9FFF.toInt(),
|
||||
val good: Int = 0xFF4CD37F.toInt(),
|
||||
val error: Int = 0xFFFF8A80.toInt(),
|
||||
val warning: Int = 0xFFFFB547.toInt(),
|
||||
)
|
||||
|
||||
object Themes {
|
||||
@@ -144,6 +145,7 @@ object Themes {
|
||||
"signal" -> current.copy(signal = color)
|
||||
"good" -> current.copy(good = color)
|
||||
"error" -> current.copy(error = color)
|
||||
"warning" -> current.copy(warning = color)
|
||||
else -> return
|
||||
}
|
||||
setCustomColors(context, updated)
|
||||
@@ -164,6 +166,7 @@ object Themes {
|
||||
signal = Color(colors.signal),
|
||||
good = Color(colors.good),
|
||||
error = Color(colors.error),
|
||||
warning = Color(colors.warning),
|
||||
)
|
||||
|
||||
fun current(context: Context): Palette {
|
||||
@@ -229,7 +232,9 @@ val Palette.onSignal: Color get() = if (signal.luminance() > 0.18f) Color(0xFF03
|
||||
|
||||
@Composable
|
||||
fun DroidDeckTheme(theme: String? = null, appScale: Int = AppUiPrefs.DEFAULT_SCALE, content: @Composable () -> Unit) {
|
||||
val id = theme ?: SessionPrefs.theme(LocalContext.current)
|
||||
val context = LocalContext.current
|
||||
remember(context) { Themes.loadGradient(context) }
|
||||
val id = theme ?: SessionPrefs.theme(context)
|
||||
if (id == Themes.INNER_GAMER) InnerGamerHue(Themes.rgbSpeed)
|
||||
val p = Themes.byId(id)
|
||||
val scheme = darkColorScheme(
|
||||
|
||||
@@ -2544,6 +2544,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s إذا لم يكن ذلك ممكنًا، وصِّل هذا الجهاز بكمبيوتر يستخدم ADB ونفِّذ الأمر أدناه. عُد إلى هنا وتحقَّق مرة أخرى.</string>
|
||||
<string name="phantom_instructions_off">يمكن بدء جلسات Steam.</string>
|
||||
<string name="phantom_instructions_not_applicable">لا يستخدم إصدار Android هذا هذا الحدّ.</string>
|
||||
<string name="phantom_title_uncounted">يتولى DroidDeck حد العمليات الفرعية</string>
|
||||
<string name="phantom_instructions_uncounted">يشغّل DroidDeck برامج الجلسة في عمليات لا يحتسبها Android، لذا يمكن إبقاء خيارات المطوّرين متوقفة.</string>
|
||||
<string name="phantom_fix_toggle">فعِّل «إيقاف القيود المفروضة على العمليات الثانوية» في خيارات المطوّرين، واترك خيارات المطوّرين مفعَّلة بعد ذلك.</string>
|
||||
<string name="phantom_fix_no_toggle">لا يحتوي إصدار Android هذا على مفتاح لذلك. استخدِم تصحيح الأخطاء اللاسلكي لتغييره من هذا الجهاز.</string>
|
||||
<string name="upd_block_no_apk">لا يتوفّر تنزيل لهذا الإصدار الخاص بهذه النسخة من DroidDeck.</string>
|
||||
@@ -4299,6 +4301,7 @@
|
||||
<string name="theme_custom_signal">الإبرازات</string>
|
||||
<string name="theme_custom_good">نجاح</string>
|
||||
<string name="theme_custom_error">خطأ</string>
|
||||
<string name="theme_custom_warning">تحذير</string>
|
||||
<string name="hud_only_during_game">عرض HUD أثناء اللعب فقط</string>
|
||||
<string name="hud_only_during_game_hint">إخفاء HUD عند عدم اكتشاف إطارات اللعبة.</string>
|
||||
<string name="steam_store_close_steam">أغلق Steam أولاً</string>
|
||||
|
||||
@@ -2536,6 +2536,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Si no es posible, conecta este dispositivo a una computadora con ADB y ejecuta el comando de abajo. Después vuelve aquí y comprueba de nuevo.</string>
|
||||
<string name="phantom_instructions_off">Ya se pueden iniciar sesiones de Steam.</string>
|
||||
<string name="phantom_instructions_not_applicable">Esta versión de Android no usa este límite.</string>
|
||||
<string name="phantom_title_uncounted">DroidDeck gestiona el límite de procesos secundarios</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck ejecuta los programas de la sesión en procesos que Android no cuenta, así que las Opciones de desarrollador pueden quedar desactivadas.</string>
|
||||
<string name="phantom_fix_toggle">Activa “Inhabilitar restricciones de procesos secundarios” en Opciones de desarrollador y deja activadas las Opciones de desarrollador después.</string>
|
||||
<string name="phantom_fix_no_toggle">Esta versión de Android no tiene un interruptor para ello. Usa la Depuración inalámbrica para cambiarlo desde este dispositivo.</string>
|
||||
<string name="upd_block_no_apk">Esta versión no tiene descarga para esta copia de DroidDeck.</string>
|
||||
@@ -4179,6 +4181,7 @@
|
||||
<string name="theme_custom_signal">Destacados</string>
|
||||
<string name="theme_custom_good">Éxito</string>
|
||||
<string name="theme_custom_error">Error</string>
|
||||
<string name="theme_custom_warning">Advertencia</string>
|
||||
<string name="hud_only_during_game">Mostrar el HUD solo durante una partida</string>
|
||||
<string name="hud_only_during_game_hint">Ocultar el HUD cuando no se detecten fotogramas del juego.</string>
|
||||
<string name="steam_store_close_steam">Cierra Steam primero</string>
|
||||
|
||||
@@ -2440,6 +2440,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Ако това не е възможно, свържи устройството с компютър с ADB и изпълни командата отдолу. Върни се тук и провери отново.</string>
|
||||
<string name="phantom_instructions_off">Сесиите на Steam могат да стартират.</string>
|
||||
<string name="phantom_instructions_not_applicable">Тази версия на Android не използва това ограничение.</string>
|
||||
<string name="phantom_title_uncounted">DroidDeck се справя с ограничението за дъщерни процеси</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck изпълнява програмите на сесията в процеси, които Android не отчита, така че опциите за програмисти могат да останат изключени.</string>
|
||||
<string name="phantom_fix_toggle">Включи „Деактивиране на ограниченията за дъщерните процеси“ в Опции за програмисти и остави Опции за програмисти включени след това.</string>
|
||||
<string name="phantom_fix_no_toggle">Тази версия на Android няма превключвател за това. Използвай безжично отстраняване на грешки, за да го промениш от това устройство.</string>
|
||||
<string name="upd_block_no_apk">Тази версия няма изтегляне за това копие на DroidDeck.</string>
|
||||
@@ -4139,6 +4141,7 @@
|
||||
<string name="theme_custom_signal">Акценти</string>
|
||||
<string name="theme_custom_good">Успех</string>
|
||||
<string name="theme_custom_error">Грешка</string>
|
||||
<string name="theme_custom_warning">Предупреждение</string>
|
||||
<string name="hud_only_during_game">Показвай HUD само по време на игра</string>
|
||||
<string name="hud_only_during_game_hint">Скривай HUD, когато не се засичат кадри от играта.</string>
|
||||
<string name="steam_store_close_steam">Първо затворете Steam</string>
|
||||
|
||||
@@ -2492,6 +2492,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Pokud to není možné, připojte toto zařízení k počítači s ADB a spusťte příkaz níže. Vraťte se sem a zkontrolujte to znovu.</string>
|
||||
<string name="phantom_instructions_off">Relace Steamu se mohou spouštět.</string>
|
||||
<string name="phantom_instructions_not_applicable">Tato verze Androidu tento limit nepoužívá.</string>
|
||||
<string name="phantom_title_uncounted">Limit podřízených procesů řeší DroidDeck</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck spouští programy relace v procesech, které Android nezapočítává, takže možnosti pro vývojáře mohou zůstat vypnuté.</string>
|
||||
<string name="phantom_fix_toggle">Zapněte „Deaktivace omezení podřízených procesů“ v Možnostech pro vývojáře a pak je nechte zapnuté.</string>
|
||||
<string name="phantom_fix_no_toggle">Tato verze Androidu pro to nemá přepínač. Použijte bezdrátové ladění a změňte to z tohoto zařízení.</string>
|
||||
<string name="upd_block_no_apk">Toto sestavení nemá stažení pro tuto kopii DroidDecku.</string>
|
||||
@@ -4219,6 +4221,7 @@
|
||||
<string name="theme_custom_signal">Zvýraznění</string>
|
||||
<string name="theme_custom_good">Úspěch</string>
|
||||
<string name="theme_custom_error">Chyba</string>
|
||||
<string name="theme_custom_warning">Varování</string>
|
||||
<string name="hud_only_during_game">Zobrazovat HUD pouze během hry</string>
|
||||
<string name="hud_only_during_game_hint">Skrýt HUD, když nejsou detekovány snímky hry.</string>
|
||||
<string name="steam_store_close_steam">Nejprve zavřete Steam</string>
|
||||
|
||||
@@ -2440,6 +2440,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Hvis det ikke er muligt, så forbind enheden til en computer med ADB, og køre kommandoen nedenfor. Kom tilbage hertil, og tjek igen.</string>
|
||||
<string name="phantom_instructions_off">Steam-sessioner kan starte.</string>
|
||||
<string name="phantom_instructions_not_applicable">Denne Android-version bruger ikke denne grænse.</string>
|
||||
<string name="phantom_title_uncounted">DroidDeck håndterer grænsen for underprocesser</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck kører sessionens programmer i processer, som Android ikke tæller med, så Indstillinger for udviklere kan forblive slået fra.</string>
|
||||
<string name="phantom_fix_toggle">Tænd „Deaktiver begrænsningerne for underprocesser“ i Udvikleremuligheder, og lad Udvikleremuligheder være tændt bagefter.</string>
|
||||
<string name="phantom_fix_no_toggle">Denne Android-version har ingen kontakt til det. Brug Trådløs fejlretning til at ændre det fra denne enhed.</string>
|
||||
<string name="upd_block_no_apk">Denne version har ingen download til denne kopi af DroidDeck.</string>
|
||||
@@ -4139,6 +4141,7 @@
|
||||
<string name="theme_custom_signal">Fremhævninger</string>
|
||||
<string name="theme_custom_good">Succes</string>
|
||||
<string name="theme_custom_error">Fejl</string>
|
||||
<string name="theme_custom_warning">Advarsel</string>
|
||||
<string name="hud_only_during_game">Vis kun HUD under spil</string>
|
||||
<string name="hud_only_during_game_hint">Skjul HUD, når der ikke registreres spilbilleder.</string>
|
||||
<string name="steam_store_close_steam">Luk Steam først</string>
|
||||
|
||||
@@ -2432,6 +2432,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Falls das nicht möglich ist, verbinde dieses Gerät per ADB mit einem Computer und führe den Befehl unten aus. Kehre dann hierher zurück und prüfe erneut.</string>
|
||||
<string name="phantom_instructions_off">Steam-Sitzungen können starten.</string>
|
||||
<string name="phantom_instructions_not_applicable">Diese Android-Version nutzt dieses Limit nicht.</string>
|
||||
<string name="phantom_title_uncounted">Limit für untergeordnete Prozesse übernimmt DroidDeck</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck führt die Programme der Sitzung in Prozessen aus, die Android nicht mitzählt, daher können die Entwickleroptionen ausgeschaltet bleiben.</string>
|
||||
<string name="phantom_fix_toggle">Aktiviere „Beschränkungen für Unterprozesse deaktivieren“ in den Entwickleroptionen und lass die Entwickleroptionen danach aktiviert.</string>
|
||||
<string name="phantom_fix_no_toggle">Diese Android-Version hat dafür keinen Schalter. Nutze Debugging über WLAN, um es auf diesem Gerät zu ändern.</string>
|
||||
<string name="upd_block_no_apk">Dieser Build hat keinen Download für diese DroidDeck-Installation.</string>
|
||||
@@ -4139,6 +4141,7 @@
|
||||
<string name="theme_custom_signal">Hervorhebungen</string>
|
||||
<string name="theme_custom_good">Erfolg</string>
|
||||
<string name="theme_custom_error">Fehler</string>
|
||||
<string name="theme_custom_warning">Warnung</string>
|
||||
<string name="hud_only_during_game">HUD nur während eines Spiels anzeigen</string>
|
||||
<string name="hud_only_during_game_hint">HUD ausblenden, wenn keine Spielframes erkannt werden.</string>
|
||||
<string name="steam_store_close_steam">Schließe zuerst Steam</string>
|
||||
|
||||
@@ -2440,6 +2440,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Αν αυτό δεν είναι δυνατό, συνδέστε αυτή τη συσκευή σε έναν υπολογιστή με ADB και εκτελέστε την παρακάτω εντολή. Επιστρέψτε εδώ και ελέγξτε ξανά.</string>
|
||||
<string name="phantom_instructions_off">Οι συνεδρίες Steam μπορούν να ξεκινήσουν.</string>
|
||||
<string name="phantom_instructions_not_applicable">Αυτή η έκδοση Android δεν χρησιμοποιεί αυτό το όριο.</string>
|
||||
<string name="phantom_title_uncounted">Το DroidDeck χειρίζεται το όριο θυγατρικών διεργασιών</string>
|
||||
<string name="phantom_instructions_uncounted">Το DroidDeck εκτελεί τα προγράμματα της συνεδρίας σε διεργασίες που το Android δεν μετράει, οπότε οι Επιλογές για προγραμματιστές μπορούν να μείνουν απενεργοποιημένες.</string>
|
||||
<string name="phantom_fix_toggle">Ενεργοποιήστε την «Απενεργοπ. περιορισμών σε θυγατρικές διεργασίες» στις Επιλογές προγραμματιστή και αφήστε τις Επιλογές προγραμματιστή ενεργές μετά.</string>
|
||||
<string name="phantom_fix_no_toggle">Αυτή η έκδοση Android δεν έχει διακόπτη για αυτό. Χρησιμοποιήστε τον ασύρματο εντοπισμό σφαλμάτων για να το αλλάξετε από αυτή τη συσκευή.</string>
|
||||
<string name="upd_block_no_apk">Αυτή η έκδοση δεν έχει λήψη για αυτό το αντίγραφο του DroidDeck.</string>
|
||||
@@ -4139,6 +4141,7 @@
|
||||
<string name="theme_custom_signal">Επισημάνσεις</string>
|
||||
<string name="theme_custom_good">Επιτυχία</string>
|
||||
<string name="theme_custom_error">Σφάλμα</string>
|
||||
<string name="theme_custom_warning">Προειδοποίηση</string>
|
||||
<string name="hud_only_during_game">Εμφάνιση HUD μόνο κατά τη διάρκεια παιχνιδιού</string>
|
||||
<string name="hud_only_during_game_hint">Απόκρυψη HUD όταν δεν ανιχνεύονται καρέ παιχνιδιού.</string>
|
||||
<string name="steam_store_close_steam">Κλείστε πρώτα το Steam</string>
|
||||
|
||||
@@ -2466,6 +2466,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Si no es posible, conecta este dispositivo a un ordenador con ADB y ejecuta el comando de abajo. Después vuelve aquí y comprueba de nuevo.</string>
|
||||
<string name="phantom_instructions_off">Ya se pueden iniciar sesiones de Steam.</string>
|
||||
<string name="phantom_instructions_not_applicable">Esta versión de Android no usa este límite.</string>
|
||||
<string name="phantom_title_uncounted">DroidDeck gestiona el límite de procesos secundarios</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck ejecuta los programas de la sesión en procesos que Android no cuenta, así que las Opciones para desarrolladores pueden seguir desactivadas.</string>
|
||||
<string name="phantom_fix_toggle">Activa “Inhabilitar restricciones de procesos secundarios” en Opciones de desarrollador y deja activadas las Opciones de desarrollador después.</string>
|
||||
<string name="phantom_fix_no_toggle">Esta versión de Android no tiene un interruptor para ello. Usa la Depuración inalámbrica para cambiarlo desde este dispositivo.</string>
|
||||
<string name="upd_block_no_apk">Esta versión no tiene descarga para esta copia de DroidDeck.</string>
|
||||
@@ -4179,6 +4181,7 @@
|
||||
<string name="theme_custom_signal">Destacados</string>
|
||||
<string name="theme_custom_good">Éxito</string>
|
||||
<string name="theme_custom_error">Error</string>
|
||||
<string name="theme_custom_warning">Advertencia</string>
|
||||
<string name="hud_only_during_game">Mostrar el HUD solo durante una partida</string>
|
||||
<string name="hud_only_during_game_hint">Ocultar el HUD cuando no se detecten fotogramas del juego.</string>
|
||||
<string name="steam_store_close_steam">Cierra Steam primero</string>
|
||||
|
||||
@@ -2440,6 +2440,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Jos se ei ole mahdollista, yhdistä tämä laite tietokoneeseen ADB:llä ja suorita alla oleva komento. Palaa tähän ja tarkista uudelleen.</string>
|
||||
<string name="phantom_instructions_off">Steam-istunnot voivat käynnistyä.</string>
|
||||
<string name="phantom_instructions_not_applicable">Tämä Android-versio ei käytä tätä rajaa.</string>
|
||||
<string name="phantom_title_uncounted">DroidDeck hoitaa aliprosessirajoituksen</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck ajaa istunnon ohjelmat prosesseissa, joita Android ei laske, joten kehittäjäasetukset voivat pysyä pois päältä.</string>
|
||||
<string name="phantom_fix_toggle">Ota käyttöön ”Poista käytöstä alatason prosessirajoitukset” Kehittäjäasetuksissa, ja pidä Kehittäjäasetukset päällä sen jälkeen.</string>
|
||||
<string name="phantom_fix_no_toggle">Tässä Android-versiossa ei ole kytkintä sille. Käytä langatonta virheenkorjausta muuttaaksesi sitä tältä laitteelta.</string>
|
||||
<string name="upd_block_no_apk">Tälle versiolle ei ole latausta tähän DroidDeck-kopioon.</string>
|
||||
@@ -4139,6 +4141,7 @@
|
||||
<string name="theme_custom_signal">Korostukset</string>
|
||||
<string name="theme_custom_good">Onnistuminen</string>
|
||||
<string name="theme_custom_error">Virhe</string>
|
||||
<string name="theme_custom_warning">Varoitus</string>
|
||||
<string name="hud_only_during_game">Näytä HUD vain pelin aikana</string>
|
||||
<string name="hud_only_during_game_hint">Piilota HUD, kun pelin ruutuja ei havaita.</string>
|
||||
<string name="steam_store_close_steam">Sulje Steam ensin</string>
|
||||
|
||||
@@ -2465,6 +2465,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Si ce n\'est pas possible, connectez cet appareil à un ordinateur avec ADB et exécutez la commande ci-dessous. Revenez ensuite ici et vérifiez à nouveau.</string>
|
||||
<string name="phantom_instructions_off">Les sessions Steam peuvent démarrer.</string>
|
||||
<string name="phantom_instructions_not_applicable">Cette version d\'Android n\'utilise pas cette limite.</string>
|
||||
<string name="phantom_title_uncounted">Limite de processus enfants gérée par DroidDeck</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck exécute les programmes de la session dans des processus qu’Android ne compte pas : les options pour les développeurs peuvent rester désactivées.</string>
|
||||
<string name="phantom_fix_toggle">Activez « Désactiver les limites pour les processus enfant » dans les options pour les développeurs, puis laissez les options pour les développeurs activées.</string>
|
||||
<string name="phantom_fix_no_toggle">Cette version d\'Android ne dispose pas de cet interrupteur. Utilisez le débogage sans fil pour le modifier depuis cet appareil.</string>
|
||||
<string name="upd_block_no_apk">Cette version ne propose aucun téléchargement pour cette copie de DroidDeck.</string>
|
||||
@@ -4178,6 +4180,7 @@
|
||||
<string name="theme_custom_signal">Mises en évidence</string>
|
||||
<string name="theme_custom_good">Succès</string>
|
||||
<string name="theme_custom_error">Erreur</string>
|
||||
<string name="theme_custom_warning">Avertissement</string>
|
||||
<string name="hud_only_during_game">Afficher le HUD uniquement pendant une partie</string>
|
||||
<string name="hud_only_during_game_hint">Masquer le HUD lorsqu’aucune image du jeu n’est détectée.</string>
|
||||
<string name="steam_store_close_steam">Fermez d\'abord Steam</string>
|
||||
|
||||
@@ -2440,6 +2440,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s अगर यह संभव नहीं है, तो इस डिवाइस को ADB वाले कंप्यूटर से कनेक्ट करें और नीचे दिया कमांड चलाएं। यहां वापस आएं और फिर से जांचें।</string>
|
||||
<string name="phantom_instructions_off">Steam सेशन शुरू हो सकते हैं।</string>
|
||||
<string name="phantom_instructions_not_applicable">यह Android वर्शन इस सीमा का उपयोग नहीं करता।</string>
|
||||
<string name="phantom_title_uncounted">चाइल्ड-प्रोसेस सीमा DroidDeck संभालता है</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck सत्र के प्रोग्राम उन प्रोसेस में चलाता है जिन्हें Android नहीं गिनता, इसलिए डेवलपर विकल्प बंद रह सकते हैं।</string>
|
||||
<string name="phantom_fix_toggle">डेवलपर विकल्प में “चाइल्ड प्रोसेस से जुड़ी पाबंदियां हटाएं” चालू करें, और बाद में डेवलपर विकल्प चालू रहने दें।</string>
|
||||
<string name="phantom_fix_no_toggle">इस Android वर्शन में इसके लिए कोई स्विच नहीं है। इसे इस डिवाइस से बदलने के लिए वायरलेस डीबगिंग इस्तेमाल करें।</string>
|
||||
<string name="upd_block_no_apk">इस बिल्ड में DroidDeck की इस कॉपी के लिए कोई डाउनलोड नहीं है।</string>
|
||||
@@ -4139,6 +4141,7 @@
|
||||
<string name="theme_custom_signal">हाइलाइट</string>
|
||||
<string name="theme_custom_good">सफलता</string>
|
||||
<string name="theme_custom_error">त्रुटि</string>
|
||||
<string name="theme_custom_warning">चेतावनी</string>
|
||||
<string name="hud_only_during_game">HUD केवल गेम के दौरान दिखाएँ</string>
|
||||
<string name="hud_only_during_game_hint">गेम के फ़्रेम का पता न चलने पर HUD छिपाएँ।</string>
|
||||
<string name="steam_store_close_steam">पहले Steam बंद करें</string>
|
||||
|
||||
@@ -2440,6 +2440,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Ha ez nem lehetséges, csatlakoztassa ezt az eszközt egy ADB-vel rendelkező számítógéphez, és futtassa az alábbi parancsot. Térjen vissza ide, és ellenőrizze újra.</string>
|
||||
<string name="phantom_instructions_off">A Steam-munkamenetek elindulhatnak.</string>
|
||||
<string name="phantom_instructions_not_applicable">Ez az Android-verzió nem használja ezt a korlátot.</string>
|
||||
<string name="phantom_title_uncounted">A gyermekfolyamat-korlátot a DroidDeck kezeli</string>
|
||||
<string name="phantom_instructions_uncounted">A DroidDeck a munkamenet programjait olyan folyamatokban futtatja, amelyeket az Android nem számol bele, így a fejlesztői beállítások kikapcsolva maradhatnak.</string>
|
||||
<string name="phantom_fix_toggle">Kapcsolja be az „Alárendelt folyamatok korlátozásának kikapcsolása” lehetőséget a Fejlesztői beállításokban, és utána hagyja bekapcsolva a Fejlesztői beállításokat.</string>
|
||||
<string name="phantom_fix_no_toggle">Ehhez az Android-verzióhoz nincs kapcsoló. Használja a vezeték nélküli hibakeresést a módosításához erről az eszközről.</string>
|
||||
<string name="upd_block_no_apk">Ehhez a buildhez nincs letöltés a DroidDeck ezen másolatához.</string>
|
||||
@@ -4139,6 +4141,7 @@
|
||||
<string name="theme_custom_signal">Kiemelések</string>
|
||||
<string name="theme_custom_good">Siker</string>
|
||||
<string name="theme_custom_error">Hiba</string>
|
||||
<string name="theme_custom_warning">Figyelmeztetés</string>
|
||||
<string name="hud_only_during_game">HUD megjelenítése csak játék közben</string>
|
||||
<string name="hud_only_during_game_hint">HUD elrejtése, ha nem észlelhetők játék képkockái.</string>
|
||||
<string name="steam_store_close_steam">Előbb zárd be a Steamet</string>
|
||||
|
||||
@@ -2415,6 +2415,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Jika itu tidak memungkinkan, sambungkan perangkat ini ke komputer dengan ADB dan jalankan perintah di bawah. Kembali ke sini dan periksa lagi.</string>
|
||||
<string name="phantom_instructions_off">Sesi Steam dapat dimulai.</string>
|
||||
<string name="phantom_instructions_not_applicable">Versi Android ini tidak menggunakan batas ini.</string>
|
||||
<string name="phantom_title_uncounted">Batas proses anak ditangani DroidDeck</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck menjalankan program sesi dalam proses yang tidak dihitung Android, jadi Opsi developer bisa tetap nonaktif.</string>
|
||||
<string name="phantom_fix_toggle">Aktifkan “Nonaktifkan batasan proses turunan” di Opsi developer, dan biarkan Opsi developer tetap aktif setelahnya.</string>
|
||||
<string name="phantom_fix_no_toggle">Versi Android ini tidak memiliki sakelar untuk itu. Gunakan Debugging nirkabel untuk mengubahnya dari perangkat ini.</string>
|
||||
<string name="upd_block_no_apk">Build ini tidak memiliki unduhan untuk salinan DroidDeck ini.</string>
|
||||
@@ -4109,6 +4111,7 @@
|
||||
<string name="theme_custom_signal">Sorotan</string>
|
||||
<string name="theme_custom_good">Berhasil</string>
|
||||
<string name="theme_custom_error">Kesalahan</string>
|
||||
<string name="theme_custom_warning">Peringatan</string>
|
||||
<string name="hud_only_during_game">Tampilkan HUD hanya saat bermain</string>
|
||||
<string name="hud_only_during_game_hint">Sembunyikan HUD saat tidak ada frame game yang terdeteksi.</string>
|
||||
<string name="steam_store_close_steam">Tutup Steam terlebih dahulu</string>
|
||||
|
||||
@@ -2457,6 +2457,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Se non è possibile, collega questo dispositivo a un computer con ADB ed esegui il comando qui sotto. Poi torna qui e ricontrolla.</string>
|
||||
<string name="phantom_instructions_off">Le sessioni Steam possono avviarsi.</string>
|
||||
<string name="phantom_instructions_not_applicable">Questa versione di Android non usa questo limite.</string>
|
||||
<string name="phantom_title_uncounted">Limite dei processi figli gestito da DroidDeck</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck esegue i programmi della sessione in processi che Android non conteggia, quindi le Opzioni sviluppatore possono restare disattivate.</string>
|
||||
<string name="phantom_fix_toggle">Attiva “Disattiva limitazioni per i processi secondari” in Opzioni sviluppatore e poi lascia attive le Opzioni sviluppatore.</string>
|
||||
<string name="phantom_fix_no_toggle">Questa versione di Android non ha un interruttore per farlo. Usa il debug wireless per cambiarlo da questo dispositivo.</string>
|
||||
<string name="upd_block_no_apk">Questa build non ha un download per questa copia di DroidDeck.</string>
|
||||
@@ -4178,6 +4180,7 @@
|
||||
<string name="theme_custom_signal">Evidenziazioni</string>
|
||||
<string name="theme_custom_good">Successo</string>
|
||||
<string name="theme_custom_error">Errore</string>
|
||||
<string name="theme_custom_warning">Avviso</string>
|
||||
<string name="hud_only_during_game">Mostra l’HUD solo durante il gioco</string>
|
||||
<string name="hud_only_during_game_hint">Nascondi l’HUD quando non vengono rilevati fotogrammi del gioco.</string>
|
||||
<string name="steam_store_close_steam">Chiudi prima Steam</string>
|
||||
|
||||
@@ -2415,6 +2415,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s それができない場合は、このデバイスをADBが使えるPCに接続し、以下のコマンドを実行してください。その後ここに戻って再確認してください。</string>
|
||||
<string name="phantom_instructions_off">Steamセッションを開始できます。</string>
|
||||
<string name="phantom_instructions_not_applicable">このAndroidバージョンではこの制限は使用されません。</string>
|
||||
<string name="phantom_title_uncounted">子プロセスの制限は DroidDeck が対処します</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck はセッションのプログラムを Android が数えないプロセスで実行するため、開発者向けオプションはオフのままでかまいません。</string>
|
||||
<string name="phantom_fix_toggle">開発者向けオプションで「子プロセスの制限を無効化」をオンにし、その後も開発者向けオプションをオンのままにしてください。</string>
|
||||
<string name="phantom_fix_no_toggle">このAndroidバージョンにはこのスイッチがありません。ワイヤレスデバッグを使って、このデバイスから変更してください。</string>
|
||||
<string name="upd_block_no_apk">このビルドには、このDroidDeckコピー用のダウンロードがありません。</string>
|
||||
@@ -4109,6 +4111,7 @@
|
||||
<string name="theme_custom_signal">強調表示</string>
|
||||
<string name="theme_custom_good">成功</string>
|
||||
<string name="theme_custom_error">エラー</string>
|
||||
<string name="theme_custom_warning">警告</string>
|
||||
<string name="hud_only_during_game">ゲーム中のみHUDを表示</string>
|
||||
<string name="hud_only_during_game_hint">ゲームのフレームが検出されないときはHUDを非表示にする。</string>
|
||||
<string name="steam_store_close_steam">先に Steam を閉じてください</string>
|
||||
|
||||
@@ -2415,6 +2415,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s 이 방법을 사용할 수 없으면 이 기기를 ADB가 설치된 PC에 연결하고 아래 명령을 실행하세요. 그런 다음 여기로 돌아와 다시 확인하세요.</string>
|
||||
<string name="phantom_instructions_off">Steam 세션을 시작할 수 있습니다.</string>
|
||||
<string name="phantom_instructions_not_applicable">이 Android 버전에서는 이 제한을 사용하지 않습니다.</string>
|
||||
<string name="phantom_title_uncounted">하위 프로세스 제한은 DroidDeck이 처리합니다</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck은 세션의 프로그램을 Android가 세지 않는 프로세스에서 실행하므로 개발자 옵션을 꺼 둔 채로 두어도 됩니다.</string>
|
||||
<string name="phantom_fix_toggle">개발자 옵션에서 “하위 프로세스 제한 사용 중지”를 켜고, 이후에도 개발자 옵션을 켜 둔 상태로 유지하세요.</string>
|
||||
<string name="phantom_fix_no_toggle">이 Android 버전에는 해당 스위치가 없습니다. 무선 디버깅을 사용하여 이 기기에서 변경하세요.</string>
|
||||
<string name="upd_block_no_apk">이 빌드에는 이 DroidDeck 복사본용 다운로드가 없습니다.</string>
|
||||
@@ -4109,6 +4111,7 @@
|
||||
<string name="theme_custom_signal">강조 표시</string>
|
||||
<string name="theme_custom_good">성공</string>
|
||||
<string name="theme_custom_error">오류</string>
|
||||
<string name="theme_custom_warning">경고</string>
|
||||
<string name="hud_only_during_game">게임 중에만 HUD 표시</string>
|
||||
<string name="hud_only_during_game_hint">게임 프레임이 감지되지 않으면 HUD 숨기기.</string>
|
||||
<string name="steam_store_close_steam">먼저 Steam을 닫으세요</string>
|
||||
|
||||
@@ -2415,6 +2415,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Jika itu tidak boleh, sambungkan peranti ini ke komputer dengan ADB dan jalankan arahan di bawah. Kembali ke sini dan semak semula.</string>
|
||||
<string name="phantom_instructions_off">Sesi Steam boleh dimulakan.</string>
|
||||
<string name="phantom_instructions_not_applicable">Versi Android ini tidak menggunakan had ini.</string>
|
||||
<string name="phantom_title_uncounted">Had proses anak dikendalikan oleh DroidDeck</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck menjalankan program sesi dalam proses yang tidak dikira oleh Android, jadi Pilihan pembangun boleh kekal dimatikan.</string>
|
||||
<string name="phantom_fix_toggle">Hidupkan “Lumpuhkan sekatan proses anak” dalam Pilihan pembangun, dan biarkan Pilihan pembangun hidup selepas itu.</string>
|
||||
<string name="phantom_fix_no_toggle">Versi Android ini tidak mempunyai suis untuknya. Gunakan Debugging Wayarles untuk menukarnya daripada peranti ini.</string>
|
||||
<string name="upd_block_no_apk">Binaan ini tidak mempunyai muat turun untuk salinan DroidDeck ini.</string>
|
||||
@@ -4109,6 +4111,7 @@
|
||||
<string name="theme_custom_signal">Sorotan</string>
|
||||
<string name="theme_custom_good">Berjaya</string>
|
||||
<string name="theme_custom_error">Ralat</string>
|
||||
<string name="theme_custom_warning">Amaran</string>
|
||||
<string name="hud_only_during_game">Paparkan HUD hanya semasa bermain</string>
|
||||
<string name="hud_only_during_game_hint">Sembunyikan HUD apabila bingkai permainan tidak dikesan.</string>
|
||||
<string name="steam_store_close_steam">Tutup Steam dahulu</string>
|
||||
|
||||
@@ -2440,6 +2440,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Hvis det ikke er mulig, koble denne enheten til en datamaskin med ADB og kjør kommandoen under. Kom tilbake hit og kontroller igjen.</string>
|
||||
<string name="phantom_instructions_off">Steam-sesjoner kan starte.</string>
|
||||
<string name="phantom_instructions_not_applicable">Denne Android-versjonen bruker ikke denne grensen.</string>
|
||||
<string name="phantom_title_uncounted">DroidDeck håndterer grensen for underprosesser</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck kjører programmene i økten i prosesser som Android ikke teller med, så utvikleralternativer kan forbli av.</string>
|
||||
<string name="phantom_fix_toggle">Slå på «Slå av begrensninger for underordnede prosesser» i Utvikleralternativer, og la Utvikleralternativer stå på etterpå.</string>
|
||||
<string name="phantom_fix_no_toggle">Denne Android-versjonen har ingen bryter for det. Bruk trådløs feilsøking for å endre det fra denne enheten.</string>
|
||||
<string name="upd_block_no_apk">Denne builden har ingen nedlasting for denne kopien av DroidDeck.</string>
|
||||
@@ -4139,6 +4141,7 @@
|
||||
<string name="theme_custom_signal">Uthevinger</string>
|
||||
<string name="theme_custom_good">Suksess</string>
|
||||
<string name="theme_custom_error">Feil</string>
|
||||
<string name="theme_custom_warning">Advarsel</string>
|
||||
<string name="hud_only_during_game">Vis HUD bare mens du spiller</string>
|
||||
<string name="hud_only_during_game_hint">Skjul HUD når ingen spillbilder registreres.</string>
|
||||
<string name="steam_store_close_steam">Lukk Steam først</string>
|
||||
|
||||
@@ -2440,6 +2440,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Als dat niet mogelijk is, sluit dit apparaat aan op een computer met ADB en voer de onderstaande opdracht uit. Kom hierna terug en controleer opnieuw.</string>
|
||||
<string name="phantom_instructions_off">Steam-sessies kunnen starten.</string>
|
||||
<string name="phantom_instructions_not_applicable">Deze Android-versie gebruikt deze limiet niet.</string>
|
||||
<string name="phantom_title_uncounted">Limiet voor onderliggende processen geregeld door DroidDeck</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck voert de programma\'s van de sessie uit in processen die Android niet meetelt, dus Ontwikkelaarsopties kunnen uit blijven.</string>
|
||||
<string name="phantom_fix_toggle">Schakel “Beperkingen voor onderliggende processen uitzetten” in bij Ontwikkelaarsopties en laat Ontwikkelaarsopties daarna aan staan.</string>
|
||||
<string name="phantom_fix_no_toggle">Deze Android-versie heeft hier geen schakelaar voor. Gebruik draadloze foutopsporing om dit vanaf dit apparaat te wijzigen.</string>
|
||||
<string name="upd_block_no_apk">Deze build heeft geen download voor dit exemplaar van DroidDeck.</string>
|
||||
@@ -4139,6 +4141,7 @@
|
||||
<string name="theme_custom_signal">Accenten</string>
|
||||
<string name="theme_custom_good">Geslaagd</string>
|
||||
<string name="theme_custom_error">Fout</string>
|
||||
<string name="theme_custom_warning">Waarschuwing</string>
|
||||
<string name="hud_only_during_game">HUD alleen tijdens een game weergeven</string>
|
||||
<string name="hud_only_during_game_hint">Verberg de HUD wanneer er geen gameframes worden gedetecteerd.</string>
|
||||
<string name="steam_store_close_steam">Sluit eerst Steam</string>
|
||||
|
||||
@@ -2492,6 +2492,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Jeśli to niemożliwe, podłącz to urządzenie do komputera z ADB i uruchom poniższe polecenie. Wróć tutaj i sprawdź ponownie.</string>
|
||||
<string name="phantom_instructions_off">Sesje Steam mogą się uruchamiać.</string>
|
||||
<string name="phantom_instructions_not_applicable">Ta wersja systemu Android nie używa tego limitu.</string>
|
||||
<string name="phantom_title_uncounted">Limitem procesów podrzędnych zajmuje się DroidDeck</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck uruchamia programy sesji w procesach, których Android nie liczy, więc Opcje programisty mogą pozostać wyłączone.</string>
|
||||
<string name="phantom_fix_toggle">Włącz „Wyłącz ograniczenia procesów podrzędnych aplikacji” w Opcjach programisty i nie wyłączaj potem Opcji programisty.</string>
|
||||
<string name="phantom_fix_no_toggle">Ta wersja systemu Android nie ma dla niego przełącznika. Użyj debugowania bezprzewodowego, aby zmienić go z tego urządzenia.</string>
|
||||
<string name="upd_block_no_apk">Ta wersja nie ma pliku do pobrania dla tej kopii DroidDeck.</string>
|
||||
@@ -4219,6 +4221,7 @@
|
||||
<string name="theme_custom_signal">Wyróżnienia</string>
|
||||
<string name="theme_custom_good">Sukces</string>
|
||||
<string name="theme_custom_error">Błąd</string>
|
||||
<string name="theme_custom_warning">Ostrzeżenie</string>
|
||||
<string name="hud_only_during_game">Pokazuj HUD tylko podczas gry</string>
|
||||
<string name="hud_only_during_game_hint">Ukryj HUD, gdy nie wykryto klatek gry.</string>
|
||||
<string name="steam_store_close_steam">Najpierw zamknij Steam</string>
|
||||
|
||||
@@ -1812,6 +1812,7 @@
|
||||
<string name="theme_custom_signal">Destaques e indicadores</string>
|
||||
<string name="theme_custom_good">Sucesso</string>
|
||||
<string name="theme_custom_error">Erro</string>
|
||||
<string name="theme_custom_warning">Aviso</string>
|
||||
<string name="pckb_key_esc">Esc</string>
|
||||
<string name="pckb_key_ins">Ins</string>
|
||||
<string name="pckb_key_del">Del</string>
|
||||
@@ -2471,6 +2472,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Se não for possível, ligue este dispositivo a um computador com ADB e execute o comando abaixo. Volte aqui e verifique novamente.</string>
|
||||
<string name="phantom_instructions_off">As sessões Steam podem ser iniciadas.</string>
|
||||
<string name="phantom_instructions_not_applicable">Esta versão do Android não usa este limite.</string>
|
||||
<string name="phantom_title_uncounted">Limite de processos filhos gerido pelo DroidDeck</string>
|
||||
<string name="phantom_instructions_uncounted">O DroidDeck executa os programas da sessão em processos que o Android não conta, por isso as Opções de programador podem continuar desativadas.</string>
|
||||
<string name="phantom_fix_toggle">Ative «Desativar restrições de processos secundários» nas Opções de programador e mantenha as Opções de programador ativadas depois.</string>
|
||||
<string name="phantom_fix_no_toggle">Esta versão do Android não tem um interruptor para isto. Use a depuração sem fios para o alterar a partir deste dispositivo.</string>
|
||||
<string name="upd_block_no_apk">Esta versão não tem transferência para esta cópia do DroidDeck.</string>
|
||||
|
||||
@@ -1820,6 +1820,7 @@
|
||||
<string name="theme_custom_signal">Destaques e indicadores</string>
|
||||
<string name="theme_custom_good">Sucesso</string>
|
||||
<string name="theme_custom_error">Erro</string>
|
||||
<string name="theme_custom_warning">Aviso</string>
|
||||
<string name="pckb_key_esc">Esc</string>
|
||||
<string name="pckb_key_ins">Ins</string>
|
||||
<string name="pckb_key_del">Del</string>
|
||||
@@ -2479,6 +2480,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Se não for possível, conecte este dispositivo a um computador com ADB e execute o comando abaixo. Depois volte aqui e verifique de novo.</string>
|
||||
<string name="phantom_instructions_off">As sessões do Steam podem ser iniciadas.</string>
|
||||
<string name="phantom_instructions_not_applicable">Esta versão do Android não usa esse limite.</string>
|
||||
<string name="phantom_title_uncounted">Limite de processos filhos gerenciado pelo DroidDeck</string>
|
||||
<string name="phantom_instructions_uncounted">O DroidDeck executa os programas da sessão em processos que o Android não conta, então as Opções do desenvolvedor podem continuar desativadas.</string>
|
||||
<string name="phantom_fix_toggle">Ative “Desativar restrições de processos filhos” nas Opções do desenvolvedor e mantenha as Opções do desenvolvedor ativadas depois.</string>
|
||||
<string name="phantom_fix_no_toggle">Esta versão do Android não tem uma chave para isso. Use a depuração por Wi-Fi para alterar pelo próprio dispositivo.</string>
|
||||
<string name="upd_block_no_apk">Esta versão não tem download para esta cópia do DroidDeck.</string>
|
||||
|
||||
@@ -2466,6 +2466,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Dacă nu este posibil, conectează acest dispozitiv la un computer cu ADB și rulează comanda de mai jos. Revino aici și verifică din nou.</string>
|
||||
<string name="phantom_instructions_off">Sesiunile Steam pot porni.</string>
|
||||
<string name="phantom_instructions_not_applicable">Această versiune de Android nu folosește această limită.</string>
|
||||
<string name="phantom_title_uncounted">Limita proceselor copil este gestionată de DroidDeck</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck rulează programele sesiunii în procese pe care Android nu le numără, așa că Opțiunile pentru dezvoltatori pot rămâne dezactivate.</string>
|
||||
<string name="phantom_fix_toggle">Activează „Dezactivează restricțiile pentru procese secundare” în Opțiunile pentru dezvoltatori, și lasă Opțiunile pentru dezvoltatori activate după aceea.</string>
|
||||
<string name="phantom_fix_no_toggle">Această versiune de Android nu are un comutator pentru asta. Folosește Depanarea wireless pentru a o schimba de pe acest dispozitiv.</string>
|
||||
<string name="upd_block_no_apk">Această versiune nu are o descărcare pentru această copie de DroidDeck.</string>
|
||||
@@ -4179,6 +4181,7 @@
|
||||
<string name="theme_custom_signal">Evidențieri</string>
|
||||
<string name="theme_custom_good">Succes</string>
|
||||
<string name="theme_custom_error">Eroare</string>
|
||||
<string name="theme_custom_warning">Avertisment</string>
|
||||
<string name="hud_only_during_game">Afișează HUD-ul doar în timpul jocului</string>
|
||||
<string name="hud_only_during_game_hint">Ascunde HUD-ul când nu sunt detectate cadre ale jocului.</string>
|
||||
<string name="steam_store_close_steam">Închide mai întâi Steam</string>
|
||||
|
||||
@@ -2493,6 +2493,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Если это невозможно, подключите устройство к компьютеру с ADB и выполните команду ниже. Затем вернитесь сюда и проверьте снова.</string>
|
||||
<string name="phantom_instructions_off">Сессии Steam могут запускаться.</string>
|
||||
<string name="phantom_instructions_not_applicable">Эта версия Android не использует это ограничение.</string>
|
||||
<string name="phantom_title_uncounted">Ограничение дочерних процессов обходит DroidDeck</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck запускает программы сеанса в процессах, которые Android не учитывает, поэтому параметры разработчика можно не включать.</string>
|
||||
<string name="phantom_fix_toggle">Включите «Отключить ограничения для дочерних процессов» в разделе «Для разработчиков» и оставьте этот раздел включенным.</string>
|
||||
<string name="phantom_fix_no_toggle">В этой версии Android нет такого переключателя. Измените настройку с этого устройства через отладку по Wi-Fi.</string>
|
||||
<string name="upd_block_no_apk">В этой сборке нет загрузки для этой копии DroidDeck.</string>
|
||||
@@ -4220,6 +4222,7 @@
|
||||
<string name="theme_custom_signal">Выделения</string>
|
||||
<string name="theme_custom_good">Успех</string>
|
||||
<string name="theme_custom_error">Ошибка</string>
|
||||
<string name="theme_custom_warning">Предупреждение</string>
|
||||
<string name="hud_only_during_game">Показывать HUD только во время игры</string>
|
||||
<string name="hud_only_during_game_hint">Скрывать HUD, когда кадры игры не обнаруживаются.</string>
|
||||
<string name="steam_store_close_steam">Сначала закройте Steam</string>
|
||||
|
||||
@@ -2440,6 +2440,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Om det inte är möjligt ansluter du den här enheten till en dator med ADB och kör kommandot nedan. Kom tillbaka hit och kontrollera igen.</string>
|
||||
<string name="phantom_instructions_off">Steam-sessioner kan starta.</string>
|
||||
<string name="phantom_instructions_not_applicable">Den här Android-versionen använder inte den här gränsen.</string>
|
||||
<string name="phantom_title_uncounted">DroidDeck hanterar gränsen för underprocesser</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck kör sessionens program i processer som Android inte räknar, så Utvecklaralternativ kan vara avstängda.</string>
|
||||
<string name="phantom_fix_toggle">Slå på ”Inaktivera begränsningar på underordnade processer” i Utvecklaralternativ, och låt Utvecklaralternativ vara kvar på efteråt.</string>
|
||||
<string name="phantom_fix_no_toggle">Den här Android-versionen har ingen växel för det. Använd trådlös felsökning för att ändra det från den här enheten.</string>
|
||||
<string name="upd_block_no_apk">Den här versionen har ingen nedladdning för den här kopian av DroidDeck.</string>
|
||||
@@ -4139,6 +4141,7 @@
|
||||
<string name="theme_custom_signal">Markeringar</string>
|
||||
<string name="theme_custom_good">Lyckades</string>
|
||||
<string name="theme_custom_error">Fel</string>
|
||||
<string name="theme_custom_warning">Varning</string>
|
||||
<string name="hud_only_during_game">Visa HUD endast under spel</string>
|
||||
<string name="hud_only_during_game_hint">Dölj HUD när inga spelbildrutor upptäcks.</string>
|
||||
<string name="steam_store_close_steam">Stäng Steam först</string>
|
||||
|
||||
@@ -2415,6 +2415,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s หากทำไม่ได้ ให้เชื่อมต่ออุปกรณ์นี้กับคอมพิวเตอร์ที่มี ADB แล้วรันคำสั่งด้านล่าง กลับมาที่นี่แล้วตรวจสอบอีกครั้ง</string>
|
||||
<string name="phantom_instructions_off">เซสชัน Steam สามารถเริ่มได้</string>
|
||||
<string name="phantom_instructions_not_applicable">Android รุ่นนี้ไม่ใช้ขีดจำกัดนี้</string>
|
||||
<string name="phantom_title_uncounted">DroidDeck จัดการขีดจำกัดโปรเซสลูกให้</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck เรียกใช้โปรแกรมของเซสชันในโปรเซสที่ Android ไม่นับ จึงปิดตัวเลือกสำหรับนักพัฒนาซอฟต์แวร์ไว้ได้</string>
|
||||
<string name="phantom_fix_toggle">เปิด “ปิดการจำกัดการประมวลผลข้อมูลย่อย” ในตัวเลือกสำหรับนักพัฒนา และเปิดตัวเลือกสำหรับนักพัฒนาไว้ต่อไปหลังจากนั้น</string>
|
||||
<string name="phantom_fix_no_toggle">Android รุ่นนี้ไม่มีสวิตช์สำหรับสิ่งนี้ ใช้ Wireless debugging เพื่อเปลี่ยนค่าจากอุปกรณ์นี้</string>
|
||||
<string name="upd_block_no_apk">บิลด์นี้ไม่มีให้ดาวน์โหลดสำหรับสำเนานี้ของ DroidDeck</string>
|
||||
@@ -4109,6 +4111,7 @@
|
||||
<string name="theme_custom_signal">จุดเน้น</string>
|
||||
<string name="theme_custom_good">สำเร็จ</string>
|
||||
<string name="theme_custom_error">ข้อผิดพลาด</string>
|
||||
<string name="theme_custom_warning">คำเตือน</string>
|
||||
<string name="hud_only_during_game">แสดง HUD เฉพาะขณะเล่นเกม</string>
|
||||
<string name="hud_only_during_game_hint">ซ่อน HUD เมื่อไม่พบเฟรมของเกม</string>
|
||||
<string name="steam_store_close_steam">ปิด Steam ก่อน</string>
|
||||
|
||||
@@ -2432,6 +2432,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Bu mümkün değilse bu cihazı ADB\'li bir bilgisayara bağlayıp aşağıdaki komutu çalıştırın. Buraya dönüp yeniden kontrol edin.</string>
|
||||
<string name="phantom_instructions_off">Steam oturumları başlayabilir.</string>
|
||||
<string name="phantom_instructions_not_applicable">Bu Android sürümü bu sınırı kullanmaz.</string>
|
||||
<string name="phantom_title_uncounted">Alt işlem sınırını DroidDeck yönetiyor</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck oturumun programlarını Android\'in saymadığı işlemlerde çalıştırır; bu yüzden Geliştirici seçenekleri kapalı kalabilir.</string>
|
||||
<string name="phantom_fix_toggle">Geliştirici seçenekleri\'nde “Alt işlem kısıtlamalarını devre dışı bırak” seçeneğini açın ve sonrasında Geliştirici seçeneklerini açık tutun.</string>
|
||||
<string name="phantom_fix_no_toggle">Bu Android sürümünde bunun için bir anahtar yok. Bu cihazdan değiştirmek için Kablosuz hata ayıklamayı kullanın.</string>
|
||||
<string name="upd_block_no_apk">Bu derlemede bu DroidDeck kopyası için bir indirme yok.</string>
|
||||
@@ -4139,6 +4141,7 @@
|
||||
<string name="theme_custom_signal">Vurgular</string>
|
||||
<string name="theme_custom_good">Başarılı</string>
|
||||
<string name="theme_custom_error">Hata</string>
|
||||
<string name="theme_custom_warning">Uyarı</string>
|
||||
<string name="hud_only_during_game">HUD\'yi yalnızca oyun sırasında göster</string>
|
||||
<string name="hud_only_during_game_hint">Oyun kareleri algılanmadığında HUD\'yi gizle.</string>
|
||||
<string name="steam_store_close_steam">Önce Steam\'i kapatın</string>
|
||||
|
||||
@@ -2492,6 +2492,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Якщо це неможливо, підключіть цей пристрій до комп’ютера з ADB і виконайте команду нижче. Потім поверніться сюди і перевірте ще раз.</string>
|
||||
<string name="phantom_instructions_off">Сеанси Steam можуть запускатися.</string>
|
||||
<string name="phantom_instructions_not_applicable">Ця версія Android не використовує це обмеження.</string>
|
||||
<string name="phantom_title_uncounted">Обмеження дочірніх процесів обходить DroidDeck</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck запускає програми сеансу в процесах, які Android не враховує, тож параметри розробника можна не вмикати.</string>
|
||||
<string name="phantom_fix_toggle">Увімкніть «Вимкнути обмеження для дочірніх процесів» у розділі «Параметри розробника» і залишіть «Параметри розробника» увімкненими після цього.</string>
|
||||
<string name="phantom_fix_no_toggle">У цій версії Android немає перемикача для цього. Змініть це з цього пристрою за допомогою бездротового налагодження.</string>
|
||||
<string name="upd_block_no_apk">У цій збірці немає завантаження для цієї копії DroidDeck.</string>
|
||||
@@ -4219,6 +4221,7 @@
|
||||
<string name="theme_custom_signal">Виділення</string>
|
||||
<string name="theme_custom_good">Успіх</string>
|
||||
<string name="theme_custom_error">Помилка</string>
|
||||
<string name="theme_custom_warning">Попередження</string>
|
||||
<string name="hud_only_during_game">Показувати HUD лише під час гри</string>
|
||||
<string name="hud_only_during_game_hint">Приховувати HUD, коли кадри гри не виявляються.</string>
|
||||
<string name="steam_store_close_steam">Спочатку закрийте Steam</string>
|
||||
|
||||
@@ -2415,6 +2415,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s Nếu không thể, hãy kết nối thiết bị này với một máy tính có ADB và chạy lệnh dưới đây. Quay lại đây và kiểm tra lại.</string>
|
||||
<string name="phantom_instructions_off">Phiên Steam có thể khởi động.</string>
|
||||
<string name="phantom_instructions_not_applicable">Phiên bản Android này không dùng giới hạn này.</string>
|
||||
<string name="phantom_title_uncounted">DroidDeck xử lý giới hạn tiến trình con</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck chạy các chương trình của phiên trong những tiến trình mà Android không tính, nên có thể để tắt Tùy chọn cho nhà phát triển.</string>
|
||||
<string name="phantom_fix_toggle">Bật “Tắt các mục hạn chế đối với tiến trình con” trong Developer options, và giữ Developer options luôn mở sau đó.</string>
|
||||
<string name="phantom_fix_no_toggle">Phiên bản Android này không có công tắc cho việc đó. Dùng Gỡ lỗi qua mạng không dây để đổi nó từ thiết bị này.</string>
|
||||
<string name="upd_block_no_apk">Bản build này không có tệp tải cho bản DroidDeck này.</string>
|
||||
@@ -4109,6 +4111,7 @@
|
||||
<string name="theme_custom_signal">Điểm nhấn</string>
|
||||
<string name="theme_custom_good">Thành công</string>
|
||||
<string name="theme_custom_error">Lỗi</string>
|
||||
<string name="theme_custom_warning">Cảnh báo</string>
|
||||
<string name="hud_only_during_game">Chỉ hiển thị HUD khi đang chơi</string>
|
||||
<string name="hud_only_during_game_hint">Ẩn HUD khi không phát hiện khung hình trò chơi.</string>
|
||||
<string name="steam_store_close_steam">Hãy đóng Steam trước</string>
|
||||
|
||||
@@ -2492,6 +2492,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s 如果无法做到,请将此设备连接到装有 ADB 的电脑并运行下方命令,然后返回此处重新检查。</string>
|
||||
<string name="phantom_instructions_off">可以启动 Steam 会话了。</string>
|
||||
<string name="phantom_instructions_not_applicable">此 Android 版本不使用该限制。</string>
|
||||
<string name="phantom_title_uncounted">子进程限制由 DroidDeck 处理</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck 在 Android 不计数的进程中运行会话程序,因此开发者选项可以保持关闭。</string>
|
||||
<string name="phantom_fix_toggle">在开发者选项中打开“停止限制子进程”,之后请保持开发者选项开启。</string>
|
||||
<string name="phantom_fix_no_toggle">此 Android 版本没有该开关。请使用无线调试在此设备上更改。</string>
|
||||
<string name="upd_block_no_apk">此构建没有适用于此 DroidDeck 副本的下载。</string>
|
||||
@@ -4109,6 +4111,7 @@
|
||||
<string name="theme_custom_signal">高亮</string>
|
||||
<string name="theme_custom_good">成功</string>
|
||||
<string name="theme_custom_error">错误</string>
|
||||
<string name="theme_custom_warning">警告</string>
|
||||
<string name="hud_only_during_game">仅在游戏期间显示 HUD</string>
|
||||
<string name="hud_only_during_game_hint">未检测到游戏帧时隐藏 HUD。</string>
|
||||
<string name="steam_store_close_steam">请先关闭 Steam</string>
|
||||
|
||||
@@ -2412,6 +2412,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s 如無法這樣做,請將此裝置連接到已安裝 ADB 的電腦,並執行以下指令,然後返回這裡再檢查一次。</string>
|
||||
<string name="phantom_instructions_off">可以啟動 Steam 會話。</string>
|
||||
<string name="phantom_instructions_not_applicable">此 Android 版本不使用此限制。</string>
|
||||
<string name="phantom_title_uncounted">子程序限制由 DroidDeck 處理</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck 在 Android 不計算的程序中執行工作階段的程式,因此開發人員選項可以保持關閉。</string>
|
||||
<string name="phantom_fix_toggle">在開發人員選項中開啟「停用對子處理過程的限制」,之後請保持開發人員選項開啟。</string>
|
||||
<string name="phantom_fix_no_toggle">此 Android 版本沒有此開關。請使用無線偵錯,直接在此裝置上更改。</string>
|
||||
<string name="upd_block_no_apk">此版本沒有適用於此 DroidDeck 版本的下載。</string>
|
||||
@@ -4109,6 +4111,7 @@
|
||||
<string name="theme_custom_signal">重點標示</string>
|
||||
<string name="theme_custom_good">成功</string>
|
||||
<string name="theme_custom_error">錯誤</string>
|
||||
<string name="theme_custom_warning">警告</string>
|
||||
<string name="hud_only_during_game">只在遊戲期間顯示 HUD</string>
|
||||
<string name="hud_only_during_game_hint">未偵測到遊戲畫面時隱藏 HUD。</string>
|
||||
<string name="steam_store_close_steam">請先關閉 Steam</string>
|
||||
|
||||
@@ -2412,6 +2412,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s 如果無法這麼做,請將此裝置連接到裝有 ADB 的電腦並執行下方指令,然後返回這裡重新檢查。</string>
|
||||
<string name="phantom_instructions_off">可以啟動 Steam 工作階段。</string>
|
||||
<string name="phantom_instructions_not_applicable">此 Android 版本不使用這項限制。</string>
|
||||
<string name="phantom_title_uncounted">子程序限制由 DroidDeck 處理</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck 在 Android 不計算的程序中執行工作階段的程式,因此開發人員選項可以保持關閉。</string>
|
||||
<string name="phantom_fix_toggle">在開發人員選項中開啟「停止限制子程序」,之後請保持開發人員選項開啟。</string>
|
||||
<string name="phantom_fix_no_toggle">此 Android 版本沒有這個開關。請使用無線偵錯,直接在此裝置上變更。</string>
|
||||
<string name="upd_block_no_apk">此組建版本沒有適用於此 DroidDeck 複本的下載檔案。</string>
|
||||
@@ -4109,6 +4111,7 @@
|
||||
<string name="theme_custom_signal">醒目標示</string>
|
||||
<string name="theme_custom_good">成功</string>
|
||||
<string name="theme_custom_error">錯誤</string>
|
||||
<string name="theme_custom_warning">警告</string>
|
||||
<string name="hud_only_during_game">僅在遊戲期間顯示 HUD</string>
|
||||
<string name="hud_only_during_game_hint">未偵測到遊戲畫面時隱藏 HUD。</string>
|
||||
<string name="steam_store_close_steam">請先關閉 Steam</string>
|
||||
|
||||
@@ -2028,6 +2028,7 @@
|
||||
<string name="theme_custom_signal">Highlights</string>
|
||||
<string name="theme_custom_good">Success</string>
|
||||
<string name="theme_custom_error">Error</string>
|
||||
<string name="theme_custom_warning">Warning</string>
|
||||
<string name="pckb_key_esc">Esc</string>
|
||||
<string name="pckb_key_ins">Ins</string>
|
||||
<string name="pckb_key_del">Del</string>
|
||||
@@ -2742,6 +2743,8 @@
|
||||
<string name="phantom_instructions_fix">%1$s If that is not possible, connect this device to a computer with ADB and run the command below. Return here and check again.</string>
|
||||
<string name="phantom_instructions_off">Steam sessions can start.</string>
|
||||
<string name="phantom_instructions_not_applicable">This Android version does not use this limit.</string>
|
||||
<string name="phantom_title_uncounted">Child-process limit handled by DroidDeck</string>
|
||||
<string name="phantom_instructions_uncounted">DroidDeck runs most of the session\'s programs in processes Android does not count, which keeps the session well under the limit, so Developer options can stay off. Steam and some of its helpers still count.</string>
|
||||
<string name="phantom_fix_toggle">Turn on “Disable child process restrictions” in Developer options, and keep Developer options on afterwards.</string>
|
||||
<string name="phantom_fix_no_toggle">This Android version has no switch for it. Use Wireless debugging to change it from this device.</string>
|
||||
<string name="upd_block_no_apk">This build has no download for this copy of DroidDeck.</string>
|
||||
|
||||
@@ -81,4 +81,10 @@ class PhantomProcessLimitTest {
|
||||
assertFalse(PhantomProcessLimit.hasDeveloperToggle(33))
|
||||
assertTrue(PhantomProcessLimit.hasDeveloperToggle(34))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theLimitOnDoesNotBlockSteamWhenTheSessionStaysOutOfItsCount() {
|
||||
assertFalse(PhantomProcessLimit.blocksSteam(PhantomProcessStatus.UNCOUNTED))
|
||||
assertTrue(PhantomProcessLimit.blocksSteam(PhantomProcessStatus.ENABLED))
|
||||
}
|
||||
}
|
||||
@@ -145,4 +145,15 @@ class AddedGamesCandidatesTest {
|
||||
SessionPrefs.setAddedGamesDirs(app, listOf(games.path))
|
||||
assertEquals("My Game [Repack]", AddedGames.scan(app).single().name)
|
||||
}
|
||||
|
||||
@Test fun linksAndFoldersNamedLikeAnExeAreNotCandidates() {
|
||||
val elsewhere = tmp.newFolder("Elsewhere")
|
||||
exe(elsewhere, "Other.exe")
|
||||
val game = tmp.newFolder("Linked")
|
||||
exe(game, "bin/Linked.exe")
|
||||
File(game, "Folder.exe").mkdirs()
|
||||
java.nio.file.Files.createSymbolicLink(File(game, "other").toPath(), elsewhere.toPath())
|
||||
java.nio.file.Files.createSymbolicLink(File(game, "Alias.exe").toPath(), File(elsewhere, "Other.exe").toPath())
|
||||
assertEquals(listOf("bin/Linked.exe"), names(game))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.stores.SteamLiveShortcuts
|
||||
import java.io.File
|
||||
import java.util.Collections
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class AddedGamesSessionListingTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@After fun restore() {
|
||||
AddedGamesPublisher.now = false
|
||||
AddedGamesPublisher.live = SteamLiveShortcuts::sync
|
||||
SessionState.running = false
|
||||
SessionState.stopRequested = false
|
||||
SessionState.sessionId = null
|
||||
SessionState.phase = SessionPhase.IDLE
|
||||
}
|
||||
|
||||
private val stale = """[{"name":"Old","exe":"/root/Games/Old/Old.exe","folder":"/root/Games/Old","dir":"/root/Games/Old","appid":2147483649,"seen":0}]"""
|
||||
|
||||
private fun gamesFolder(vararg names: String): File {
|
||||
val games = tmp.newFolder("PC")
|
||||
for (n in names) File(games, "$n/$n.exe").apply { parentFile!!.mkdirs() }.writeText("game")
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
SessionPrefs.setAddedGamesDirs(app, listOf(games.path))
|
||||
return games
|
||||
}
|
||||
|
||||
private fun session(phase: SessionPhase) {
|
||||
SessionState.sessionId = "session-test"
|
||||
SessionState.stopRequested = false
|
||||
SessionState.phase = phase
|
||||
SessionState.running = true
|
||||
}
|
||||
|
||||
private fun until(what: String, check: () -> Boolean) {
|
||||
val end = System.currentTimeMillis() + 30_000
|
||||
while (!check()) {
|
||||
assertTrue(what, System.currentTimeMillis() < end)
|
||||
Thread.sleep(20)
|
||||
}
|
||||
}
|
||||
|
||||
private fun scanLock(): Any =
|
||||
AddedGames::class.java.getDeclaredField("scanning").apply { isAccessible = true }.get(null)!!
|
||||
|
||||
private fun refreshes() = Thread.getAllStackTraces().keys.filter { it.name == "added-games-refresh" }
|
||||
|
||||
@Test fun aSessionStartsFromTheLastListingWhileTheLibraryScanHoldsTheLock() {
|
||||
gamesFolder("Alpha")
|
||||
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
|
||||
val done = CountDownLatch(1)
|
||||
var returned: File? = null
|
||||
var seen = ""
|
||||
synchronized(scanLock()) {
|
||||
Thread {
|
||||
returned = AddedGamesPublisher.sessionListing(app)
|
||||
seen = listing.readText()
|
||||
done.countDown()
|
||||
}.start()
|
||||
assertTrue("the session start waited for the library scan", done.await(5, TimeUnit.SECONDS))
|
||||
}
|
||||
assertEquals(listing.path, returned!!.path)
|
||||
assertEquals(stale, seen)
|
||||
refreshes().forEach { it.join(30_000) }
|
||||
assertTrue(refreshes().isEmpty())
|
||||
val fresh = listing.readText()
|
||||
assertTrue(fresh.contains("\"Alpha\""))
|
||||
assertFalse(fresh.contains("\"Old\""))
|
||||
assertFalse(File(listing.parentFile, listing.name + ".part").exists())
|
||||
}
|
||||
|
||||
@Test fun aFirstSessionScansBeforeStarting() {
|
||||
gamesFolder("Alpha")
|
||||
AddedGamesPublisher.now = false
|
||||
val listing = AddedGames.listingFile(app)
|
||||
listing.delete()
|
||||
assertEquals(listing.path, AddedGamesPublisher.sessionListing(app).path)
|
||||
assertTrue(listing.readText().contains("\"Alpha\""))
|
||||
assertTrue(refreshes().isEmpty())
|
||||
assertFalse(File(listing.parentFile, listing.name + ".part").exists())
|
||||
}
|
||||
|
||||
@Test fun aListingThatCannotBeReplacedKeepsTheOldOne() {
|
||||
val listing = AddedGames.listingFile(app).apply { parentFile?.mkdirs() }
|
||||
listing.writeText("[]")
|
||||
val blocked = File(listing.parentFile, listing.name + ".part").apply { mkdirs() }
|
||||
gamesFolder("Alpha")
|
||||
AddedGames.writeListing(app, AddedGames.scan(app))
|
||||
assertEquals("[]", listing.readText())
|
||||
assertFalse(blocked.exists())
|
||||
}
|
||||
|
||||
@Test fun anUnreadableListingIsRescannedBeforeStarting() {
|
||||
gamesFolder("Alpha")
|
||||
AddedGamesPublisher.now = false
|
||||
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText("[{\"name\":") }
|
||||
AddedGamesPublisher.sessionListing(app)
|
||||
assertTrue(listing.readText().contains("\"Alpha\""))
|
||||
assertTrue(refreshes().isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aGameRemovedWhileTheClientStartsIsNotAddedToIt() {
|
||||
val games = gamesFolder("Alpha", "Beta")
|
||||
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
|
||||
val delivered = Collections.synchronizedList(ArrayList<String>())
|
||||
AddedGamesPublisher.live = { _, found, include -> delivered.addAll(found.filter(include).map { it.name }); true }
|
||||
session(SessionPhase.STARTING_STEAM)
|
||||
AddedGamesPublisher.sessionListing(app)
|
||||
until("the refresh did not write the listing") { listing.readText().contains("\"Beta\"") }
|
||||
SessionPrefs.setAddedGameRemoved(app, File(games, "Beta").path, true)
|
||||
SessionState.phase = SessionPhase.READY
|
||||
refreshes().forEach { it.join(30_000) }
|
||||
assertTrue(refreshes().isEmpty())
|
||||
assertEquals(listOf("Alpha"), delivered.toList())
|
||||
}
|
||||
|
||||
@Test fun aDeliveryTheClientRefusesIsRetriedUntilItIsTaken() {
|
||||
gamesFolder("Alpha")
|
||||
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
|
||||
val attempts = Collections.synchronizedList(ArrayList<List<String>>())
|
||||
AddedGamesPublisher.live = { _, found, include -> attempts.add(found.filter(include).map { it.name }); attempts.size > 1 }
|
||||
session(SessionPhase.READY)
|
||||
AddedGamesPublisher.sessionListing(app)
|
||||
refreshes().forEach { it.join(30_000) }
|
||||
assertTrue(refreshes().isEmpty())
|
||||
assertEquals(listOf(listOf("Alpha"), listOf("Alpha")), attempts.toList())
|
||||
}
|
||||
|
||||
@Test fun anEndedSessionStopsTheRetries() {
|
||||
gamesFolder("Alpha")
|
||||
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
|
||||
val attempts = Collections.synchronizedList(ArrayList<String>())
|
||||
AddedGamesPublisher.live = { _, found, _ -> attempts.addAll(found.map { it.name }); SessionState.running = false; false }
|
||||
session(SessionPhase.READY)
|
||||
AddedGamesPublisher.sessionListing(app)
|
||||
refreshes().forEach { it.join(30_000) }
|
||||
assertTrue(refreshes().isEmpty())
|
||||
assertEquals(listOf("Alpha"), attempts.toList())
|
||||
}
|
||||
|
||||
@Test fun aDeliveryQueuedForAnEndedSessionIsNotSentToTheNextOne() {
|
||||
gamesFolder("Alpha")
|
||||
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
|
||||
val delivered = Collections.synchronizedList(ArrayList<String>())
|
||||
AddedGamesPublisher.live = { _, found, include -> delivered.addAll(found.filter(include).map { it.name }); true }
|
||||
session(SessionPhase.READY)
|
||||
val first = CountDownLatch(1)
|
||||
val firstHeld = CountDownLatch(1)
|
||||
val second = CountDownLatch(1)
|
||||
val secondHeld = CountDownLatch(1)
|
||||
AddedGamesPublisher.later(app) { firstHeld.countDown(); first.await() }
|
||||
try {
|
||||
assertTrue(firstHeld.await(30, TimeUnit.SECONDS))
|
||||
AddedGamesPublisher.sessionListing(app)
|
||||
val refresh = refreshes().single()
|
||||
until("the refresh did not wait for its scan") { refresh.state == Thread.State.WAITING }
|
||||
AddedGamesPublisher.later(app) { secondHeld.countDown(); second.await() }
|
||||
first.countDown()
|
||||
assertTrue(secondHeld.await(30, TimeUnit.SECONDS))
|
||||
until("the refresh did not queue its delivery") {
|
||||
refresh.state == Thread.State.WAITING && refresh.stackTrace.any { it.methodName == "deliver" }
|
||||
}
|
||||
SessionState.sessionId = "session-next"
|
||||
} finally {
|
||||
first.countDown()
|
||||
second.countDown()
|
||||
}
|
||||
refreshes().forEach { it.join(30_000) }
|
||||
assertTrue(refreshes().isEmpty())
|
||||
assertTrue(delivered.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun theRefreshWaitsForEarlierPublicationsBeforeWriting() {
|
||||
gamesFolder("Alpha")
|
||||
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
|
||||
val hold = CountDownLatch(1)
|
||||
val holding = CountDownLatch(1)
|
||||
AddedGamesPublisher.later(app) { holding.countDown(); hold.await() }
|
||||
try {
|
||||
assertTrue(holding.await(30, TimeUnit.SECONDS))
|
||||
AddedGamesPublisher.sessionListing(app)
|
||||
val refresh = refreshes().single()
|
||||
until("the refresh neither finished nor waited") { refresh.state == Thread.State.WAITING || !refresh.isAlive }
|
||||
assertTrue("the refresh wrote while an earlier publication was running", refresh.isAlive)
|
||||
assertEquals(stale, listing.readText())
|
||||
} finally {
|
||||
hold.countDown()
|
||||
}
|
||||
refreshes().forEach { it.join(30_000) }
|
||||
assertTrue(refreshes().isEmpty())
|
||||
assertTrue(listing.readText().contains("\"Alpha\""))
|
||||
}
|
||||
}
|
||||
@@ -201,6 +201,25 @@ class DirectTouchHoldTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun aDragLiftsAtOnce() {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
touch(MotionEvent.ACTION_MOVE, 80f)
|
||||
advance(80)
|
||||
touches.clear()
|
||||
touch(MotionEvent.ACTION_UP, 80f)
|
||||
assertEquals(listOf("up 0 at 80.0,30.0"), touches)
|
||||
}
|
||||
|
||||
@Test fun aTapStaysPressedLongEnoughToBeSeen() {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
advance(10)
|
||||
touch(MotionEvent.ACTION_UP)
|
||||
advance(49)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0"), touches)
|
||||
advance(1)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 40.0,30.0"), touches)
|
||||
}
|
||||
|
||||
private fun advance(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms))
|
||||
private fun touch(action: Int, x: Float = 40f): Boolean {
|
||||
val event = MotionEvent.obtain(0, 0, action, x, 30f, 0)
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class SteamLiveShortcutsSyncTest {
|
||||
@Test fun everyGameKnownOrAddedIsDelivered() {
|
||||
assertTrue(SteamLiveShortcuts.synced("""{"added":2,"missed":0}"""))
|
||||
assertTrue(SteamLiveShortcuts.synced("""{"added":0,"missed":0}"""))
|
||||
}
|
||||
|
||||
@Test fun aGameTheClientRefusedIsNotDelivered() {
|
||||
assertFalse(SteamLiveShortcuts.synced("""{"added":1,"missed":1}"""))
|
||||
assertFalse(SteamLiveShortcuts.synced("""{"added":0,"missed":3}"""))
|
||||
}
|
||||
|
||||
@Test fun noAnswerIsNotDelivered() {
|
||||
assertFalse(SteamLiveShortcuts.synced(null))
|
||||
assertFalse(SteamLiveShortcuts.synced("1"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class IdleFramesTest {
|
||||
@Test
|
||||
fun idleLoopsDrawThirtyFramesASecondAndShareEachOne() {
|
||||
val start = 5_000_000_000L
|
||||
val frame = 8_333_333L
|
||||
val drawn = (0 until 120).count { IdleFrames.due(start + it * frame) }
|
||||
assertEquals(30, drawn)
|
||||
|
||||
val later = start + 1_000_000_000L
|
||||
assertEquals(listOf(true, true, true), List(3) { IdleFrames.due(later) })
|
||||
assertEquals(listOf(false, false), List(2) { IdleFrames.due(later + frame) })
|
||||
assertEquals(listOf(true, true), List(2) { IdleFrames.due(later + 4 * frame) })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
# Android's child-process limit without developer options
|
||||
|
||||
Research log for removing DroidDeck's requirement to turn off "Restrict child processes" (or run
|
||||
`settings put global settings_enable_monitor_phantom_procs false` over wireless ADB). The goal:
|
||||
Android must not kill a Steam session for having too many Linux processes, and the user must not
|
||||
need developer options.
|
||||
|
||||
Status: **working on the AYN Thor (Android 13).** With Android's limit on and no developer option,
|
||||
a Steam session with a game running keeps 12 processes in the app's counted cgroups (63 without
|
||||
this work), and Android killed nothing in minutes of forced scans. DroidDeck's Setup reports the
|
||||
limit as handled and no longer blocks Steam. Both counting gaps below are in identical code on
|
||||
Android 12 through 16; a stock Android 14+ phone is still to be tested. The experiments are in
|
||||
`tools/phantomlab` (see the end).
|
||||
|
||||
## How Android counts and kills
|
||||
|
||||
Source: `frameworks/base/services/core/java/com/android/server/am/PhantomProcessList.java`
|
||||
(android12-release to android16-release and main; the parts below are unchanged across them).
|
||||
|
||||
1. **What is counted.** For every app process AMS knows (`mPidsSelfLocked`),
|
||||
`lookForPhantomProcessesLocked(app)` reads
|
||||
`/sys/fs/cgroup/uid_<app.info.uid>/pid_<pid>/cgroup.procs` (`/acct/...` on cgroup v1). Every
|
||||
pid listed there other than the app process itself is a "phantom process". `cgroup.procs`
|
||||
lists thread-group ids, so threads never count.
|
||||
2. **What is skipped.**
|
||||
- `if (app.appZygote || app.isKilled() || app.isKilledByAm()) return;`. `appZygote` is true
|
||||
for uids in `FIRST_APP_ZYGOTE_ISOLATED_UID..LAST_APP_ZYGOTE_ISOLATED_UID` (90000–98999),
|
||||
i.e. every process forked from an app zygote (`ProcessRecord` constructor).
|
||||
- A pid that is itself an app process (`mPidsSelfLocked.get(pid) != null`).
|
||||
- A pid whose `/proc/<pid>/cmdline` cannot be opened, whose uid cannot be read, or for which
|
||||
`pidfd_open` fails. These only happen once the process is gone (an empty cmdline reads as
|
||||
`""`, not `null`, so it is still counted).
|
||||
3. **When.** Only after AMS refreshes CPU stats (`AppProfiler.updateCpuStatsNow` →
|
||||
`updateProcessCpuStatesLocked`), at most every 5 s (`MONITOR_CPU_MIN_TIME`), and only when
|
||||
something asks for it: activity and process lifecycle events, mostly. Also from
|
||||
`setProcessGroupForPhantomProcessOfApp` when an app changes scheduling group. A new phantom
|
||||
schedules `trimPhantomProcessesIfNecessary`.
|
||||
4. **The kill.** When the device-wide total exceeds `max_phantom_processes` (32), phantoms are
|
||||
sorted by their app's oom adj (most important first), then youngest first, and the surplus is
|
||||
killed from the end of that list (`SIGKILL` and `killProcessGroup`): the least important app's
|
||||
oldest processes go first. As the foreground app, other apps' phantoms go first, so the
|
||||
practical budget is our own 32, and of ours the **oldest** die first: the session's PipeWire,
|
||||
D-Bus and Steam itself, not the game that pushed the count over.
|
||||
5. **The second killer.** `ActivityManagerService.updatePhantomProcessCpuTimeLPr`: when the app is
|
||||
at `PROCESS_STATE_HOME` or below (backgrounded, no foreground service) and a phantom used
|
||||
"excessive" CPU, `killPhantomProcessGroupLocked` kills every phantom of that app **and the app**.
|
||||
|
||||
`settings_enable_monitor_phantom_procs=false` (the developer option) switches off both on Android
|
||||
12L and later; Android 12 does not have the setting, and there only the `device_config` limit below
|
||||
applies. Raising
|
||||
`max_phantom_processes` through `device_config` (shell only) avoids only the first: the
|
||||
excessive-CPU check still runs while monitoring is on.
|
||||
|
||||
Today an idle Steam session is about 30 processes and a session with a game about 45 (#566, #575).
|
||||
|
||||
## Gap 1: an isolated process's children are never counted
|
||||
|
||||
Two independent reasons, either of which is enough:
|
||||
|
||||
- **Wrong cgroup path.** The path is built from `app.info.uid`, the *package's* uid (10148 here),
|
||||
but an isolated process runs as its own uid (99000+ for `android:isolatedProcess`, 90000+ from an
|
||||
app zygote) and its cgroup is `uid_<isolated uid>/pid_<pid>`. The lookup finds nothing
|
||||
(`FileNotFoundException`, logged only with `DEBUG_PROCESSES`) and the process is skipped.
|
||||
- **App zygote skip.** Processes forked from an app zygote (`android:useAppZygote="true"`) are
|
||||
skipped outright by the `app.appZygote` check, by design ("doesn't have its own acct entry").
|
||||
This one survives even if Google fixes the path.
|
||||
|
||||
Measured with `max_phantom_processes=4` and monitoring on, children killed by Android:
|
||||
|
||||
| Where the children were forked | Children | Thor (Android 13) | Emulator (Android 15) |
|
||||
|---|---|---|---|
|
||||
| Main app process (control) | 10 | 6 ("Trimming phantom processes") | 6 |
|
||||
| plain `isolatedProcess` service (uid 99000+) | 10 | 0 | 0 |
|
||||
| `isolatedProcess` + `useAppZygote` service (uid 90000) | 40 | 0 | 0 |
|
||||
|
||||
`cgroup.procs` of `/sys/fs/cgroup/uid_90000/pid_<service>` held all 41 pids the whole time; the
|
||||
phantom list (`dumpsys activity processes`, "All Active App Child Processes") only ever showed the
|
||||
main process's children. With the limit at 4, the Thor also trimmed another app's `logcat` child,
|
||||
as expected for the device-wide count.
|
||||
|
||||
## Gap 2: a process that execs in place is an app process, not a phantom
|
||||
|
||||
An `android:process` service process can `execve()` a Linux program in place. If it first clears
|
||||
`FD_CLOEXEC` on its binder fd, the binder node stays alive, so AMS never sees the process die. The
|
||||
pid stays in `mPidsSelfLocked` and is never counted. Its own children are counted as usual.
|
||||
|
||||
Same results on the Thor and the emulator:
|
||||
|
||||
| Worker `:wN` | Result |
|
||||
|---|---|
|
||||
| exec `/system/bin/sleep`, binder fd closed by exec (control) | "has died" at once; AMS restarts the service |
|
||||
| exec `/system/bin/sleep`, binder fd kept | stays `fg`/`(service)` while bound; survives a density change, `am send-trim-memory`, Home/back cycles |
|
||||
| exec `sh` forking 6 `sleep`s, binder fd kept | `sh` not counted; its 6 children counted (2 trimmed at limit 4) |
|
||||
| guest exits (killed) | AMS logs "has died" and removes the cgroup, as for any app process |
|
||||
|
||||
Calls AMS makes into the process after the exec fail cleanly: the kernel logs
|
||||
`binder_alloc_buf, no vma` and AMS gets `DeadObjectException` ("Failed for dead process.
|
||||
ClientTransactionItem=ConfigurationChangeItem", "Remote exception" for trim). Nothing kills the
|
||||
process for it. It is frozen like any cached process when the app goes to the background without a
|
||||
foreground service.
|
||||
|
||||
## What else was tried
|
||||
|
||||
| Idea | Result |
|
||||
|---|---|
|
||||
| Move a process to another cgroup (`cgroup.procs` of root, of `uid_N`) | `EACCES`: dirs are `system:system 0775` and SELinux denies `cgroup_v2` writes to apps |
|
||||
| Make a sub-cgroup under our `pid_N` (children of a sub-cgroup are not in its `cgroup.procs`) | `EACCES` |
|
||||
| `clone3(CLONE_INTO_CGROUP)` | apps cannot open `/sys/fs/cgroup` (SELinux `read` denied) |
|
||||
| `unshare(CLONE_NEWUSER)` / `CLONE_NEWCGROUP` | `EINVAL` (no user namespaces in GKI) / `EPERM` |
|
||||
| Empty `/proc/<pid>/cmdline` | read as `""`, still counted; changing it needs `PR_SET_MM` (`CAP_SYS_RESOURCE`) |
|
||||
| Run "processes" as threads (`CLONE_THREAD`) | only with a shared address space; Steam, Chromium and Wine rely on real processes |
|
||||
| More `android:process` services hosting the tree | each process's children are still phantoms; only the process itself is free (Gap 2) |
|
||||
| Rely on kill order | we are the foreground app, so our own newest processes die first |
|
||||
|
||||
## What an isolated process can do
|
||||
|
||||
Measured from both isolated variants (domain `isolated_app`) against the normal app
|
||||
(`untrusted_app`), with fds created by the app and passed over binder:
|
||||
|
||||
| | app | isolated |
|
||||
|---|---|---|
|
||||
| `fork` | ✅ | ✅ (children uncounted) |
|
||||
| `execve` of an executable in the APK's lib dir (as `libddexec.so`) | ✅ | ✅ |
|
||||
| `execve` of `/system/bin/*` | ✅ | ✅ |
|
||||
| create `AF_INET` socket | ✅ | ❌ `EACCES` |
|
||||
| `connect`/`send`/`recv` on a TCP or UDP socket the app created | ✅ | ✅ (policy: "network sockets received over IPC") |
|
||||
| read/write a passed unix stream socket / pipe | ✅ | ✅ |
|
||||
| `open()` an app data file by path | ✅ | ❌ `ENOENT` (not mounted) |
|
||||
| read/write/`mmap` a passed app data file | ✅ | ✅ |
|
||||
| `mmap(PROT_EXEC)` of a passed app data file | ✅ | ❌ `EACCES` |
|
||||
| receive a passed directory fd | ✅ | ❌ (binder refuses the transaction) |
|
||||
| `mmap(PROT_EXEC)` of a memfd, anonymous RWX (JIT) | ✅ | ✅ |
|
||||
| GPU device (`/dev/kgsl-3d0`, `/dev/mali0`) | ✅ | ❌ (`neverallow`, also for passed fds) |
|
||||
| signal or read `/proc` of the app's processes | ✅ | ❌ (`EPERM`, `EACCES`) |
|
||||
|
||||
This table is the emulator (stock, enforcing policy). **The Thor's ROM runs `isolated_app`
|
||||
permissive** (every isolated denial logs `permissive=1`; `untrusted_app` is enforcing): there an
|
||||
isolated process could also create inet sockets and open `/dev/kgsl-3d0`. That is an AYN quirk and
|
||||
must not be relied on; design for the enforcing column.
|
||||
|
||||
Isolated processes can talk to each other through abstract unix sockets. Everything else in the
|
||||
app's world (files, sockets to the app's servers, the GPU) has to be brokered through fds.
|
||||
|
||||
## Routes
|
||||
|
||||
### A. An isolated tier for everything that does not touch the GPU
|
||||
|
||||
Run a session's GPU-free processes inside one app-zygote isolated service; their whole fork tree is
|
||||
invisible. Needed:
|
||||
|
||||
- **Loader:** `libddexec.so` already starts programs without the kernel loading them; it would take
|
||||
its ELF from an inherited fd and copy segments into anonymous or memfd memory, since isolated
|
||||
processes cannot map app files executable. A broker can hand out one sealed memfd per library so
|
||||
pages stay shared.
|
||||
- **File broker:** the native hook already funnels path calls through `rewrite_path`; in the
|
||||
isolated tier those calls become requests to a broker in the app, which opens the file and returns
|
||||
the fd. Directories cannot be passed, so `opendir`/`getdents` are served from listings.
|
||||
Raw syscalls (Wine's preloader, FEX internals) need a seccomp `SIGSYS` trap, which the hook
|
||||
already uses for Android's own filter.
|
||||
- **Sockets:** `socket(AF_INET*)` → broker-created socket; then the process connects itself.
|
||||
Unix sockets between isolated processes become abstract sockets; connections to servers in the
|
||||
app (compositor, PipeWire, VkBridge) are connected by the broker.
|
||||
- **No signals across the boundary:** a process and everything it signals or ptraces must be on the
|
||||
same side. Wine's processes all depend on `wineserver` signalling them, so Wine stays with the game.
|
||||
- **GPU:** only through a remoting layer such as VkBridge (already used on Mali), never directly.
|
||||
|
||||
Candidates for the tier: the Steam client and its web helper's renderer/utility processes (with
|
||||
the web helper's GPU work remoted or in software), the session scripts, D-Bus services, PipeWire
|
||||
helpers, Python daemons. A cross-tier launch (Steam starting the game's `reaper`) runs through the
|
||||
broker, with a small stand-in process left in the tier for Steam to wait on. Stand-ins are free
|
||||
there.
|
||||
|
||||
### B. Exec-in-place workers for long-lived processes
|
||||
|
||||
Declare a pool of `android:process` services (`:g0`…`:g95`). Each long-lived program runs as the
|
||||
main process of one worker (Gap 2): full app privileges, direct GPU, normal signals and `/proc`
|
||||
(same uid and SELinux domain), and the app hears its exit through binder death. Costs and limits:
|
||||
|
||||
- A worker is a zygote fork (~100 ms); a pre-started pool removes the wait.
|
||||
- Only the worker's main process is free; its children count. So each long-lived program must be
|
||||
started in its own worker, not forked by its parent.
|
||||
- Programs the app or the session script start and do not wait on (Xwayland, D-Bus, PipeWire,
|
||||
helpers, `wineserver -p`) can move with a `droiddeck-spawn` client and no other change.
|
||||
- A program another guest forks and waits on (Wine's processes, Steam's children) needs the hook to
|
||||
hand the exec to a worker and translate the pid for the parent: `wait4`, `kill`, `/proc/<pid>`,
|
||||
`SIGCHLD`. All app processes share zygote's session (sid 0, pgid of zygote), so `setpgid` and
|
||||
process-group signals across workers are possible.
|
||||
- Relies on AMS never pinging a process; today it only sends oneway calls that fail harmlessly.
|
||||
|
||||
### Measured on the Thor: a real session
|
||||
|
||||
An idle Steam session (Big Picture at the library, Decky on, 0.7.11 / main `b08d8e8e1`) holds
|
||||
**48 counted processes** in the app's cgroup, well past 32 before any game starts:
|
||||
9 bash, 6 python3, 5 dbus-daemon (with the portals and at-spi under the session bus), 4 Decky
|
||||
PluginLoader, 4 steamwebhelper, 2 Xwayland, gamescope and its reaper, PipeWire and WirePlumber,
|
||||
Steam, the clipboard bridge, and the app's own logcat, PulseAudio and audio relay.
|
||||
|
||||
Prototype of B on this branch (`runtime/GuestWorkers.kt`, `droiddeck-spawn`, `dd_spawn` in the
|
||||
session script; `DD_SPAWN_DAEMONS=0` turns it off): 24 `:gN` worker services, a spawn socket in the
|
||||
app, and the session script starting the clipboard bridge, the system bus, login1 and the session
|
||||
bus through it. Result:
|
||||
|
||||
- Each of the four runs as its own app process (`/sys/fs/cgroup/uid_<app>/pid_<worker>` with one
|
||||
process). login1's sleep handshake, NetworkManager (state 70, full connectivity) and the Steam
|
||||
library all work.
|
||||
- Counted processes: **45** instead of 48. The session bus took its 9 activated children with it, so
|
||||
they are still counted, under its worker.
|
||||
|
||||
So starting top-level daemons in workers is not enough. What is left is the processes other
|
||||
programs start. Of the 47 counted processes in that session, **40 are exec'd programs** and only 7
|
||||
are forks without an exec (the session script's `( … ) &` subshells). A handoff inside the native
|
||||
hook, at `execve()` in a forked child, could move all 40, leaving about 7 counted at idle. That needs
|
||||
the pid translation described in B (the parent keeps the forked pid; `wait4`, `kill`, `SIGCHLD` and
|
||||
`/proc/<pid>` go to the worker's process).
|
||||
|
||||
### Handoff in the native hook (prototype, on this branch)
|
||||
|
||||
`tools/nativeguest/hook/handoff.c`. At `execve()` in a forked child, a program named in
|
||||
`DD_HANDOFF` is sent to the app's spawn socket instead of exec'd: the request carries argv, the
|
||||
environment, the working directory and every inheritable fd with its number, and a worker execs
|
||||
the program with those fds in place. The child records "my pid is now worker pid P" in a memfd
|
||||
table its parent created, and exits. In the parent, `wait4`/`waitpid`/`wait`/`wait3`/`waitid` and
|
||||
`kill` treat the forked pid as P until P exits; the app writes P's exit status (from
|
||||
`ApplicationExitInfo`) into the table and sends the parent `SIGCHLD`. The child's side is
|
||||
vfork-safe (Python's subprocess execs under `vfork`). Details that mattered:
|
||||
|
||||
- **Scripts:** the list also matches the `#!` interpreter (`python3` for `droiddeck-agent`).
|
||||
- **Exec chains:** a forked child that first execs a wrapper (`env`, `taskset`, a shell script,
|
||||
Wine re-executing itself through `wine-preloader`) keeps its parent's table fd across the exec,
|
||||
so the wrapper's own exec can still be handed off.
|
||||
- **Not handed off:** Steam and the web helper's browser process (gamescope finds a window's app by
|
||||
walking its process's parents) and its utility processes (the client refuses its transport —
|
||||
"no transport is available" — from processes that are not its children). The web helper's
|
||||
renderers hand off fine.
|
||||
- One-shot programs cost a worker start (~100 ms) each, so the list names long-lived programs only
|
||||
(`xprop+-spy`: `name+prefix` matches only when an argument starts with prefix).
|
||||
|
||||
Default list: the portals, at-spi, `python3`, PipeWire, WirePlumber, Decky's PluginLoader, the log's
|
||||
`gnudd`, `xprop -spy`, the web helper's renderers, `wine`, `wine-preloader`, `wineserver`.
|
||||
|
||||
Measured on the Thor, same session and game as above:
|
||||
|
||||
| | counted children, idle | counted, Bully (Proton) running |
|
||||
|---|---|---|
|
||||
| main, no handoff | 48 | 63 |
|
||||
| handoff | **26** | **29** |
|
||||
|
||||
With the handoff on, Bully reached its menu at 30 fps, kept focus, and Steam's library, Decky, the
|
||||
portals, NetworkManager/login1 and the agent all worked.
|
||||
|
||||
Then Android's own limit was switched back on (`settings_enable_monitor_phantom_procs=true`,
|
||||
default limit 32) with the game running, and a scan was forced every 20 s for 3 minutes
|
||||
(`dumpsys meminfo` refreshes the CPU stats the scan runs on; process starts and activity changes do
|
||||
too, irregularly):
|
||||
|
||||
| | Android listed | killed | session |
|
||||
|---|---|---|---|
|
||||
| no handoff (`DD_SPAWN_DAEMONS=0`, same build) | 63 | **33**, oldest first: the session's bash, Python daemons, D-Bus, Xwayland, Steam, PipeWire, gamescope's reaper | FAILED |
|
||||
| handoff | 27–29 (device-wide) | **0** in 9 scans | game running throughout |
|
||||
|
||||
### Taken further: the session itself in workers
|
||||
|
||||
A second round moved most of what was still counted:
|
||||
|
||||
- **The app's own processes:** `HostProcess.startUncounted` runs a host command in a worker with the
|
||||
same contract as `HostProcess.start` (output lines, exit code, working directory). The session
|
||||
root, the app log's logcat, PulseAudio and the DirectAudio relay use it. A worker cannot `chdir`
|
||||
before its exec, so Android's `sh` does it from an environment of its own and exports the
|
||||
program's (`env -i` cannot be used: the APK's library path contains `==`).
|
||||
- **PulseAudio** closes every inherited fd at start, the worker's binder fd included, and Android
|
||||
then killed the worker as dead (the SIGKILL came from system_server's `ActivityManager` thread,
|
||||
seen with the `signal_generate` ftrace event, which shell can enable on the Thor). The daemon
|
||||
spares the fd named in `PULSE_PASSED_FD`; the worker replaces `@DDH_WORKER_BINDER_FD@` in a
|
||||
program's arguments and environment with its `/dev/binder` fd number, so PulseAudio is given it.
|
||||
Started as a normal child the token reads as fd 0, which the daemon ignores.
|
||||
- **The script's long-lived subshells:** `dd_job FUNCTION` runs a function in a new `bash` that first
|
||||
loads the shell's variables, functions and options from a state file, so it is an exec'd program
|
||||
the hook can hand off (`bash+dd-job`). `$!`, `kill` and `wait` keep working. The zRAM scanner,
|
||||
the property watcher, Decky's supervisor and the request/timer loop use it.
|
||||
- **The log pipeline** is `droiddeck-log-writer`, a script of its own instead of a `{ gnudd; cat; }`
|
||||
subshell.
|
||||
- **gamescope, its reaper and the inner `droiddeck-session steam`** are handed off. Steam, its web
|
||||
helper's browser process and its utility processes still are not (see above).
|
||||
|
||||
Things this needed, found the hard way:
|
||||
|
||||
- **The binder fd is the worker's life.** It sits above every fd number the program gets; programs
|
||||
that close all inherited fds (gamescope) are kept from closing it (the hook's kept fds, also
|
||||
against `CLOSE_RANGE_CLOEXEC`); children never send it along with a handoff; and the hook closes
|
||||
copies in every other process (`DDH_WORKER_PID`), so a worker's exit is seen when its program
|
||||
exits. A worker that lost its binder fd was killed by Android within milliseconds.
|
||||
- **A session of its own (`setsid`) for every worker.** All app processes are in zygote's process
|
||||
group, so a program signalling its group reached the app itself (the hook also refuses
|
||||
`kill(0)`/`kill(-pgid)` into zygote's group, and `kill(-1)`). `reap_orphans` in the session
|
||||
script stands down when its parent is zygote.
|
||||
- **Nested handoffs** (a program in a worker handing off its own child): inherited `DDH_*`
|
||||
variables are dropped from each request.
|
||||
- **Requests carry up to 240 fds,** in chunks of 60 (`LocalSocket` reads at most 64 per read), after
|
||||
the request itself; the spawn server catches everything per connection (an uncaught exception there
|
||||
took the whole app down once).
|
||||
- **The table is made at a process's first fork,** not only when `DD_SPAWN` is in its environment at
|
||||
start: a shell that exports it has no sign of it in its own environment.
|
||||
- **Exit status:** the program's hook records it with `on_exit` or in `_exit()` into the parent's
|
||||
table; the app's `ApplicationExitInfo` is only the fallback (signals). A program inherits its
|
||||
forked parent's ignored signals, open-files limit and umask (`DDH_SIGIGN`, `DDH_NOFILE`,
|
||||
`DDH_UMASK`).
|
||||
|
||||
Measured on the Thor, Bully under Proton, Android's limit on (default 32), a scan forced every 20 s:
|
||||
|
||||
| | counted, idle | counted, in game | killed in 3 min |
|
||||
|---|---|---|---|
|
||||
| main (no handoff) | 48 | 63 | 33, session failed |
|
||||
| first round | 26 | 29 | 0 |
|
||||
| second round | 9 | 14 | 0 |
|
||||
| **third round** | **7–9** | **12** | **0** in 2 min, game kept focus |
|
||||
|
||||
Still counted at idle: `run_gamescope`'s subshell, Steam, its web helper's browser and
|
||||
two or three utility processes, the session bus's activation babysitter and Decky's
|
||||
multiprocessing child (forks without an exec). In game, also Steam's launch chain (`sh`,
|
||||
`pw-audio-namespace`, `reaper`) and the `wineserver` daemon (a fork of its first process, which
|
||||
lingers in its worker; see below).
|
||||
|
||||
### Third round
|
||||
|
||||
- **PulseAudio in a worker** (above).
|
||||
- **`posix_spawn()`:** Python 3.13+ (`subprocess`, even with `close_fds`) and GLib's `g_spawn` start
|
||||
programs with `posix_spawn()`, whose child makes the exec system call itself, past the hook. A
|
||||
listed program is now spawned with `fork()` and the hook's `execve()`; the hook replays glibc's
|
||||
file actions and attributes in the child, and a close-on-exec pipe returns an exec error as
|
||||
`posix_spawn()`'s result. Proton's Wine and at-spi's bus came out of the count this way.
|
||||
- **The table fd survives a child that closes every inherited fd** (Python's `subprocess` before
|
||||
exec): it sits at fd 800 or above and is one of the hook's kept fds. Reopening it from
|
||||
`/proc/<owner>/fd` does not work on Android (EACCES). A nonce in the table's header tells it from
|
||||
a file a program put at that number (inode numbers are rewritten by the hardlink emulation).
|
||||
- **The exit status comes from the program itself.** The worker first runs a `bash` that `cd`s and
|
||||
execs the program; that `bash` closed the `DDH_TABLE` fd as someone else's table, so the
|
||||
program after it could never report, and statuses came from `ApplicationExitInfo`, late or
|
||||
unknown. The `DDH_TABLE` fd is now kept through that exec, and `_exit()` reports as `exit()` does.
|
||||
- **Daemons:** Android kills every process in a worker's cgroup when the worker's own process ends
|
||||
(`libprocessgroup: Successfully killed process cgroup`). `wineserver` forks the server and leaves
|
||||
with `_exit(0)`, so the server died with it and Wine stopped with "the wine server failed to run".
|
||||
A handed-off program's process now reports its status and then stays, with no fds but the
|
||||
binder's and all signals blocked, until no other process is left in its cgroup (found through
|
||||
`/proc/<pid>/cgroup`, as `cgroup.procs` is not readable). It does so only when it is
|
||||
single-threaded at exit, and never for the processes the app starts itself (the session root),
|
||||
whose exit the app waits for.
|
||||
- **`reap_orphans`** in the session script killed every process whose parent was zygote (all the
|
||||
app's workers, the session root among them) when the inner `droiddeck-session` ended in a
|
||||
worker: the guest cannot see zygote in `/proc`. It now stands down when `DDH_WORKER_PID` is
|
||||
its own pid.
|
||||
- **`DD_HANDOFF_DEBUG=/path`** appends the hook's trace to a file. On stderr it broke Steam's
|
||||
login, and the trace from a game's processes went to a pipe nobody read.
|
||||
- **Finding the sender of a SIGKILL:** shell can enable the `signal/signal_generate` ftrace event
|
||||
on the Thor (`/sys/kernel/tracing`), which names the sending thread; Perfetto recorded nothing
|
||||
there.
|
||||
- **Ending a game from Steam** (`SteamClient.Apps.TerminateApp`, the overlay's Exit game) left Wine
|
||||
running since the first round: Steam sends SIGINT to the launch's `reaper` and its parent, and the
|
||||
reaper ends what is under it, which handed-off programs are not. Each handed-off program now
|
||||
lists itself as `P<pid>` with the process that forked its child and, for when that process is
|
||||
gone (Wine starts a process through a fork that exits at once), the worker's program it descended
|
||||
from. A signal to `reaper SteamLaunch` from a hooked process also goes, as SIGTERM for SIGINT
|
||||
(Wine takes SIGINT for a console's Ctrl+C), to the groups of every listed program under that
|
||||
reaper, all found before any is signalled.
|
||||
- **Process groups:** a handed-off program runs in a session of its own, outside the group its
|
||||
forked parent's child was in. It lists itself as `GROUP.PID.START` for that group (`DDH_PGID`,
|
||||
also for the processes it forks), and the hook's `kill(-GROUP)`, `kill(0)` and `killpg()` also
|
||||
signal the groups those programs lead.
|
||||
- **Tried and dropped:** handing off Steam's launch chain (`sh`, `steam-launch-wrapper`, `reaper`):
|
||||
the client tracks the process it forked, which then exits at once, and called the game closed.
|
||||
Showing a handed-off program's forking process as its parent in `/proc/<pid>/stat`, `status` and
|
||||
`getppid()` left Steam's UI at "Loading library data": the client checks the parents of the
|
||||
processes on its IPC connections with `lsof -F R`. And `posix_spawn()` emulation must make only
|
||||
system calls in its child (no hook wrapper takes a lock there): one Steam fork hung on a lock
|
||||
another thread held.
|
||||
|
||||
Quitting the game (also from Steam), stopping the session (no worker is left) and starting
|
||||
again all work. Started from the front end with the limit on, Setup shows "Child-process limit
|
||||
handled by DroidDeck" and Steam starts.
|
||||
|
||||
### Cost
|
||||
|
||||
Measured on the Thor, Bully under Proton, the handoff on (`childProcessHandoff`) against off, two
|
||||
sessions each:
|
||||
|
||||
| | off | on, first | on, now |
|
||||
|---|---|---|---|
|
||||
| one program started, `fork`+`exec` of `/usr/bin/true` | 37–39 ms | 197 ms | 80 ms |
|
||||
| `start steam` to READY | 14.0–14.2 s | 20.0–20.2 s | 18.2–18.5 s |
|
||||
| `launch` to the game's focus | 10.1 s | 14.7–14.8 s | 11.6–11.7 s |
|
||||
| in game: frames, CPU of the app's uid, `system_server` | 29.9 fps, 1.02–1.05 s/s, 21 ms/s | 29.8 fps, 1.11 s/s, 21–27 ms/s | 29.8–29.9 fps, 1.10–1.11 s/s, 22 ms/s |
|
||||
| memory of the app's processes (RSS) | 3.57–3.62 GB | 3.42–3.50 GB | 3.49–3.66 GB |
|
||||
|
||||
Running costs nothing measurable; starting things does. A handed-off program costs a worker: a
|
||||
zygote fork, its runtime (40–50 ms of CPU) and the bind, and the worker waited 100 ms before its
|
||||
exec so as not to cut off its reply. Now the app closes a pipe once it has the reply and the worker
|
||||
execs then, and two workers are kept bound ahead of need while a session runs (12 MB of PSS each);
|
||||
four did no better. Starting a session takes about 10 more CPU-seconds (51 s against 41 s for the
|
||||
app's uid), and the last 4 s come from the session script's own steps running beside the
|
||||
handed-off daemons. With only the hook's handoffs off (`DD_SPAWN_DAEMONS=0`), READY came at
|
||||
14.1 s: the app's own workers (the session root, PulseAudio, logcat) cost nothing there.
|
||||
|
||||
**In the app:** `PhantomProcessStatus.UNCOUNTED` is reported when the limit is on but the session
|
||||
runs in workers (`GuestWorkers.enabled`: the native userland, Android 11+, and the
|
||||
`childProcessHandoff` session preference, on by default). It does not block Steam. Turning the
|
||||
preference off (`droiddeckctl prefs set session childProcessHandoff false --type bool`, with
|
||||
Setup > Developer > Debugging tools on; see `docs/agent-control.md`) brings back
|
||||
the old behavior and the old requirement.
|
||||
|
||||
### C. Plan
|
||||
|
||||
1. ~~Verify both gaps on the Thor~~ done; still to do on a stock Android 14+ phone (enforcing
|
||||
SELinux, unlike the Thor) and on a Mali device.
|
||||
2. ~~B for the processes DroidDeck and the session script start themselves~~ done.
|
||||
3. ~~B inside the hook, with pid translation~~ done.
|
||||
4. ~~The session root, its jobs, the log pipeline, the gamescope chain~~ done: 9 idle, 14 in game.
|
||||
Third round (PulseAudio, `posix_spawn`, daemons): 7–9 idle, 12 in game.
|
||||
5. ~~Setup no longer requires the developer option while the session runs in workers~~ done.
|
||||
6. Open:
|
||||
- ~~PulseAudio in a worker~~ done;
|
||||
- ~~`posix_spawn()` and daemons in workers~~ done;
|
||||
- `/proc/<pid>/stat` showing the virtual parent, so that Steam and its web helper can be handed
|
||||
off too;
|
||||
- pre-started workers, so that a handoff costs no zygote fork (about 100 ms now);
|
||||
- more games (Wine-heavy launchers, anti-cheat), the desktop mode and proot sessions (which keep
|
||||
the old behavior);
|
||||
- a settings switch for `childProcessHandoff`.
|
||||
7. A (the isolated tier) only if B stops working on a future Android; it needs a file and socket
|
||||
broker and keeps the GPU outside.
|
||||
|
||||
## Robustness
|
||||
|
||||
- Gap 1's path mismatch is a bug that could be fixed; the app-zygote skip is deliberate. Use app
|
||||
zygote isolated services so either one is enough.
|
||||
- Gap 2 depends on AMS not probing liveness. A future check (a ping, or watching a pidfd for the
|
||||
binder) would end it; the session would then fall back to counted processes, which is today's
|
||||
behavior.
|
||||
- OEM ROMs with their own process managers (MIUI/HyperOS, ColorOS) are outside this.
|
||||
|
||||
## phantomlab
|
||||
|
||||
`tools/phantomlab` is a standalone test app (package `com.droiddeck.phantomlab`, no Gradle). It
|
||||
forks sleepers from the main process, a plain isolated service, an app-zygote isolated service and
|
||||
eight `:wN` workers, execs in place, and probes what a process may do.
|
||||
|
||||
The limit of 4 below is device-wide: a trim while it is set can kill other apps' child processes,
|
||||
which restoring the setting does not bring back. Use a test device or an emulator with nothing else
|
||||
running, and note the current values first, to put them back afterwards:
|
||||
|
||||
```
|
||||
adb shell settings get global settings_enable_monitor_phantom_procs
|
||||
adb shell device_config get activity_manager max_phantom_processes
|
||||
adb shell device_config get_sync_disabled_for_tests
|
||||
```
|
||||
|
||||
Android 12 and some Android 13 builds have no `get_sync_disabled_for_tests`; there `adb shell
|
||||
device_config is_sync_disabled_for_tests` answers only true or false, so it cannot tell `persistent`
|
||||
from `until_reboot`. Note `none` when it says false. When it says true, sync is already off: skip
|
||||
the `set_sync_disabled_for_tests persistent` step below, which keeps whichever mode it was, and
|
||||
leave the mode alone when you restore the rest.
|
||||
|
||||
```
|
||||
tools/phantomlab/build.sh # build/phantomlab.apk, debug-signed
|
||||
adb install -r tools/phantomlab/build/phantomlab.apk
|
||||
adb shell device_config set_sync_disabled_for_tests persistent
|
||||
adb shell device_config put activity_manager max_phantom_processes 4
|
||||
adb shell settings put global settings_enable_monitor_phantom_procs true
|
||||
adb shell am start -n com.droiddeck.phantomlab/.Main --es cmd spawn --es target iso:a --ei n 40
|
||||
adb shell "am start -n com.droiddeck.phantomlab/.Main --es cmd exec --es target w0 --ei keep 1 --es argv '/system/bin/sleep|100000'"
|
||||
adb shell am start -n com.droiddeck.phantomlab/.Main --es cmd probe --es target iso:a --es what self,memfd_exec,exec,fds,escape,libexec --es fds tcp,udp,unix,file:probe.txt
|
||||
adb logcat -s PLAB ActivityManager | grep -i 'PLAB\|Trimming'
|
||||
```
|
||||
|
||||
Targets: `main`, `proc` (`:proc`), `isoplain`, `iso:<name>` (one app-zygote instance per name),
|
||||
`w0`…`w7`. Android scans only on CPU-stat refreshes, so switch apps a few times (5 s apart) before
|
||||
reading the phantom list. Restore the noted values afterwards: `adb shell device_config put
|
||||
activity_manager max_phantom_processes <value>` (or `adb shell device_config delete activity_manager
|
||||
max_phantom_processes` if it was null), `adb shell device_config set_sync_disabled_for_tests <mode>`
|
||||
and `adb shell settings put global settings_enable_monitor_phantom_procs <value>`, and end the lab's
|
||||
sleepers with `adb shell am force-stop com.droiddeck.phantomlab`.
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/bin/bash
|
||||
# Appends stdin to a session log up to a byte cap, then reads and drops the rest, so that the session
|
||||
# writing into it never gets SIGPIPE. A program of its own, rather than a subshell of the session, so
|
||||
# that the native hook can start it outside the app's counted child processes.
|
||||
# usage: droiddeck-log-writer FILE CAP_BYTES
|
||||
dd=$(command -v gnudd || echo dd)
|
||||
"$dd" of="$1" oflag=append conv=notrunc iflag=count_bytes count="$2" bs=65536 status=none
|
||||
exec cat >/dev/null
|
||||
@@ -14,6 +14,59 @@ export HOME=${HOME:-/root}
|
||||
mode=${1:-desktop}
|
||||
shift || true
|
||||
step() { echo "== STEP $(date -u +%H:%M:%S.%3N) $*"; }
|
||||
# Starts a long-lived program in its own Android process, which Android does not count against
|
||||
# the session's child processes (docs/phantom-processes.md); a normal background job otherwise.
|
||||
# Its pid is in $dd_spawned either way, and the ones not started as jobs in $dd_daemons, which
|
||||
# the session stops as it ends.
|
||||
dd_daemons=
|
||||
dd_spawn() {
|
||||
dd_spawned=
|
||||
if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ] && [ -x /usr/local/bin/droiddeck-spawn ]; then
|
||||
local f=${XDG_RUNTIME_DIR:-/tmp}/.dd-spawn.$$ rc=0
|
||||
/usr/local/bin/droiddeck-spawn --pid-file "$f" -- "$@" || rc=$?
|
||||
dd_spawned=$(cat "$f" 2>/dev/null)
|
||||
rm -f "$f"
|
||||
if [ "$rc" = 0 ] && [ -n "$dd_spawned" ]; then
|
||||
dd_daemons="$dd_daemons $dd_spawned"
|
||||
return 0
|
||||
fi
|
||||
# started, but its pid is unknown: not a second time
|
||||
[ "$rc" = 3 ] && { dd_spawned=; return 0; }
|
||||
fi
|
||||
"$@" &
|
||||
dd_spawned=$!
|
||||
}
|
||||
dd_stop_daemons() {
|
||||
[ -n "$dd_daemons" ] && kill $dd_daemons 2>/dev/null
|
||||
dd_daemons=
|
||||
}
|
||||
dd_session_pid=$$
|
||||
# Runs function $1 (with its arguments) in the background in a new bash that first loads this shell's
|
||||
# variables, functions and options: a background subshell, but an exec'd program, which the native
|
||||
# hook can hand to its own process (DD_HANDOFF "bash+dd-job"). $! is its pid, as for ( ... ) &.
|
||||
dd_job() {
|
||||
local state
|
||||
if [ -n "${DD_HANDOFF:-}" ] && state=$(mktemp "${XDG_RUNTIME_DIR:-/tmp}/.dd-job.XXXXXX" 2>/dev/null); then
|
||||
{
|
||||
declare -p | grep -Ev '^declare -[a-zA-Z]*r|^declare -[-a-zA-Z]* (BASH[A-Z_]*|FUNCNAME|GROUPS|DIRSTACK|PIPESTATUS|COPROC|LINENO|_)='
|
||||
declare -f
|
||||
shopt -p
|
||||
set +o
|
||||
} > "$state" 2>/dev/null
|
||||
/bin/bash -c 'source "$1" 2>/dev/null; rm -f "$1"; shift; "$@"' dd-job "$state" "$@" &
|
||||
else
|
||||
"$@" &
|
||||
fi
|
||||
}
|
||||
# Long-lived programs the session's guests start run in their own processes too
|
||||
# (tools/nativeguest/hook/handoff.c). Not Steam, its web helper's browser process (gamescope finds a
|
||||
# window's app by walking its process's parents) or its utility processes (the client only accepts
|
||||
# its transport from its own children).
|
||||
if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ]; then
|
||||
export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver}
|
||||
else
|
||||
unset DD_HANDOFF
|
||||
fi
|
||||
steam_setup_failed() {
|
||||
echo "== steam: the Steam client could not be set up (status $1)"
|
||||
[ -z "${DD_STEAM_EXIT_FILE:-}" ] || printf '%s\n' "$1" > "$DD_STEAM_EXIT_FILE"
|
||||
@@ -24,8 +77,12 @@ if [ -n "${DD_LOG:-}" ] && [ -z "${DD_INSIDE:-}" ]; then
|
||||
if [ "$(stat -c %s "$DD_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then
|
||||
mv -f "$DD_LOG" "$DD_LOG.1"
|
||||
fi
|
||||
dd=$(command -v gnudd || echo dd)
|
||||
exec > >({ "$dd" of="$DD_LOG" oflag=append conv=notrunc iflag=count_bytes count="${DD_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
|
||||
if [ -x /usr/local/bin/droiddeck-log-writer ]; then
|
||||
exec > >(exec /usr/local/bin/droiddeck-log-writer "$DD_LOG" "${DD_LOG_CAP:-268435456}") 2>&1
|
||||
else
|
||||
dd=$(command -v gnudd || echo dd)
|
||||
exec > >({ "$dd" of="$DD_LOG" oflag=append conv=notrunc iflag=count_bytes count="${DD_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
|
||||
fi
|
||||
echo "== droiddeck-session $(date) mode=$mode $*"
|
||||
echo "== uid=$(id -u) size=${DD_WIDTH:-?}x${DD_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}"
|
||||
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
|
||||
@@ -610,6 +667,11 @@ dd_stretch_game_screen() {
|
||||
export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11
|
||||
reap_orphans() {
|
||||
local round p stat pid left
|
||||
# Started by the app as an Android process of its own: its parent is zygote, whose other
|
||||
# children are the app's processes. The guest may not see zygote in /proc; a worker's own
|
||||
# program has DDH_WORKER_PID.
|
||||
[ "${DDH_WORKER_PID:-}" = "$$" ] && return 0
|
||||
case "$(tr -d '\0' < "/proc/$PPID/cmdline" 2>/dev/null)" in ''|zygote*) return 0 ;; esac
|
||||
for round in 1 2 3 4 5; do
|
||||
left=
|
||||
for p in /proc/[0-9]*; do
|
||||
@@ -628,7 +690,7 @@ reap_orphans() {
|
||||
}
|
||||
|
||||
if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -x /usr/local/bin/droiddeck-clipboard ]; then
|
||||
/usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" &
|
||||
dd_spawn /usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD"
|
||||
fi
|
||||
|
||||
[ "${DD_DESKTOP:-}" = 1 ] || start_agent
|
||||
@@ -771,7 +833,7 @@ case $mode in
|
||||
fi
|
||||
if [ "${DD_ZRAM:-0}" = 1 ]; then
|
||||
step "zRAM compression: on"
|
||||
(
|
||||
_dd_job_zram() {
|
||||
dd_zram_scan() {
|
||||
_dd_game=0 _dd_pids=() _dd_others=() _dd_apps=
|
||||
local _d _c _args _name _a _id _fex _lower _bnet=() _bnet_game=0
|
||||
@@ -1116,7 +1178,7 @@ case $mode in
|
||||
_dd_sample_at= _dd_freed=0 _dd_client_out=0 _dd_note_client=0 _dd_note_session=0
|
||||
_dd_trim_at=-30 _dd_back_at=-30 _dd_forced_at=-10 _dd_full_at=-60 _dd_noted_at=-5
|
||||
_dd_rest=0 _dd_rest_until=0 _dd_rest_available=0
|
||||
while kill -0 $$ 2>/dev/null; do
|
||||
while kill -0 "$dd_session_pid" 2>/dev/null; do
|
||||
dd_memory_tick
|
||||
if [ "$_dd_available" -ge 0 ] &&
|
||||
{ [ "$_dd_available" -lt $((_dd_mem_total * 2 / 5)) ] || [ "$_dd_rate" -ge $((16 * 1024)) ]; }; then
|
||||
@@ -1125,7 +1187,8 @@ case $mode in
|
||||
nap 5
|
||||
fi
|
||||
done
|
||||
) &
|
||||
}
|
||||
dd_job _dd_job_zram
|
||||
fi
|
||||
if [ "${DD_LAUNCHER_CORES:-1}" != 0 ] && [ -n "${DD_LAUNCH_DIR:-}" ] && [ -z "${DD_DESKTOP:-}" ] \
|
||||
&& [ "${DD_STEAM_UI:-}" != desktop ] && [ -x /usr/local/bin/droiddeck-launcher-cores ]; then
|
||||
@@ -1217,7 +1280,7 @@ case $mode in
|
||||
) &
|
||||
fi
|
||||
fi
|
||||
[ -z "${DD_DESKTOP:-}" ] && (
|
||||
_dd_job_properties() {
|
||||
stretch=0 restore=0
|
||||
[ "${DD_STRETCHED:-0}" = 1 ] && stretch=1
|
||||
[ "${DD_RESTORE_ON_RESUME:-1}" = 1 ] && restore=1
|
||||
@@ -1296,8 +1359,9 @@ case $mode in
|
||||
&& echo "== stretch 16:9 to panel: the client sized the game screen to the output ($DD_STRETCH_OUTPUT), set to $DD_STRETCH_GAME"
|
||||
;;
|
||||
esac
|
||||
done < <(xprop -spy -root "${atoms[@]}" 2>/dev/null)
|
||||
) &
|
||||
done < <(exec xprop -spy -root "${atoms[@]}" 2>/dev/null)
|
||||
}
|
||||
[ -n "${DD_DESKTOP:-}" ] || dd_job _dd_job_properties
|
||||
steam_hold_launch() {
|
||||
local game=$1 shortcut= waited=0 status=0
|
||||
_dd_focused() { xprop -root GAMESCOPE_FOCUSED_APP 2>/dev/null | sed -n 's/.*= *//p'; }
|
||||
@@ -1384,8 +1448,8 @@ case $mode in
|
||||
fi
|
||||
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then
|
||||
write_system_bus_config
|
||||
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
|
||||
system_bus=$!
|
||||
dd_spawn dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile
|
||||
system_bus=$dd_spawned
|
||||
for _ in $(seq 1 50); do
|
||||
[ -S /run/dbus/system_bus_socket ] && break
|
||||
sleep 0.1
|
||||
@@ -1393,8 +1457,8 @@ case $mode in
|
||||
if [ -S /run/dbus/system_bus_socket ]; then
|
||||
echo "== network: system bus up, NetworkManager stand-in running"
|
||||
rm -f "$DD_LAUNCH_DIR/steam-sleep-ready"
|
||||
droiddeck-login1 --with-netmanager &
|
||||
login_manager=$!
|
||||
dd_spawn droiddeck-login1 --with-netmanager
|
||||
login_manager=$dd_spawned
|
||||
for ((_i = 0; _i < 50; _i++)); do
|
||||
[ -f "$DD_LAUNCH_DIR/steam-sleep-ready" ] && break
|
||||
kill -0 "$login_manager" 2>/dev/null || break
|
||||
@@ -1418,7 +1482,7 @@ case $mode in
|
||||
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then
|
||||
_dd_bus=${XDG_RUNTIME_DIR:-/run/droiddeck}/bus
|
||||
rm -f "$_dd_bus"
|
||||
dbus-daemon --session --address="unix:path=$_dd_bus" --nofork --nopidfile &
|
||||
dd_spawn dbus-daemon --session --address="unix:path=$_dd_bus" --nofork --nopidfile
|
||||
for _ in $(seq 1 50); do
|
||||
[ -S "$_dd_bus" ] && break
|
||||
nap 0.1
|
||||
@@ -1456,7 +1520,7 @@ case $mode in
|
||||
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ -x "$decky_loader" ]; then
|
||||
decky_arch=$(cat "$HOME/homebrew/services/.droiddeck-decky-arch" 2>/dev/null || echo unknown)
|
||||
if [ "$decky_arch" = arm64 ] || { [ "$decky_arch" = x86_64 ] && /usr/local/bin/droiddeck-fex prepare >/dev/null; }; then
|
||||
(
|
||||
_dd_job_decky() {
|
||||
decky_child=
|
||||
decky_stop() { [ -z "$decky_child" ] || kill "$decky_child" 2>/dev/null; [ -z "$decky_child" ] || wait "$decky_child" 2>/dev/null; exit 0; }
|
||||
trap decky_stop TERM INT HUP
|
||||
@@ -1480,7 +1544,8 @@ case $mode in
|
||||
echo "== Decky: loader exited with status $decky_status; restart $((decky_exits + 1))/5 in ${decky_delay}s"
|
||||
sleep "$decky_delay"
|
||||
done
|
||||
) &
|
||||
}
|
||||
dd_job _dd_job_decky
|
||||
decky_supervisor=$!
|
||||
echo "== Decky: session supervisor started ($decky_arch)"
|
||||
else
|
||||
@@ -1681,7 +1746,7 @@ case $mode in
|
||||
rm -f "$DD_LAUNCH_DIR/steam-stop" "$DD_LAUNCH_DIR/steam-game" "$DD_LAUNCH_DIR/steam-game.tmp"
|
||||
requests=1
|
||||
fi
|
||||
(
|
||||
_dd_job_requests() {
|
||||
tick=0
|
||||
beat=0
|
||||
library_job=
|
||||
@@ -1859,7 +1924,8 @@ case $mode in
|
||||
fi
|
||||
fi
|
||||
done
|
||||
) &
|
||||
}
|
||||
dd_job _dd_job_requests
|
||||
stop_watcher=$!
|
||||
if [ "${DD_VENUS:-0}" = 1 ] && [ -x /usr/local/bin/droiddeck-glprobe ] && [ "${GALLIUM_DRIVER:-}" = zink ]; then
|
||||
LIBGL_DEBUG=verbose MESA_LOG_LEVEL=debug timeout 20 /usr/local/bin/droiddeck-glprobe 2>&1 | grep -v drirc | head -60 | sed 's/^/== glprobe: /'
|
||||
@@ -2013,6 +2079,7 @@ case $mode in
|
||||
wait "$decky_supervisor" 2>/dev/null || true
|
||||
echo "== Decky: session supervisor stopped"
|
||||
fi
|
||||
dd_stop_daemons
|
||||
_dd_jobs=$(jobs -p)
|
||||
[ -n "$_dd_jobs" ] && kill $_dd_jobs 2>/dev/null
|
||||
echo "== steam: the client on the desktop has exited"
|
||||
@@ -2022,6 +2089,7 @@ case $mode in
|
||||
wait "$decky_supervisor" 2>/dev/null || true
|
||||
echo "== Decky: session supervisor stopped"
|
||||
fi
|
||||
dd_stop_daemons
|
||||
_dd_jobs=$(jobs -p)
|
||||
[ -n "$_dd_jobs" ] && kill $_dd_jobs 2>/dev/null
|
||||
reap_orphans
|
||||
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Starts a program as the main process of its own Android process, outside the session's cgroup.
|
||||
|
||||
usage: droiddeck-spawn [--wait] [--pid-file FILE] [--] PROGRAM [ARGS...]
|
||||
|
||||
Android counts the session's processes against its child-process limit; a program started this
|
||||
way is not counted (its own children are). It gets this process's environment, working directory
|
||||
and stdin/stdout/stderr, and is not a child of the caller: the pid printed on stdout (or written to
|
||||
FILE) is the one to signal. Without --wait this returns once the program has started; with --wait
|
||||
it waits for it and exits with its status. Where the app offers no spawner, the program is started as a normal child.
|
||||
"""
|
||||
import array
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
|
||||
|
||||
# Exit status when the program started but its pid could not be reported: the caller must not
|
||||
# start it again.
|
||||
STARTED_UNREPORTED = 3
|
||||
|
||||
|
||||
def report(pid, pid_file):
|
||||
try:
|
||||
if pid_file:
|
||||
with open(pid_file, "w") as f:
|
||||
f.write("%s\n" % pid)
|
||||
else:
|
||||
print(pid, flush=True)
|
||||
return True
|
||||
except OSError as e:
|
||||
print("droiddeck-spawn: started pid %s but could not report it: %s" % (pid, e), file=sys.stderr)
|
||||
return False
|
||||
|
||||
|
||||
def fallback(argv, wait, pid_file):
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
try:
|
||||
os.execvp(argv[0], argv)
|
||||
except OSError as e:
|
||||
print("droiddeck-spawn: %s: %s" % (argv[0], e.strerror), file=sys.stderr)
|
||||
os._exit(127)
|
||||
reported = report(pid, pid_file)
|
||||
if wait:
|
||||
return os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1])
|
||||
return 0 if reported else STARTED_UNREPORTED
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
wait = False
|
||||
pid_file = None
|
||||
while args and args[0].startswith("--"):
|
||||
flag = args.pop(0)
|
||||
if flag == "--":
|
||||
break
|
||||
if flag == "--wait":
|
||||
wait = True
|
||||
elif flag == "--pid-file" and args:
|
||||
pid_file = args.pop(0)
|
||||
else:
|
||||
print(__doc__.strip(), file=sys.stderr)
|
||||
return 2
|
||||
if not args:
|
||||
print(__doc__.strip(), file=sys.stderr)
|
||||
return 2
|
||||
name = os.environ.get("DD_SPAWN")
|
||||
if not name:
|
||||
return fallback(args, wait, pid_file)
|
||||
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
try:
|
||||
s.connect("\0" + name)
|
||||
except OSError:
|
||||
return fallback(args, wait, pid_file)
|
||||
payload = json.dumps({"argv": args, "env": dict(os.environ), "cwd": os.getcwd(), "wait": wait}).encode()
|
||||
s.sendmsg([struct.pack(">I", len(payload)), payload],
|
||||
[(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", [0, 1, 2]))])
|
||||
reply = s.makefile("r")
|
||||
first = reply.readline().split()
|
||||
if len(first) != 2 or first[0] != "pid":
|
||||
print("droiddeck-spawn: %s; starting %s as a child" % (" ".join(first[1:]) or "no answer", args[0]),
|
||||
file=sys.stderr)
|
||||
return fallback(args, wait, pid_file)
|
||||
reported = report(first[1], pid_file)
|
||||
if not wait:
|
||||
return 0 if reported else STARTED_UNREPORTED
|
||||
done = reply.readline().split()
|
||||
status = int(done[1]) if len(done) == 2 and done[0] == "exit" else 1
|
||||
return status if 0 <= status < 256 else 128 + (status & 0x7f)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -82,6 +82,7 @@
|
||||
#include "hook/exec_probe.c"
|
||||
#include "hook/static_programs.c"
|
||||
#include "hook/go_programs.c"
|
||||
#include "hook/handoff.c"
|
||||
#include "hook/exec.c"
|
||||
#include "hook/net.c"
|
||||
#include "hook/sockets.c"
|
||||
|
||||
@@ -374,6 +374,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
}
|
||||
if (depth == 0 && !in_exec_rehearsal()) ddh_try(filename, argv, envp);
|
||||
|
||||
// Scripts get the path exactly as the caller wrote it ("./x.sh" stays "./x.sh" in $0),
|
||||
// like the kernel would pass it; routing below uses the absolute form.
|
||||
@@ -659,7 +660,9 @@ pid_t fork(void) {
|
||||
int n = __atomic_add_fetch(&forks, 1, __ATOMIC_RELAXED);
|
||||
if (n == 1 || n >= DDNATV_FORKS_BEFORE_REHEARSAL) prepare_exec_in_parent(n >= DDNATV_FORKS_BEFORE_REHEARSAL ? 2 : 1);
|
||||
}
|
||||
ddh_prepare();
|
||||
pid_t pid = orig_fork();
|
||||
if (pid == 0) ddh_drop_worker_binder();
|
||||
// A child forked from a signal handler that interrupted a rehearsal is not rehearsing: its
|
||||
// execve() is a real one (only read in the usual case, so no page is copied for it)
|
||||
if (pid == 0 && __atomic_load_n(&g_exec_rehearsal, __ATOMIC_RELAXED)) __atomic_store_n(&g_exec_rehearsal, 0, __ATOMIC_RELAXED);
|
||||
@@ -1065,6 +1068,176 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path,
|
||||
|
||||
static int apply_closefrom(posix_spawn_file_actions_t *actions);
|
||||
|
||||
// glibc's file actions (posix/spawn_int.h, unchanged since 2.35)
|
||||
struct ddh_spawn_action {
|
||||
enum { DDH_DO_CLOSE, DDH_DO_DUP2, DDH_DO_OPEN, DDH_DO_CHDIR, DDH_DO_FCHDIR, DDH_DO_CLOSEFROM, DDH_DO_TCSETPGRP } tag;
|
||||
union {
|
||||
struct { int fd; } close_action;
|
||||
struct { int fd; int newfd; } dup2_action;
|
||||
struct { int fd; char *path; int oflag; mode_t mode; } open_action;
|
||||
struct { char *path; } chdir_action;
|
||||
struct { int fd; } fchdir_action;
|
||||
struct { int from; } closefrom_action;
|
||||
struct { int fd; } setpgrp_action;
|
||||
} action;
|
||||
};
|
||||
|
||||
#ifndef POSIX_SPAWN_SETSID
|
||||
#define POSIX_SPAWN_SETSID 0x80
|
||||
#endif
|
||||
|
||||
static int ddh_spawn_errno(long ret) {
|
||||
return ret < 0 ? errno : 0;
|
||||
}
|
||||
|
||||
static int ddh_spawn_close_part(unsigned int first, unsigned int last, void *unused) {
|
||||
(void)unused;
|
||||
return (int)call_orig_syscall(SYS_close_range, first, last, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
// What glibc's spawn child does before its exec (posix/spawni.c), as an errno. Its fd and
|
||||
// directory work is done with system calls, not the hook's wrappers: those take locks that another
|
||||
// thread of the parent may have held at fork() (Steam has many threads).
|
||||
static int ddh_spawn_child_setup(const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr) {
|
||||
short flags = 0;
|
||||
if (attr) posix_spawnattr_getflags(attr, &flags);
|
||||
if (flags & POSIX_SPAWN_SETSIGDEF) {
|
||||
sigset_t def;
|
||||
posix_spawnattr_getsigdefault(attr, &def);
|
||||
for (int sig = 1; sig < _NSIG; sig++) {
|
||||
if (sigismember(&def, sig) == 1) signal(sig, SIG_DFL);
|
||||
}
|
||||
}
|
||||
if ((flags & POSIX_SPAWN_SETSID) && setsid() < 0) return errno;
|
||||
if (flags & POSIX_SPAWN_SETPGROUP) {
|
||||
pid_t group = 0;
|
||||
posix_spawnattr_getpgroup(attr, &group);
|
||||
if (setpgid(0, group) != 0) return errno;
|
||||
}
|
||||
if (flags & (POSIX_SPAWN_SETSCHEDULER | POSIX_SPAWN_SETSCHEDPARAM)) {
|
||||
struct sched_param param;
|
||||
posix_spawnattr_getschedparam(attr, ¶m);
|
||||
int policy = 0;
|
||||
posix_spawnattr_getschedpolicy(attr, &policy);
|
||||
int r = (flags & POSIX_SPAWN_SETSCHEDULER) ? sched_setscheduler(0, policy, ¶m) : sched_setparam(0, ¶m);
|
||||
if (r == -1) return errno;
|
||||
}
|
||||
const struct ddh_spawn_action *a = fa ? (const struct ddh_spawn_action *)fa->__actions : NULL;
|
||||
char path[PATH_MAX];
|
||||
int err;
|
||||
for (int i = 0; a && i < fa->__used; i++) {
|
||||
switch (a[i].tag) {
|
||||
case DDH_DO_CLOSE:
|
||||
// the handoff table and the worker's binder stay open (kept fds)
|
||||
if (!is_kept_fd(a[i].action.close_action.fd))
|
||||
call_orig_syscall(SYS_close, (unsigned long)a[i].action.close_action.fd, 0, 0, 0, 0, 0);
|
||||
break;
|
||||
case DDH_DO_OPEN: {
|
||||
const char *real = rewrite_path(a[i].action.open_action.path, path, sizeof(path));
|
||||
// as glibc: the target goes first, so a full fd table still has room for the open
|
||||
if (!is_kept_fd(a[i].action.open_action.fd))
|
||||
call_orig_syscall(SYS_close, (unsigned long)a[i].action.open_action.fd, 0, 0, 0, 0, 0);
|
||||
long fd = call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)real,
|
||||
(unsigned long)a[i].action.open_action.oflag, a[i].action.open_action.mode, 0, 0);
|
||||
if (fd < 0) return errno;
|
||||
if (fd != a[i].action.open_action.fd) {
|
||||
if ((err = ddh_spawn_errno(call_orig_syscall(SYS_dup3, (unsigned long)fd, (unsigned long)a[i].action.open_action.fd, 0, 0, 0, 0))))
|
||||
return err;
|
||||
call_orig_syscall(SYS_close, (unsigned long)fd, 0, 0, 0, 0, 0);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case DDH_DO_DUP2: {
|
||||
int from = a[i].action.dup2_action.fd, to = a[i].action.dup2_action.newfd;
|
||||
if (from == to) {
|
||||
long fdflags = call_orig_syscall(SYS_fcntl, (unsigned long)from, F_GETFD, 0, 0, 0, 0);
|
||||
if (fdflags < 0) return errno;
|
||||
if ((err = ddh_spawn_errno(call_orig_syscall(SYS_fcntl, (unsigned long)from, F_SETFD, (unsigned long)(fdflags & ~FD_CLOEXEC), 0, 0, 0))))
|
||||
return err;
|
||||
} else if ((err = ddh_spawn_errno(call_orig_syscall(SYS_dup3, (unsigned long)from, (unsigned long)to, 0, 0, 0, 0)))) {
|
||||
return err;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case DDH_DO_CHDIR: {
|
||||
const char *real = rewrite_path_follow(a[i].action.chdir_action.path, path, sizeof(path));
|
||||
if ((err = ddh_spawn_errno(call_orig_syscall(SYS_chdir, (unsigned long)real, 0, 0, 0, 0, 0)))) return err;
|
||||
break;
|
||||
}
|
||||
case DDH_DO_FCHDIR:
|
||||
if ((err = ddh_spawn_errno(call_orig_syscall(SYS_fchdir, (unsigned long)a[i].action.fchdir_action.fd, 0, 0, 0, 0, 0))))
|
||||
return err;
|
||||
break;
|
||||
case DDH_DO_CLOSEFROM:
|
||||
for_each_range_without((unsigned int)a[i].action.closefrom_action.from, ~0U, g_kept_fds, g_kept_fd_count,
|
||||
ddh_spawn_close_part, NULL);
|
||||
break;
|
||||
case DDH_DO_TCSETPGRP:
|
||||
if (tcsetpgrp(a[i].action.setpgrp_action.fd, getpgrp()) != 0) return errno;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (flags & POSIX_SPAWN_SETSIGMASK) {
|
||||
sigset_t mask;
|
||||
posix_spawnattr_getsigmask(attr, &mask);
|
||||
sigprocmask(SIG_SETMASK, &mask, NULL);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// posix_spawn() as fork() and execve(), so that ddh_try() sees the exec. -1 when it cannot be.
|
||||
static int ddh_spawn_forked(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa,
|
||||
const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) {
|
||||
if (fa) {
|
||||
const struct ddh_spawn_action *a = (const struct ddh_spawn_action *)fa->__actions;
|
||||
// A terminal action stays with glibc, which blocks signals around the file actions: here a
|
||||
// SIGTTOU could stop the child at tcsetpgrp() with the parent waiting on its report.
|
||||
for (int i = 0; i < fa->__used; i++) {
|
||||
if ((unsigned)a[i].tag >= DDH_DO_TCSETPGRP) return -1;
|
||||
}
|
||||
}
|
||||
int report[2];
|
||||
if (pipe2(report, O_CLOEXEC) != 0) return -1;
|
||||
pid_t child = fork();
|
||||
if (child < 0) {
|
||||
int err = errno;
|
||||
close(report[0]);
|
||||
close(report[1]);
|
||||
return err;
|
||||
}
|
||||
if (child == 0) {
|
||||
call_orig_syscall(SYS_close, (unsigned long)report[0], 0, 0, 0, 0, 0);
|
||||
// Out of the file actions' way: high, and one of the fds they leave open (closefrom(3) is common)
|
||||
int to_parent = (int)call_orig_syscall(SYS_fcntl, (unsigned long)report[1], F_DUPFD_CLOEXEC, 1000, 0, 0, 0);
|
||||
if (to_parent >= 0) {
|
||||
call_orig_syscall(SYS_close, (unsigned long)report[1], 0, 0, 0, 0, 0);
|
||||
ddh_keep(to_parent);
|
||||
} else {
|
||||
to_parent = report[1];
|
||||
}
|
||||
int err = ddh_spawn_child_setup(fa, attr);
|
||||
if (!err) {
|
||||
execve(path, argv, envp);
|
||||
err = errno;
|
||||
}
|
||||
syscall(SYS_write, to_parent, &err, sizeof(err));
|
||||
_exit(127);
|
||||
}
|
||||
close(report[1]);
|
||||
int err = 0;
|
||||
ssize_t n;
|
||||
do n = read(report[0], &err, sizeof(err));
|
||||
while (n < 0 && errno == EINTR);
|
||||
close(report[0]);
|
||||
if (n == (ssize_t)sizeof(err)) {
|
||||
while (waitpid(child, NULL, 0) < 0 && errno == EINTR) {
|
||||
}
|
||||
return err;
|
||||
}
|
||||
if (pid) *pid = child;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int posix_spawn(pid_t *pid, const char *path,
|
||||
const posix_spawn_file_actions_t *file_actions,
|
||||
const posix_spawnattr_t *attrp,
|
||||
@@ -1074,7 +1247,12 @@ int posix_spawn(pid_t *pid, const char *path,
|
||||
if (bad) return bad;
|
||||
}
|
||||
posix_spawnattr_t sanitized;
|
||||
return ddnatv_posix_spawn(pid, path, file_actions, spawn_attr_for_android(attrp, &sanitized), argv, envp, 0);
|
||||
const posix_spawnattr_t *attr = spawn_attr_for_android(attrp, &sanitized);
|
||||
if (ddh_spawn_wanted(path, argv, envp ? envp : environ)) {
|
||||
int ret = ddh_spawn_forked(pid, path, file_actions, attr, argv, envp ? envp : environ);
|
||||
if (ret != -1) return ret;
|
||||
}
|
||||
return ddnatv_posix_spawn(pid, path, file_actions, attr, argv, envp, 0);
|
||||
}
|
||||
|
||||
int posix_spawnp(pid_t *pid, const char *file,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -10,9 +10,13 @@
|
||||
// closefrom(3)) made it abort later ("CHECK failed" in mmap_posix.cc). Its memory files open when
|
||||
// the hook starts survive close(), close_range() and closefrom(); phones that run ARM code
|
||||
// themselves have none.
|
||||
#define DDNATV_MAX_KEPT_FDS 4
|
||||
#define DDNATV_MAX_KEPT_FDS 12
|
||||
static int g_kept_fds[DDNATV_MAX_KEPT_FDS]; // ascending
|
||||
static int g_kept_fd_count = 0;
|
||||
// Of those, the ones also kept from close-on-exec: a worker process's binder fds (hook/handoff.c),
|
||||
// which must outlive the program's own execs.
|
||||
static int g_cloexec_kept_fds[8]; // ascending
|
||||
static int g_cloexec_kept_count = 0;
|
||||
|
||||
static int is_kept_fd(int fd) {
|
||||
for (int i = 0; i < g_kept_fd_count; i++) {
|
||||
@@ -438,6 +442,9 @@ int setns(int fd, int nstype) {
|
||||
#ifndef CLOSE_RANGE_CLOEXEC
|
||||
#define CLOSE_RANGE_CLOEXEC (1U << 2)
|
||||
#endif
|
||||
#ifndef CLOSE_RANGE_UNSHARE
|
||||
#define CLOSE_RANGE_UNSHARE (1U << 1)
|
||||
#endif
|
||||
|
||||
static int close_range_all(unsigned int first, unsigned int last, int flags);
|
||||
|
||||
@@ -448,10 +455,22 @@ static int close_range_part(unsigned int first, unsigned int last, void *flags)
|
||||
int close_range(unsigned int first, unsigned int last, int flags) {
|
||||
if (!(flags & CLOSE_RANGE_CLOEXEC)) forget_proc_root_range(first, last);
|
||||
// Close-on-exec only (CLOSE_RANGE_CLOEXEC) leaves the translator's files open
|
||||
if (g_kept_fd_count > 0 && !(flags & CLOSE_RANGE_CLOEXEC)) {
|
||||
return for_each_range_without(first, last, g_kept_fds, g_kept_fd_count, close_range_part, &flags);
|
||||
const int *kept = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_fds : g_kept_fds;
|
||||
int kept_count = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_count : g_kept_fd_count;
|
||||
if (kept_count == 0) return close_range_all(first, last, flags);
|
||||
// The table is unshared once, even when every fd in the range is kept: the system call itself on
|
||||
// the one number no fd has (close_range_all() would emulate a missing call by closing fds)
|
||||
if (flags & CLOSE_RANGE_UNSHARE) {
|
||||
static long (*raw_syscall)(long, ...) = NULL;
|
||||
if (!raw_syscall) raw_syscall = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall");
|
||||
if (!raw_syscall) {
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
}
|
||||
if (raw_syscall(__NR_close_range, ~0U, ~0U, CLOSE_RANGE_UNSHARE) != 0) return -1;
|
||||
flags &= ~CLOSE_RANGE_UNSHARE;
|
||||
}
|
||||
return close_range_all(first, last, flags);
|
||||
return for_each_range_without(first, last, kept, kept_count, close_range_part, &flags);
|
||||
}
|
||||
|
||||
// glibc's closefrom() makes the close_range system call itself, past the function above
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
build/
|
||||
@@ -0,0 +1,36 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.droiddeck.phantomlab">
|
||||
|
||||
<uses-sdk android:minSdkVersion="29" android:targetSdkVersion="34" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<application
|
||||
android:label="PhantomLab"
|
||||
android:extractNativeLibs="true"
|
||||
android:zygotePreloadName="com.droiddeck.phantomlab.Preload">
|
||||
|
||||
<activity android:name=".Main" android:exported="true" android:launchMode="singleTask"
|
||||
android:configChanges="density|orientation|screenSize|screenLayout|smallestScreenSize|uiMode|keyboard|keyboardHidden|navigation|fontScale">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<service android:name=".Iso" android:exported="false"
|
||||
android:isolatedProcess="true" android:useAppZygote="true" />
|
||||
<service android:name=".IsoPlain" android:exported="false"
|
||||
android:isolatedProcess="true" />
|
||||
<service android:name=".Proc" android:exported="false" android:process=":proc" />
|
||||
|
||||
<service android:name=".W0" android:exported="false" android:process=":w0" />
|
||||
<service android:name=".W1" android:exported="false" android:process=":w1" />
|
||||
<service android:name=".W2" android:exported="false" android:process=":w2" />
|
||||
<service android:name=".W3" android:exported="false" android:process=":w3" />
|
||||
<service android:name=".W4" android:exported="false" android:process=":w4" />
|
||||
<service android:name=".W5" android:exported="false" android:process=":w5" />
|
||||
<service android:name=".W6" android:exported="false" android:process=":w6" />
|
||||
<service android:name=".W7" android:exported="false" android:process=":w7" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds phantomlab.apk without Gradle: javac, d8, aapt2, the NDK's clang, apksigner (debug key).
|
||||
# usage: tools/phantomlab/build.sh [out.apk] (ANDROID_SDK_ROOT or ANDROID_HOME must be set)
|
||||
set -euo pipefail
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
sdk=${ANDROID_SDK_ROOT:-${ANDROID_HOME:?set ANDROID_SDK_ROOT}}
|
||||
bt=$(ls -d "$sdk"/build-tools/* | sort -V | tail -1)
|
||||
platform=$(ls -d "$sdk"/platforms/android-* | sort -V | tail -1)
|
||||
ndk=${ANDROID_NDK_ROOT:-$(ls -d "$sdk"/ndk/* | sort -V | tail -1)}
|
||||
out=${1:-$here/build/phantomlab.apk}
|
||||
work=$here/build
|
||||
exe=""
|
||||
case "$(uname -s)" in MINGW*|MSYS*|CYGWIN*) exe=".exe" ;; esac
|
||||
bat=""
|
||||
[ -n "$exe" ] && bat=".bat"
|
||||
|
||||
rm -rf "$work/classes" "$work/dex" "$work/lib" "$work/unsigned.apk"
|
||||
mkdir -p "$work/classes" "$work/dex"
|
||||
|
||||
sources=()
|
||||
while IFS= read -r -d '' f; do sources+=("$f"); done < <(find "$here/src" -name '*.java' -print0)
|
||||
javac -nowarn --release 8 -cp "$platform/android.jar" -d "$work/classes" "${sources[@]}" 2>&1 | { grep -v "^warning\|^Note:" || true; }
|
||||
classes=()
|
||||
while IFS= read -r -d '' f; do classes+=("$f"); done < <(find "$work/classes" -name '*.class' -print0)
|
||||
"$bt/d8$bat" --min-api 29 --lib "$platform/android.jar" --output "$work/dex" "${classes[@]}"
|
||||
|
||||
host=$(ls -d "$ndk"/toolchains/llvm/prebuilt/* | head -1)
|
||||
for abi in arm64-v8a x86_64; do
|
||||
case $abi in arm64-v8a) triple=aarch64-linux-android29 ;; x86_64) triple=x86_64-linux-android29 ;; esac
|
||||
mkdir -p "$work/lib/$abi"
|
||||
"$host/bin/clang$exe" --target=$triple -shared -fPIC -O2 -Wall -o "$work/lib/$abi/liblab.so" "$here/jni/lab.c" -llog
|
||||
"$host/bin/clang$exe" --target=$triple -fPIE -pie -O2 -Wall -o "$work/lib/$abi/libplabexe.so" "$here/jni/exe.c"
|
||||
done
|
||||
|
||||
"$bt/aapt2$exe" link -o "$work/unsigned.apk" -I "$platform/android.jar" --manifest "$here/AndroidManifest.xml"
|
||||
python3 - "$work" <<'EOF'
|
||||
import os, sys, zipfile
|
||||
work = sys.argv[1]
|
||||
with zipfile.ZipFile(os.path.join(work, "unsigned.apk"), "a", zipfile.ZIP_DEFLATED) as z:
|
||||
z.write(os.path.join(work, "dex", "classes.dex"), "classes.dex")
|
||||
for abi in os.listdir(os.path.join(work, "lib")):
|
||||
for so in ("liblab.so", "libplabexe.so"):
|
||||
z.write(os.path.join(work, "lib", abi, so), "lib/%s/%s" % (abi, so))
|
||||
EOF
|
||||
|
||||
key=$work/debug.keystore
|
||||
[ -f "$key" ] || keytool -genkeypair -keystore "$key" -storepass android -keypass android -alias lab \
|
||||
-keyalg RSA -keysize 2048 -validity 10000 -dname "CN=phantomlab" >/dev/null 2>&1
|
||||
"$bt/zipalign$exe" -f -p 4 "$work/unsigned.apk" "$work/aligned.apk"
|
||||
"$bt/apksigner$bat" sign --ks "$key" --ks-pass pass:android --out "$out" "$work/aligned.apk"
|
||||
echo "$out"
|
||||
@@ -0,0 +1,24 @@
|
||||
// libplabexe.so: an executable shipped as a "library" so the APK's lib directory holds it.
|
||||
// Reports its identity and reads fd 3 when it is open, then exits with status 7.
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
char buf[128] = "";
|
||||
ssize_t n = -1;
|
||||
struct pollfd p = {.fd = 3, .events = POLLIN};
|
||||
if (poll(&p, 1, 500) > 0 && (p.revents & (POLLIN | POLLHUP))) n = read(3, buf, sizeof(buf) - 1);
|
||||
if (n > 0) buf[n] = 0;
|
||||
char ctx[128] = "";
|
||||
int fd = open("/proc/self/attr/current", O_RDONLY);
|
||||
if (fd >= 0) {
|
||||
ssize_t m = read(fd, ctx, sizeof(ctx) - 1);
|
||||
if (m > 0) ctx[m] = 0;
|
||||
close(fd);
|
||||
}
|
||||
dprintf(2, "plabexe uid=%d ctx=%s fd3=%s\n", getuid(), ctx, n > 0 ? buf : "none");
|
||||
return 7;
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
// Native half of phantomlab: forks sleepers, execs in place, and probes what a process may do.
|
||||
#define _GNU_SOURCE
|
||||
#include <arpa/inet.h>
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <jni.h>
|
||||
#include <netinet/in.h>
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#include <android/log.h>
|
||||
|
||||
#define TAG "PLAB"
|
||||
|
||||
JNIEXPORT jint JNICALL Java_com_droiddeck_phantomlab_Native_spawn(JNIEnv *env, jclass cls, jint n) {
|
||||
int made = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
pid_t pid = fork();
|
||||
if (pid == 0) {
|
||||
for (;;) pause();
|
||||
}
|
||||
if (pid > 0) made++;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
struct kept_fd {
|
||||
int fd, flags;
|
||||
};
|
||||
|
||||
static int keep_binder_fds(struct kept_fd *kept, int max) {
|
||||
DIR *d = opendir("/proc/self/fd");
|
||||
if (!d) return 0;
|
||||
int count = 0;
|
||||
struct dirent *e;
|
||||
char path[64], target[256];
|
||||
while ((e = readdir(d)) != NULL && count < max) {
|
||||
int fd = atoi(e->d_name);
|
||||
if (fd <= 2) continue;
|
||||
snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
|
||||
ssize_t len = readlink(path, target, sizeof(target) - 1);
|
||||
if (len <= 0) continue;
|
||||
target[len] = 0;
|
||||
if (strstr(target, "binder")) {
|
||||
int flags = fcntl(fd, F_GETFD);
|
||||
if (flags < 0 || fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) != 0) continue;
|
||||
kept[count].fd = fd;
|
||||
kept[count].flags = flags;
|
||||
count++;
|
||||
__android_log_print(ANDROID_LOG_INFO, TAG, "keeping fd %d (%s) across exec", fd, target);
|
||||
}
|
||||
}
|
||||
closedir(d);
|
||||
return count;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_droiddeck_phantomlab_Native_execInPlace(JNIEnv *env, jclass cls, jobjectArray jargv, jboolean keep) {
|
||||
int n = (*env)->GetArrayLength(env, jargv);
|
||||
char **argv = calloc(n + 1, sizeof(char *));
|
||||
for (int i = 0; i < n; i++) {
|
||||
jstring s = (*env)->GetObjectArrayElement(env, jargv, i);
|
||||
const char *c = (*env)->GetStringUTFChars(env, s, NULL);
|
||||
argv[i] = strdup(c);
|
||||
}
|
||||
struct kept_fd kept[16];
|
||||
int kept_count = keep ? keep_binder_fds(kept, 16) : 0;
|
||||
execv(argv[0], argv);
|
||||
__android_log_print(ANDROID_LOG_ERROR, TAG, "execv %s failed: %s", argv[0], strerror(errno));
|
||||
for (int i = 0; i < kept_count; i++) fcntl(kept[i].fd, F_SETFD, kept[i].flags);
|
||||
}
|
||||
|
||||
static char *report;
|
||||
static size_t report_len, report_cap;
|
||||
|
||||
static void out(const char *fmt, ...) {
|
||||
char line[1024];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
int len = vsnprintf(line, sizeof(line), fmt, ap);
|
||||
va_end(ap);
|
||||
if (len < 0) return;
|
||||
if (len >= (int)sizeof(line)) len = sizeof(line) - 1;
|
||||
if (report_len + len + 2 > report_cap) {
|
||||
report_cap = (report_len + len + 2) * 2;
|
||||
report = realloc(report, report_cap);
|
||||
}
|
||||
memcpy(report + report_len, line, len);
|
||||
report_len += len;
|
||||
report[report_len++] = '\n';
|
||||
report[report_len] = 0;
|
||||
}
|
||||
|
||||
static void read_small(const char *path, char *buf, size_t size) {
|
||||
buf[0] = 0;
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
snprintf(buf, size, "<%s>", strerror(errno));
|
||||
return;
|
||||
}
|
||||
ssize_t n = read(fd, buf, size - 1);
|
||||
close(fd);
|
||||
if (n < 0) n = 0;
|
||||
buf[n] = 0;
|
||||
for (ssize_t i = 0; i < n; i++) if (buf[i] == '\n' || buf[i] == 0) buf[i] = ' ';
|
||||
}
|
||||
|
||||
#if defined(__aarch64__)
|
||||
static const unsigned char ret42[] = {0x40, 0x05, 0x80, 0x52, 0xc0, 0x03, 0x5f, 0xd6};
|
||||
#else
|
||||
static const unsigned char ret42[] = {0xb8, 0x2a, 0x00, 0x00, 0x00, 0xc3};
|
||||
#endif
|
||||
|
||||
static int call_code(void *code) {
|
||||
__builtin___clear_cache((char *)code, (char *)code + sizeof(ret42));
|
||||
return ((int (*)(void))code)();
|
||||
}
|
||||
|
||||
static void probe_memfd_exec(void) {
|
||||
int fd = syscall(SYS_memfd_create, "lab", 0);
|
||||
if (fd < 0) {
|
||||
out("memfd_exec: memfd_create %s", strerror(errno));
|
||||
return;
|
||||
}
|
||||
write(fd, ret42, sizeof(ret42));
|
||||
void *p = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0);
|
||||
if (p == MAP_FAILED) out("memfd_exec: mmap exec %s", strerror(errno));
|
||||
else out("memfd_exec: ran, returned %d", call_code(p));
|
||||
close(fd);
|
||||
}
|
||||
|
||||
static void probe_anon_exec(void) {
|
||||
void *p = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
memcpy(p, ret42, sizeof(ret42));
|
||||
if (mprotect(p, 4096, PROT_READ | PROT_EXEC) != 0) out("anon_exec: mprotect %s", strerror(errno));
|
||||
else out("anon_exec: ran, returned %d", call_code(p));
|
||||
}
|
||||
|
||||
static int run_child(char *const argv[], int execfd) {
|
||||
pid_t pid = fork();
|
||||
if (pid < 0) {
|
||||
out("fork: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
if (pid == 0) {
|
||||
if (execfd >= 0) syscall(SYS_execveat, execfd, "", argv, environ, AT_EMPTY_PATH);
|
||||
else execv(argv[0], argv);
|
||||
_exit(100 + errno);
|
||||
}
|
||||
int status = 0;
|
||||
waitpid(pid, &status, 0);
|
||||
return WIFEXITED(status) ? WEXITSTATUS(status) : 1000 + WTERMSIG(status);
|
||||
}
|
||||
|
||||
static const char *exec_result(int st, const char *ran) {
|
||||
if (st < 0) return "not run";
|
||||
return st >= 100 && st < 1000 ? strerror(st - 100) : ran;
|
||||
}
|
||||
|
||||
static int wait_fd(int fd, short events) {
|
||||
struct pollfd p = {.fd = fd, .events = events};
|
||||
int r = poll(&p, 1, 2000);
|
||||
if (r == 0) errno = ETIMEDOUT;
|
||||
return r > 0 ? 0 : -1;
|
||||
}
|
||||
|
||||
static void probe_tcp(int i, int fd) {
|
||||
struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons(80)};
|
||||
inet_pton(AF_INET, "1.1.1.1", &a.sin_addr);
|
||||
int fl = fcntl(fd, F_GETFL);
|
||||
if (fl < 0 || fcntl(fd, F_SETFL, fl | O_NONBLOCK) != 0) {
|
||||
out("fd%d tcp: fcntl %s", i, strerror(errno));
|
||||
return;
|
||||
}
|
||||
int r = connect(fd, (struct sockaddr *)&a, sizeof(a));
|
||||
if (r != 0 && errno == EINPROGRESS) {
|
||||
int err = 0;
|
||||
socklen_t el = sizeof(err);
|
||||
if (wait_fd(fd, POLLOUT) == 0 && getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &el) == 0) {
|
||||
r = err ? -1 : 0;
|
||||
errno = err;
|
||||
} else {
|
||||
r = -1;
|
||||
}
|
||||
}
|
||||
if (r != 0) {
|
||||
out("fd%d tcp: connect %s", i, strerror(errno));
|
||||
} else {
|
||||
const char *req = "HEAD / HTTP/1.0\r\nHost: 1.1.1.1\r\n\r\n";
|
||||
if (wait_fd(fd, POLLOUT) != 0 || write(fd, req, strlen(req)) < 0) {
|
||||
out("fd%d tcp: connected, write %s", i, strerror(errno));
|
||||
} else {
|
||||
char resp[64] = "";
|
||||
ssize_t n = wait_fd(fd, POLLIN) == 0 ? read(fd, resp, sizeof(resp) - 1) : -1;
|
||||
if (n > 0) resp[n] = 0;
|
||||
char *nl = strchr(resp, '\r');
|
||||
if (nl) *nl = 0;
|
||||
out("fd%d tcp: connected, got \"%s\"", i, n > 0 ? resp : strerror(errno));
|
||||
}
|
||||
}
|
||||
fcntl(fd, F_SETFL, fl);
|
||||
}
|
||||
|
||||
static void probe_exec(void) {
|
||||
char *argv[] = {"/system/bin/true", NULL};
|
||||
int st = run_child(argv, -1);
|
||||
out("execve /system/bin/true: %s", exec_result(st, st == 0 ? "ok" : "status"));
|
||||
int src = open("/system/bin/toybox", O_RDONLY);
|
||||
int mfd = syscall(SYS_memfd_create, "toybox", 0);
|
||||
char buf[65536];
|
||||
ssize_t n;
|
||||
while (src >= 0 && (n = read(src, buf, sizeof(buf))) > 0) write(mfd, buf, n);
|
||||
if (src >= 0) close(src);
|
||||
char *targv[] = {"true", NULL};
|
||||
st = run_child(targv, mfd);
|
||||
out("execveat memfd(toybox true): %s", exec_result(st, st == 0 ? "ok" : "status"));
|
||||
close(mfd);
|
||||
}
|
||||
|
||||
static void probe_fd(int i, int fd) {
|
||||
struct stat st;
|
||||
if (fstat(fd, &st) != 0) {
|
||||
out("fd%d: fstat %s", i, strerror(errno));
|
||||
return;
|
||||
}
|
||||
char target[256] = "";
|
||||
char path[64];
|
||||
snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
|
||||
ssize_t len = readlink(path, target, sizeof(target) - 1);
|
||||
if (len > 0) target[len] = 0;
|
||||
if (S_ISSOCK(st.st_mode)) {
|
||||
int type = 0, family = 0;
|
||||
socklen_t sl = sizeof(type);
|
||||
getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &sl);
|
||||
struct sockaddr_storage ss;
|
||||
socklen_t al = sizeof(ss);
|
||||
getsockname(fd, (struct sockaddr *)&ss, &al);
|
||||
family = ss.ss_family;
|
||||
if (family == AF_INET && type == SOCK_STREAM) {
|
||||
probe_tcp(i, fd);
|
||||
} else if (family == AF_INET && type == SOCK_DGRAM) {
|
||||
struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons(53)};
|
||||
inet_pton(AF_INET, "1.1.1.1", &a.sin_addr);
|
||||
int r = connect(fd, (struct sockaddr *)&a, sizeof(a));
|
||||
out("fd%d udp: connect %s", i, r == 0 ? "ok" : strerror(errno));
|
||||
} else {
|
||||
char buf[64] = "";
|
||||
ssize_t r = wait_fd(fd, POLLIN) == 0 ? read(fd, buf, sizeof(buf) - 1) : -1;
|
||||
if (r > 0) buf[r - 1] = 0;
|
||||
out("fd%d unix(family %d): read %s", i, family, r > 0 ? buf : strerror(errno));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (S_ISDIR(st.st_mode)) {
|
||||
int f = openat(fd, "probe.txt", O_RDONLY);
|
||||
out("fd%d dir %s: openat child %s", i, target, f >= 0 ? "ok" : strerror(errno));
|
||||
if (f >= 0) close(f);
|
||||
return;
|
||||
}
|
||||
char buf[64] = "";
|
||||
ssize_t r = pread(fd, buf, sizeof(buf) - 1, 0);
|
||||
if (r > 0) buf[r - 1] = 0;
|
||||
out("fd%d file %s: read %s", i, target, r >= 0 ? buf : strerror(errno));
|
||||
void *p = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE, fd, 0);
|
||||
out("fd%d mmap read: %s", i, p == MAP_FAILED ? strerror(errno) : "ok");
|
||||
if (p != MAP_FAILED) munmap(p, 4096);
|
||||
p = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0);
|
||||
out("fd%d mmap exec: %s", i, p == MAP_FAILED ? strerror(errno) : "ok");
|
||||
if (p != MAP_FAILED) munmap(p, 4096);
|
||||
char *argv[] = {"x", NULL};
|
||||
int st2 = run_child(argv, fd);
|
||||
out("fd%d execveat: %s", i, exec_result(st2, "ran"));
|
||||
}
|
||||
|
||||
static void probe_self(void) {
|
||||
char buf[512];
|
||||
out("uid=%d gid=%d pid=%d ppid=%d", getuid(), getgid(), getpid(), getppid());
|
||||
read_small("/proc/self/attr/current", buf, sizeof(buf));
|
||||
out("selinux: %s", buf);
|
||||
read_small("/proc/self/cgroup", buf, sizeof(buf));
|
||||
out("cgroup: %s", buf);
|
||||
int s = socket(AF_INET, SOCK_STREAM, 0);
|
||||
out("socket(AF_INET): %s", s >= 0 ? "ok" : strerror(errno));
|
||||
if (s >= 0) close(s);
|
||||
s = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
out("socket(AF_UNIX): %s", s >= 0 ? "ok" : strerror(errno));
|
||||
if (s >= 0) close(s);
|
||||
int f = open("/data/data/com.droiddeck.phantomlab/files/probe.txt", O_RDONLY);
|
||||
out("open app data by path: %s", f >= 0 ? "ok" : strerror(errno));
|
||||
if (f >= 0) close(f);
|
||||
const char *gpus[] = {"/dev/kgsl-3d0", "/dev/mali0", "/dev/dri/renderD128", NULL};
|
||||
for (int i = 0; gpus[i]; i++) {
|
||||
if (access(gpus[i], F_OK) != 0) continue;
|
||||
f = open(gpus[i], O_RDWR);
|
||||
out("open %s: %s", gpus[i], f >= 0 ? "ok" : strerror(errno));
|
||||
if (f >= 0) close(f);
|
||||
}
|
||||
}
|
||||
|
||||
static void probe_pid(const char *spec) {
|
||||
int pid = atoi(spec);
|
||||
char path[64], buf[256];
|
||||
snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
|
||||
read_small(path, buf, sizeof(buf));
|
||||
out("read /proc/%d/cmdline: %s", pid, buf);
|
||||
out("kill(%d, 0): %s", pid, kill(pid, 0) == 0 ? "ok" : strerror(errno));
|
||||
out("kill(%d, SIGCONT): %s", pid, kill(pid, SIGCONT) == 0 ? "ok" : strerror(errno));
|
||||
}
|
||||
|
||||
static void try_write(const char *path, const char *value) {
|
||||
int fd = open(path, O_WRONLY | O_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
out("write %s: open %s", path, strerror(errno));
|
||||
return;
|
||||
}
|
||||
ssize_t n = write(fd, value, strlen(value));
|
||||
out("write %s: %s", path, n >= 0 ? "ok" : strerror(errno));
|
||||
close(fd);
|
||||
}
|
||||
|
||||
// Every way a process could leave the cgroup Android counts it in.
|
||||
static void probe_escape(void) {
|
||||
char own[256], pid[32], path[300];
|
||||
read_small("/proc/self/cgroup", own, sizeof(own));
|
||||
char *v2 = strstr(own, "0::");
|
||||
char dir[200] = "";
|
||||
if (v2) sscanf(v2 + 3, "%199s", dir);
|
||||
snprintf(pid, sizeof(pid), "%d", getpid());
|
||||
try_write("/sys/fs/cgroup/cgroup.procs", pid);
|
||||
char parent[200];
|
||||
snprintf(parent, sizeof(parent), "%s", dir);
|
||||
char *slash = strrchr(parent, '/');
|
||||
if (slash) *slash = 0;
|
||||
snprintf(path, sizeof(path), "/sys/fs/cgroup%s/cgroup.procs", parent);
|
||||
try_write(path, pid);
|
||||
snprintf(path, sizeof(path), "/sys/fs/cgroup%s/lab", dir);
|
||||
out("mkdir %s: %s", path, mkdir(path, 0755) == 0 ? "ok" : strerror(errno));
|
||||
int r = syscall(SYS_unshare, 0x10000000 /* CLONE_NEWUSER */);
|
||||
out("unshare(CLONE_NEWUSER): %s", r == 0 ? "ok" : strerror(errno));
|
||||
r = syscall(SYS_unshare, 0x02000000 /* CLONE_NEWCGROUP */);
|
||||
out("unshare(CLONE_NEWCGROUP): %s", r == 0 ? "ok" : strerror(errno));
|
||||
int cg = open("/sys/fs/cgroup", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
|
||||
if (cg < 0) {
|
||||
out("open /sys/fs/cgroup: %s", strerror(errno));
|
||||
} else {
|
||||
struct {
|
||||
unsigned long long flags, pidfd, child_tid, parent_tid, exit_signal, stack, stack_size, tls, set_tid,
|
||||
set_tid_size, cgroup;
|
||||
} args = {.flags = 0x200000000ULL /* CLONE_INTO_CGROUP */, .exit_signal = SIGCHLD, .cgroup = (unsigned)cg};
|
||||
long child = syscall(435 /* clone3 */, &args, sizeof(args));
|
||||
if (child == 0) _exit(0);
|
||||
if (child > 0) waitpid(child, NULL, 0);
|
||||
out("clone3(CLONE_INTO_CGROUP, root): %s", child > 0 ? "ok" : strerror(errno));
|
||||
close(cg);
|
||||
}
|
||||
}
|
||||
|
||||
// Runs path with fd as its fd 3 and its stderr captured.
|
||||
static void probe_libexec(const char *path, int fd) {
|
||||
int pipefd[2];
|
||||
if (pipe(pipefd) != 0) {
|
||||
out("exec %s: pipe %s", path, strerror(errno));
|
||||
return;
|
||||
}
|
||||
pid_t pid = fork();
|
||||
if (pid < 0) {
|
||||
out("exec %s: fork %s", path, strerror(errno));
|
||||
close(pipefd[0]);
|
||||
close(pipefd[1]);
|
||||
return;
|
||||
}
|
||||
if (pid == 0) {
|
||||
dup2(pipefd[1], 2);
|
||||
if (fd >= 0) dup2(fd, 3);
|
||||
char *argv[] = {(char *)path, NULL};
|
||||
execv(path, argv);
|
||||
dprintf(2, "execv: %s", strerror(errno));
|
||||
_exit(127);
|
||||
}
|
||||
close(pipefd[1]);
|
||||
char buf[512] = "";
|
||||
ssize_t n = read(pipefd[0], buf, sizeof(buf) - 1);
|
||||
if (n > 0) buf[n] = 0;
|
||||
char *nl = strchr(buf, '\n');
|
||||
if (nl) *nl = 0;
|
||||
close(pipefd[0]);
|
||||
int status = 0;
|
||||
waitpid(pid, &status, 0);
|
||||
out("exec %s: status %d, said \"%s\"", path, WIFEXITED(status) ? WEXITSTATUS(status) : -WTERMSIG(status), buf);
|
||||
}
|
||||
|
||||
JNIEXPORT jstring JNICALL Java_com_droiddeck_phantomlab_Native_probe(JNIEnv *env, jclass cls, jstring jwhat, jintArray jfds) {
|
||||
report_len = 0;
|
||||
if (report) report[0] = 0;
|
||||
const char *what = jwhat ? (*env)->GetStringUTFChars(env, jwhat, NULL) : "self";
|
||||
int n = (*env)->GetArrayLength(env, jfds);
|
||||
jint *fds = (*env)->GetIntArrayElements(env, jfds, NULL);
|
||||
char spec[1024];
|
||||
snprintf(spec, sizeof(spec), "%s", what);
|
||||
char *save = NULL;
|
||||
for (char *tok = strtok_r(spec, ",", &save); tok; tok = strtok_r(NULL, ",", &save)) {
|
||||
if (!strcmp(tok, "self")) probe_self();
|
||||
else if (!strcmp(tok, "memfd_exec")) probe_memfd_exec();
|
||||
else if (!strcmp(tok, "anon_exec")) probe_anon_exec();
|
||||
else if (!strcmp(tok, "exec")) probe_exec();
|
||||
else if (!strcmp(tok, "fds")) for (int i = 0; i < n; i++) probe_fd(i, fds[i]);
|
||||
else if (!strncmp(tok, "pid=", 4)) probe_pid(tok + 4);
|
||||
else if (!strcmp(tok, "escape")) probe_escape();
|
||||
else if (!strncmp(tok, "libexec=", 8)) probe_libexec(tok + 8, n > 0 ? fds[0] : -1);
|
||||
}
|
||||
(*env)->ReleaseIntArrayElements(env, jfds, fds, 0);
|
||||
return (*env)->NewStringUTF(env, report ? report : "");
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class Iso extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class IsoPlain extends LabService {}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.os.Binder;
|
||||
import android.os.Handler;
|
||||
import android.os.IBinder;
|
||||
import android.os.Looper;
|
||||
import android.os.Parcel;
|
||||
import android.os.ParcelFileDescriptor;
|
||||
import android.os.Process;
|
||||
import android.util.Log;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class LabService extends Service {
|
||||
static final int SPAWN = 1;
|
||||
static final int PROBE = 2;
|
||||
static final int EXEC = 3;
|
||||
static final int WHO = 4;
|
||||
|
||||
private final Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
private final Binder binder = new Binder() {
|
||||
@Override
|
||||
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
|
||||
switch (code) {
|
||||
case SPAWN: {
|
||||
int n = data.readInt();
|
||||
reply.writeInt(Native.spawn(n));
|
||||
return true;
|
||||
}
|
||||
case PROBE: {
|
||||
String what = data.readString().replace("libexec",
|
||||
"libexec=" + getApplicationInfo().nativeLibraryDir + "/libplabexe.so");
|
||||
ParcelFileDescriptor[] pfds = readFds(data);
|
||||
try {
|
||||
int[] fds = new int[pfds.length];
|
||||
for (int i = 0; i < fds.length; i++) fds[i] = pfds[i] == null ? -1 : pfds[i].getFd();
|
||||
reply.writeString(Native.probe(what, fds));
|
||||
} finally {
|
||||
closeAll(pfds);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
case EXEC: {
|
||||
final String[] argv = data.createStringArray();
|
||||
final boolean keep = data.readInt() != 0;
|
||||
Log.i(Main.TAG, "pid " + Process.myPid() + " execs " + String.join(" ", argv) + " keepBinder=" + keep);
|
||||
handler.postDelayed(() -> Native.execInPlace(argv, keep), 500);
|
||||
reply.writeInt(Process.myPid());
|
||||
return true;
|
||||
}
|
||||
case WHO:
|
||||
reply.writeString("pid=" + Process.myPid() + " uid=" + Process.myUid()
|
||||
+ " isolated=" + Process.isIsolated());
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private static ParcelFileDescriptor[] readFds(Parcel data) {
|
||||
ParcelFileDescriptor[] pfds = new ParcelFileDescriptor[data.readInt()];
|
||||
try {
|
||||
for (int i = 0; i < pfds.length; i++) pfds[i] = data.readFileDescriptor();
|
||||
} catch (RuntimeException e) {
|
||||
closeAll(pfds);
|
||||
throw e;
|
||||
}
|
||||
return pfds;
|
||||
}
|
||||
|
||||
private static void closeAll(ParcelFileDescriptor[] pfds) {
|
||||
for (ParcelFileDescriptor pfd : pfds) {
|
||||
if (pfd == null) continue;
|
||||
try {
|
||||
pfd.close();
|
||||
} catch (IOException e) {
|
||||
Log.w(Main.TAG, "close fd failed " + e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
Log.i(Main.TAG, getClass().getSimpleName() + " bound in pid " + Process.myPid() + " uid " + Process.myUid());
|
||||
return binder;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.ServiceConnection;
|
||||
import android.os.Bundle;
|
||||
import android.os.IBinder;
|
||||
import android.os.Parcel;
|
||||
import android.os.ParcelFileDescriptor;
|
||||
import android.os.Process;
|
||||
import android.os.RemoteException;
|
||||
import android.system.ErrnoException;
|
||||
import android.system.Os;
|
||||
import android.system.OsConstants;
|
||||
import android.util.Log;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.File;
|
||||
import java.io.FileDescriptor;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* Drive with: am start -n com.droiddeck.phantomlab/.Main --es cmd spawn --es target iso --ei n 40
|
||||
* Results go to logcat under the PLAB tag.
|
||||
*/
|
||||
public class Main extends Activity {
|
||||
static final String TAG = "PLAB";
|
||||
|
||||
private static final Map<String, IBinder> binders = new HashMap<>();
|
||||
private static final Map<String, List<Task>> pending = new HashMap<>();
|
||||
private static final Map<String, ServiceConnection> connections = new HashMap<>();
|
||||
private static final ExecutorService worker = Executors.newSingleThreadExecutor();
|
||||
private TextView text;
|
||||
|
||||
private interface Op {
|
||||
void run(IBinder binder) throws Exception;
|
||||
}
|
||||
|
||||
private final class Task {
|
||||
final String target;
|
||||
final String name;
|
||||
final Op op;
|
||||
final Closeable owned;
|
||||
|
||||
Task(String target, String name, Op op, Closeable owned) {
|
||||
this.target = target;
|
||||
this.name = name;
|
||||
this.op = op;
|
||||
this.owned = owned;
|
||||
}
|
||||
|
||||
void run(IBinder binder) {
|
||||
worker.execute(() -> {
|
||||
try {
|
||||
op.run(binder);
|
||||
} catch (Exception e) {
|
||||
log(target + " " + name + " failed " + e);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void cancel() {
|
||||
log(target + " " + name + " cancelled");
|
||||
release();
|
||||
}
|
||||
|
||||
private void release() {
|
||||
if (owned == null) return;
|
||||
try {
|
||||
owned.close();
|
||||
} catch (IOException e) {
|
||||
log(target + " " + name + " close failed " + e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class ProbeFds implements Closeable {
|
||||
final List<ParcelFileDescriptor> sent = new ArrayList<>();
|
||||
final List<FileDescriptor> owned = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
IOException failure = null;
|
||||
for (ParcelFileDescriptor p : sent) {
|
||||
try {
|
||||
p.close();
|
||||
} catch (IOException e) {
|
||||
failure = e;
|
||||
}
|
||||
}
|
||||
for (FileDescriptor fd : owned) {
|
||||
try {
|
||||
Os.close(fd);
|
||||
} catch (ErrnoException e) {
|
||||
failure = new IOException(e);
|
||||
}
|
||||
}
|
||||
sent.clear();
|
||||
owned.clear();
|
||||
if (failure != null) throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
text = new TextView(this);
|
||||
setContentView(text);
|
||||
log("main pid " + Process.myPid() + " uid " + Process.myUid());
|
||||
handle(getIntent());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onNewIntent(Intent intent) {
|
||||
super.onNewIntent(intent);
|
||||
handle(intent);
|
||||
}
|
||||
|
||||
private void log(String s) {
|
||||
Log.i(TAG, s);
|
||||
runOnUiThread(() -> text.append(s + "\n"));
|
||||
}
|
||||
|
||||
private static Class<?> serviceClass(String target) {
|
||||
String base = target.contains(":") ? target.substring(0, target.indexOf(':')) : target;
|
||||
switch (base) {
|
||||
case "iso": return Iso.class;
|
||||
case "isoplain": return IsoPlain.class;
|
||||
case "proc": return Proc.class;
|
||||
default:
|
||||
if (base.startsWith("w")) {
|
||||
try {
|
||||
return Class.forName("com.droiddeck.phantomlab.W" + base.substring(1));
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new IllegalArgumentException(target);
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException(target);
|
||||
}
|
||||
}
|
||||
|
||||
private void withBinder(String target, String name, Op op, Closeable owned) {
|
||||
Task task = new Task(target, name, op, owned);
|
||||
IBinder binder = binders.get(target);
|
||||
if (binder != null) {
|
||||
task.run(binder);
|
||||
return;
|
||||
}
|
||||
List<Task> q = pending.get(target);
|
||||
if (q == null) {
|
||||
q = new ArrayList<>();
|
||||
pending.put(target, q);
|
||||
}
|
||||
q.add(task);
|
||||
if (!connections.containsKey(target)) bind(target);
|
||||
}
|
||||
|
||||
private void bind(String target) {
|
||||
ServiceConnection conn = new ServiceConnection() {
|
||||
@Override
|
||||
public void onServiceConnected(ComponentName name, IBinder service) {
|
||||
log("connected " + target);
|
||||
binders.put(target, service);
|
||||
List<Task> ops = pending.remove(target);
|
||||
if (ops != null) for (Task t : ops) t.run(service);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onServiceDisconnected(ComponentName name) {
|
||||
log("DISCONNECTED " + target);
|
||||
binders.remove(target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindingDied(ComponentName name) {
|
||||
log("BINDING DIED " + target);
|
||||
if (connections.get(target) != this) return;
|
||||
List<Task> ops = pending.remove(target);
|
||||
unbind(target);
|
||||
if (ops != null) {
|
||||
pending.put(target, ops);
|
||||
bind(target);
|
||||
}
|
||||
}
|
||||
};
|
||||
connections.put(target, conn);
|
||||
boolean ok = false;
|
||||
try {
|
||||
Intent intent = new Intent(this, serviceClass(target));
|
||||
int flags = Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT;
|
||||
if (target.contains(":")) {
|
||||
ok = getApplicationContext().bindIsolatedService(intent, flags, target.replace(':', '_'), getMainExecutor(), conn);
|
||||
} else {
|
||||
ok = getApplicationContext().bindService(intent, conn, flags);
|
||||
}
|
||||
} finally {
|
||||
log("bind " + target + " -> " + ok);
|
||||
if (!ok) unbind(target);
|
||||
}
|
||||
}
|
||||
|
||||
private void unbind(String target) {
|
||||
ServiceConnection c = connections.remove(target);
|
||||
binders.remove(target);
|
||||
List<Task> q = pending.remove(target);
|
||||
if (q != null) for (Task t : q) t.cancel();
|
||||
if (c == null) return;
|
||||
try {
|
||||
getApplicationContext().unbindService(c);
|
||||
} catch (IllegalArgumentException e) {
|
||||
log("unbind " + target + " " + e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Parcel call(IBinder binder, int code, Parcel data) throws RemoteException {
|
||||
Parcel reply = Parcel.obtain();
|
||||
binder.transact(code, data, reply, 0);
|
||||
return reply;
|
||||
}
|
||||
|
||||
private void handle(Intent intent) {
|
||||
String cmd = intent.getStringExtra("cmd");
|
||||
if (cmd == null) return;
|
||||
String target = intent.getStringExtra("target");
|
||||
try {
|
||||
switch (cmd) {
|
||||
case "spawn": {
|
||||
int n = intent.getIntExtra("n", 10);
|
||||
if ("main".equals(target)) {
|
||||
log("main spawned " + Native.spawn(n));
|
||||
return;
|
||||
}
|
||||
withBinder(target, "spawn", b -> {
|
||||
Parcel d = Parcel.obtain();
|
||||
d.writeInt(n);
|
||||
log(target + " spawned " + call(b, LabService.SPAWN, d).readInt());
|
||||
}, null);
|
||||
return;
|
||||
}
|
||||
case "who":
|
||||
withBinder(target, "who", b -> log(target + " " + call(b, LabService.WHO, Parcel.obtain()).readString()), null);
|
||||
return;
|
||||
case "exec": {
|
||||
String[] argv = intent.getStringExtra("argv").split("\\|");
|
||||
boolean keepBinder = intent.getIntExtra("keep", 1) != 0;
|
||||
withBinder(target, "exec", b -> {
|
||||
Parcel d = Parcel.obtain();
|
||||
d.writeStringArray(argv);
|
||||
d.writeInt(keepBinder ? 1 : 0);
|
||||
log(target + " exec in pid " + call(b, LabService.EXEC, d).readInt());
|
||||
}, null);
|
||||
return;
|
||||
}
|
||||
case "probe": {
|
||||
String what = intent.getStringExtra("what");
|
||||
ProbeFds fds = probeFds(intent.getStringExtra("fds"));
|
||||
withBinder(target, "probe", b -> {
|
||||
Parcel d = Parcel.obtain();
|
||||
d.writeString(what);
|
||||
d.writeInt(fds.sent.size());
|
||||
for (ParcelFileDescriptor p : fds.sent) d.writeFileDescriptor(p.getFileDescriptor());
|
||||
for (String line : call(b, LabService.PROBE, d).readString().split("\n")) log(target + " probe " + line);
|
||||
}, fds);
|
||||
return;
|
||||
}
|
||||
case "unbind": {
|
||||
unbind(target);
|
||||
log("unbound " + target);
|
||||
return;
|
||||
}
|
||||
default:
|
||||
log("unknown cmd " + cmd);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log(cmd + " failed " + e);
|
||||
}
|
||||
}
|
||||
|
||||
/** fds: comma separated list of tcp, udp, file:<name>, unix, memfd. */
|
||||
private ProbeFds probeFds(String spec) throws Exception {
|
||||
ProbeFds fds = new ProbeFds();
|
||||
if (spec == null || spec.isEmpty()) return fds;
|
||||
try {
|
||||
for (String s : spec.split(",")) {
|
||||
if (s.equals("tcp") || s.equals("udp")) {
|
||||
FileDescriptor fd = Os.socket(OsConstants.AF_INET,
|
||||
s.equals("tcp") ? OsConstants.SOCK_STREAM : OsConstants.SOCK_DGRAM, 0);
|
||||
fds.owned.add(fd);
|
||||
fds.sent.add(ParcelFileDescriptor.dup(fd));
|
||||
} else if (s.equals("unix")) {
|
||||
FileDescriptor a = new FileDescriptor();
|
||||
FileDescriptor b = new FileDescriptor();
|
||||
Os.socketpair(OsConstants.AF_UNIX, OsConstants.SOCK_STREAM, 0, a, b);
|
||||
fds.owned.add(a);
|
||||
fds.owned.add(b);
|
||||
Os.write(a, "hello from main\n".getBytes(), 0, 16);
|
||||
fds.sent.add(ParcelFileDescriptor.dup(b));
|
||||
} else if (s.startsWith("file:")) {
|
||||
File f = new File(getFilesDir(), s.substring(5));
|
||||
if (!f.exists()) {
|
||||
try (FileOutputStream o = new FileOutputStream(f)) {
|
||||
o.write("data file contents\n".getBytes());
|
||||
}
|
||||
}
|
||||
fds.sent.add(ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_WRITE));
|
||||
} else if (s.startsWith("path:")) {
|
||||
fds.sent.add(ParcelFileDescriptor.open(new File(s.substring(5)), ParcelFileDescriptor.MODE_READ_ONLY));
|
||||
} else if (s.equals("dir")) {
|
||||
fds.sent.add(ParcelFileDescriptor.open(getFilesDir(), ParcelFileDescriptor.MODE_READ_ONLY));
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
fds.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
return fds;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
final class Native {
|
||||
static {
|
||||
System.loadLibrary("lab");
|
||||
}
|
||||
|
||||
/** Forks n children that sleep until killed; returns how many were started. */
|
||||
static native int spawn(int n);
|
||||
|
||||
/** execve(argv) in this process; with keepBinder, the binder fds stay open across it. */
|
||||
static native void execInPlace(String[] argv, boolean keepBinder);
|
||||
|
||||
/** Runs the capability probes named in what, using the given fds; returns a report. */
|
||||
static native String probe(String what, int[] fds);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
import android.app.ZygotePreload;
|
||||
import android.content.pm.ApplicationInfo;
|
||||
|
||||
public class Preload implements ZygotePreload {
|
||||
@Override
|
||||
public void doPreload(ApplicationInfo appInfo) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class Proc extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W0 extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W1 extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W2 extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W3 extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W4 extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W5 extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W6 extends LabService {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W7 extends LabService {}
|
||||
@@ -0,0 +1,290 @@
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
|
||||
PARENT = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <spawn.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
extern char **environ;
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
pid_t pid;
|
||||
if (strcmp(argv[1], "spawn") == 0) {
|
||||
// as Python's subprocess does since 3.13, with its close_fds as a file action
|
||||
posix_spawn_file_actions_t actions;
|
||||
posix_spawn_file_actions_init(&actions);
|
||||
posix_spawn_file_actions_addclosefrom_np(&actions, 3);
|
||||
char *args[] = {"target", argv[2], NULL};
|
||||
int err = posix_spawn(&pid, argc > 3 ? argv[3] : "/bin/target", &actions, NULL, args, environ);
|
||||
printf("spawned\t%d\n", err);
|
||||
if (err) return 0;
|
||||
} else if ((pid = fork()) == 0) {
|
||||
if (strcmp(argv[1], "closefds") == 0) {
|
||||
// as Python's subprocess does before exec; an ordinary fd shows that it closed them
|
||||
int probe = open("/dev/null", O_RDONLY);
|
||||
printf("closerange\t%ld\n", (long)syscall(SYS_close_range, 3, ~0U, 0));
|
||||
printf("closed\t%d\n", probe >= 3 && fcntl(probe, F_GETFD) < 0);
|
||||
fflush(stdout);
|
||||
}
|
||||
if (strcmp(argv[1], "group") == 0) setpgid(0, 0);
|
||||
execl("/bin/target", "target", argv[2], (char *)NULL);
|
||||
_exit(127);
|
||||
}
|
||||
int status = 0;
|
||||
int group = strcmp(argv[1], "group") == 0;
|
||||
if (group) {
|
||||
setpgid(pid, pid);
|
||||
usleep(300000);
|
||||
// the child is in a group of its own: not ours
|
||||
printf("ours\t%d\n", (int)waitpid(0, &status, WNOHANG));
|
||||
}
|
||||
if (strcmp(argv[1], "kill") == 0) {
|
||||
printf("nohang\t%d\n", (int)waitpid(pid, &status, WNOHANG));
|
||||
usleep(300000);
|
||||
printf("kill\t%d\n", kill(pid, SIGTERM));
|
||||
}
|
||||
pid_t r = waitpid(group ? -pid : pid, &status, 0);
|
||||
printf("same\t%d\n", r == pid);
|
||||
if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status));
|
||||
if (WIFSIGNALED(status)) printf("signal\t%d\n", WTERMSIG(status));
|
||||
printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG));
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
TARGET = r"""
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (strcmp(argv[1], "sleep") == 0) for (;;) pause();
|
||||
return atoi(argv[1]);
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class FakeSpawner(threading.Thread):
|
||||
"""Stands in for the app's spawn socket: runs the program and reports its exit into the table."""
|
||||
|
||||
def __init__(self, name, prefix, root):
|
||||
super().__init__(daemon=True)
|
||||
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.sock.bind("\0" + name)
|
||||
self.sock.listen(4)
|
||||
self.prefix = prefix
|
||||
self.root = root
|
||||
self.requests = []
|
||||
|
||||
def run(self):
|
||||
while True:
|
||||
try:
|
||||
conn, _ = self.sock.accept()
|
||||
except OSError:
|
||||
return
|
||||
header = self.read(conn, 4)
|
||||
payload = self.read(conn, struct.unpack(">I", header)[0]) if header else b""
|
||||
if not payload:
|
||||
conn.close()
|
||||
continue
|
||||
request = json.loads(payload)
|
||||
fds = []
|
||||
while len(fds) < len(request["fds"]) + 1:
|
||||
data, chunk, _, _ = socket.recv_fds(conn, 1, request["fdchunks"])
|
||||
fds.extend(chunk)
|
||||
if not data:
|
||||
break # the client went away between chunks
|
||||
if len(fds) < len(request["fds"]) + 1:
|
||||
for fd in fds:
|
||||
os.close(fd)
|
||||
conn.close()
|
||||
continue
|
||||
self.requests.append(request)
|
||||
table = fds[request["table"]]
|
||||
program = str(self.root) + request["file"]
|
||||
# As a worker does: a process whose pid goes back first, which runs the program only
|
||||
# once the hook takes it on with "go"
|
||||
gate_r, gate_w = os.pipe()
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
os.close(gate_w)
|
||||
if os.read(gate_r, 1) == b"1":
|
||||
argv = list(self.prefix) + [program] + request["argv"][1:]
|
||||
os.execv(argv[0] if os.path.isabs(argv[0]) else shutil.which(argv[0]), argv)
|
||||
os._exit(127)
|
||||
os.close(gate_r)
|
||||
conn.sendall(b"pid %d\n" % pid)
|
||||
went = not request.get("ack") or self.read(conn, 3) == b"go\n"
|
||||
conn.close()
|
||||
for fd in fds:
|
||||
if fd != table:
|
||||
os.close(fd)
|
||||
if went:
|
||||
os.write(gate_w, b"1")
|
||||
os.close(gate_w)
|
||||
if not went:
|
||||
os.waitpid(pid, 0)
|
||||
os.close(table)
|
||||
continue
|
||||
threading.Thread(target=self.report, args=(pid, table, request), daemon=True).start()
|
||||
|
||||
@staticmethod
|
||||
def read(conn, size):
|
||||
data = b""
|
||||
while len(data) < size:
|
||||
more = conn.recv(size - len(data))
|
||||
if not more:
|
||||
return b"" # the client went away
|
||||
data += more
|
||||
return data
|
||||
|
||||
@staticmethod
|
||||
def report(pid, table, request):
|
||||
code = os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1])
|
||||
status = (-code) & 0x7F if code < 0 else (code & 0xFF) << 8
|
||||
entry = 64 + request["slot"] * 32
|
||||
os.pwrite(table, struct.pack("<i", status), entry + 16)
|
||||
os.pwrite(table, struct.pack("<i", 2), entry + 12)
|
||||
os.close(table)
|
||||
os.kill(request["parent"], signal.SIGCHLD)
|
||||
|
||||
|
||||
class NativeHookHandoffTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.cc, cls.prefix = runner()
|
||||
if cls.cc is None:
|
||||
raise unittest.SkipTest("no aarch64 compiler and runner")
|
||||
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
(tmp / "parent.c").write_text(PARENT)
|
||||
cls.parent = tmp / "parent"
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(cls.parent), str(tmp / "parent.c")], check=True)
|
||||
cls.root = tmp / "root"
|
||||
(cls.root / "bin").mkdir(parents=True)
|
||||
(tmp / "target.c").write_text(TARGET)
|
||||
subprocess.run([cls.cc, "-static", "-O1", "-o", str(cls.root / "bin/target"), str(tmp / "target.c")], check=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_parent(self, *argv, handoff="target", hook=True):
|
||||
name = "dd-handoff-test-%d-%s-%s-%d" % (os.getpid(), self.id().rsplit(".", 1)[-1], handoff, hook)
|
||||
spawner = FakeSpawner(name, self.prefix or [], self.root)
|
||||
spawner.start()
|
||||
self.addCleanup(spawner.sock.close)
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "DD_SPAWN": name, "DD_HANDOFF": handoff}
|
||||
if hook:
|
||||
hook_env["LD_PRELOAD"] = str(self.hook)
|
||||
env = {k: v for k, v in os.environ.items() if k not in hook_env}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(self.parent), *argv], env=env, capture_output=True, text=True, timeout=120)
|
||||
result = dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line)
|
||||
return result, spawner.requests, out
|
||||
|
||||
def test_the_parent_waits_for_the_handed_off_program(self):
|
||||
result, requests, out = self.run_parent("wait", "7")
|
||||
self.assertEqual(1, len(requests), out.stderr)
|
||||
self.assertEqual("/bin/target", requests[0]["file"])
|
||||
self.assertEqual(["target", "7"], requests[0]["argv"])
|
||||
self.assertEqual("1", result.get("same"), out.stdout)
|
||||
self.assertEqual("7", result.get("exit"), out.stdout)
|
||||
self.assertEqual("-1", result.get("again"), out.stdout)
|
||||
|
||||
def test_a_child_that_closed_its_inherited_fds_is_handed_off(self):
|
||||
result, requests, out = self.run_parent("closefds", "5")
|
||||
if result.get("closerange") != "0":
|
||||
self.skipTest("close_range does not work here: %s" % result.get("closerange"))
|
||||
self.assertEqual("1", result.get("closed"), out.stdout)
|
||||
self.assertEqual(1, len(requests), out.stderr)
|
||||
self.assertEqual("1", result.get("same"), out.stdout)
|
||||
self.assertEqual("5", result.get("exit"), out.stdout)
|
||||
|
||||
def test_a_posix_spawn_is_handed_off(self):
|
||||
result, requests, out = self.run_parent("spawn", "6")
|
||||
self.assertEqual("0", result.get("spawned"), out.stdout)
|
||||
self.assertEqual(1, len(requests), out.stderr)
|
||||
self.assertEqual(["target", "6"], requests[0]["argv"])
|
||||
self.assertEqual("1", result.get("same"), out.stdout)
|
||||
self.assertEqual("6", result.get("exit"), out.stdout)
|
||||
|
||||
def test_a_posix_spawn_of_a_missing_program_fails_as_it_would(self):
|
||||
# posix_spawn() returns the exec's error, even with closefrom(3) among the file actions
|
||||
result, requests, out = self.run_parent("spawn", "6", "/bin/missing", handoff="missing")
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
self.assertEqual([], requests)
|
||||
self.assertEqual(str(errno.ENOENT), result.get("spawned"), out.stdout)
|
||||
self.assertNotIn("exit", result, out.stdout)
|
||||
self.assertNotIn("signal", result, out.stdout)
|
||||
|
||||
def test_a_posix_spawn_of_a_missing_program_not_listed_is_unchanged(self):
|
||||
# As without the hook: ENOENT natively; qemu-user, which runs glibc's vfork-style spawn child
|
||||
# as a separate process, gets 0 and an exit status of 127.
|
||||
result, requests, out = self.run_parent("spawn", "6", "/bin/missing", handoff="other")
|
||||
plain, _, plain_out = self.run_parent("spawn", "6", "/bin/missing", handoff="other", hook=False)
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
self.assertEqual(0, plain_out.returncode, plain_out.stderr)
|
||||
self.assertIn("spawned", result, out.stdout)
|
||||
self.assertIn("spawned", plain, plain_out.stdout)
|
||||
self.assertEqual([], requests)
|
||||
self.assertEqual(plain.get("spawned"), result.get("spawned"), out.stdout + plain_out.stdout)
|
||||
self.assertEqual(plain.get("exit"), result.get("exit"), out.stdout + plain_out.stdout)
|
||||
|
||||
def test_a_posix_spawn_of_a_script_without_its_interpreter_fails_as_it_would(self):
|
||||
script = self.root / "bin/orphan"
|
||||
script.write_text("#!/bin/no-such-interpreter\n")
|
||||
script.chmod(0o755)
|
||||
result, requests, out = self.run_parent("spawn", "6", "/bin/orphan", handoff="orphan")
|
||||
self.assertEqual([], requests)
|
||||
self.assertEqual(str(errno.ENOENT), result.get("spawned"), out.stdout)
|
||||
|
||||
def test_a_wait_for_a_group_takes_only_that_groups_children(self):
|
||||
result, requests, out = self.run_parent("group", "4")
|
||||
self.assertEqual(1, len(requests), out.stderr)
|
||||
self.assertEqual("-1", result.get("ours"), out.stdout)
|
||||
self.assertEqual("1", result.get("same"), out.stdout)
|
||||
self.assertEqual("4", result.get("exit"), out.stdout)
|
||||
|
||||
def test_kill_reaches_the_program_and_its_signal_is_reported(self):
|
||||
result, requests, out = self.run_parent("kill", "sleep")
|
||||
self.assertEqual(1, len(requests), out.stderr)
|
||||
self.assertEqual("0", result.get("nohang"), out.stdout)
|
||||
self.assertEqual("0", result.get("kill"), out.stdout)
|
||||
self.assertEqual(str(int(signal.SIGTERM)), result.get("signal"), out.stdout)
|
||||
|
||||
def test_a_program_not_listed_is_a_normal_child(self):
|
||||
result, requests, out = self.run_parent("wait", "3", handoff="other")
|
||||
self.assertEqual([], requests)
|
||||
self.assertEqual("1", result.get("same"), out.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -34,7 +34,10 @@ class SessionBusTest(unittest.TestCase):
|
||||
match = re.search(r'^ *if \[ -z "\$\{DBUS_SESSION_BUS_ADDRESS:-\}" \]; then\n.*?^ *fi\n *fi\n',
|
||||
SESSION.read_text(), re.M | re.S)
|
||||
self.assertIsNotNone(match)
|
||||
script = "nap() { sleep \"$1\"; }\n" + match.group(0) + 'echo "ADDRESS=$DBUS_SESSION_BUS_ADDRESS"\nkill %1 2>/dev/null\n'
|
||||
spawn = re.search(r'^dd_spawn\(\) \{\n.*?^\}\n', SESSION.read_text(), re.M | re.S)
|
||||
self.assertIsNotNone(spawn)
|
||||
script = ("nap() { sleep \"$1\"; }\n" + spawn.group(0) + match.group(0) +
|
||||
'echo "ADDRESS=$DBUS_SESSION_BUS_ADDRESS"\nkill $dd_spawned 2>/dev/null\n')
|
||||
env = {"PATH": "%s:/usr/bin:/bin" % self.bin, "XDG_RUNTIME_DIR": str(self.runtime)}
|
||||
if env_address:
|
||||
env["DBUS_SESSION_BUS_ADDRESS"] = env_address
|
||||
|
||||
Reference in new issue
Block a user