mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-27 16:45:41 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89ef2f1e90 |
No files matched your search
@@ -414,69 +414,5 @@
|
||||
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>
|
||||
@@ -20,8 +20,6 @@ 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
|
||||
com.droiddeck.launcher.runtime.NativeGuest.init(this)
|
||||
com.droiddeck.launcher.session.Onboarding.attach(this)
|
||||
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
|
||||
|
||||
@@ -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() }
|
||||
}
|
||||
@@ -1,380 +0,0 @@
|
||||
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.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 }
|
||||
reply?.writeInt(Process.myPid())
|
||||
Handler(Looper.getMainLooper()).postDelayed({ exec(argv, env, fds, targets) }, EXEC_DELAY_MS)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent): IBinder = binder
|
||||
|
||||
private fun exec(argv: Array<String>, env: Array<String>, fds: List<ParcelFileDescriptor?>, targets: IntArray) {
|
||||
try {
|
||||
keepBinderOpen()
|
||||
// Out of the way first, so that placing one fd cannot overwrite another not yet placed.
|
||||
val moved = fds.map { pfd -> pfd?.let { Os.fcntlInt(it.fileDescriptor, OsConstants.F_DUPFD, MOVED_FDS) } }
|
||||
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)
|
||||
}
|
||||
Os.execve(argv[0], argv, env)
|
||||
} catch (e: ErrnoException) {
|
||||
Log.e(TAG, "could not exec ${argv.firstOrNull()}", e)
|
||||
}
|
||||
Process.killProcess(Process.myPid())
|
||||
}
|
||||
|
||||
/** Binder fds stay open across the exec, above the numbers the program's fds go to. */
|
||||
private fun keepBinderOpen() {
|
||||
File("/proc/self/fd").listFiles()?.forEach { link ->
|
||||
val target = runCatching { Os.readlink(link.path) }.getOrNull() ?: return@forEach
|
||||
if (!target.contains("binder")) return@forEach
|
||||
val fd = ParcelFileDescriptor.adoptFd(link.name.toIntOrNull() ?: return@forEach)
|
||||
kept.add(fd)
|
||||
Os.fcntlInt(fd.fileDescriptor, OsConstants.F_DUPFD, BINDER_FDS)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val RUN = IBinder.FIRST_CALL_TRANSACTION
|
||||
private const val EXEC_DELAY_MS = 100L
|
||||
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, val connection: ServiceConnection) {
|
||||
@Volatile var pid = -1
|
||||
}
|
||||
|
||||
private val slots = arrayOfNulls<Slot>(classes.size)
|
||||
@Volatile private var server: Thread? = null
|
||||
|
||||
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 {
|
||||
val app = context.applicationContext
|
||||
val connected = CountDownLatch(1)
|
||||
var service: IBinder? = null
|
||||
val slot: Slot
|
||||
synchronized(slots) {
|
||||
val index = slots.indexOfFirst { it == null }
|
||||
if (index < 0) {
|
||||
Log.w(TAG, "all ${slots.size} workers are busy")
|
||||
return -1
|
||||
}
|
||||
val connection = object : ServiceConnection {
|
||||
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
|
||||
service = binder
|
||||
connected.countDown()
|
||||
}
|
||||
|
||||
override fun onServiceDisconnected(name: ComponentName) = release(app, index, onExit)
|
||||
|
||||
override fun onBindingDied(name: ComponentName) = release(app, index, onExit)
|
||||
}
|
||||
slot = Slot(index, connection)
|
||||
slots[index] = slot
|
||||
}
|
||||
val intent = Intent(app, classes[slot.index])
|
||||
if (!app.bindService(intent, slot.connection, Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT) ||
|
||||
!connected.await(10, TimeUnit.SECONDS)) {
|
||||
Log.w(TAG, "worker ${slot.index} did not start")
|
||||
release(app, slot.index, null)
|
||||
return -1
|
||||
}
|
||||
val data = Parcel.obtain()
|
||||
val reply = Parcel.obtain()
|
||||
try {
|
||||
data.writeStringArray(argv.toTypedArray())
|
||||
data.writeStringArray(env.toTypedArray())
|
||||
data.writeInt(fds.size)
|
||||
fds.forEach { data.writeFileDescriptor(it.fileDescriptor) }
|
||||
data.writeIntArray(targets)
|
||||
service!!.transact(GuestWorker.RUN, data, reply, 0)
|
||||
slot.pid = reply.readInt()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "worker ${slot.index} refused ${argv.firstOrNull()}", e)
|
||||
release(app, slot.index, null)
|
||||
return -1
|
||||
} finally {
|
||||
data.recycle()
|
||||
reply.recycle()
|
||||
}
|
||||
Log.i(TAG, "worker ${slot.index} (pid ${slot.pid}) runs ${argv.lastOrNull { !it.startsWith("-") }}")
|
||||
return slot.pid
|
||||
}
|
||||
|
||||
private fun release(app: Context, index: Int, onExit: ((Int) -> Unit)?) {
|
||||
val slot = synchronized(slots) { slots[index]?.also { slots[index] = null } } ?: return
|
||||
runCatching { app.unbindService(slot.connection) }
|
||||
if (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)
|
||||
repeat(20) {
|
||||
am.getHistoricalProcessExitReasons(app.packageName, pid, 1).firstOrNull()?.let {
|
||||
return if (it.reason == android.app.ApplicationExitInfo.REASON_SIGNALED) it.status and 0x7f
|
||||
else (it.status and 0xff) shl 8
|
||||
}
|
||||
Thread.sleep(50)
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
/** Kills every worker's program; for session teardown. */
|
||||
fun stopAll() {
|
||||
val pids = synchronized(slots) { slots.mapNotNull { it?.pid?.takeIf { pid -> pid > 0 } } }
|
||||
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 serve(context: Context) {
|
||||
val app = context.applicationContext
|
||||
synchronized(this) {
|
||||
if (server != null) return
|
||||
server = Thread({
|
||||
val socket = try {
|
||||
LocalServerSocket(socketName(app))
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "no spawn socket", e)
|
||||
return@Thread
|
||||
}
|
||||
while (true) {
|
||||
val client = runCatching { socket.accept() }.getOrNull() ?: continue
|
||||
Thread({ handle(app, client) }, "guest-spawn").start()
|
||||
}
|
||||
}, "guest-spawn-server").apply { isDaemon = true; start() }
|
||||
}
|
||||
}
|
||||
|
||||
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 received = client.ancillaryFileDescriptors.orEmpty()
|
||||
val fds = received.map { ParcelFileDescriptor.dup(it) }
|
||||
received.forEach { runCatching { Os.close(it) } }
|
||||
val request = JSONObject(String(payload))
|
||||
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] }
|
||||
}
|
||||
val cwd = request.optString("cwd", "/")
|
||||
val wait = request.optBoolean("wait", false)
|
||||
val file = request.optString("file", "")
|
||||
// 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)
|
||||
val slot = request.optInt("slot", -1)
|
||||
val parent = request.optInt("parent", -1)
|
||||
val programFds = fds.filterIndexed { i, _ -> i != tableIndex }
|
||||
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())
|
||||
fds.forEach { runCatching { it.close() } }
|
||||
return
|
||||
}
|
||||
val shell = listOf("/usr/bin/bash", "/bin/bash").first { File(root, it.removePrefix("/")).isFile }
|
||||
val args = if (file.isNotEmpty()) {
|
||||
listOf("-c", "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", "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
|
||||
val exited = CountDownLatch(1)
|
||||
var status = -1
|
||||
val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, numbers) { code ->
|
||||
status = code
|
||||
if (table != null && slot >= 0) reportExit(table, slot, code, parent)
|
||||
exited.countDown()
|
||||
}
|
||||
programFds.forEach { runCatching { it.close() } }
|
||||
if (pid <= 0) table?.let { runCatching { it.close() } }
|
||||
out.write(if (pid > 0) "pid $pid\n".toByteArray() else "error no worker\n".toByteArray())
|
||||
out.flush()
|
||||
if (pid > 0 && wait) {
|
||||
exited.await()
|
||||
out.write("exit $status\n".toByteArray())
|
||||
out.flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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, ...
|
||||
private fun reportExit(table: ParcelFileDescriptor, slot: Int, status: Int, parent: Int) {
|
||||
runCatching {
|
||||
val entry = 64L + slot * 32L
|
||||
val word = java.nio.ByteBuffer.allocate(4).order(java.nio.ByteOrder.nativeOrder())
|
||||
Os.pwrite(table.fileDescriptor, word.putInt(0, if (status < 0) 9 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,7 +129,6 @@ 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-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",
|
||||
|
||||
@@ -693,18 +693,16 @@ 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)
|
||||
if (com.droiddeck.launcher.runtime.NativeGuest.enabled(this)) {
|
||||
com.droiddeck.launcher.runtime.GuestWorkers.serve(this)
|
||||
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('"', ' ')) }
|
||||
@@ -1526,7 +1524,6 @@ class SessionService : Service() {
|
||||
private fun teardown(prootPid: Int, expectedStartTime: Long? = null) {
|
||||
fun stillSameProcess(): Boolean = expectedStartTime == null || readStat(prootPid)?.second == expectedStartTime
|
||||
if (!stillSameProcess()) return
|
||||
if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.stopAll()
|
||||
val tree = descendants(prootPid)
|
||||
if (!stillSameProcess()) return
|
||||
saveWineRegistries(tree)
|
||||
|
||||
@@ -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? {
|
||||
|
||||
@@ -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\""))
|
||||
}
|
||||
}
|
||||
@@ -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"))
|
||||
}
|
||||
}
|
||||
@@ -1,313 +0,0 @@
|
||||
# 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: **two gaps in Android's process counting are confirmed on the AYN Thor (Android 13,
|
||||
kernel 5.15) and the Android 15 emulator**; both are in identical code on Android 12 through 16.
|
||||
A DroidDeck prototype is next. 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**.
|
||||
|
||||
Both are switched off only by `settings_enable_monitor_phantom_procs=false` (the developer option)
|
||||
or by raising `max_phantom_processes` through `device_config` (shell only).
|
||||
|
||||
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 |
|
||||
|
||||
Still counted with a game running: the session script's 9 bash subshells, gamescope with its two
|
||||
Xwayland servers, its reaper and an autolaunched D-Bus, Steam with its web helper browser and two
|
||||
utility processes, Steam's launch chain (`sh`, `pw-audio-namespace`, `reaper`), and the app's own
|
||||
logcat, PulseAudio and audio relay. The app's three can use `GuestWorkers.start` directly, and the
|
||||
autolaunched bus goes away once gamescope sees the session bus address.
|
||||
|
||||
### C. Plan
|
||||
|
||||
1. ~~Verify both gaps on the Thor (Android 13, 5.15)~~ done; still to do on one stock Android 14+
|
||||
phone with an enforcing `isolated_app`.
|
||||
2. ~~B for the processes DroidDeck and the session script start themselves~~ done (45 of 48).
|
||||
3. ~~B inside the hook, with pid translation~~ prototype done: 26 idle, 29 with a game, no kills
|
||||
with Android's limit on.
|
||||
4. To finish B:
|
||||
- the app's own logcat, PulseAudio and audio relay through `GuestWorkers.start`;
|
||||
- fewer session-script subshells, or start them with `dd_spawn bash -c`;
|
||||
- the autolaunched D-Bus under gamescope;
|
||||
- Xwayland, if gamescope keeps working without them as its children;
|
||||
- `/proc/<pid>/stat` showing the virtual parent, so Steam, its web helper and the launch chain
|
||||
can be handed off too;
|
||||
- a pre-started worker or two, so a handoff costs no zygote fork.
|
||||
5. Then the session can stop requiring the developer option where the in-game count stays well
|
||||
under 32. Keep the check as a warning and fall back to counted processes if a worker cannot
|
||||
start.
|
||||
6. 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.
|
||||
|
||||
```
|
||||
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 afterwards with
|
||||
`device_config delete activity_manager max_phantom_processes` and
|
||||
`device_config set_sync_disabled_for_tests none`.
|
||||
@@ -14,31 +14,6 @@ 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.
|
||||
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.$$
|
||||
if /usr/local/bin/droiddeck-spawn --pid-file "$f" -- "$@"; then
|
||||
dd_spawned=$(cat "$f" 2>/dev/null)
|
||||
rm -f "$f"
|
||||
[ -n "$dd_spawned" ] && return 0
|
||||
fi
|
||||
fi
|
||||
"$@" &
|
||||
dd_spawned=$!
|
||||
}
|
||||
# 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:python3: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"
|
||||
@@ -653,7 +628,7 @@ reap_orphans() {
|
||||
}
|
||||
|
||||
if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -x /usr/local/bin/droiddeck-clipboard ]; then
|
||||
dd_spawn /usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD"
|
||||
/usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" &
|
||||
fi
|
||||
|
||||
[ "${DD_DESKTOP:-}" = 1 ] || start_agent
|
||||
@@ -1409,8 +1384,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
|
||||
dd_spawn dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile
|
||||
system_bus=$dd_spawned
|
||||
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
|
||||
system_bus=$!
|
||||
for _ in $(seq 1 50); do
|
||||
[ -S /run/dbus/system_bus_socket ] && break
|
||||
sleep 0.1
|
||||
@@ -1418,8 +1393,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"
|
||||
dd_spawn droiddeck-login1 --with-netmanager
|
||||
login_manager=$dd_spawned
|
||||
droiddeck-login1 --with-netmanager &
|
||||
login_manager=$!
|
||||
for ((_i = 0; _i < 50; _i++)); do
|
||||
[ -f "$DD_LAUNCH_DIR/steam-sleep-ready" ] && break
|
||||
kill -0 "$login_manager" 2>/dev/null || break
|
||||
@@ -1443,7 +1418,7 @@ case $mode in
|
||||
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then
|
||||
_dd_bus=${XDG_RUNTIME_DIR:-/run/droiddeck}/bus
|
||||
rm -f "$_dd_bus"
|
||||
dd_spawn dbus-daemon --session --address="unix:path=$_dd_bus" --nofork --nopidfile
|
||||
dbus-daemon --session --address="unix:path=$_dd_bus" --nofork --nopidfile &
|
||||
for _ in $(seq 1 50); do
|
||||
[ -S "$_dd_bus" ] && break
|
||||
nap 0.1
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
#!/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
|
||||
|
||||
|
||||
def report(pid, pid_file):
|
||||
if pid_file:
|
||||
with open(pid_file, "w") as f:
|
||||
f.write("%s\n" % pid)
|
||||
else:
|
||||
print(pid, flush=True)
|
||||
|
||||
|
||||
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)
|
||||
report(pid, pid_file)
|
||||
if wait:
|
||||
return os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1])
|
||||
return 0
|
||||
|
||||
|
||||
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)
|
||||
report(first[1], pid_file)
|
||||
if not wait:
|
||||
return 0
|
||||
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,7 +82,6 @@
|
||||
#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,7 +374,6 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
}
|
||||
if (depth == 0) 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.
|
||||
|
||||
@@ -1,550 +0,0 @@
|
||||
// Part of libddnatv-hook.so, included by ddnatv-hook.c after exec.c.
|
||||
//
|
||||
// Exec handoff. Android counts every process in the app's cgroup against its child-process limit,
|
||||
// but not the app's own processes (docs/phantom-processes.md). A program a guest starts with
|
||||
// fork() + execve() can instead run as the main process of one of the app's worker processes: the
|
||||
// forked child sends the exec to the app (DD_SPAWN, an abstract socket) with its open fds, records
|
||||
// the worker's pid in a table it shares with its parent, and exits. For the parent nothing changes:
|
||||
// wait*(), kill() and SIGCHLD treat the pid fork() returned as that program until it exits; the app
|
||||
// writes its exit status into the table and sends the parent SIGCHLD.
|
||||
//
|
||||
// Only programs named in DD_HANDOFF (basenames separated by ':', or "*") are handed off. The child's
|
||||
// side runs where vfork() children run too, so it allocates nothing and writes no globals.
|
||||
|
||||
#define DDH_SLOTS 1024
|
||||
#define DDH_FREE 0
|
||||
#define DDH_CLAIMED 3
|
||||
#define DDH_HANDED 1
|
||||
#define DDH_EXITED 2
|
||||
#define DDH_MAGIC 0x6464686f
|
||||
|
||||
struct ddh_entry {
|
||||
int32_t child; // the pid the parent got from fork()
|
||||
int32_t real; // the worker's pid
|
||||
int32_t parent;
|
||||
int32_t state;
|
||||
int32_t status; // wait status, written by the app
|
||||
int32_t reaped; // the parent has reaped the forked child itself
|
||||
int32_t pad[2];
|
||||
};
|
||||
|
||||
struct ddh_table {
|
||||
int32_t magic;
|
||||
int32_t pad[15];
|
||||
struct ddh_entry e[DDH_SLOTS];
|
||||
};
|
||||
|
||||
static struct ddh_table *g_ddh; // this process's table, for the children it forks
|
||||
static int g_ddh_fd = -1;
|
||||
static pid_t g_ddh_owner;
|
||||
// The parent's table, when this image was exec'd by a child the parent forked (a wrapper such as
|
||||
// env or a script that execs its program): that exec can still be handed off.
|
||||
static struct ddh_table *g_ddh_up;
|
||||
static int g_ddh_up_fd = -1;
|
||||
|
||||
static const char *ddh_env(char *const envp[], const char *name) {
|
||||
size_t n = strlen(name);
|
||||
for (char *const *e = envp; e && *e; e++) {
|
||||
if (strncmp(*e, name, n) == 0 && (*e)[n] == '=') return *e + n + 1;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// In the parent, before fork(): the table the children write to.
|
||||
static void ddh_prepare(void) {
|
||||
if (g_ddh || !getenv("DD_SPAWN")) return;
|
||||
int fd = (int)syscall(SYS_memfd_create, "ddnatv-handoff", 1 /* MFD_CLOEXEC */);
|
||||
if (fd < 0) return;
|
||||
if (ftruncate(fd, sizeof(struct ddh_table)) != 0) {
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
void *p = mmap(NULL, sizeof(struct ddh_table), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
if (p == MAP_FAILED) {
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
g_ddh = p;
|
||||
g_ddh->magic = DDH_MAGIC;
|
||||
g_ddh->pad[0] = getpid();
|
||||
g_ddh_fd = fd;
|
||||
g_ddh_owner = getpid();
|
||||
}
|
||||
|
||||
// A table inherited across exec: the parent's if its owner is still our parent, else closed.
|
||||
static void ddh_find_parent_table(void) {
|
||||
char path[64], target[64];
|
||||
pid_t parent = getppid();
|
||||
for (int fd = 3; fd < 1024; fd++) {
|
||||
int n = snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
|
||||
if (n <= 0) continue;
|
||||
long len = syscall(SYS_readlinkat, AT_FDCWD, path, target, sizeof(target) - 1);
|
||||
if (len <= 0) continue;
|
||||
target[len] = 0;
|
||||
if (strncmp(target, "/memfd:ddnatv-handoff", 21) != 0) continue;
|
||||
struct ddh_table *t = mmap(NULL, sizeof(struct ddh_table), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
if (t != MAP_FAILED && t->magic == DDH_MAGIC && t->pad[0] == parent && !g_ddh_up) {
|
||||
g_ddh_up = t;
|
||||
g_ddh_up_fd = fd;
|
||||
syscall(SYS_fcntl, fd, F_SETFD, FD_CLOEXEC);
|
||||
continue;
|
||||
}
|
||||
if (t != MAP_FAILED) munmap(t, sizeof(struct ddh_table));
|
||||
syscall(SYS_close, fd);
|
||||
}
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void ddh_init(void) {
|
||||
if (!getenv("DD_SPAWN")) return;
|
||||
ddh_find_parent_table();
|
||||
ddh_prepare();
|
||||
}
|
||||
|
||||
static int ddh_has_arg(char *const argv[], const char *prefix, size_t len) {
|
||||
for (int i = 1; argv && argv[i]; i++) {
|
||||
if (strncmp(argv[i], prefix, len) == 0) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// An entry is a basename, or "name+prefix" for that program only when an argument starts with prefix.
|
||||
static int ddh_listed(const char *list, const char *name, char *const argv[]) {
|
||||
if (!list || !name || !*name) return 0;
|
||||
if (strcmp(list, "*") == 0) return 1;
|
||||
size_t n = strlen(name);
|
||||
for (const char *p = list; *p;) {
|
||||
const char *end = strchr(p, ':');
|
||||
size_t len = end ? (size_t)(end - p) : strlen(p);
|
||||
const char *plus = memchr(p, '+', len);
|
||||
size_t base = plus ? (size_t)(plus - p) : len;
|
||||
if (base == n && strncmp(p, name, n) == 0 &&
|
||||
(!plus || ddh_has_arg(argv, plus + 1, len - base - 1))) return 1;
|
||||
if (!end) break;
|
||||
p = end + 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const char *ddh_base(const char *path) {
|
||||
const char *s = path ? strrchr(path, '/') : NULL;
|
||||
return s ? s + 1 : path;
|
||||
}
|
||||
|
||||
struct ddh_buf {
|
||||
char *p;
|
||||
size_t len, cap;
|
||||
};
|
||||
|
||||
static void ddh_put(struct ddh_buf *b, const char *s, size_t n) {
|
||||
if (b->p && b->len + n <= b->cap) memcpy(b->p + b->len, s, n);
|
||||
b->len += n;
|
||||
}
|
||||
|
||||
static void ddh_puts(struct ddh_buf *b, const char *s) { ddh_put(b, s, strlen(s)); }
|
||||
|
||||
static void ddh_putint(struct ddh_buf *b, long v) {
|
||||
char tmp[24];
|
||||
int i = sizeof(tmp);
|
||||
int neg = v < 0;
|
||||
unsigned long u = neg ? (unsigned long)-v : (unsigned long)v;
|
||||
do {
|
||||
tmp[--i] = (char)('0' + u % 10);
|
||||
u /= 10;
|
||||
} while (u);
|
||||
if (neg) tmp[--i] = '-';
|
||||
ddh_put(b, tmp + i, sizeof(tmp) - i);
|
||||
}
|
||||
|
||||
static void ddh_putstr(struct ddh_buf *b, const char *s) {
|
||||
static const char hex[] = "0123456789abcdef";
|
||||
ddh_put(b, "\"", 1);
|
||||
for (const unsigned char *c = (const unsigned char *)s; *c; c++) {
|
||||
if (*c == '"' || *c == '\\') {
|
||||
char esc[2] = {'\\', (char)*c};
|
||||
ddh_put(b, esc, 2);
|
||||
} else if (*c < 0x20) {
|
||||
char esc[6] = {'\\', 'u', '0', '0', hex[*c >> 4], hex[*c & 15]};
|
||||
ddh_put(b, esc, 6);
|
||||
} else {
|
||||
ddh_put(b, (const char *)c, 1);
|
||||
}
|
||||
}
|
||||
ddh_put(b, "\"", 1);
|
||||
}
|
||||
|
||||
static void ddh_putarray(struct ddh_buf *b, char *const v[]) {
|
||||
ddh_put(b, "[", 1);
|
||||
for (int i = 0; v && v[i]; i++) {
|
||||
if (i) ddh_put(b, ",", 1);
|
||||
ddh_putstr(b, v[i]);
|
||||
}
|
||||
ddh_put(b, "]", 1);
|
||||
}
|
||||
|
||||
#define DDH_MAX_FDS 240
|
||||
|
||||
// The fds the program would have inherited: every open fd without FD_CLOEXEC.
|
||||
static int ddh_open_fds(int *fds, int max) {
|
||||
int n = 0;
|
||||
int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/fd", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
|
||||
if (dir < 0) return -1;
|
||||
char buf[4096];
|
||||
for (;;) {
|
||||
long got = syscall(SYS_getdents64, dir, buf, sizeof(buf));
|
||||
if (got <= 0) break;
|
||||
for (long off = 0; off < got;) {
|
||||
struct {
|
||||
uint64_t ino;
|
||||
int64_t off;
|
||||
unsigned short reclen;
|
||||
unsigned char type;
|
||||
char name[];
|
||||
} *d = (void *)(buf + off);
|
||||
off += d->reclen;
|
||||
if (d->name[0] < '0' || d->name[0] > '9') continue;
|
||||
int fd = 0;
|
||||
for (const char *c = d->name; *c; c++) fd = fd * 10 + (*c - '0');
|
||||
if (fd == dir) continue;
|
||||
int flags = (int)syscall(SYS_fcntl, fd, F_GETFD);
|
||||
if (flags < 0 || (flags & FD_CLOEXEC)) continue;
|
||||
if (n == max) {
|
||||
syscall(SYS_close, dir);
|
||||
return -1;
|
||||
}
|
||||
fds[n++] = fd;
|
||||
}
|
||||
}
|
||||
syscall(SYS_close, dir);
|
||||
return n;
|
||||
}
|
||||
|
||||
// The interpreter a script names on its "#!" line ("/usr/bin/env NAME" gives NAME), into buf.
|
||||
static const char *ddh_interpreter(const char *path, char *buf, size_t size) {
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return NULL;
|
||||
long n = read(fd, buf, size - 1);
|
||||
close(fd);
|
||||
if (n < 3 || buf[0] != '#' || buf[1] != '!') return NULL;
|
||||
buf[n] = 0;
|
||||
char *p = buf + 2;
|
||||
while (*p == ' ' || *p == '\t') p++;
|
||||
char *end = p;
|
||||
while (*end && *end != ' ' && *end != '\t' && *end != '\n') end++;
|
||||
char *word = NULL;
|
||||
if (*end == ' ' || *end == '\t') {
|
||||
word = end + 1;
|
||||
while (*word == ' ' || *word == '\t') word++;
|
||||
}
|
||||
*end = 0;
|
||||
const char *name = ddh_base(p);
|
||||
if (strcmp(name, "env") == 0 && word && *word) {
|
||||
end = word;
|
||||
while (*end && *end != ' ' && *end != '\t' && *end != '\n') end++;
|
||||
*end = 0;
|
||||
return word;
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
// In a forked child at execve(): hands the program to a worker and exits, or returns to exec it here.
|
||||
static void ddh_debug(char *const envp[], const char *what, const char *filename) {
|
||||
if (!ddh_env(envp, "DD_HANDOFF_DEBUG")) return;
|
||||
char line[512];
|
||||
struct ddh_buf b = {line, 0, sizeof(line) - 1};
|
||||
ddh_puts(&b, "ddnatv handoff: ");
|
||||
ddh_putint(&b, getpid());
|
||||
ddh_puts(&b, " ");
|
||||
ddh_puts(&b, what);
|
||||
ddh_puts(&b, " ");
|
||||
ddh_puts(&b, filename ? filename : "?");
|
||||
ddh_puts(&b, "\n");
|
||||
if (b.len > b.cap) b.len = b.cap;
|
||||
syscall(SYS_write, 2, line, b.len);
|
||||
}
|
||||
|
||||
static void ddh_try(const char *filename, char *const argv[], char *const envp[]) {
|
||||
struct ddh_table *table;
|
||||
int table_fd;
|
||||
if (g_ddh && getpid() != g_ddh_owner) {
|
||||
table = g_ddh;
|
||||
table_fd = g_ddh_fd;
|
||||
} else if (g_ddh_up && getppid() == g_ddh_up->pad[0]) {
|
||||
table = g_ddh_up;
|
||||
table_fd = g_ddh_up_fd;
|
||||
} else {
|
||||
ddh_debug(envp, "not a child its parent can track:", filename);
|
||||
return;
|
||||
}
|
||||
const char *sock = ddh_env(envp, "DD_SPAWN");
|
||||
const char *list = ddh_env(envp, "DD_HANDOFF");
|
||||
if (!sock || !list || access(filename, X_OK) != 0) return;
|
||||
// Whatever this exec becomes can still hand off its own exec (a wrapper, a script).
|
||||
syscall(SYS_fcntl, table_fd, F_SETFD, 0);
|
||||
char shebang[256];
|
||||
const char *interp = NULL;
|
||||
if (!ddh_listed(list, ddh_base(filename), argv) && !(argv && ddh_listed(list, ddh_base(argv[0]), argv)) &&
|
||||
!((interp = ddh_interpreter(filename, shebang, sizeof(shebang))) && ddh_listed(list, interp, argv))) return;
|
||||
|
||||
int fds[DDH_MAX_FDS + 1];
|
||||
int nfds = ddh_open_fds(fds, DDH_MAX_FDS);
|
||||
if (nfds < 0) return;
|
||||
|
||||
int slot = -1;
|
||||
for (int i = 0; i < DDH_SLOTS; i++) {
|
||||
int expected = DDH_FREE;
|
||||
if (__atomic_compare_exchange_n(&table->e[i].state, &expected, DDH_CLAIMED, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) {
|
||||
slot = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (slot < 0) return;
|
||||
struct ddh_entry *e = &table->e[slot];
|
||||
pid_t me = getpid(), parent = getppid();
|
||||
char cwd[PATH_MAX];
|
||||
if (!getcwd(cwd, sizeof(cwd))) strcpy(cwd, "/");
|
||||
|
||||
struct ddh_buf b = {0};
|
||||
for (int pass = 0; pass < 2; pass++) {
|
||||
b.len = 0;
|
||||
ddh_puts(&b, "{\"file\":");
|
||||
ddh_putstr(&b, filename);
|
||||
ddh_puts(&b, ",\"argv\":");
|
||||
ddh_putarray(&b, argv);
|
||||
ddh_puts(&b, ",\"envlist\":");
|
||||
ddh_putarray(&b, envp);
|
||||
ddh_puts(&b, ",\"cwd\":");
|
||||
ddh_putstr(&b, cwd);
|
||||
ddh_puts(&b, ",\"fds\":[");
|
||||
for (int i = 0; i < nfds; i++) {
|
||||
if (i) ddh_put(&b, ",", 1);
|
||||
ddh_putint(&b, fds[i]);
|
||||
}
|
||||
ddh_puts(&b, "],\"table\":");
|
||||
ddh_putint(&b, nfds);
|
||||
ddh_puts(&b, ",\"slot\":");
|
||||
ddh_putint(&b, slot);
|
||||
ddh_puts(&b, ",\"parent\":");
|
||||
ddh_putint(&b, parent);
|
||||
ddh_puts(&b, ",\"child\":");
|
||||
ddh_putint(&b, me);
|
||||
ddh_puts(&b, "}");
|
||||
if (pass == 0) {
|
||||
b.cap = b.len + 4;
|
||||
b.p = mmap(NULL, b.cap, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
if (b.p == MAP_FAILED) {
|
||||
__atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
fds[nfds] = table_fd;
|
||||
|
||||
long pid = -1;
|
||||
int s = (int)syscall(SYS_socket, AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||
struct sockaddr_un addr = {.sun_family = AF_UNIX};
|
||||
size_t namelen = strlen(sock);
|
||||
if (s >= 0 && namelen + 1 < sizeof(addr.sun_path)) {
|
||||
memcpy(addr.sun_path + 1, sock, namelen);
|
||||
socklen_t alen = (socklen_t)(offsetof(struct sockaddr_un, sun_path) + 1 + namelen);
|
||||
if (syscall(SYS_connect, s, &addr, alen) == 0) {
|
||||
uint32_t len = (uint32_t)b.len;
|
||||
unsigned char header[4] = {(unsigned char)(len >> 24), (unsigned char)(len >> 16), (unsigned char)(len >> 8), (unsigned char)len};
|
||||
struct iovec iov[2] = {{header, 4}, {b.p, b.len}};
|
||||
char control[CMSG_SPACE(sizeof(int) * (DDH_MAX_FDS + 1))];
|
||||
struct msghdr msg = {.msg_iov = iov, .msg_iovlen = 2, .msg_control = control,
|
||||
.msg_controllen = CMSG_SPACE(sizeof(int) * (nfds + 1))};
|
||||
struct cmsghdr *cm = CMSG_FIRSTHDR(&msg);
|
||||
cm->cmsg_level = SOL_SOCKET;
|
||||
cm->cmsg_type = SCM_RIGHTS;
|
||||
cm->cmsg_len = CMSG_LEN(sizeof(int) * (nfds + 1));
|
||||
memcpy(CMSG_DATA(cm), fds, sizeof(int) * (nfds + 1));
|
||||
if (syscall(SYS_sendmsg, s, &msg, MSG_NOSIGNAL) == (long)(b.len + 4)) {
|
||||
char reply[64];
|
||||
size_t got = 0;
|
||||
while (got < sizeof(reply) - 1) {
|
||||
long r = syscall(SYS_read, s, reply + got, 1);
|
||||
if (r <= 0 || reply[got] == '\n') break;
|
||||
got++;
|
||||
}
|
||||
reply[got] = 0;
|
||||
if (strncmp(reply, "pid ", 4) == 0) pid = atol(reply + 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (s >= 0) syscall(SYS_close, s);
|
||||
munmap(b.p, b.cap);
|
||||
if (pid <= 0) {
|
||||
__atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE);
|
||||
ddh_debug(envp, "spawner refused", filename);
|
||||
return;
|
||||
}
|
||||
e->child = me;
|
||||
e->parent = parent;
|
||||
e->real = (int32_t)pid;
|
||||
e->reaped = 0;
|
||||
int expected = DDH_CLAIMED;
|
||||
// the app may already have written DDH_EXITED for a program that ended at once
|
||||
__atomic_compare_exchange_n(&e->state, &expected, DDH_HANDED, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED);
|
||||
syscall(SYS_exit_group, 0);
|
||||
}
|
||||
|
||||
// ---- the parent's side -----------------------------------------------------------------------
|
||||
|
||||
static struct ddh_entry *ddh_find(pid_t child) {
|
||||
if (!g_ddh || child <= 0) return NULL;
|
||||
pid_t me = getpid();
|
||||
for (int i = 0; i < DDH_SLOTS; i++) {
|
||||
struct ddh_entry *e = &g_ddh->e[i];
|
||||
int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE);
|
||||
if ((st == DDH_HANDED || st == DDH_EXITED) && e->parent == me && e->child == child) return e;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int ddh_any_live(void) {
|
||||
if (!g_ddh) return 0;
|
||||
pid_t me = getpid();
|
||||
for (int i = 0; i < DDH_SLOTS; i++) {
|
||||
struct ddh_entry *e = &g_ddh->e[i];
|
||||
int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE);
|
||||
if ((st == DDH_HANDED || st == DDH_EXITED) && e->parent == me) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static struct ddh_entry *ddh_exited(void) {
|
||||
if (!g_ddh) return NULL;
|
||||
pid_t me = getpid();
|
||||
for (int i = 0; i < DDH_SLOTS; i++) {
|
||||
struct ddh_entry *e = &g_ddh->e[i];
|
||||
if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) == DDH_EXITED && e->parent == me) return e;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// A worker that is gone with no status from the app (it crashed with the app): reported as killed.
|
||||
static void ddh_check_gone(void) {
|
||||
if (!g_ddh) return;
|
||||
pid_t me = getpid();
|
||||
for (int i = 0; i < DDH_SLOTS; i++) {
|
||||
struct ddh_entry *e = &g_ddh->e[i];
|
||||
if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) != DDH_HANDED || e->parent != me) continue;
|
||||
if (syscall(SYS_kill, e->real, 0) == 0 || errno != ESRCH) continue;
|
||||
if (e->pad[0] == 0) {
|
||||
e->pad[0] = 1; // give the app time to write the status
|
||||
continue;
|
||||
}
|
||||
if (++e->pad[0] > 50) {
|
||||
e->status = SIGKILL;
|
||||
__atomic_store_n(&e->state, DDH_EXITED, __ATOMIC_RELEASE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void ddh_release(struct ddh_entry *e, int *status) {
|
||||
if (status) *status = e->status;
|
||||
memset(e, 0, offsetof(struct ddh_entry, state));
|
||||
e->status = 0;
|
||||
e->reaped = 0;
|
||||
e->pad[0] = 0;
|
||||
__atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE);
|
||||
}
|
||||
|
||||
typedef pid_t (*ddh_wait4_f)(pid_t, int *, int, struct rusage *);
|
||||
|
||||
static ddh_wait4_f ddh_real_wait4(void) {
|
||||
static ddh_wait4_f f;
|
||||
if (!f) f = (ddh_wait4_f)dlsym(RTLD_NEXT, "wait4");
|
||||
return f;
|
||||
}
|
||||
|
||||
static int ddh_nap(void) {
|
||||
struct timespec ts = {0, 20 * 1000 * 1000};
|
||||
return nanosleep(&ts, NULL);
|
||||
}
|
||||
|
||||
static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) {
|
||||
ddh_wait4_f real = ddh_real_wait4();
|
||||
if (!real) {
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
}
|
||||
if (!g_ddh) return real(pid, status, options, ru);
|
||||
for (;;) {
|
||||
ddh_check_gone();
|
||||
struct ddh_entry *e = pid > 0 ? ddh_find(pid) : NULL;
|
||||
if (pid > 0 && e) {
|
||||
if (!e->reaped && real(pid, NULL, WNOHANG, NULL) == pid) e->reaped = 1;
|
||||
if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) == DDH_EXITED) {
|
||||
if (ru) memset(ru, 0, sizeof(*ru));
|
||||
ddh_release(e, status);
|
||||
return pid;
|
||||
}
|
||||
if (options & WNOHANG) return 0;
|
||||
if (ddh_nap() != 0) return -1;
|
||||
continue;
|
||||
}
|
||||
if (pid <= 0 && (e = ddh_exited())) {
|
||||
pid_t child = e->child;
|
||||
if (!e->reaped && real(child, NULL, WNOHANG, NULL) == child) e->reaped = 1;
|
||||
if (ru) memset(ru, 0, sizeof(*ru));
|
||||
ddh_release(e, status);
|
||||
return child;
|
||||
}
|
||||
int live = pid <= 0 && ddh_any_live();
|
||||
int wstatus = 0;
|
||||
pid_t r = real(pid, &wstatus, live ? options | WNOHANG : options, ru);
|
||||
if (r > 0) {
|
||||
struct ddh_entry *h = ddh_find(r);
|
||||
if (h && !h->reaped) {
|
||||
h->reaped = 1; // the forked child that handed its program off
|
||||
continue;
|
||||
}
|
||||
if (status) *status = wstatus;
|
||||
return r;
|
||||
}
|
||||
if (!live) return r;
|
||||
if (r < 0 && errno != ECHILD) return r;
|
||||
if (options & WNOHANG) return 0;
|
||||
if (ddh_nap() != 0) return -1;
|
||||
}
|
||||
}
|
||||
|
||||
pid_t wait4(pid_t pid, int *status, int options, struct rusage *ru) { return ddh_wait(pid, status, options, ru); }
|
||||
pid_t waitpid(pid_t pid, int *status, int options) { return ddh_wait(pid, status, options, NULL); }
|
||||
pid_t wait(int *status) { return ddh_wait(-1, status, 0, NULL); }
|
||||
pid_t wait3(int *status, int options, struct rusage *ru) { return ddh_wait(-1, status, options, ru); }
|
||||
|
||||
int waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) {
|
||||
typedef int (*f_t)(idtype_t, id_t, siginfo_t *, int);
|
||||
static f_t real;
|
||||
if (!real) real = (f_t)dlsym(RTLD_NEXT, "waitid");
|
||||
if (!real) {
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
}
|
||||
if (!g_ddh || !(options & WEXITED) || (idtype != P_PID && idtype != P_ALL) || !ddh_any_live())
|
||||
return real(idtype, id, info, options);
|
||||
// Only exits are asked for here: answer through ddh_wait and describe the result as waitid does.
|
||||
int status = 0;
|
||||
pid_t r = ddh_wait(idtype == P_PID ? (pid_t)id : -1, &status, options & WNOHANG, NULL);
|
||||
if (r < 0) return -1;
|
||||
if (info) {
|
||||
memset(info, 0, sizeof(*info));
|
||||
if (r > 0) {
|
||||
info->si_signo = SIGCHLD;
|
||||
info->si_pid = r;
|
||||
info->si_code = WIFEXITED(status) ? CLD_EXITED : CLD_KILLED;
|
||||
info->si_status = WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int kill(pid_t pid, int sig) {
|
||||
if (g_ddh && pid > 0) {
|
||||
struct ddh_entry *e = ddh_find(pid);
|
||||
if (e && __atomic_load_n(&e->state, __ATOMIC_ACQUIRE) == DDH_HANDED) pid = e->real;
|
||||
}
|
||||
return (int)syscall(SYS_kill, pid, sig);
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
build/
|
||||
@@ -1,36 +0,0 @@
|
||||
<?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>
|
||||
@@ -1,47 +0,0 @@
|
||||
#!/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"
|
||||
|
||||
javac -nowarn --release 8 -cp "$platform/android.jar" -d "$work/classes" $(find "$here/src" -name '*.java') 2>&1 | grep -v "^warning\|^Note:" || true
|
||||
"$bt/d8$bat" --min-api 29 --lib "$platform/android.jar" --output "$work/dex" $(find "$work/classes" -name '*.class')
|
||||
|
||||
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"
|
||||
@@ -1,21 +0,0 @@
|
||||
// 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 <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
char buf[128] = "";
|
||||
ssize_t 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;
|
||||
}
|
||||
@@ -1,360 +0,0 @@
|
||||
// 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 <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;
|
||||
}
|
||||
|
||||
static void keep_binder_fds(void) {
|
||||
DIR *d = opendir("/proc/self/fd");
|
||||
if (!d) return;
|
||||
struct dirent *e;
|
||||
char path[64], target[256];
|
||||
while ((e = readdir(d)) != NULL) {
|
||||
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")) {
|
||||
fcntl(fd, F_SETFD, 0);
|
||||
__android_log_print(ANDROID_LOG_INFO, TAG, "keeping fd %d (%s) across exec", fd, target);
|
||||
}
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
if (keep) keep_binder_fds();
|
||||
execv(argv[0], argv);
|
||||
__android_log_print(ANDROID_LOG_ERROR, TAG, "execv %s failed: %s", argv[0], strerror(errno));
|
||||
}
|
||||
|
||||
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) {
|
||||
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 void probe_exec(void) {
|
||||
char *argv[] = {"/system/bin/true", NULL};
|
||||
int st = run_child(argv, -1);
|
||||
out("execve /system/bin/true: %s", st == 0 ? "ok" : (st >= 100 && st < 1000 ? strerror(st - 100) : "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", st == 0 ? "ok" : (st >= 100 && st < 1000 ? strerror(st - 100) : "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) {
|
||||
struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons(80)};
|
||||
inet_pton(AF_INET, "1.1.1.1", &a.sin_addr);
|
||||
if (connect(fd, (struct sockaddr *)&a, sizeof(a)) != 0) {
|
||||
out("fd%d tcp: connect %s", i, strerror(errno));
|
||||
return;
|
||||
}
|
||||
const char *req = "HEAD / HTTP/1.0\r\nHost: 1.1.1.1\r\n\r\n";
|
||||
write(fd, req, strlen(req));
|
||||
char resp[64] = "";
|
||||
ssize_t r = read(fd, resp, sizeof(resp) - 1);
|
||||
if (r > 0) resp[r] = 0;
|
||||
char *nl = strchr(resp, '\r');
|
||||
if (nl) *nl = 0;
|
||||
out("fd%d tcp: connected, got \"%s\"", i, r > 0 ? resp : strerror(errno));
|
||||
} 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 = read(fd, buf, sizeof(buf) - 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, st2 >= 100 && st2 < 1000 ? strerror(st2 - 100) : "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];
|
||||
pipe(pipefd);
|
||||
pid_t pid = fork();
|
||||
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 : "");
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class Iso extends LabService {}
|
||||
@@ -1,3 +0,0 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class IsoPlain extends LabService {}
|
||||
@@ -1,71 +0,0 @@
|
||||
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;
|
||||
|
||||
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");
|
||||
int[] fds = readFds(data);
|
||||
reply.writeString(Native.probe(what, fds));
|
||||
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 int[] readFds(Parcel data) {
|
||||
int n = data.readInt();
|
||||
int[] fds = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
ParcelFileDescriptor pfd = data.readFileDescriptor();
|
||||
fds[i] = pfd == null ? -1 : pfd.detachFd();
|
||||
}
|
||||
return fds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
Log.i(Main.TAG, getClass().getSimpleName() + " bound in pid " + Process.myPid() + " uid " + Process.myUid());
|
||||
return binder;
|
||||
}
|
||||
}
|
||||
@@ -1,239 +0,0 @@
|
||||
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.system.Os;
|
||||
import android.system.OsConstants;
|
||||
import android.util.Log;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileDescriptor;
|
||||
import java.io.FileOutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 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<Runnable>> pending = new HashMap<>();
|
||||
private static final Map<String, ServiceConnection> connections = new HashMap<>();
|
||||
private TextView text;
|
||||
private static final List<FileDescriptor> keep = new ArrayList<>();
|
||||
|
||||
@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);
|
||||
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, Runnable op) {
|
||||
if (binders.containsKey(target)) {
|
||||
op.run();
|
||||
return;
|
||||
}
|
||||
List<Runnable> q = pending.get(target);
|
||||
if (q != null) {
|
||||
q.add(op);
|
||||
return;
|
||||
}
|
||||
q = new ArrayList<>();
|
||||
q.add(op);
|
||||
pending.put(target, q);
|
||||
ServiceConnection conn = new ServiceConnection() {
|
||||
@Override
|
||||
public void onServiceConnected(ComponentName name, IBinder service) {
|
||||
log("connected " + target);
|
||||
binders.put(target, service);
|
||||
List<Runnable> ops = pending.remove(target);
|
||||
if (ops != null) for (Runnable r : ops) r.run();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onServiceDisconnected(ComponentName name) {
|
||||
log("DISCONNECTED " + target);
|
||||
binders.remove(target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindingDied(ComponentName name) {
|
||||
log("BINDING DIED " + target);
|
||||
}
|
||||
};
|
||||
connections.put(target, conn);
|
||||
Intent intent = new Intent(this, serviceClass(target));
|
||||
int flags = Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT;
|
||||
boolean ok;
|
||||
if (target.contains(":")) {
|
||||
ok = getApplicationContext().bindIsolatedService(intent, flags, target.replace(':', '_'), getMainExecutor(), conn);
|
||||
} else {
|
||||
ok = getApplicationContext().bindService(intent, conn, flags);
|
||||
}
|
||||
log("bind " + target + " -> " + ok);
|
||||
}
|
||||
|
||||
private Parcel call(String target, int code, Parcel data) throws Exception {
|
||||
Parcel reply = Parcel.obtain();
|
||||
binders.get(target).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, () -> {
|
||||
try {
|
||||
Parcel d = Parcel.obtain();
|
||||
d.writeInt(n);
|
||||
log(target + " spawned " + call(target, LabService.SPAWN, d).readInt());
|
||||
} catch (Exception e) {
|
||||
log(target + " spawn failed " + e);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "who":
|
||||
withBinder(target, () -> {
|
||||
try {
|
||||
log(target + " " + call(target, LabService.WHO, Parcel.obtain()).readString());
|
||||
} catch (Exception e) {
|
||||
log(target + " who failed " + e);
|
||||
}
|
||||
});
|
||||
return;
|
||||
case "exec": {
|
||||
String[] argv = intent.getStringExtra("argv").split("\\|");
|
||||
boolean keepBinder = intent.getIntExtra("keep", 1) != 0;
|
||||
withBinder(target, () -> {
|
||||
try {
|
||||
Parcel d = Parcel.obtain();
|
||||
d.writeStringArray(argv);
|
||||
d.writeInt(keepBinder ? 1 : 0);
|
||||
log(target + " exec in pid " + call(target, LabService.EXEC, d).readInt());
|
||||
} catch (Exception e) {
|
||||
log(target + " exec failed " + e);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "probe": {
|
||||
String what = intent.getStringExtra("what");
|
||||
List<ParcelFileDescriptor> fds = probeFds(intent.getStringExtra("fds"));
|
||||
withBinder(target, () -> {
|
||||
try {
|
||||
Parcel d = Parcel.obtain();
|
||||
d.writeString(what);
|
||||
d.writeInt(fds.size());
|
||||
for (ParcelFileDescriptor p : fds) d.writeFileDescriptor(p.getFileDescriptor());
|
||||
for (String line : call(target, LabService.PROBE, d).readString().split("\n")) log(target + " probe " + line);
|
||||
} catch (Exception e) {
|
||||
log(target + " probe failed " + e);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "unbind": {
|
||||
ServiceConnection c = connections.remove(target);
|
||||
binders.remove(target);
|
||||
if (c != null) getApplicationContext().unbindService(c);
|
||||
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 List<ParcelFileDescriptor> probeFds(String spec) throws Exception {
|
||||
List<ParcelFileDescriptor> out = new ArrayList<>();
|
||||
if (spec == null || spec.isEmpty()) return out;
|
||||
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);
|
||||
keep.add(fd);
|
||||
out.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);
|
||||
Os.write(a, "hello from main\n".getBytes(), 0, 16);
|
||||
keep.add(a);
|
||||
out.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());
|
||||
}
|
||||
}
|
||||
out.add(ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_WRITE));
|
||||
} else if (s.startsWith("path:")) {
|
||||
out.add(ParcelFileDescriptor.open(new File(s.substring(5)), ParcelFileDescriptor.MODE_READ_ONLY));
|
||||
} else if (s.equals("dir")) {
|
||||
out.add(ParcelFileDescriptor.open(getFilesDir(), ParcelFileDescriptor.MODE_READ_ONLY));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
import android.app.ZygotePreload;
|
||||
import android.content.pm.ApplicationInfo;
|
||||
|
||||
public class Preload implements ZygotePreload {
|
||||
@Override
|
||||
public void doPreload(ApplicationInfo appInfo) {
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class Proc extends LabService {}
|
||||
@@ -1,3 +0,0 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W0 extends LabService {}
|
||||
@@ -1,3 +0,0 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W1 extends LabService {}
|
||||
@@ -1,3 +0,0 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W2 extends LabService {}
|
||||
@@ -1,3 +0,0 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W3 extends LabService {}
|
||||
@@ -1,3 +0,0 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W4 extends LabService {}
|
||||
@@ -1,3 +0,0 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W5 extends LabService {}
|
||||
@@ -1,3 +0,0 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W6 extends LabService {}
|
||||
@@ -1,3 +0,0 @@
|
||||
package com.droiddeck.phantomlab;
|
||||
|
||||
public class W7 extends LabService {}
|
||||
@@ -1,164 +0,0 @@
|
||||
import json
|
||||
import os
|
||||
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"""
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
pid_t pid = fork();
|
||||
if (pid == 0) {
|
||||
execl("/bin/target", "target", argv[2], (char *)NULL);
|
||||
_exit(127);
|
||||
}
|
||||
int status = 0;
|
||||
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(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, fds, _, _ = socket.recv_fds(conn, 4, 256)
|
||||
length = struct.unpack(">I", header)[0]
|
||||
payload = b""
|
||||
while len(payload) < length:
|
||||
payload += conn.recv(length - len(payload))
|
||||
request = json.loads(payload)
|
||||
self.requests.append(request)
|
||||
table = fds[request["table"]]
|
||||
program = str(self.root) + request["file"]
|
||||
proc = subprocess.Popen(list(self.prefix) + [program] + request["argv"][1:])
|
||||
conn.sendall(b"pid %d\n" % proc.pid)
|
||||
conn.close()
|
||||
for fd in fds:
|
||||
if fd != table:
|
||||
os.close(fd)
|
||||
threading.Thread(target=self.report, args=(proc, table, request), daemon=True).start()
|
||||
|
||||
@staticmethod
|
||||
def report(proc, table, request):
|
||||
code = proc.wait()
|
||||
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"):
|
||||
name = "dd-handoff-test-%d-%s" % (os.getpid(), self.id().rsplit(".", 1)[-1])
|
||||
spawner = FakeSpawner(name, self.prefix or [], self.root)
|
||||
spawner.start()
|
||||
self.addCleanup(spawner.sock.close)
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook), "DD_SPAWN": name,
|
||||
"DD_HANDOFF": handoff}
|
||||
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_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,10 +34,7 @@ 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)
|
||||
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')
|
||||
script = "nap() { sleep \"$1\"; }\n" + match.group(0) + 'echo "ADDRESS=$DBUS_SESSION_BUS_ADDRESS"\nkill %1 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