diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 1986000ee7..82f8b019ef 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -36,6 +36,21 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] = diffed from `plugin-api/src` history (predates the dump; symbol-accurate). ### 26.43 — unreleased +- **breaking — A `ShellCommand` stops at its timeout or `cancel()`, with every process it started** _(ADFA-7178)_ + A timeout used to wait for the command to exit, and a stop killed only the command's own + process, never its children. Each command now runs in a process group of its own, and a + timeout, `cancel()` or `cancelAllCommands()` stops the whole group: SIGTERM, then SIGKILL + 250 ms later. `await()` returns within a second of the timeout, and a stopped command frees its slot. + On Android 11, whose `setsid` always forks, the IDE uses the Terminal's `setsid` instead, but + only if that one runs commands in place when the IDE first checks it. Where neither does, for + example because the Terminal isn't installed yet, commands get no group of their own until the + IDE's next start, and a stop leaves their children running, as before. + A command that exits on its own is never reported as timed out. If a background child still + holds its output 500 ms after the command exits, the child is stopped, and `await()` returns + within about 1.5 s of the exit. A command that exits before the IDE starts reading its output + is the exception: Java drains and closes the output as it exits, so such a child is not seen. + A child whose output goes elsewhere (`server >log 2>&1 &`) is left running, as is a process + that calls `setsid` itself. - **breaking — JavaScript highlighting and the IDE's grammar names are the IDE's** _(ADFA-7084)_ The IDE now highlights `js`, `mjs`, `cjs` and `jsx` itself. A `LanguageDefinition` can still claim them, but only with a language server: its grammar is ignored for them, and its server diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt index 23072e7655..e12df3bdd6 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImpl.kt @@ -7,20 +7,27 @@ import com.itsaky.androidide.plugins.extensions.CommandSpec import com.itsaky.androidide.plugins.services.CommandExecution import com.itsaky.androidide.plugins.services.IdeCommandService import com.itsaky.androidide.utils.TermuxProcessEnvironment +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.receiveAsFlow +import kotlinx.coroutines.joinAll import kotlinx.coroutines.launch -import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.runInterruptible +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import java.io.BufferedReader +import java.io.Closeable import java.io.File import java.io.IOException +import java.io.InputStream import java.io.InputStreamReader import java.nio.file.InvalidPathException import java.util.UUID @@ -32,6 +39,7 @@ class IdeCommandServiceImpl internal constructor( private val projectRootProvider: () -> File?, private val appFilesDir: File, private val gradleTaskRunner: GradleTaskRunner = GradleTaskRunner(IdeBuildServiceImpl.getInstance()::startTasks), + private val processGroups: ProcessGroups = ProcessGroups.android(File(appFilesDir, "usr/bin/setsid")), ) : IdeCommandService { private val runningCommands = ConcurrentHashMap() @@ -60,13 +68,14 @@ class IdeCommandServiceImpl internal constructor( } catch (e: IOException) { return RejectedCommandExecution(executionId, "Invalid working directory: ${e.message}") } + val command = processGroups.isolate(listOf(spec.executable) + spec.arguments, workDir) val processBuilder = try { - shellProcess(spec, workDir) + shellProcess(command.command, spec.environment, workDir) } catch (e: IllegalArgumentException) { return RejectedCommandExecution(executionId, "Invalid environment: ${e.message}") } - CommandExecutionImpl(executionId, processBuilder, timeoutMs) + CommandExecutionImpl(executionId, processBuilder::start, command.grouped, processGroups, timeoutMs) } } runningCommands[executionId] = execution @@ -75,12 +84,13 @@ class IdeCommandServiceImpl internal constructor( } private fun shellProcess( - spec: CommandSpec.ShellCommand, + command: List, + environment: Map, workDir: File?, ): ProcessBuilder = - ProcessBuilder(listOf(spec.executable) + spec.arguments).apply { + ProcessBuilder(command).apply { workDir?.let { directory(it) } - environment().putAll(spec.environment) + environment().putAll(environment) redirectErrorStream(false) TermuxProcessEnvironment.applyTo(environment(), appFilesDir) } @@ -131,15 +141,32 @@ internal interface RunningCommand : CommandExecution { fun isRunning(): Boolean } -private class CommandExecutionImpl( +/** + * A shell command. However it ends - on its own, by timing out, by [cancel], or with an error - + * nothing it started is left running and no thread is left reading its output, with two + * exceptions. A command that exits on its own with its output closed may leave a process behind on + * purpose, as `nohup server >log 2>&1 &` does. And a process that left the group with its own + * `setsid` is not stopped; on a desktop JVM, its reader is not freed either. + * + * @param startProcess starts the process, which is the leader of its own process group if [grouped]. + * @param outputGraceMs how long output may stay open once the command has exited. + */ +internal class CommandExecutionImpl( override val executionId: String, - private val processBuilder: ProcessBuilder, + private val startProcess: () -> Process, + private val grouped: Boolean, + private val processGroups: ProcessGroups, private val timeoutMs: Long, + private val outputGraceMs: Long = OUTPUT_GRACE_MS, ) : RunningCommand { private val outputChannel = Channel(capacity = Channel.UNLIMITED) private val resultDeferred = CompletableDeferred() private val scope = CoroutineScope(Dispatchers.IO + Job()) + + @Volatile private var process: Process? = null + + // Appended to by the reader threads, read by whichever thread ends the command. private val stdoutBuilder = StringBuilder() private val stderrBuilder = StringBuilder() @@ -153,97 +180,126 @@ private class CommandExecutionImpl( this.onComplete = onComplete scope.launch { val startTime = System.currentTimeMillis() - - runCatching { - withTimeout(timeoutMs) { - process = processBuilder.start() - val proc = process!! - - val stdoutJob = launch { readStream(proc, isStdErr = false) } - val stderrJob = launch { readStream(proc, isStdErr = true) } - - val exitCode = proc.waitFor() - stdoutJob.join() - stderrJob.join() - - outputChannel.send(CommandOutput.ExitCode(exitCode)) - outputChannel.close() - - val duration = System.currentTimeMillis() - startTime - if (exitCode == 0) { - CommandResult.Success(exitCode, stdoutBuilder.toString(), stderrBuilder.toString(), duration) - } else { - CommandResult.Failure(exitCode, stdoutBuilder.toString(), stderrBuilder.toString(), null, duration) - } + var started: Process? = null + var readers = emptyList() + var exitCode: Int? = null + var outputClosed = false + var cancelled = false + var error: Exception? = null + try { + withTimeoutOrNull(timeoutMs) { + // Recorded before the next suspension point, so that a cancel() landing while + // startProcess() ran, when there was no process yet to stop, has the finally below + // stop it (ADFA-7109). + val proc = startProcess() + started = proc + process = proc + readers = listOf(readLines(proc.inputStream, isStdErr = false), readLines(proc.errorStream, isStdErr = true)) + // Interruptible, so that the timeout and cancel() end the wait at once. + runInterruptible { proc.waitFor() } } - }.onSuccess { result -> - resultDeferred.complete(result) - }.onFailure { e -> - process?.destroyForcibly() - outputChannel.close() - val stdout = stdoutBuilder.toString() - val stderr = stderrBuilder.toString() - val duration = System.currentTimeMillis() - startTime - val failureResult = - when (e) { - is kotlinx.coroutines.TimeoutCancellationException -> { - CommandResult.Failure(-1, stdout, stderr, "Command timed out after ${timeoutMs}ms: ${e.message}", duration) - } - - is kotlinx.coroutines.CancellationException -> { - CommandResult.Cancelled(stdout, stderr) - } - - else -> { - CommandResult.Failure(-1, stdout, stderr, "Unexpected error: ${e.message}", duration) - } + // Read from the process, not the block's result: one that exits just as the time runs + // out ended on its own. + exitCode = started?.takeUnless { it.isAlive }?.exitValue() + if (exitCode != null) { + // Not under the timeout: the command has ended. A background child can hold the + // output open long after that, and is then stopped below. Unless no reader was in + // read() yet when the command exited: Process then drains the pipe and closes its + // end (ProcessPipeInputStream.processExited), so the output looks closed. + outputClosed = withTimeoutOrNull(outputGraceMs) { readers.joinAll() } != null + } + } catch (e: CancellationException) { + cancelled = true + } catch (e: Exception) { + error = e + } finally { + withContext(NonCancellable) { + started?.let { proc -> + if (exitCode == null || !outputClosed) processGroups.stop(proc, grouped) + // Ends the reads of any process that escaped the group or outlived the kill. + // A desktop JVM, where the unit tests run, does not wake a read on close. + closeQuietly(proc.inputStream, proc.errorStream, proc.outputStream) } - if (resultDeferred.isActive) { - resultDeferred.complete(failureResult) + withTimeoutOrNull(READERS_STOP_MS) { readers.joinAll() } } } + val stdout = snapshot(stdoutBuilder) + val stderr = snapshot(stderrBuilder) + val duration = System.currentTimeMillis() - startTime + val result = + when { + error != null -> CommandResult.Failure(-1, stdout, stderr, "Unexpected error: ${error.message}", duration) + exitCode == 0 -> CommandResult.Success(0, stdout, stderr, duration) + exitCode != null -> CommandResult.Failure(exitCode, stdout, stderr, null, duration) + cancelled -> CommandResult.Cancelled(stdout, stderr) + else -> CommandResult.Failure(-1, stdout, stderr, "Command timed out after ${timeoutMs}ms", duration) + } + exitCode?.let { outputChannel.trySend(CommandOutput.ExitCode(it)) } + outputChannel.close() + // First, so that a caller resuming from await() finds the slot free. onComplete() + // cancel() has already completed it with Cancelled. + resultDeferred.complete(result) } } - private suspend fun readStream( - process: Process, + private fun readLines( + stream: InputStream, isStdErr: Boolean, - ) { - val stream = if (isStdErr) process.errorStream else process.inputStream - val builder = if (isStdErr) stderrBuilder else stdoutBuilder - BufferedReader(InputStreamReader(stream)).use { reader -> - var line = reader.readLine() - while (line != null) { - if (builder.length + line.length <= MAX_OUTPUT_BYTES) { - builder.appendLine(line) + ): Job = + scope.launch { + val builder = if (isStdErr) stderrBuilder else stdoutBuilder + try { + BufferedReader(InputStreamReader(stream)).use { reader -> + while (true) { + val line = reader.readLine() ?: break + synchronized(builder) { + if (builder.length + line.length <= MAX_OUTPUT_BYTES) builder.appendLine(line) + } + outputChannel.trySend(if (isStdErr) CommandOutput.StdErr(line) else CommandOutput.StdOut(line)) + } } - val output = if (isStdErr) CommandOutput.StdErr(line) else CommandOutput.StdOut(line) - outputChannel.send(output) - line = reader.readLine() + } catch (e: IOException) { + // Closed under the read when the command was stopped. } } - } + + private fun snapshot(builder: StringBuilder): String = synchronized(builder) { builder.toString() } override suspend fun await(): CommandResult = resultDeferred.await() override fun cancel() { - process?.destroyForcibly() outputChannel.close() + // First, so that a caller resuming from await() finds the slot free. + onComplete() if (resultDeferred.isActive) { - resultDeferred.complete( - CommandResult.Cancelled(stdoutBuilder.toString(), stderrBuilder.toString()), - ) + resultDeferred.complete(CommandResult.Cancelled(snapshot(stdoutBuilder), snapshot(stderrBuilder))) } + // The command's coroutine stops the process and its group as it ends. scope.cancel() - onComplete() } override fun isRunning(): Boolean = process?.isAlive == true companion object { private const val MAX_OUTPUT_BYTES = 10 * 1024 * 1024 + + /** How long output may stay open once the command has exited. */ + const val OUTPUT_GRACE_MS = 500L + + /** How long a reader may take to end once the command is stopped and its output closed. */ + private const val READERS_STOP_MS = 500L + } +} + +private fun closeQuietly(vararg closeables: Closeable) { + for (closeable in closeables) { + try { + closeable.close() + } catch (e: IOException) { + // An InterruptedIOException here (ADFA-3945) only means a read was cut short. + } } } diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt new file mode 100644 index 0000000000..0620c96d26 --- /dev/null +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt @@ -0,0 +1,194 @@ +package com.itsaky.androidide.plugins.manager.services + +import android.system.ErrnoException +import android.system.Os +import android.system.OsConstants +import kotlinx.coroutines.delay +import org.slf4j.LoggerFactory +import java.io.File +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.TimeUnit + +/** A signal [ProcessGroups] sends. [PROBE] delivers nothing; it only asks whether the group exists. */ +internal enum class GroupSignal { PROBE, TERM, KILL } + +/** A command line, and whether it runs as the leader of a process group of its own. */ +internal data class GroupedCommand( + val command: List, + val grouped: Boolean, +) + +/** + * Runs each shell command as the leader of a process group of its own, so that stopping it stops + * every process it started, not only the one the IDE holds. Without a group, a command's children + * (`a | b`, `cmd &`, pip's build steps) outlive it. + * + * @param setsidPath the `setsid` program, one that runs its command in place (see [usableSetsid]), so + * the process the IDE holds becomes the group's leader and its process id the group's. Null where + * there is none: commands then share the IDE's group, and only their own process can be stopped. + * @param signal sends a [GroupSignal] to every process in group `pgid`, as `kill(-pgid, sig)` does. + * Returns false when no process is left in the group. + */ +internal class ProcessGroups( + private val setsidPath: String?, + private val signal: (pgid: Int, signal: GroupSignal) -> Boolean, +) { + /** [command], changed to run in a group of its own when that is possible. */ + fun isolate( + command: List, + workDir: File?, + ): GroupedCommand { + val setsid = setsidPath ?: return GroupedCommand(command, grouped = false) + // Without the program, start() fails as it always has, rather than setsid failing later. + val program = programPath(command.first(), workDir) ?: return GroupedCommand(command, grouped = false) + return GroupedCommand(listOf(setsid, program) + command.drop(1), grouped = true) + } + + /** + * Stops [process] and, if it is [grouped], every process in its group: SIGTERM first, so a + * command such as pip can clean up, then SIGKILL for whatever is still there [KILL_AFTER_MS] later. + */ + suspend fun stop( + process: Process, + grouped: Boolean, + ) { + val pgid = if (grouped) process.pidOrNull() else null + if (grouped && pgid == null) log.warn("No process id for a command's group; stopping only its own process") + var noGroupYet = false + if (pgid != null) { + var left = signal(pgid, GroupSignal.TERM) + // Expected only for a stop landing before setsid ran; otherwise setsid did not make a group. + noGroupYet = !left && process.isAlive + if (noGroupYet) log.warn("No process group {} yet; stopping the command's own process", pgid) + val deadline = System.nanoTime() + KILL_AFTER_MS * NANOS_PER_MILLI + while (left && System.nanoTime() < deadline) { + delay(POLL_MS) + left = signal(pgid, GroupSignal.PROBE) + } + if (left) signal(pgid, GroupSignal.KILL) + } + // Also the whole story where there is no group. + process.destroyForcibly() + // setsid may have run since the TERM found no group, and the command started children in it. + if (noGroupYet && pgid != null) signal(pgid, GroupSignal.KILL) + } + + companion object { + private val log = LoggerFactory.getLogger(ProcessGroups::class.java) + + const val KILL_AFTER_MS = 250L + private const val POLL_MS = 20L + private const val NANOS_PER_MILLI = 1_000_000L + + private const val ANDROID_SETSID = "/system/bin/setsid" + private const val ANDROID_SH = "/system/bin/sh" + private const val CHECK_TIMEOUT_S = 5L + + private val android = ConcurrentHashMap() + + /** + * Android's toybox `setsid`, or else [terminalSetsid], the util-linux one the Terminal installs, + * whichever first runs commands in place (see [usableSetsid]); and `kill(2)` through [Os]. + * Checked once per [terminalSetsid]. + */ + fun android(terminalSetsid: File): ProcessGroups = + android.computeIfAbsent(terminalSetsid.path) { + ProcessGroups(usableSetsid(listOf(ANDROID_SETSID, terminalSetsid.path), ANDROID_SH), ::osSignal) + } + + private fun osSignal( + pgid: Int, + signal: GroupSignal, + ): Boolean { + val number = + when (signal) { + GroupSignal.PROBE -> 0 + GroupSignal.TERM -> OsConstants.SIGTERM + GroupSignal.KILL -> OsConstants.SIGKILL + } + return try { + Os.kill(-pgid, number) + true + } catch (e: ErrnoException) { + // ESRCH: the group is empty. + false + } + } + + /** + * The first of [candidates] that runs its command in place, which is checked by running [shell] + * under it once; null, with a warning, if none does. Toybox's `setsid`, like util-linux's, forks + * only when its caller leads a group, which a [ProcessBuilder] child never does, except in + * Android 11: there it makes itself a group leader first, so it always forks and exits 0 at + * once. Every command would then seem to end as it started, and its group would not be the one + * the IDE holds. + */ + fun usableSetsid( + candidates: List, + shell: String, + ): String? { + val setsid = candidates.firstOrNull { File(it).canExecute() && runsInPlace(it, shell) } + if (setsid == null) log.warn("No setsid runs commands in place: a stop reaches only a command's own process ({})", candidates) + return setsid + } + + private fun runsInPlace( + setsid: String, + shell: String, + ): Boolean { + val inPlace = + runCatching { + val process = ProcessBuilder(setsid, shell, "-c", "echo \$\$").redirectErrorStream(true).start() + if (!process.waitFor(CHECK_TIMEOUT_S, TimeUnit.SECONDS)) { + process.destroyForcibly() + return@runCatching false + } + val printed = process.inputStream.bufferedReader().use { it.readLine() } + printed != null && printed.trim() == process.pidOrNull()?.toString() + }.getOrDefault(false) + if (!inPlace) log.warn("{} forks, so it is not used", setsid) + return inPlace + } + } +} + +/** + * Where [name] is, as [ProcessBuilder] finds it: a bare name in the IDE's own PATH, which it uses + * rather than the command's. `setsid` would search the command's, which puts Termux's first, so it + * is given the path. Null if there is no such program. + */ +private fun programPath( + name: String, + workDir: File?, +): String? { + val file = + when { + '/' !in name -> { + System + .getenv("PATH") + .orEmpty() + .split(':') + .filter { it.isNotEmpty() } + .map { File(it, name) } + .firstOrNull { it.isFile && it.canExecute() } + } + + File(name).isAbsolute -> { + File(name) + } + + else -> { + File(workDir ?: File("").absoluteFile, name) + } + } + return file?.takeIf { it.isFile && it.canExecute() }?.absolutePath +} + +/** + * The process id, which Android's API does not offer. Android's process class keeps it in a `pid` + * field, which Termux's `ShellUtils.getPid` reads too; a desktop JVM, where the unit tests run, has + * the `pid()` method instead. + */ +private fun Process.pidOrNull(): Int? = + runCatching { javaClass.getDeclaredField("pid").apply { isAccessible = true }.getInt(this) }.getOrNull() + ?: runCatching { (Process::class.java.getMethod("pid").invoke(this) as Long).toInt() }.getOrNull() diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt index ecbb1c891d..b3eec8c186 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeCommandServiceImplTest.kt @@ -2,33 +2,171 @@ package com.itsaky.androidide.plugins.manager.services import com.google.common.truth.Truth.assertThat import com.itsaky.androidide.plugins.PluginPermission +import com.itsaky.androidide.plugins.extensions.CommandOutput import com.itsaky.androidide.plugins.extensions.CommandResult import com.itsaky.androidide.plugins.extensions.CommandSpec +import com.itsaky.androidide.plugins.services.CommandExecution +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.After +import org.junit.Assert.assertThrows +import org.junit.Assume.assumeTrue import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.FileInputStream +import java.util.concurrent.CountDownLatch class IdeCommandServiceImplTest { @get:Rule val tmp = TemporaryFolder() + private val projectRoot by lazy { tmp.newFolder("project") } + private val filesDir by lazy { tmp.newFolder("files") } + private val pidFile by lazy { File(tmp.root, "pids") } + + /** Created by [releaseOnceReading] to end a script's [WAIT_FOR_RELEASE]. */ + private val releaseFile by lazy { File(tmp.root, "release") } + + /** `setsid` and `kill` from util-linux and procps, standing in for Android's toybox and [android.system.Os]. */ + private val hostGroups = ProcessGroups(SETSID, ::hostSignal) + + private fun hostSignal( + pgid: Int, + signal: GroupSignal, + ): Boolean { + val name = + when (signal) { + GroupSignal.PROBE -> "0" + GroupSignal.TERM -> "TERM" + GroupSignal.KILL -> "KILL" + } + return ProcessBuilder(KILL, "-s", name, "--", "-$pgid") + .redirectOutput(DEV_NULL) + .redirectError(DEV_NULL) + .start() + .waitFor() == 0 + } + + @After + fun killLeftovers() { + if (pidFile.exists()) { + for (pid in pidFile.readLines().mapNotNull { it.trim().toIntOrNull() }) { + ProcessBuilder(KILL, "-s", "KILL", "$pid").start().waitFor() + } + } + // A cancel returns before its readers end, so they must not count against the next test. + val deadline = System.currentTimeMillis() + 2_000 + while (readerThreads().isNotEmpty() && System.currentTimeMillis() < deadline) Thread.sleep(10) + } + + private fun service(processGroups: ProcessGroups = hostGroups) = + IdeCommandServiceImpl( + pluginId = "test.plugin", + permissions = setOf(PluginPermission.SYSTEM_COMMANDS), + projectRootProvider = { projectRoot }, + appFilesDir = filesDir, + processGroups = processGroups, + ) + private fun resultFor(workingDirectory: String): CommandResult = resultFor(CommandSpec.ShellCommand("true", workingDirectory = workingDirectory)) private fun resultFor(spec: CommandSpec): CommandResult { - val projectRoot = tmp.newFolder("project") - val service = - IdeCommandServiceImpl( - pluginId = "test.plugin", - permissions = setOf(PluginPermission.SYSTEM_COMMANDS), - projectRootProvider = { projectRoot }, - appFilesDir = tmp.newFolder("files"), - ) - val execution = service.executeCommand(spec, 5_000) + val execution = service(ProcessGroups.android(File(filesDir, "usr/bin/setsid"))).executeCommand(spec, 5_000) return runBlocking { execution.await() } } + /** + * `sh -c [script]`, where `$1` is [pidFile] for the script to write the ids of its processes to, + * and `$2` is [releaseFile]. + */ + private fun shell(script: String) = CommandSpec.ShellCommand("sh", listOf("-c", script, "sh", pidFile.path, releaseFile.path)) + + /** + * Lets a script that echoed `done` and ends in [WAIT_FOR_RELEASE] exit, once `done` has been read + * and both output readers are blocked in read() again, where they hold the output open. + */ + private fun CommandExecution.releaseOnceReading() { + runBlocking { withTimeout(5_000) { output.first { it == CommandOutput.StdOut("done") } } } + val deadline = System.currentTimeMillis() + 5_000 + while (Thread.getAllStackTraces().values.count { it.inReader() && it.inRead() } < 2) { + check(System.currentTimeMillis() < deadline) { "the output readers are not in read()" } + Thread.sleep(5) + } + releaseFile.createNewFile() + } + + private fun CommandExecution.awaitWithin(ms: Long): CommandResult = runBlocking { withTimeout(ms) { await() } } + + /** The [count] process ids the command wrote to [pidFile], once it has written them. */ + private fun pids(count: Int): List { + val deadline = System.currentTimeMillis() + 5_000 + while (System.currentTimeMillis() < deadline) { + val pids = if (pidFile.exists()) pidFile.readLines().mapNotNull { it.trim().toIntOrNull() } else emptyList() + if (pids.size >= count) return pids + Thread.sleep(10) + } + throw AssertionError("the command wrote no $count process ids to $pidFile") + } + + private fun alive(pid: Int): Boolean { + val stat = File("/proc/$pid/stat").takeIf { it.exists() }?.runCatching { readText() }?.getOrNull() ?: return false + // The state follows the parenthesised name; a zombie has exited. + return stat.substringAfterLast(") ").first() !in "ZX" + } + + /** Whether every process in [pids] is gone within [ms]. */ + private fun goneWithin( + pids: List, + ms: Long, + ): Boolean { + val deadline = System.currentTimeMillis() + ms + while (pids.any(::alive)) { + if (System.currentTimeMillis() > deadline) return false + Thread.sleep(10) + } + return true + } + + /** Whether every command's output reader has ended within [ms]. A cancel returns before they do. */ + private fun readersGoneWithin(ms: Long): Boolean { + val deadline = System.currentTimeMillis() + ms + while (readerThreads().isNotEmpty()) { + if (System.currentTimeMillis() > deadline) return false + Thread.sleep(10) + } + return true + } + + /** Threads still in a command's output reader. */ + private fun readerThreads(): List = + Thread + .getAllStackTraces() + .filterValues { it.inReader() } + .keys + .map { it.name } + + private fun Array.inReader(): Boolean { + val reader = "${CommandExecutionImpl::class.java.name}\$readLines" + return any { it.className.startsWith(reader) } + } + + /** Blocked reading a pipe, inside the process stream's lock that its exit has to take to close it. */ + private fun Array.inRead(): Boolean = any { it.className == FileInputStream::class.java.name } + + private fun assumeHostTools() = + assumeTrue( + "needs util-linux setsid and procps kill", + File(SETSID).canExecute() && File(KILL).canExecute(), + ) + @Test fun `a working directory with a NUL character fails the command`() { val result = resultFor("sub\u0000dir") @@ -52,4 +190,333 @@ class IdeCommandServiceImplTest { assertThat(result).isInstanceOf(CommandResult.Failure::class.java) assertThat((result as CommandResult.Failure).error).startsWith("Invalid environment") } + + @Test + fun `a command past its timeout is stopped with every process it started`() { + assumeHostTools() + val started = System.currentTimeMillis() + + val result = service().executeCommand(shell(CHILDREN_SCRIPT), 1_000).awaitWithin(10_000) + + assertThat(System.currentTimeMillis() - started).isLessThan(2_000) + assertThat(result).isInstanceOf(CommandResult.Failure::class.java) + assertThat((result as CommandResult.Failure).error).isEqualTo("Command timed out after 1000ms") + assertThat(pids(CHILDREN_SCRIPT_PIDS).filter(::alive)).isEmpty() + assertThat(readerThreads()).isEmpty() + } + + @Test + fun `cancel stops the command and every process it started`() { + assumeHostTools() + val execution = service().executeCommand(shell(CHILDREN_SCRIPT), 60_000) + val pids = pids(CHILDREN_SCRIPT_PIDS) + + execution.cancel() + + assertThat(execution.awaitWithin(1_000)).isInstanceOf(CommandResult.Cancelled::class.java) + assertThat(readersGoneWithin(1_000)).isTrue() + assertThat(goneWithin(pids, 1_000)).isTrue() + } + + @Test + fun `cancel while the process is starting stops it once it has started`() { + assumeHostTools() + val starting = CountDownLatch(1) + val release = CountDownLatch(1) + val script = "sleep 600 & echo \$! >> \"\$1\"; echo \$\$ >> \"\$1\"; wait" + val execution = + CommandExecutionImpl( + "test", + { + starting.countDown() + release.await() + // Returns once the command has started a child, so that a stop must reach both. + ProcessBuilder(SETSID, "sh", "-c", script, "sh", pidFile.path).start().also { pids(2) } + }, + grouped = true, + processGroups = hostGroups, + timeoutMs = 60_000, + ) + execution.start {} + starting.await() + + execution.cancel() + release.countDown() + + assertThat(goneWithin(pids(2), 1_000)).isTrue() + } + + @Test + fun `cancelAllCommands stops every process the commands started`() { + assumeHostTools() + val service = service() + service.executeCommand(shell(CHILDREN_SCRIPT), 60_000) + val pids = pids(CHILDREN_SCRIPT_PIDS) + + service.cancelAllCommands() + + assertThat(readersGoneWithin(1_000)).isTrue() + assertThat(goneWithin(pids, 1_000)).isTrue() + assertThat(service.getRunningCommandCount()).isEqualTo(0) + } + + @Test + fun `a command that exits before its timeout is not timed out while a child holds its output`() { + assumeHostTools() + val script = "echo done; sleep 600 & echo \$! >> \"\$1\"; $WAIT_FOR_RELEASE" + // The output stays open past the 2 s limit, until the grace ends and the child is stopped. + val execution = + CommandExecutionImpl( + "test", + ProcessBuilder(SETSID, "sh", "-c", script, "sh", pidFile.path, releaseFile.path)::start, + grouped = true, + processGroups = hostGroups, + timeoutMs = 2_000, + outputGraceMs = 3_000, + ) + execution.start {} + execution.releaseOnceReading() + + val result = execution.awaitWithin(10_000) + + assertThat(result).isInstanceOf(CommandResult.Success::class.java) + result as CommandResult.Success + assertThat(result.stdout).isEqualTo("done\n") + assertThat(result.stderr).isEmpty() + assertThat(result.durationMs).isAtLeast(3_000) + assertThat(pids(1).filter(::alive)).isEmpty() + } + + @Test + fun `a process that ignores SIGTERM is killed`() { + assumeHostTools() + // The ignored TERM is inherited by the shell's child. + val script = "trap '' TERM; echo \$\$ >> \"\$1\"; sleep 600 & echo \$! >> \"\$1\"; wait" + + val result = service().executeCommand(shell(script), 300).awaitWithin(10_000) + + assertThat((result as CommandResult.Failure).error).isEqualTo("Command timed out after 300ms") + assertThat(goneWithin(pids(2), 1_000)).isTrue() + } + + @Test + fun `a command returns soon after it exits though a child holds its output`() { + assumeHostTools() + val execution = service().executeCommand(shell("echo done; sleep 600 & echo \$! >> \"\$1\"; $WAIT_FOR_RELEASE"), 60_000) + execution.releaseOnceReading() + val released = System.currentTimeMillis() + + val result = execution.awaitWithin(10_000) + + // What the changelog promises: within about 1.5 s of the exit. + assertThat(System.currentTimeMillis() - released).isLessThan(1_500) + assertThat(result).isInstanceOf(CommandResult.Success::class.java) + assertThat((result as CommandResult.Success).stdout).isEqualTo("done\n") + assertThat(readerThreads()).isEmpty() + assertThat(pids(1).filter(::alive)).isEmpty() + } + + @Test + fun `a command that exits with its output closed may leave a process running`() { + assumeHostTools() + + val result = service().executeCommand(shell("sleep 600 >/dev/null 2>&1 & echo \$! >> \"\$1\""), 60_000).awaitWithin(10_000) + + assertThat(result).isInstanceOf(CommandResult.Success::class.java) + assertThat(pids(1).filter(::alive)).hasSize(1) + } + + @Test + fun `stopped commands free their slots`() { + assumeHostTools() + val service = service() + // Long enough that none has timed out by the fourth call, even on a slow machine. + val timedOut = List(3) { service.executeCommand(shell("sleep 600"), 1_000) } + assertThrows(IllegalStateException::class.java) { service.executeCommand(shell("true"), 1_000) } + + timedOut.forEach { it.awaitWithin(10_000) } + val deadline = System.currentTimeMillis() + 1_000 + while (service.getRunningCommandCount() > 0 && System.currentTimeMillis() < deadline) Thread.sleep(10) + val cancelled = List(3) { service.executeCommand(shell("sleep 600"), 60_000) } + cancelled.forEach { service.cancelCommand(it.executionId) } + + assertThat(service.getRunningCommandCount()).isEqualTo(0) + assertThat(service.executeCommand(shell("true"), 5_000).awaitWithin(5_000)).isInstanceOf(CommandResult.Success::class.java) + } + + @Test + fun `a command's slot is free once its await returns`() { + assumeHostTools() + val service = service() + val running = mutableListOf() + + runBlocking { + // Unconfined: the code after await() runs inside the completion, as soon as the result is set. + val finished = service.executeCommand(shell("sleep 0.2"), 5_000) + launch(Dispatchers.Unconfined) { + finished.await() + running += service.getRunningCommandCount() + }.join() + val cancelled = service.executeCommand(shell("sleep 600"), 60_000) + val waiter = + launch(Dispatchers.Unconfined) { + cancelled.await() + running += service.getRunningCommandCount() + } + cancelled.cancel() + waiter.join() + } + + assertThat(running).containsExactly(0, 0) + } + + @Test + fun `setsid is used when it runs the command in place`() { + assumeHostTools() + + assertThat(ProcessGroups.usableSetsid(listOf(SETSID), SH)).isEqualTo(SETSID) + } + + @Test + fun `a missing setsid is not used`() { + assertThat(ProcessGroups.usableSetsid(listOf(File(tmp.root, "none").path), SH)).isNull() + } + + // As Android 11's toybox setsid does: it forks, and its parent exits 0 at once. + @Test + fun `a setsid that forks is not used, so a command still runs to its end`() { + assumeHostTools() + val groups = ProcessGroups(ProcessGroups.usableSetsid(listOf(forkingSetsid().path), SH), ::hostSignal) + + val result = service(groups).executeCommand(shell("sleep 1; echo late"), 10_000).awaitWithin(10_000) + + assertThat((result as CommandResult.Success).stdout).isEqualTo("late\n") + } + + // Android 11 again, with the Terminal's util-linux setsid installed: commands still get a group. + @Test + fun `where the first setsid forks, the next one that runs commands in place is used`() { + assumeHostTools() + val setsid = ProcessGroups.usableSetsid(listOf(forkingSetsid().path, File(tmp.root, "none").path, SETSID), SH) + val groups = ProcessGroups(setsid, ::hostSignal) + + val execution = service(groups).executeCommand(shell(CHILDREN_SCRIPT), 300) + val result = execution.awaitWithin(10_000) + + assertThat(setsid).isEqualTo(SETSID) + assertThat((result as CommandResult.Failure).error).isEqualTo("Command timed out after 300ms") + assertThat(goneWithin(pids(CHILDREN_SCRIPT_PIDS), 1_000)).isTrue() + } + + /** A `setsid` that forks and exits 0 at once, as Android 11's toybox one does. */ + private fun forkingSetsid() = + File(tmp.root, "forking-setsid").apply { + writeText("#!/bin/sh\n\"\$@\" &\nexit 0\n") + setExecutable(true) + } + + @Test + fun `a stop that finds no group yet signals the group again once the command is killed`() { + val sent = mutableListOf() + val process = FakeProcess { sent += "destroy" } + val groups = + ProcessGroups("/setsid") { pgid, signal -> + sent += "$signal $pgid" + // setsid runs, and the command starts a child, just after the TERM finds no group. + signal != GroupSignal.TERM + } + + runBlocking { groups.stop(process, grouped = true) } + + assertThat(sent).containsExactly("TERM ${FakeProcess.PID}", "destroy", "KILL ${FakeProcess.PID}").inOrder() + } + + @Test + fun `without setsid a timeout still stops the command itself`() { + assumeHostTools() + val noGroups = ProcessGroups(null) { _, _ -> throw AssertionError("signalled a group that does not exist") } + + val result = service(noGroups).executeCommand(shell("echo \$\$ >> \"\$1\"; exec sleep 600"), 300).awaitWithin(10_000) + + assertThat((result as CommandResult.Failure).error).isEqualTo("Command timed out after 300ms") + assertThat(goneWithin(pids(1), 1_000)).isTrue() + } + + @Test + fun `a command runs in a group of its own when setsid can run it`() { + val command = ProcessGroups("/setsid") { _, _ -> true }.isolate(listOf("sh", "-c", "true"), null) + + assertThat(command.grouped).isTrue() + assertThat(command.command[0]).isEqualTo("/setsid") + // The sh ProcessBuilder would run, found in the IDE's PATH rather than the command's. + assertThat(File(command.command[1]).isAbsolute).isTrue() + assertThat(File(command.command[1]).name).isEqualTo("sh") + assertThat(command.command.drop(2)).containsExactly("-c", "true").inOrder() + } + + @Test + fun `a command with no such program is left to fail as before`() { + val command = listOf("no-such-program-7178", "x") + + val isolated = ProcessGroups("/setsid") { _, _ -> true }.isolate(command, null) + + assertThat(isolated).isEqualTo(GroupedCommand(command, grouped = false)) + } + + /** Alive until destroyed, with its process id where [ProcessGroups] reads it on Android. */ + private class FakeProcess( + private val onDestroy: () -> Unit, + ) : Process() { + @JvmField + val pid = PID + private var alive = true + + override fun getOutputStream() = ByteArrayOutputStream() + + override fun getInputStream() = ByteArrayInputStream(ByteArray(0)) + + override fun getErrorStream() = ByteArrayInputStream(ByteArray(0)) + + override fun waitFor() = 0 + + override fun exitValue() = if (alive) throw IllegalThreadStateException("running") else 0 + + override fun isAlive() = alive + + override fun destroy() { + alive = false + onDestroy() + } + + override fun destroyForcibly(): Process { + destroy() + return this + } + + companion object { + const val PID = 4242 + } + } + + private companion object { + const val SETSID = "/usr/bin/setsid" + const val KILL = "/usr/bin/kill" + const val SH = "/bin/sh" + + /** + * Ends a script that leaves a child holding its output: the shell waits for `$2` to exist, + * which [releaseOnceReading] creates once the readers are in read(). A shell that exits first + * has its output drained and closed by [Process], which hides the child. Also ends once `$1`, + * which the script has written to, is deleted with the test's folder, so that a test failing + * first leaves no shell behind. + */ + const val WAIT_FOR_RELEASE = "until [ -e \"\$2\" ] || [ ! -e \"\$1\" ]; do sleep 0.01; done" + val DEV_NULL = File("/dev/null") + + /** A child, a double-forked grandchild, the shell itself, and a child it waits for. */ + const val CHILDREN_SCRIPT = + "sleep 600 & echo \$! >> \"\$1\"; (sleep 600 & echo \$! >> \"\$1\"); " + + "echo \$\$ >> \"\$1\"; sleep 600 & echo \$! >> \"\$1\"; wait" + const val CHILDREN_SCRIPT_PIDS = 4 + } } diff --git a/termux/termux-app/src/main/java/com/itsaky/androidide/terminal/AgentRunner.kt b/termux/termux-app/src/main/java/com/itsaky/androidide/terminal/AgentRunner.kt index 7a9ac7a9b1..063f5f8302 100644 --- a/termux/termux-app/src/main/java/com/itsaky/androidide/terminal/AgentRunner.kt +++ b/termux/termux-app/src/main/java/com/itsaky/androidide/terminal/AgentRunner.kt @@ -33,6 +33,7 @@ class AgentRunner( directory.mkdirs() installScript() File(directory, "$id.cmd").writeText(command) + File(directory, "$id.show").writeText(displayed(command)) File(directory, "$id.dir").writeText(workingDirectory.orEmpty()) return id } @@ -57,7 +58,7 @@ class AgentRunner( * * @return true if taken back; false if the runner took it first, or it was never prepared. */ - fun withdraw(id: String): Boolean = File(directory, "$id.cmd").delete().also { if (it) File(directory, "$id.dir").delete() } + fun withdraw(id: String): Boolean = File(directory, "$id.cmd").delete().also { if (it) deleteCompanions(id) } /** * Deletes the files of command [id], which will never run; the runner deletes them once it @@ -65,6 +66,11 @@ class AgentRunner( */ fun discard(id: String) { File(directory, "$id.cmd").delete() + deleteCompanions(id) + } + + private fun deleteCompanions(id: String) { + File(directory, "$id.show").delete() File(directory, "$id.dir").delete() } @@ -94,6 +100,23 @@ class AgentRunner( /** Runs commands from Termux's tmp directory, which Termux clears when its service stops. */ val termux = AgentRunner(File(TermuxConstants.TERMUX_TMP_PREFIX_DIR_PATH)) + + /** + * [command] as the session shows it before running it: each control character but tab and + * newline written as ``. Printed raw, a value in a plugin's command line would drive + * the terminal: OSC 52 sets the clipboard, and a CR or a cursor move rewrites the echo. + */ + internal fun displayed(command: String): String = + buildString { + for (c in command) { + val control = c < ' ' || c in '\u007f'..'\u009f' // C0, DEL and C1 + if (control && c != '\t' && c != '\n') { + append("') + } else { + append(c) + } + } + } } } diff --git a/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh b/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh index 8aec84d8d6..dfdf9d24b1 100644 --- a/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh +++ b/termux/termux-app/src/main/resources/com/itsaky/androidide/terminal/agent-run.sh @@ -20,10 +20,23 @@ trap 'mark "D;$?"' EXIT mv -- "$dir/$id.cmd" "$dir/$id.run" 2>/dev/null || exit 1 cmd=$(cat "$dir/$id.run") || exit 1 wd=$(cat "$dir/$id.dir") || exit 1 -rm -f "$dir/$id.run" "$dir/$id.dir" +# The command as shown: AgentRunner made its control characters visible, which printed raw would +# drive the terminal. +shown=$(cat "$dir/$id.show") || exit 1 +rm -f "$dir/$id.run" "$dir/$id.dir" "$dir/$id.show" mark C -printf '$ %s\n' "$cmd" +printf '$ %s\n' "$shown" cd -- "${wd:-$HOME}" || exit 1 +# A syntax error message quotes the command raw, so the syntax is checked first and an error is +# shown with its control characters replaced. Exits 2, as eval does on a syntax error, but before +# any of the command runs: eval would run the lines ahead of the error. The check has extglob on: +# eval runs a command's lines one at a time, so a "shopt -s extglob" on one line applies to the +# next, but -n runs nothing. The cost: an extglob pattern in a command that never turns extglob on +# passes the check, and eval's message rejecting it quotes the line raw. +if ! err=$(bash -O extglob -n -c "$cmd" 2>&1); then + while IFS= read -r line; do printf '%s\n' "${line//[[:cntrl:]]/?}"; done <<<"$err" >&2 + exit 2 +fi # In a subshell, so an exec or a trap in the command cannot take the EXIT trap with it. (eval "$cmd") diff --git a/termux/termux-app/src/test/java/com/itsaky/androidide/terminal/AgentRunnerTest.kt b/termux/termux-app/src/test/java/com/itsaky/androidide/terminal/AgentRunnerTest.kt index 22d22e99cd..d437670e80 100644 --- a/termux/termux-app/src/test/java/com/itsaky/androidide/terminal/AgentRunnerTest.kt +++ b/termux/termux-app/src/test/java/com/itsaky/androidide/terminal/AgentRunnerTest.kt @@ -31,20 +31,21 @@ class AgentRunnerTest { val output: String, ) - private fun run(id: String): Run { + /** What the runner writes to the terminal for command [id], before the terminal reads it. */ + private fun rawOutput(id: String): String { val process = ProcessBuilder(BASH, File(tmp.root, "agent-run").path, id) .apply { environment()["HOME"] = tmp.root.path } .redirectErrorStream(true) .start() - // A pty turns \n into \r\n on the way out; the pipe here does not. - val bytes = - process.inputStream - .readBytes() - .toString(Charsets.UTF_8) - .replace("\n", "\r\n") - .toByteArray() + val output = process.inputStream.readBytes().toString(Charsets.UTF_8) process.waitFor() + return output + } + + private fun run(id: String): Run { + // A pty turns \n into \r\n on the way out; the pipe here does not. + val bytes = rawOutput(id).replace("\n", "\r\n").toByteArray() val marks = mutableListOf() lateinit var terminal: TerminalEmulator @@ -98,6 +99,60 @@ class AgentRunnerTest { assertThat(run.output).isEqualTo("\$ echo \"it's quoted\"; exit 3\nit's quoted") } + @Test + fun controlCharactersInTheCommandAreEchoedVisiblyAndRunUnchanged() { + val out = File(tmp.root, "out") + // Printed raw, the OSC 52 would put "PWNED", base64-encoded here, on the clipboard. + val id = runner.prepare(": '\u001b]52;c;UFdORUQ=\u0007'; printf '%s' 'a\rb\u009bc' > ${out.path}", null) + + val output = rawOutput(id) + + assertThat(output).doesNotContain("\u001b]52") + assertThat(output).contains("\$ : ']52;c;UFdORUQ='; printf '%s' 'abc' > ${out.path}\n") + assertThat(out.readText()).isEqualTo("a\rb\u009bc") + } + + @Test + fun syntaxErrorIsReportedWithoutItsControlCharactersAndNothingRuns() { + val out = File(tmp.root, "out") + // bash quotes the line of a syntax error in its message, OSC 52 and all. + val id = runner.prepare("touch ${out.path}; echo '\u001b]52;c;UFdORUQ=\u0007' (", null) + + val output = rawOutput(id) + + // The runner's own marks are the only control sequences left. + val text = output.replace(Regex("\u001b]133;[^\u0007]*\u0007"), "") + assertThat(text).doesNotContain("\u001b") + assertThat(text).doesNotContain("\u0007") + assertThat(text).contains("?]52;c;UFdORUQ=?") + assertThat(output).contains("\u001b]133;D;2;") + assertThat(out.exists()).isFalse() + } + + @Test + fun commandThatTurnsOnExtglobBeforeUsingItRuns() { + val run = run(runner.prepare("shopt -s extglob\ncase ab in +(a|b)) echo matched;; esac", null)) + + assertThat(run.output.lines().last()).isEqualTo("matched") + assertThat(run.marks.last().exitCode).isEqualTo(0) + } + + @Test + fun carriageReturnInTheCommandCannotRewriteItsEcho() { + // Printed raw, the CR would return to the start of the line, and the echo would show only + // what follows it. + val run = run(runner.prepare(": 'rm -rf ~'\r: 'harmless'", null)) + + assertThat(run.output.lines().first()).isEqualTo("\$ : 'rm -rf ~': 'harmless'") + assertThat(run.marks.last().exitCode).isEqualTo(0) + } + + @Test + fun displayedCommandMakesOnlyControlCharactersVisible() { + assertThat(AgentRunner.displayed("a\u0000b\u001bc\u007fd\u0080e\u009ff\u00a0g\th\ni\u00e9\u2028")) + .isEqualTo("abcdef\u00a0g\th\ni\u00e9\u2028") + } + @Test fun commandRunsInItsWorkingDirectory() { val dir = tmp.newFolder("project") @@ -178,8 +233,7 @@ class AgentRunnerTest { runner.discard(id) - assertThat(File(tmp.root, "$id.cmd").exists()).isFalse() - assertThat(File(tmp.root, "$id.dir").exists()).isFalse() + assertThat(tmp.root.list()).asList().containsExactly("agent-run") } @Test