Compare commits

...
18 changed files with 936 additions and 54 deletions

No files matched your search

+64
View File
@@ -481,5 +481,69 @@
<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" />
<service android:name=".runtime.GuestWorker64" android:exported="false" android:process=":g64" />
<service android:name=".runtime.GuestWorker65" android:exported="false" android:process=":g65" />
<service android:name=".runtime.GuestWorker66" android:exported="false" android:process=":g66" />
<service android:name=".runtime.GuestWorker67" android:exported="false" android:process=":g67" />
<service android:name=".runtime.GuestWorker68" android:exported="false" android:process=":g68" />
<service android:name=".runtime.GuestWorker69" android:exported="false" android:process=":g69" />
<service android:name=".runtime.GuestWorker70" android:exported="false" android:process=":g70" />
<service android:name=".runtime.GuestWorker71" android:exported="false" android:process=":g71" />
<service android:name=".runtime.GuestWorker72" android:exported="false" android:process=":g72" />
<service android:name=".runtime.GuestWorker73" android:exported="false" android:process=":g73" />
<service android:name=".runtime.GuestWorker74" android:exported="false" android:process=":g74" />
<service android:name=".runtime.GuestWorker75" android:exported="false" android:process=":g75" />
<service android:name=".runtime.GuestWorker76" android:exported="false" android:process=":g76" />
<service android:name=".runtime.GuestWorker77" android:exported="false" android:process=":g77" />
<service android:name=".runtime.GuestWorker78" android:exported="false" android:process=":g78" />
<service android:name=".runtime.GuestWorker79" android:exported="false" android:process=":g79" />
<service android:name=".runtime.GuestWorker80" android:exported="false" android:process=":g80" />
<service android:name=".runtime.GuestWorker81" android:exported="false" android:process=":g81" />
<service android:name=".runtime.GuestWorker82" android:exported="false" android:process=":g82" />
<service android:name=".runtime.GuestWorker83" android:exported="false" android:process=":g83" />
<service android:name=".runtime.GuestWorker84" android:exported="false" android:process=":g84" />
<service android:name=".runtime.GuestWorker85" android:exported="false" android:process=":g85" />
<service android:name=".runtime.GuestWorker86" android:exported="false" android:process=":g86" />
<service android:name=".runtime.GuestWorker87" android:exported="false" android:process=":g87" />
<service android:name=".runtime.GuestWorker88" android:exported="false" android:process=":g88" />
<service android:name=".runtime.GuestWorker89" android:exported="false" android:process=":g89" />
<service android:name=".runtime.GuestWorker90" android:exported="false" android:process=":g90" />
<service android:name=".runtime.GuestWorker91" android:exported="false" android:process=":g91" />
<service android:name=".runtime.GuestWorker92" android:exported="false" android:process=":g92" />
<service android:name=".runtime.GuestWorker93" android:exported="false" android:process=":g93" />
<service android:name=".runtime.GuestWorker94" android:exported="false" android:process=":g94" />
<service android:name=".runtime.GuestWorker95" android:exported="false" android:process=":g95" />
<service android:name=".runtime.GuestWorker96" android:exported="false" android:process=":g96" />
<service android:name=".runtime.GuestWorker97" android:exported="false" android:process=":g97" />
<service android:name=".runtime.GuestWorker98" android:exported="false" android:process=":g98" />
<service android:name=".runtime.GuestWorker99" android:exported="false" android:process=":g99" />
<service android:name=".runtime.GuestWorker100" android:exported="false" android:process=":g100" />
<service android:name=".runtime.GuestWorker101" android:exported="false" android:process=":g101" />
<service android:name=".runtime.GuestWorker102" android:exported="false" android:process=":g102" />
<service android:name=".runtime.GuestWorker103" android:exported="false" android:process=":g103" />
<service android:name=".runtime.GuestWorker104" android:exported="false" android:process=":g104" />
<service android:name=".runtime.GuestWorker105" android:exported="false" android:process=":g105" />
<service android:name=".runtime.GuestWorker106" android:exported="false" android:process=":g106" />
<service android:name=".runtime.GuestWorker107" android:exported="false" android:process=":g107" />
<service android:name=".runtime.GuestWorker108" android:exported="false" android:process=":g108" />
<service android:name=".runtime.GuestWorker109" android:exported="false" android:process=":g109" />
<service android:name=".runtime.GuestWorker110" android:exported="false" android:process=":g110" />
<service android:name=".runtime.GuestWorker111" android:exported="false" android:process=":g111" />
<service android:name=".runtime.GuestWorker112" android:exported="false" android:process=":g112" />
<service android:name=".runtime.GuestWorker113" android:exported="false" android:process=":g113" />
<service android:name=".runtime.GuestWorker114" android:exported="false" android:process=":g114" />
<service android:name=".runtime.GuestWorker115" android:exported="false" android:process=":g115" />
<service android:name=".runtime.GuestWorker116" android:exported="false" android:process=":g116" />
<service android:name=".runtime.GuestWorker117" android:exported="false" android:process=":g117" />
<service android:name=".runtime.GuestWorker118" android:exported="false" android:process=":g118" />
<service android:name=".runtime.GuestWorker119" android:exported="false" android:process=":g119" />
<service android:name=".runtime.GuestWorker120" android:exported="false" android:process=":g120" />
<service android:name=".runtime.GuestWorker121" android:exported="false" android:process=":g121" />
<service android:name=".runtime.GuestWorker122" android:exported="false" android:process=":g122" />
<service android:name=".runtime.GuestWorker123" android:exported="false" android:process=":g123" />
<service android:name=".runtime.GuestWorker124" android:exported="false" android:process=":g124" />
<service android:name=".runtime.GuestWorker125" android:exported="false" android:process=":g125" />
<service android:name=".runtime.GuestWorker126" android:exported="false" android:process=":g126" />
<service android:name=".runtime.GuestWorker127" android:exported="false" android:process=":g127" />
</application>
</manifest>
@@ -224,6 +224,70 @@ class GuestWorker60 : GuestWorker()
class GuestWorker61 : GuestWorker()
class GuestWorker62 : GuestWorker()
class GuestWorker63 : GuestWorker()
class GuestWorker64 : GuestWorker()
class GuestWorker65 : GuestWorker()
class GuestWorker66 : GuestWorker()
class GuestWorker67 : GuestWorker()
class GuestWorker68 : GuestWorker()
class GuestWorker69 : GuestWorker()
class GuestWorker70 : GuestWorker()
class GuestWorker71 : GuestWorker()
class GuestWorker72 : GuestWorker()
class GuestWorker73 : GuestWorker()
class GuestWorker74 : GuestWorker()
class GuestWorker75 : GuestWorker()
class GuestWorker76 : GuestWorker()
class GuestWorker77 : GuestWorker()
class GuestWorker78 : GuestWorker()
class GuestWorker79 : GuestWorker()
class GuestWorker80 : GuestWorker()
class GuestWorker81 : GuestWorker()
class GuestWorker82 : GuestWorker()
class GuestWorker83 : GuestWorker()
class GuestWorker84 : GuestWorker()
class GuestWorker85 : GuestWorker()
class GuestWorker86 : GuestWorker()
class GuestWorker87 : GuestWorker()
class GuestWorker88 : GuestWorker()
class GuestWorker89 : GuestWorker()
class GuestWorker90 : GuestWorker()
class GuestWorker91 : GuestWorker()
class GuestWorker92 : GuestWorker()
class GuestWorker93 : GuestWorker()
class GuestWorker94 : GuestWorker()
class GuestWorker95 : GuestWorker()
class GuestWorker96 : GuestWorker()
class GuestWorker97 : GuestWorker()
class GuestWorker98 : GuestWorker()
class GuestWorker99 : GuestWorker()
class GuestWorker100 : GuestWorker()
class GuestWorker101 : GuestWorker()
class GuestWorker102 : GuestWorker()
class GuestWorker103 : GuestWorker()
class GuestWorker104 : GuestWorker()
class GuestWorker105 : GuestWorker()
class GuestWorker106 : GuestWorker()
class GuestWorker107 : GuestWorker()
class GuestWorker108 : GuestWorker()
class GuestWorker109 : GuestWorker()
class GuestWorker110 : GuestWorker()
class GuestWorker111 : GuestWorker()
class GuestWorker112 : GuestWorker()
class GuestWorker113 : GuestWorker()
class GuestWorker114 : GuestWorker()
class GuestWorker115 : GuestWorker()
class GuestWorker116 : GuestWorker()
class GuestWorker117 : GuestWorker()
class GuestWorker118 : GuestWorker()
class GuestWorker119 : GuestWorker()
class GuestWorker120 : GuestWorker()
class GuestWorker121 : GuestWorker()
class GuestWorker122 : GuestWorker()
class GuestWorker123 : GuestWorker()
class GuestWorker124 : GuestWorker()
class GuestWorker125 : GuestWorker()
class GuestWorker126 : GuestWorker()
class GuestWorker127 : GuestWorker()
/** The pool of [GuestWorker] processes, and the socket guests ask it through (`droiddeck-spawn`). */
object GuestWorkers {
@@ -250,7 +314,28 @@ object GuestWorkers {
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,
GuestWorker63::class.java, GuestWorker64::class.java, GuestWorker65::class.java,
GuestWorker66::class.java, GuestWorker67::class.java, GuestWorker68::class.java,
GuestWorker69::class.java, GuestWorker70::class.java, GuestWorker71::class.java,
GuestWorker72::class.java, GuestWorker73::class.java, GuestWorker74::class.java,
GuestWorker75::class.java, GuestWorker76::class.java, GuestWorker77::class.java,
GuestWorker78::class.java, GuestWorker79::class.java, GuestWorker80::class.java,
GuestWorker81::class.java, GuestWorker82::class.java, GuestWorker83::class.java,
GuestWorker84::class.java, GuestWorker85::class.java, GuestWorker86::class.java,
GuestWorker87::class.java, GuestWorker88::class.java, GuestWorker89::class.java,
GuestWorker90::class.java, GuestWorker91::class.java, GuestWorker92::class.java,
GuestWorker93::class.java, GuestWorker94::class.java, GuestWorker95::class.java,
GuestWorker96::class.java, GuestWorker97::class.java, GuestWorker98::class.java,
GuestWorker99::class.java, GuestWorker100::class.java, GuestWorker101::class.java,
GuestWorker102::class.java, GuestWorker103::class.java, GuestWorker104::class.java,
GuestWorker105::class.java, GuestWorker106::class.java, GuestWorker107::class.java,
GuestWorker108::class.java, GuestWorker109::class.java, GuestWorker110::class.java,
GuestWorker111::class.java, GuestWorker112::class.java, GuestWorker113::class.java,
GuestWorker114::class.java, GuestWorker115::class.java, GuestWorker116::class.java,
GuestWorker117::class.java, GuestWorker118::class.java, GuestWorker119::class.java,
GuestWorker120::class.java, GuestWorker121::class.java, GuestWorker122::class.java,
GuestWorker123::class.java, GuestWorker124::class.java, GuestWorker125::class.java,
GuestWorker126::class.java, GuestWorker127::class.java,
)
private class Slot(val index: Int) {
@@ -35,9 +35,40 @@ object LegacyNames {
@Synchronized
fun migrateEtc(root: File) {
for ((old, new) in LINKED_DIRS) moveAndLink(File(root, old), File(root, new))
File(root, "etc/droiddeck/empty").mkdirs()
clearEmptyStandIn(root)
File(root, NO_THERMAL).mkdirs()
}
/**
* It stands in for /sys/bus/pci/devices, and libpci exits the whole process on an entry it cannot
* parse; older builds let thermal bind mount points leak into it. The guest can write here, so a
* link is never followed: one in place of the folder is removed, and one above it stops the cleanup.
*/
private fun clearEmptyStandIn(root: File) {
val linkedAbove = listOf("etc", "etc/droiddeck").firstOrNull { Files.isSymbolicLink(File(root, it).toPath()) }
if (linkedAbove != null) {
Log.w(TAG, "not clearing the empty stand-in: $linkedAbove is a link")
return
}
val empty = File(root, "etc/droiddeck/empty")
if (Files.isSymbolicLink(empty.toPath())) runCatching { Files.delete(empty.toPath()) }
.onFailure { Log.w(TAG, "could not remove the link at $empty", it); return }
empty.mkdirs()
empty.listFiles()?.forEach { entry ->
runCatching { deleteWithoutFollowing(entry.toPath()) }.onFailure { Log.w(TAG, "could not clear $entry", it) }
}
}
private fun deleteWithoutFollowing(path: java.nio.file.Path) {
if (Files.isDirectory(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)) {
Files.newDirectoryStream(path).use { entries -> entries.forEach(::deleteWithoutFollowing) }
}
Files.deleteIfExists(path)
}
/** Stands in for a /sys/class/thermal the kernel won't list; proot adds the bound zones' mount points to it. */
const val NO_THERMAL = "etc/droiddeck/no-thermal"
@Synchronized
fun migrateRootfs(root: File) {
migrateEtc(root)
@@ -248,7 +248,7 @@ public final class LinuxRuntime {
// A kernel that refuses to list /sys/class/thermal (Pixel 10, Android 17) made mangoapp abort
// at start ("filesystem_error ... Permission denied: '/sys/class/thermal/'") until its
// wrapper gave up: it lists the directory for CPU temperatures. Empty there instead.
if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/class/thermal");
if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, LegacyNames.NO_THERMAL).getPath() + ":/sys/class/thermal");
bind(cmd, context.getFilesDir().getPath());
bind(cmd, context.getCacheDir().getPath());
bind(cmd, liveDir(context).getPath());
@@ -41,8 +41,73 @@ internal fun FrameGenMenu(
val colors = MaterialTheme.colorScheme
val engines = listOf(FrameGen.ENGINE_LSFG to "LSFG", FrameGen.ENGINE_DDFG to "DDFG")
if (legacyButtons) {
val context = LocalContext.current
val options = buildList {
add(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier))
(2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_DDFG, it)) }
(2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, it)) }
FrameGen.ADAPTIVE_TARGETS.forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it)) }
}
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, bottom = 8.dp)) {
options.forEachIndexed { index, option ->
val selected = mode == option ||
(option.engine == FrameGen.ENGINE_OFF && selectedEngine == null)
val enabled = option.engine != FrameGen.ENGINE_LSFG || lossless.ready || selected
val pick = { onPick(option) }
OutlinedButton(
onClick = pick,
enabled = enabled,
modifier = (if (index == 0) focusModifier else Modifier).fillMaxWidth()
.padding(top = if (index == 0) 0.dp else 6.dp)
.controllerConfirm(enabled = enabled, onClick = pick),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selected) colors.primary else colors.onSurface,
),
) { Text(FrameGen.label(context, option)) }
}
if (selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) {
Text(
need.orEmpty(),
color = colors.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 6.dp),
)
}
if (gameProfileId != null) {
val resetGame = onResetGame
OutlinedButton(
onClick = resetGame,
modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
.controllerConfirm(onClick = resetGame),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
) {
Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓")
}
}
if (lossless.owned) {
val using = when (lossless.source) {
Lossless.Source.STEAM -> stringResource(R.string.lsfg_using_steam)
Lossless.Source.IMPORT -> stringResource(R.string.lsfg_using_import)
Lossless.Source.NONE -> null
}
OutlinedButton(
onClick = onImportLossless,
modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
.controllerConfirm(onClick = onImportLossless),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
) {
Text(stringResource(R.string.lsfg_import) + (using?.let { " · $it" } ?: ""))
}
}
}
return
}
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 0.dp, bottom = 8.dp)) {
if (!legacyButtons) OutlinedButton(
OutlinedButton(
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
modifier = Modifier.fillMaxWidth().controllerConfirm(
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
@@ -54,7 +119,7 @@ internal fun FrameGenMenu(
),
) { Text(offLabel) }
Row(Modifier.fillMaxWidth().then(if (legacyButtons) Modifier else Modifier.padding(top = 8.dp)), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
val focusIndex = engines.indexOfFirst { (engine, _) ->
selectedEngine == engine || engine != FrameGen.ENGINE_LSFG || lossless.ready
}
@@ -887,6 +887,34 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
val steamCard: (@Composable (Modifier) -> Unit)? = if (game != null && steamScope != null) { m ->
Box(m) { GameSettingsCard(host, game, steamScope) }
} else null
val frameGenMenuContent: @Composable () -> Unit = {
FrameGenMenu(
mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen,
lossless = s.lossless,
onPick = { mode ->
val key = frameGenProfileKey
if (key == null) {
a.onFrameGenPick(mode)
} else {
com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode)
gameFrameGenMode = mode
gameFrameGenOverride = true
}
},
onImportLossless = a.onImportLossless,
legacyButtons = true,
gameProfileId = frameGenProfileKey,
hasGameOverride = gameFrameGenOverride,
onResetGame = {
val key = frameGenProfileKey
if (key != null) {
com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key)
gameFrameGenMode = com.droiddeck.launcher.gpu.FrameGen.mode(context)
gameFrameGenOverride = false
}
},
)
}
val cards = if (game?.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER) listOfNotNull(steamCard) else buildList<@Composable (Modifier) -> Unit> {
add { m ->
val back = stringResource(R.string.hop_from_games)
@@ -908,33 +936,7 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
) {
host.open = if (host.open == "fg") null else "fg"
}
if (host.open == "fg") FrameGenMenu(
mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen,
lossless = s.lossless,
onPick = { mode ->
val key = frameGenProfileKey
if (key == null) {
a.onFrameGenPick(mode)
} else {
com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode)
gameFrameGenMode = mode
gameFrameGenOverride = true
}
},
onImportLossless = a.onImportLossless,
legacyButtons = true,
gameProfileId = frameGenProfileKey,
hasGameOverride = gameFrameGenOverride,
onResetGame = {
val key = frameGenProfileKey
if (key != null) {
com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key)
gameFrameGenMode =
com.droiddeck.launcher.gpu.FrameGen.mode(context)
gameFrameGenOverride = false
}
}
)
}
}
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
@@ -966,6 +968,11 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
}
}
if (host.open == "fg") {
Box(Modifier.fillMaxWidth().padding(top = 4.dp)) {
frameGenMenuContent()
}
}
}
}
@@ -2,7 +2,10 @@ package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
@@ -12,8 +15,30 @@ internal fun FrameGenGroup(s: FrontEndState, a: FrontEndActions) {
SettingsGroup(stringResource(R.string.frame_gen_title)) {
SettingsRow(stringResource(R.string.frame_gen_title), stringResource(R.string.frame_gen_hint), highlighted = host.open == "fg") {
Box {
ValueChip(s.frameGenLabel, host.open == "fg") { host.open = if (host.open == "fg") null else "fg" }
if (host.open == "fg") FrameGenMenu(s.frameGen, s.lossless, a.onFrameGenPick, a.onImportLossless)
val open = host.open == "fg"
ValueChip(s.frameGenLabel, open) { host.open = if (open) null else "fg" }
AnchoredMenu(
open = open,
onDismiss = { if (host.open == "fg") host.open = null },
title = stringResource(R.string.frame_gen_title),
compact = true,
minWidth = 220.dp,
) { firstItemFocus ->
FrameGenMenu(
mode = s.frameGen,
lossless = s.lossless,
onPick = { mode ->
a.onFrameGenPick(mode)
host.open = null
},
onImportLossless = {
a.onImportLossless()
host.open = null
},
focusModifier = Modifier.focusRequester(firstItemFocus),
legacyButtons = true,
)
}
}
}
}
@@ -35,6 +35,37 @@ class LegacyNamesTest {
assertEquals("droiddeck", link("etc/bannerlator"))
}
@Test fun theEmptyStandInIsEmptiedAndThermalZonesGetTheirOwn() {
write("etc/droiddeck/empty/thermal_zone26/temp", "")
LegacyNames.migrateEtc(root)
assertEquals(emptyList<String>(), File(root, "etc/droiddeck/empty").list()!!.toList())
assertTrue(File(root, LegacyNames.NO_THERMAL).isDirectory)
}
@Test fun clearingTheEmptyStandInRemovesLinksWithoutTouchingWhatTheyPointAt() {
write("home/keep/file", "kept")
val links = File(root, "etc/droiddeck/empty").apply { mkdirs() }
val made = runCatching {
Files.createSymbolicLink(File(links, "dir").toPath(), File(root, "home/keep").toPath())
Files.createSymbolicLink(File(links, "dangling").toPath(), File(root, "missing").toPath())
}.isSuccess
org.junit.Assume.assumeTrue("this file system cannot make symbolic links", made)
LegacyNames.migrateEtc(root)
assertEquals(emptyList<String>(), links.list()!!.toList())
assertEquals("kept", File(root, "home/keep/file").readText())
}
@Test fun aLinkInPlaceOfTheEmptyStandInIsReplacedWithoutTouchingItsTarget() {
write("home/keep/file", "kept")
val empty = File(root, "etc/droiddeck/empty").also { it.parentFile!!.mkdirs() }
val made = runCatching { Files.createSymbolicLink(empty.toPath(), File(root, "home/keep").toPath()) }.isSuccess
org.junit.Assume.assumeTrue("this file system cannot make symbolic links", made)
LegacyNames.migrateEtc(root)
assertFalse(Files.isSymbolicLink(empty.toPath()))
assertEquals(emptyList<String>(), empty.list()!!.toList())
assertEquals("kept", File(root, "home/keep/file").readText())
}
@Test fun aFreshRuntimeGetsNoOldNames() {
write("usr/local/bin/droiddeck-session", "new")
LegacyNames.migrateRootfs(root)
+53 -3
View File
@@ -172,7 +172,7 @@ 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
Declare a pool of `android:process` services (`:g0`…`:g127`). 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:
@@ -262,8 +262,29 @@ vfork-safe (Python's subprocess execs under `vfork`). Details that mattered:
session (KDE Plasma, 17–19 counted at rest), a Konsole running 40 `sleep 600 &` jobs peaked at
61 counted and lost 27 processes to Android's limit (Konsole, D-Bus, the portal) before this, and
at 20 with no kills after. Still counted, and not handed off: a terminal's foreground jobs (a
`make -j` and its compilers), the D-Bus daemon's activation helpers (forks that never exec) and
the desktop's own programs started by KDE's launchers.
`make -j` and its compilers) and the D-Bus daemon's activation helpers (forks that never exec).
- **The desktop.** Plasma's own programs are listed (`startplasma-wayland`, `plasma_session`,
KWin, `kded6`, `ksmserver`, `plasmashell`, PowerDevil, KDE Connect, the KIO workers, the D-Bus
activated portal, dconf and activity manager) along with DroidDeck's desktop helpers. Discover's
update notifier, GeoClue's demo agent and the global-menu proxy are off in the user's Autostart.
A program a desktop launcher starts (`DD_HANDOFF_LAUNCHERS`: Plasma's shell, KRunner, Dolphin)
goes to a worker when it is a plain fork and exec: in the launcher's process group and session,
with no controlling terminal. Those launchers are Qt programs, which wait with `waitpid()` once
the hook has taken their pidfds away. A terminal's shell (its own session and terminal) stays.
Firefox runs with fission off, at most two web content processes and no crash helper. The
desktop and its apps use about 80 workers with Steam and a game running, hence 128.
Counted children on the Thor (main: the session as #3338 and #3594 left it):
| | main | this |
|---|---|---|
| desktop at rest | 30 | 0 |
| Dolphin, Konsole, Firefox, Kate and System Settings open | not measured (49 on a Pocket FIT without Firefox, the terminal running 40 jobs) | 7 |
| those, the desktop's Steam client and Bully running | not measured | 20 (30 with 64 workers: Wine's services were refused one) |
With Bully running, six scans forced with the stock limit of 32 killed nothing. What stays
counted then: Steam's client and launch chain (10), Firefox's helpers (6), Konsole's shell,
Proton's script and `wineserver`.
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`.
@@ -510,6 +531,35 @@ the old behavior and the old requirement.
7. A (the isolated tier) only if B stops working on a future Android; it needs a file and socket
broker and keeps the GPU outside.
## Zombies
Every session process is a child subreaper (`tools/linuxfs/preload/subreaper.c`, so that a
double-forked Xwayland is not left to init, which some vendor kernels kill), and most programs
never wait for a child they did not fork. What they adopted stayed a zombie: the grandchildren of
Qt's `startDetached()` under Plasma's shell, KWin and kaccess, Wine's double-forked processes,
wlroots' Xwayland under gamescope. A parent that never waits at all (Plasma's shell, for what it
launches) also kept the forked child of each program it handed off. On the Thor, main had 4
zombies in Steam mode at rest and 19 in Bully, and the desktop gained one per app closed.
The hook now reaps them from SIGCHLD (`ddh_reap_unclaimed()`):
- **Adopted:** each process records, at its pid, the parent that started it and its own start
time, in one file for the session (`DD_PARENTS`). A fork's child does it at the fork, any other
program at its start. A zombie child whose record names another parent was adopted. An own child
(recorded with this parent, or with no record, such as a static program a `vfork()` started) is
left for its program's wait.
- **A handed-off program's forked child,** as a wait's look reaps it: the program's exit stays in
the table for the parent's wait.
The program's SIGCHLD action runs first, and `sigaction()` shows it as the program set it.
`SIG_IGN` and `SA_NOCLDWAIT` stay the kernel's. A program that leaves SIGCHLD alone gets the
handler only when `DD_REAP_ADOPTED` names it (Plasma's programs, D-Bus, gamescope, Wine's
launchers, Decky's loader): with a handler, `poll()`, `sleep()` and the like return `EINTR` when a
child exits. With these changes there are no zombies left in either mode, Bully included.
qemu-user has no `PR_SET_CHILD_SUBREAPER`, so the adoption tests skip under it (CI) and were run on
the Thor's kernel.
## Robustness
- Gap 1's path mismatch is a bug that could be fixed; the app-zygote skip is deliberate. Use app
+7
View File
@@ -87,6 +87,11 @@ static const char *rewrite_path(const char *path, char *out, size_t size) {
return path;
}
// The native hook's SIGCHLD handling (hook/signals.c) is not part of this shim: its programs record their
// first parent for the session's subreapers, and reap nothing themselves.
static void ddnatv_manage_sigchld(void) {}
static void ddh_reap_unclaimed(void) __attribute__((unused));
#include "../nativeguest/hook/kept.c"
#include "../nativeguest/hook/handoff.c"
@@ -315,12 +320,14 @@ pid_t fork(void) {
}
ddh_prepare();
pid_t forker = (pid_t)syscall(SYS_gettid);
pid_t forking = (pid_t)syscall(SYS_getpid);
pid_t pid = orig_fork();
if (pid == 0) {
kept_forked();
kept_close_forked();
ddh_drop_worker_binder();
ddh_forked(forker);
ddh_record_parent((pid_t)syscall(SYS_getpid), forking);
} else if (pid > 0) {
ddh_child_created(pid, 1);
}
+12 -4
View File
@@ -9,7 +9,7 @@ export MOZ_ENABLE_WAYLAND=1 MOZ_USE_XINPUT2=1
export SHELL=/bin/bash
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
export MOZ_SHM_NO_SEALS=1
export MOZ_SHM_NO_SEALS=1 MOZ_CRASHREPORTER_DISABLE=1
export QTWEBENGINE_DISABLE_SANDBOX=1
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
export KWIN_USE_OVERLAYS=0
@@ -142,11 +142,10 @@ Exec=konsole -e /usr/local/bin/droiddeck-steam-x64
Icon=steam
Categories=System;
ENTRY
python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'
( while sleep 30; do python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'; done ) &
python3 /usr/local/bin/droiddeck-pad-defaults --every 30 &
python3 /usr/local/bin/droiddeck-desktop-gpu 2>&1 | sed 's/^/[gpu] /'
/usr/local/bin/droiddeck-desktop-window-rules 2>&1 | sed 's/^/[rules] /'
( python3 /usr/local/bin/droiddeck-library-perms 2>&1 | sed 's/^/[perms] /' ) &
python3 /usr/local/bin/droiddeck-library-perms 2>&1 &
mkdir -p /usr/local/share/applications
cat > /usr/local/share/applications/droiddeck-ime.desktop <<'ENTRY'
[Desktop Entry]
@@ -175,6 +174,15 @@ fi
if command -v flatpak >/dev/null 2>&1 && [ ! -d /var/lib/pacman ]; then
FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo >/dev/null 2>&1 &
fi
# Android counts the desktop's programs against an app's limit of 32. Off unless the user turns them
# back on in Autostart: Discover's update notifier (the packages follow DroidDeck's releases, and it
# keeps PackageKit running as root), GeoClue's demo agent (nothing asks for a location) and the
# global-menu proxy (the panel has no global menu).
mkdir -p "$HOME/.config/autostart"
for entry in org.kde.discover.notifier geoclue-demo-agent gmenudbusmenuproxy; do
[ -e "$HOME/.config/autostart/$entry.desktop" ] ||
printf '[Desktop Entry]\nType=Application\nName=%s\nHidden=true\n' "$entry" > "$HOME/.config/autostart/$entry.desktop"
done
skel_done=$HOME/.local/share/droiddeck/skel-copied
if [ -d /etc/skel ] && [ ! -e "$skel_done" ]; then
cp -rn /etc/skel/. "$HOME/" 2>/dev/null
@@ -9,3 +9,11 @@ pref("datareporting.policy.dataSubmissionEnabled", false);
pref("browser.aboutwelcome.enabled", false);
pref("browser.startup.homepage", "about:blank");
pref("layout.css.devPixelsPerPx", "1.25");
// Android counts each of Firefox's processes against the app's limit of 32: one web content process
// per two tabs' worth of sites rather than one per site, none started ahead, and extensions and
// about: pages in the processes that already exist.
pref("fission.autostart", false);
pref("dom.ipc.processCount", 2);
pref("dom.ipc.processPrelaunch.enabled", false);
pref("browser.tabs.remote.separatePrivilegedContentProcess", false);
pref("extensions.webextensions.remote", false);
@@ -1,6 +1,8 @@
#!/usr/bin/python3
import glob
import os
import sys
import time
HOME = os.environ.get("HOME", "/root")
CONFIG = os.environ.get("XDG_CONFIG_HOME", os.path.join(HOME, ".config"))
@@ -1048,8 +1050,19 @@ def switch_emulators():
print(f"droiddeck-pad-defaults: {name}: Player 1 on the controller ({cfg})")
for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch, switch_emulators):
try:
step()
except Exception as e:
print(f"droiddeck-pad-defaults: {step.__name__}: {e}")
def run_all():
for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch, switch_emulators):
try:
step()
except Exception as e:
print(f"droiddeck-pad-defaults: {step.__name__}: {e}", flush=True)
# --every SECONDS: again at that interval, for emulators set up while the desktop runs. One process
# for the whole desktop session rather than a shell loop starting a new one each time.
sys.stdout.reconfigure(line_buffering=True)
run_all()
if len(sys.argv) == 3 and sys.argv[1] == "--every":
while True:
time.sleep(float(sys.argv[2]))
run_all()
@@ -63,9 +63,16 @@ dd_job() {
# window's app by walking its process's parents) or its utility processes (the client only accepts
# its transport from its own children).
if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ]; then
export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver}
export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver:droiddeck-login1:droiddeck-snapd:droiddeck-polkitd:droiddeck-root+/usr/libexec/packagekitd:droiddeck-desktop-clipboard:droiddeck-ime:droiddeck-pad-defaults+--every:droiddeck-library-perms:droiddeck-clipboard:dbus-run-session:startplasma-wayland:plasma_session:kwin_wayland_wrapper:kwin_wayland:kded6:ksmserver:kglobalacceld:plasmashell:krunner:org_kde_powerdevil:xembedsniproxy:kaccess:xsettingsd:kdeconnectd:kunifiedpush-distributor:kactivitymanagerd:xdg-desktop-portal-kde:dconf-service:polkit-kde-authentication-agent-1:plasma-welcome:kioworker}
# The programs these start for the user (an app from the panel, a file opened in Dolphin)
export DD_HANDOFF_LAUNCHERS=${DD_HANDOFF_LAUNCHERS-plasmashell:krunner:dolphin}
# Each process's first parent, so that a process can reap the zombies it adopts as a subreaper, and
# the programs that reap them even while they leave SIGCHLD alone (hook/signals.c)
rm -f /run/droiddeck-parents.* 2>/dev/null
export DD_PARENTS=/run/droiddeck-parents.$$
export DD_REAP_ADOPTED=${DD_REAP_ADOPTED-plasmashell:plasma_session:kwin_wayland:kwin_wayland_wrapper:kaccess:ksmserver:kded6:krunner:dolphin:dbus-daemon:startplasma-wayland:gamescope:wine:wine64:wine-preloader:wine64-preloader:wineserver:PluginLoader:PluginLoader.real}
else
unset DD_HANDOFF
unset DD_HANDOFF DD_HANDOFF_LAUNCHERS DD_PARENTS DD_REAP_ADOPTED
fi
steam_setup_failed() {
echo "== steam: the Steam client could not be set up (status $1)"
+2
View File
@@ -661,12 +661,14 @@ pid_t fork(void) {
}
ddh_prepare();
pid_t forker = (pid_t)syscall(SYS_gettid);
pid_t forking = (pid_t)syscall(SYS_getpid);
pid_t pid = orig_fork();
if (pid == 0) {
kept_forked();
kept_close_forked();
ddh_drop_worker_binder();
ddh_forked(forker);
ddh_record_parent((pid_t)syscall(SYS_getpid), forking);
} else if (pid > 0) {
ddh_child_created(pid, 1);
}
+189 -2
View File
@@ -878,6 +878,9 @@ static void ddh_apply_inherited(void) {
}
}
static void ddh_open_parents(void);
static void ddh_record_own_parent(void);
__attribute__((constructor)) static void ddh_init(void) {
ddh_apply_inherited();
ddh_find_worker_binder();
@@ -885,6 +888,9 @@ __attribute__((constructor)) static void ddh_init(void) {
ddh_find_parent_table();
// tests only: as when the table could not be made here, and the first fork makes it
if (!getenv("DDH_TEST_LATE_TABLE")) ddh_prepare();
ddh_open_parents();
ddh_record_own_parent();
ddnatv_manage_sigchld();
}
static int ddh_has_arg(char *const argv[], const char *prefix, size_t len) {
@@ -1274,6 +1280,30 @@ static int ddh_job_control_job(void) {
return ddh_waiter(parent) && (pid_t)syscall(SYS_getpgid, 0) != (pid_t)syscall(SYS_getpgid, parent);
}
// Whether this is a program a desktop launcher starts for the user (DD_HANDOFF_LAUNCHERS names the
// launchers: Plasma's shell, KRunner, Dolphin): a plain fork and exec, still in the launcher's process
// group and session, with no controlling terminal. Those launchers are Qt programs, which wait with
// waitpid() once they have no pidfds (privileged.c), so the program's exit reaches them. A child the
// launcher set up as a terminal's (a session and a terminal of its own) stays its own child.
static int ddh_launched(const char *filename, char *const argv[], char *const envp[]) {
const char *list = ddh_env(envp, "DD_HANDOFF_LAUNCHERS");
if (!list || !*list || ddh_exec_stub(filename) || ddh_pressure_keeps(filename, argv)) return 0;
pid_t parent = (pid_t)syscall(SYS_getppid);
char path[48], name[32];
snprintf(path, sizeof(path), "/proc/%d/comm", (int)parent);
if (ddh_read_proc(path, name, sizeof(name)) <= 0) return 0;
name[strcspn(name, "\n")] = 0;
if (!ddh_listed(list, name, NULL)) return 0;
if ((pid_t)syscall(SYS_getpgid, 0) != (pid_t)syscall(SYS_getpgid, parent) ||
(pid_t)syscall(SYS_getsid, 0) != (pid_t)syscall(SYS_getsid, parent))
return 0;
// /dev/tty opens only for a process with a controlling terminal
int tty = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/dev/tty",
O_RDONLY | O_NOCTTY | O_NONBLOCK | O_CLOEXEC, 0, 0, 0);
if (tty >= 0) syscall(SYS_close, tty);
return tty < 0;
}
static int ddh_pressed(const char *filename, char *const argv[], char *const envp[]) {
if (ddh_exec_stub(filename) || ddh_pressure_keeps(filename, argv) || !ddh_waiter((pid_t)syscall(SYS_getppid))) return 0;
// Not a job in the foreground of its controlling terminal: a handed-off program has none (the
@@ -1302,7 +1332,11 @@ static void ddh_debug(char *const envp[], const char *what, const char *filename
struct ddh_buf b = {line, 0, sizeof(line) - 1};
ddh_puts(&b, "ddnatv handoff: ");
ddh_putint(&b, getpid());
ddh_puts(&b, " ");
ddh_puts(&b, " (parent ");
ddh_putint(&b, (long)syscall(SYS_getppid));
ddh_puts(&b, ", session ");
ddh_putint(&b, (long)syscall(SYS_getsid, 0));
ddh_puts(&b, ") ");
ddh_puts(&b, what);
ddh_puts(&b, " ");
ddh_puts(&b, filename ? filename : "?");
@@ -1364,7 +1398,8 @@ static void ddh_try_as(const char *filename, char *const argv[], char *const env
ddh_debug(envp, "a job-control job:", filename);
return;
}
if (!ddh_program_listed(list, match_file, match_argv) && !ddh_pressed(match_file, match_argv, envp)) {
if (!ddh_program_listed(list, match_file, match_argv) && !ddh_launched(match_file, match_argv, envp) &&
!ddh_pressed(match_file, match_argv, envp)) {
ddh_debug(envp, "not listed:", filename);
return;
}
@@ -1644,6 +1679,158 @@ static int32_t ddh_gen_of(const struct ddh_entry *e, pid_t child) {
return (st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN) && e->child == child ? gen : 0;
}
// ---- children no wait will come for ------------------------------------------------------------
//
// Every session process is a child subreaper (tools/linuxfs/preload/subreaper.c): a process whose
// parent exits goes to its nearest ancestor in the session, not to init, which some vendor kernels
// kill. Most programs never wait for a child they did not fork, so what they adopt stays a zombie (the
// grandchildren of Qt's startDetached() under Plasma's shell, KWin and kaccess). Each process records
// here, at its pid, the parent that started it and its own start time (DD_PARENTS, one file for the
// session): a zombie whose record names another parent was adopted.
static uint64_t *g_ddh_parents;
static void ddh_open_parents(void) {
const char *name = getenv("DD_PARENTS");
if (!name || !*name || __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE)) return;
char path[PATH_MAX];
const char *real = rewrite_path(name, path, sizeof(path));
int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)real,
O_RDWR | O_CREAT | O_CLOEXEC, 0600, 0, 0);
if (fd < 0) return;
size_t size = (size_t)DDH_FORKS * sizeof(uint64_t);
struct stat st;
if (call_orig_syscall(SYS_fstat, (unsigned long)fd, (unsigned long)&st, 0, 0, 0, 0) == 0 && (size_t)st.st_size < size)
call_orig_syscall(SYS_ftruncate, (unsigned long)fd, size, 0, 0, 0, 0);
// past the file's end a page would fault (SIGBUS): mapped only once the file has its size
void *map = MAP_FAILED;
if (call_orig_syscall(SYS_fstat, (unsigned long)fd, (unsigned long)&st, 0, 0, 0, 0) == 0 && (size_t)st.st_size >= size)
map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
syscall(SYS_close, fd);
if (map == MAP_FAILED) return;
uint64_t *none = NULL;
if (!__atomic_compare_exchange_n(&g_ddh_parents, &none, (uint64_t *)map, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE))
munmap(map, size);
}
static uint64_t ddh_parent_record(pid_t parent, long start) { return (uint64_t)(uint32_t)parent << 32 | (uint32_t)start; }
static void ddh_record_parent(pid_t me, pid_t parent) {
uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE);
if (!map || me <= 0) return;
int saved = errno;
long start = ddh_start_time(me);
errno = saved;
if (start > 0) __atomic_store_n(&map[(uint32_t)me % DDH_FORKS], ddh_parent_record(parent, start), __ATOMIC_RELEASE);
}
// At a program's start, unless its fork recorded it: the child of a vfork(), of glibc's own
// posix_spawn() (popen(), system()) or of a raw clone() records the parent it has now, which is
// still the one that started it (a vfork()'s waits for the exec).
static void ddh_record_own_parent(void) {
uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE);
if (!map) return;
pid_t me = (pid_t)syscall(SYS_getpid);
int saved = errno;
long start = ddh_start_time(me);
errno = saved;
if (start <= 0) return;
uint64_t r = __atomic_load_n(&map[(uint32_t)me % DDH_FORKS], __ATOMIC_ACQUIRE);
if ((uint32_t)r == (uint32_t)start && r >> 32) return;
__atomic_store_n(&map[(uint32_t)me % DDH_FORKS], ddh_parent_record((pid_t)syscall(SYS_getppid), start), __ATOMIC_RELEASE);
}
// /proc/PID/stat's state and start time, from a signal handler: 0 when it cannot be read.
static int ddh_proc_state(pid_t pid, char *state, long *start, pid_t *ppid) {
char path[48] = "/proc/", digits[16], stat[512];
int n = 0, len = 6;
for (unsigned int v = (unsigned int)pid; v || !n; v /= 10) digits[n++] = (char)('0' + v % 10);
while (n) path[len++] = digits[--n];
memcpy(path + len, "/stat", 6);
int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC, 0, 0, 0);
if (fd < 0) return 0;
long got = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)stat, sizeof(stat) - 1, 0, 0, 0);
call_orig_syscall(SYS_close, (unsigned long)fd, 0, 0, 0, 0, 0);
if (got <= 0) return 0;
stat[got] = 0;
char *p = strrchr(stat, ')');
if (!p || p[1] != ' ' || !p[2]) return 0;
*state = p[2];
// ") S PPID": field 4; starttime is field 22
long parent = 0;
for (const char *q = p + 4; *q >= '0' && *q <= '9'; q++) parent = parent * 10 + (*q - '0');
*ppid = (pid_t)parent;
for (int field = 2; p && field < 22; field++) p = strchr(p + 1, ' ');
long t = 0;
for (const char *q = p ? p + 1 : ""; *q >= '0' && *q <= '9'; q++) t = t * 10 + (*q - '0');
*start = t;
return 1;
}
// Reaps child if no wait will come for it: the forked child of a handed-off program (its program's
// exit stays in the table for the program's own waits, as when a wait reaps it), or a child this
// process adopted. 1 when it did.
static int ddh_reap_unwaited(pid_t me, pid_t child) {
char state = 0;
long start = 0;
pid_t ppid = 0;
if (!ddh_proc_state(child, &state, &start, &ppid) || state != 'Z' || ppid != me) return 0;
struct ddh_entry *e = ddh_find(child);
int32_t gen = e ? ddh_gen_of(e, child) : 0;
if (gen) {
if (ddh_reaped(e) || call_orig_syscall(SYS_wait4, (unsigned long)child, 0, WNOHANG, 0, 0, 0) != child) return 0;
ddh_mark_reaped(e, gen);
return 1;
}
uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE);
uint64_t r = map ? __atomic_load_n(&map[(uint32_t)child % DDH_FORKS], __ATOMIC_ACQUIRE) : 0;
if (!r || (uint32_t)r != (uint32_t)start || (pid_t)(r >> 32) == me || !(r >> 32)) return 0;
return call_orig_syscall(SYS_wait4, (unsigned long)child, 0, WNOHANG, 0, 0, 0) == child;
}
// From the SIGCHLD handler (signals.c): the zombies among this process's children that no wait will
// come for. The kernel names one zombie at a time; past one the program will reap itself, /proc.
static void ddh_reap_unclaimed(void) {
if (!__atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE) && !__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) return;
int saved = errno;
pid_t me = (pid_t)call_orig_syscall(SYS_getpid, 0, 0, 0, 0, 0, 0);
// past 64 reaped this way, the rest from /proc too
int scan = 1;
for (int i = 0; i < 64; i++) {
siginfo_t si;
memset(&si, 0, sizeof(si));
if (call_orig_syscall(SYS_waitid, P_ALL, 0, (unsigned long)&si, WEXITED | WNOHANG | WNOWAIT, 0, 0) != 0 || si.si_pid <= 0) {
scan = 0;
break;
}
if (!ddh_reap_unwaited(me, si.si_pid)) {
break;
}
}
int dir = scan ? (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/proc",
O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0, 0) : -1;
char buf[2048];
while (dir >= 0) {
long n = call_orig_syscall(SYS_getdents64, (unsigned long)dir, (unsigned long)buf, sizeof(buf), 0, 0, 0);
if (n <= 0) break;
for (long off = 0; off < n;) {
struct ddh_reap_dirent {
uint64_t ino;
int64_t off;
unsigned short reclen;
unsigned char type;
char name[];
} *d = (struct ddh_reap_dirent *)(buf + off);
off += d->reclen;
long pid = 0;
const char *c = d->name;
for (; *c >= '0' && *c <= '9'; c++) pid = pid * 10 + (*c - '0');
if (!*c && pid > 0 && pid != me) ddh_reap_unwaited(me, (pid_t)pid);
}
}
if (dir >= 0) call_orig_syscall(SYS_close, (unsigned long)dir, 0, 0, 0, 0, 0);
errno = saved;
}
// Takes e's exit for one waiter (EXITED to TAKEN): 0 when another waiter has it.
static int ddh_take(struct ddh_entry *e) {
int expected = DDH_EXITED;
+84
View File
@@ -174,10 +174,83 @@ __attribute__((constructor(101))) static void install_sigsys_handler(void) {
real_sig(SIGSYS, &sa, NULL);
}
// SIGCHLD in a session with a parents file (handoff.c, DD_PARENTS): the program's action as it set it
// runs from ddnatv_sigchld_handler(), which then reaps the children no wait will come for
// (ddh_reap_unclaimed()). sigaction() shows the program its own action. A program that leaves SIGCHLD
// alone gets the handler only when DD_REAP_ADOPTED names it: with a handler, poll(), sleep() and the
// like return EINTR when a child exits, which a program that never had one may not expect.
static struct sigaction g_app_sigchld;
static int g_sigchld_managed;
static int g_sigchld_on_default;
static void ddh_reap_unclaimed(void);
static int ddh_listed(const char *list, const char *name, char *const argv[]);
static int ddnatv_apply_sigchld(int (*real_sig)(int, const struct sigaction *, struct sigaction *));
static void ddnatv_sigchld_handler(int sig, siginfo_t *info, void *ctx) {
struct sigaction app = g_app_sigchld;
if (app.sa_handler != SIG_DFL && app.sa_handler != SIG_IGN) {
if (app.sa_flags & SA_RESETHAND) {
// as the kernel would: the default from now on, with the handler only for a named program
g_app_sigchld.sa_handler = SIG_DFL;
g_app_sigchld.sa_flags &= ~(SA_SIGINFO | SA_RESETHAND);
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
int saved = errno;
if (real_sig) ddnatv_apply_sigchld(real_sig);
errno = saved;
}
if (app.sa_flags & SA_SIGINFO) app.sa_sigaction(sig, info, ctx);
else app.sa_handler(sig);
}
ddh_reap_unclaimed();
}
// Puts g_app_sigchld into effect: as it is where the kernel reaps every child itself (SIG_IGN,
// SA_NOCLDWAIT) or the program wants no handler and is not named, else through the handler above.
static int ddnatv_apply_sigchld(int (*real_sig)(int, const struct sigaction *, struct sigaction *)) {
const struct sigaction *app = &g_app_sigchld;
int handler = app->sa_handler != SIG_DFL && app->sa_handler != SIG_IGN;
if (app->sa_handler == SIG_IGN || (app->sa_flags & SA_NOCLDWAIT) || (!handler && !g_sigchld_on_default))
return real_sig(SIGCHLD, app, NULL);
struct sigaction k;
memset(&k, 0, sizeof(k));
k.sa_sigaction = ddnatv_sigchld_handler;
k.sa_mask = app->sa_mask;
k.sa_flags = SA_SIGINFO | (handler ? (app->sa_flags & ~(SA_SIGINFO | SA_RESETHAND)) : (SA_RESTART | SA_NOCLDSTOP));
return real_sig(SIGCHLD, &k, NULL);
}
static int ddnatv_sigchld_action(int (*real_sig)(int, const struct sigaction *, struct sigaction *),
const struct sigaction *act, struct sigaction *oldact) {
struct sigaction prev = g_app_sigchld;
if (act) {
g_app_sigchld = *act;
if (ddnatv_apply_sigchld(real_sig) != 0) {
int err = errno;
g_app_sigchld = prev;
errno = err;
return -1;
}
}
if (oldact) *oldact = prev;
return 0;
}
// From the hook's start (handoff.c), once the parents file is open
static void ddnatv_manage_sigchld(void) {
if (!getenv("DD_PARENTS")) return;
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
if (!real_sig || real_sig(SIGCHLD, NULL, &g_app_sigchld) != 0) return;
const char *named = getenv("DD_REAP_ADOPTED");
g_sigchld_on_default = named && ddh_listed(named, program_invocation_short_name, NULL);
if (ddnatv_apply_sigchld(real_sig) == 0) g_sigchld_managed = 1;
}
int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact) {
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
if (!real_sig) return -1;
if (signum == SIGCHLD && g_sigchld_managed) return ddnatv_sigchld_action(real_sig, act, oldact);
if (signum == SIGSYS) {
if (act && act->sa_sigaction == ddnatv_sigsys_handler) {
return real_sig(signum, act, oldact);
@@ -192,6 +265,7 @@ int rt_sigaction(int signum, const struct sigaction *act, struct sigaction *olda
static int (*orig_rt_sigaction)(int, const struct sigaction *, struct sigaction *, size_t) = NULL;
if (!orig_rt_sigaction) orig_rt_sigaction = (int (*)(int, const struct sigaction *, struct sigaction *, size_t))dlsym(RTLD_NEXT, "rt_sigaction");
if (signum == SIGCHLD && g_sigchld_managed) return sigaction(signum, act, oldact);
if (signum == SIGSYS) {
if (act && act->sa_sigaction == ddnatv_sigsys_handler) {
return orig_rt_sigaction ? orig_rt_sigaction(signum, act, oldact, sigsetsize) : 0;
@@ -210,6 +284,16 @@ typedef void (*sighandler_t)(int);
sighandler_t signal(int signum, sighandler_t handler) {
static sighandler_t (*orig_signal)(int, sighandler_t) = NULL;
if (!orig_signal) orig_signal = (sighandler_t (*)(int, sighandler_t))dlsym(RTLD_NEXT, "signal");
if (signum == SIGCHLD && g_sigchld_managed) {
// glibc's signal(): BSD semantics
struct sigaction act, old;
memset(&act, 0, sizeof(act));
act.sa_handler = handler;
act.sa_flags = SA_RESTART;
sigemptyset(&act.sa_mask);
sigaddset(&act.sa_mask, SIGCHLD);
return sigaction(SIGCHLD, &act, &old) == 0 ? old.sa_handler : SIG_ERR;
}
if (signum == SIGSYS) {
struct sigaction act, old;
memset(&act, 0, sizeof(act));
+212 -4
View File
@@ -1025,6 +1025,19 @@ int main(int argc, char **argv) {
errno = 0;
printf("intmin\t%d\n", (int)waitpid(-2147483647 - 1, &status, WNOHANG) == -1 && errno == ESRCH);
}
if (strcmp(argv[1], "nowait") == 0) {
// no wait until the program has long exited, as Plasma's shell never waits for what it launches
usleep(2000000);
char path[64], line[256] = "";
snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid);
FILE *f = fopen(path, "r");
if (f) {
if (!fgets(line, sizeof(line), f)) line[0] = 0;
fclose(f);
}
char *s = strrchr(line, ')');
printf("zombie\t%d\n", s && s[1] == ' ' && s[2] == 'Z');
}
int group = strcmp(argv[1], "group") == 0;
if (group) {
setpgid(pid, pid);
@@ -1139,6 +1152,93 @@ int main(void) {
}
"""
# A child subreaper, as every session process is (preload/subreaper.c), that never waits for a child
# it did not fork. adopt: a child that exits at once leaves a grandchild, which exits once the child is
# gone; own: its own child, which it waits for only later; vfork: one vfork() made, its program static
# (no hook, so no record of it); handler: as adopt, with a SIGCHLD handler of its own; ignore: SIGCHLD
# ignored, so the kernel reaps.
ORPHANS = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
static volatile sig_atomic_t calls;
static void counted(int sig) { (void)sig; calls++; }
static void nap(long ms) {
struct timespec t = {ms / 1000, (ms % 1000) * 1000000L};
while (nanosleep(&t, &t) != 0 && errno == EINTR) {}
}
static int zombie(pid_t pid) {
char path[64], line[256] = "";
snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid);
FILE *f = fopen(path, "r");
if (!f) return 0;
if (!fgets(line, sizeof(line), f)) line[0] = 0;
fclose(f);
char *s = strrchr(line, ')');
return s && s[1] == ' ' && s[2] == 'Z';
}
int main(int argc, char **argv) {
const char *mode = argv[1];
int subreaper = 0;
printf("subreaper\t%d\n", prctl(PR_SET_CHILD_SUBREAPER, 1) == 0 && prctl(PR_GET_CHILD_SUBREAPER, &subreaper) == 0 && subreaper);
fflush(stdout);
if (strcmp(mode, "handler") == 0) {
struct sigaction sa, seen;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = counted;
sa.sa_flags = SA_RESTART;
sigaction(SIGCHLD, &sa, NULL);
sigaction(SIGCHLD, NULL, &seen);
printf("view\t%d\n", seen.sa_handler == counted);
}
if (strcmp(mode, "ignore") == 0) signal(SIGCHLD, SIG_IGN);
if (strcmp(mode, "own") == 0 || strcmp(mode, "vfork") == 0) {
pid_t child = strcmp(mode, "vfork") == 0 ? vfork() : fork();
if (child == 0) {
if (argc > 2) execl(argv[2], "target", "7", (char *)NULL);
_exit(7);
}
nap(1500);
int status = 0;
pid_t r = waitpid(child, &status, 0);
printf("own\t%d\n", r == child && WIFEXITED(status) ? WEXITSTATUS(status) : -1);
return 0;
}
int pipefd[2];
if (pipe(pipefd) != 0) return 1;
pid_t middle = fork();
if (middle == 0) {
pid_t grandchild = fork();
if (grandchild == 0) {
nap(300); // its parent is gone by then
_exit(5);
}
if (write(pipefd[1], &grandchild, sizeof(grandchild)) != sizeof(grandchild)) _exit(1);
_exit(0);
}
pid_t grandchild = 0;
if (read(pipefd[0], &grandchild, sizeof(grandchild)) != sizeof(grandchild)) return 1;
int status = 0;
printf("middle\t%d\n", waitpid(middle, &status, 0) == middle);
nap(1500);
printf("orphan\t%d\n", zombie(grandchild));
printf("adopted\t%d\n", waitpid(grandchild, &status, WNOHANG) == grandchild);
if (strcmp(mode, "handler") == 0) printf("calls\t%d\n", calls > 0);
return 0;
}
"""
DUPRACE = r"""
#define _GNU_SOURCE
#include <fcntl.h>
@@ -1480,7 +1580,7 @@ class NativeHookHandoffTest(unittest.TestCase):
raise RuntimeError("workers that may still run: %s" % failed)
def run_parent(self, *argv, handoff="target", hook=True, reports=True, pressure=None, as_shell=False, terminal=False,
delay=0, extra_env=None):
delay=0, extra_env=None, parent_name=None):
name = "dd-handoff-test-%d-%s-%s-%d" % (os.getpid(), self.id().rsplit(".", 1)[-1], handoff, hook)
spawner = FakeSpawner(name, self.prefix or [], self.root, reports, delay)
spawner.start()
@@ -1496,9 +1596,9 @@ class NativeHookHandoffTest(unittest.TestCase):
hook_env["QEMU_LD_PREFIX"] = self.prefix[self.prefix.index("-L") + 1]
env = {k: v for k, v in os.environ.items() if k not in hook_env}
prefix, parent = list(self.prefix or []), str(self.parent)
if as_shell:
# the hook tells a shell's child by its parent's name (qemu-user takes the program's)
shell = Path(self.tmp.name) / ("shell-%s" % self.id().rsplit(".", 1)[-1]) / "bash"
if as_shell or parent_name:
# the hook tells a shell's or a launcher's child by its parent's name (qemu-user takes the program's)
shell = Path(self.tmp.name) / ("shell-%s" % self.id().rsplit(".", 1)[-1]) / (parent_name or "bash")
shell.parent.mkdir(exist_ok=True)
shutil.copy(parent, shell)
parent = str(shell)
@@ -1707,6 +1807,41 @@ class NativeHookHandoffTest(unittest.TestCase):
self.assertEqual([], requests)
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
def run_launcher(self, *argv, parent_name="plasmashell", **kwargs):
return self.run_parent(*argv, handoff="other", pressure=1000, parent_name=parent_name,
extra_env={"DD_HANDOFF_LAUNCHERS": "plasmashell:krunner"}, **kwargs)
def test_a_program_a_desktop_launcher_starts_is_handed_off(self):
# an app from Plasma's panel: unlisted, far from the limit, still its own app process
result, requests, out = self.run_launcher("wait", "7")
self.assertEqual(1, len(requests), out.stderr)
self.assertEqual(["target", "7"], requests[0]["argv"])
self.assertEqual("7", result.get("exit"), out.stdout)
def test_a_child_of_a_program_not_named_a_launcher_is_not(self):
result, requests, out = self.run_launcher("wait", "3", parent_name="konsole")
self.assertEqual([], requests, out.stderr)
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
def test_a_launchers_child_in_a_process_group_of_its_own_is_not(self):
result, requests, out = self.run_launcher("group", "4")
self.assertEqual([], requests, out.stderr)
self.assertEqual("4" if self.child_status == "3" else "127", result.get("exit"), out.stdout)
def test_a_launchers_child_on_a_terminal_is_not(self):
# a terminal's shell, set up by its launcher (Konsole's part in Dolphin): the terminal is its own
result, requests, out = self.run_launcher("wait", "3", terminal=True)
self.assertEqual([], requests, out.stderr)
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
def test_the_steam_client_a_launcher_starts_is_not(self):
steam = self.root / "bin/steam"
if not steam.exists():
shutil.copy(self.root / "bin/target", steam)
result, requests, out = self.run_launcher("wait", "3", "/bin/steam")
self.assertEqual([], requests, out.stderr)
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
def test_near_the_limit_a_child_of_another_program_is_not(self):
result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=0)
self.assertEqual([], requests)
@@ -2245,6 +2380,79 @@ class NativeHookHandoffTest(unittest.TestCase):
pass_fds=(table,))
return parent, dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line), out
def run_orphans(self, mode, named=True, parents=True, *args):
tmp = Path(self.tmp.name)
probe = tmp / "orphans"
if not probe.exists():
(tmp / "orphans.c").write_text(ORPHANS)
subprocess.run([self.cc, "-O1", "-o", str(probe), str(tmp / "orphans.c")], check=True)
(self.root / "run").mkdir(exist_ok=True)
env = {"LD_PRELOAD": str(self.hook), "DDNATV_ROOT": str(self.root)}
if parents:
env["DD_PARENTS"] = "/run/parents-%s" % self.id().rsplit(".", 1)[-1]
if named:
env["DD_REAP_ADOPTED"] = "other:orphans"
# not a session's own settings, when run inside one
inherited = {k: v for k, v in os.environ.items() if k not in ("DD_PARENTS", "DD_REAP_ADOPTED")}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in env.items() for arg in ("-E", f"{key}={value}")]
run_env = inherited
else:
cmd = []
run_env = dict(inherited, **env)
out = subprocess.run(cmd + [str(probe), mode, *args], env=run_env, capture_output=True, text=True, timeout=60)
result = dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line)
if mode == "adopt" and result.get("subreaper") != "1":
self.skipTest("no child subreaper here (qemu-user has no PR_SET_CHILD_SUBREAPER)")
return result, out
def test_a_subreaper_reaps_the_zombie_it_adopted(self):
result, out = self.run_orphans("adopt")
self.assertEqual(0, out.returncode, out.stderr)
self.assertEqual("1", result.get("middle"), out.stdout)
self.assertEqual("0", result.get("orphan"), out.stdout + out.stderr)
self.assertEqual("0", result.get("adopted"), out.stdout)
def test_a_program_not_named_keeps_its_default_sigchld_and_its_adopted_zombie(self):
result, out = self.run_orphans("adopt", False)
self.assertEqual("1", result.get("orphan"), out.stdout + out.stderr)
self.assertEqual("1", result.get("adopted"), out.stdout)
def test_without_a_parents_file_nothing_is_reaped(self):
result, out = self.run_orphans("adopt", True, False)
self.assertEqual("1", result.get("orphan"), out.stdout + out.stderr)
def test_a_subreapers_own_child_waits_for_its_wait(self):
result, out = self.run_orphans("own")
self.assertEqual("7", result.get("own"), out.stdout + out.stderr)
def test_a_vfork_child_with_no_record_waits_for_its_parents_wait(self):
result, out = self.run_orphans("vfork", True, True, "/bin/target")
self.assertEqual("7", result.get("own"), out.stdout + out.stderr)
def test_a_programs_own_sigchld_handler_runs_and_shows_as_its_own(self):
result, out = self.run_orphans("handler", False)
self.assertEqual("1", result.get("view"), out.stdout + out.stderr)
self.assertEqual("1", result.get("calls"), out.stdout)
if result.get("subreaper") == "1":
self.assertEqual("0", result.get("orphan"), out.stdout)
def test_an_ignored_sigchld_stays_the_kernels(self):
result, out = self.run_orphans("ignore")
self.assertEqual(0, out.returncode, out.stderr)
self.assertEqual("0", result.get("orphan"), out.stdout + out.stderr)
def test_an_unwaited_handoffs_child_is_reaped(self):
# a parent that never waits until its program has long exited, as Plasma's shell
(self.root / "run").mkdir(exist_ok=True)
env = {"DD_PARENTS": "/run/parents-nowait", "DD_REAP_ADOPTED": "parent"}
result, requests, out = self.run_parent("nowait", "6", extra_env=env)
self.assertEqual(1, len(requests), out.stderr)
self.assertEqual("0", result.get("zombie"), out.stdout + out.stderr)
# its program's exit, still there for the wait that comes at last
self.assertEqual("1", result.get("same"), out.stdout)
self.assertEqual("6", result.get("exit"), out.stdout)
def test_a_guest_sees_no_pidfd_support_so_its_waits_go_through_the_handoff(self):
parent, result, out = self.run_worker_program("pidfd", PIDFD_PROBE)
self.assertEqual(0, out.returncode, out.stderr)