diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 864bbfe7b6..045f307aa7 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -36,6 +36,23 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] = diffed from `plugin-api/src` history (predates the dump; symbol-accurate). ### 26.48 — 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. A stopped command frees its slot, + and `await()` returns, once the group has stopped, so after a `cancel()` too it can take up to + about 750 ms. + On Android 11, whose `setsid` always forks, the IDE uses the Terminal's `setsid` instead, if that + one runs commands in place. Until the Terminal is installed, the IDE checks again as each command + starts, and meanwhile commands get no group of their own: 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. - **added — Hear the editor open and close a project, and save a file** _(ADFA-3570)_ **[verified]** `IdeProjectService.addProjectLifecycleListener(ProjectLifecycleListener)` calls `onProjectOpened(projectDir)` when the editor starts opening a project (its sync does not wait 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..7b096f4854 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,9 @@ class IdeCommandServiceImpl internal constructor( private val projectRootProvider: () -> File?, private val appFilesDir: File, private val gradleTaskRunner: GradleTaskRunner = GradleTaskRunner(IdeBuildServiceImpl.getInstance()::startTasks), + // Called as each shell command starts, never here: finding a usable setsid runs it, which a + // plugin that runs no shell command should not pay for as it loads. + private val processGroups: () -> ProcessGroups = { ProcessGroups.android(File(appFilesDir, "usr/bin/setsid")) }, ) : IdeCommandService { private val runningCommands = ConcurrentHashMap() @@ -62,11 +72,11 @@ class IdeCommandServiceImpl internal constructor( } val processBuilder = try { - shellProcess(spec, workDir) + shellProcess(listOf(spec.executable) + spec.arguments, spec.environment, workDir) } catch (e: IllegalArgumentException) { return RejectedCommandExecution(executionId, "Invalid environment: ${e.message}") } - CommandExecutionImpl(executionId, processBuilder, timeoutMs) + CommandExecutionImpl(executionId, { startInGroup(processBuilder, workDir) }, timeoutMs) } } runningCommands[executionId] = execution @@ -74,20 +84,31 @@ class IdeCommandServiceImpl internal constructor( return execution } + /** Run by the command's coroutine, so that finding a usable setsid never holds up the caller. */ + private fun startInGroup( + processBuilder: ProcessBuilder, + workDir: File?, + ): StartedCommand { + val groups = processGroups() + val command = groups.isolate(processBuilder.command(), workDir) + return StartedCommand(processBuilder.command(command.command).start(), command.grouped, groups) + } + 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) } override fun isCommandRunning(executionId: String): Boolean = runningCommands[executionId]?.isRunning() == true - // onComplete removes the entry: a GradleTask stays running until Gradle has stopped. + // onComplete removes the entry: a command keeps its slot until it has stopped. override fun cancelCommand(executionId: String): Boolean = runningCommands[executionId]?.let { it.cancel() @@ -96,11 +117,9 @@ class IdeCommandServiceImpl internal constructor( override fun getRunningCommandCount(): Int = runningCommands.size + // As with cancelCommand, each command frees its slot once it has stopped. fun cancelAllCommands() { - runningCommands.entries.removeAll { (_, execution) -> - execution.cancel() - true - } + runningCommands.values.forEach { it.cancel() } } private fun requirePermission() { @@ -124,126 +143,191 @@ class IdeCommandServiceImpl internal constructor( } } +/** A started shell command: its process, which leads a group of its own if [grouped], and what stops it. */ +internal class StartedCommand( + val process: Process, + val grouped: Boolean, + val processGroups: ProcessGroups, +) + internal interface RunningCommand : CommandExecution { - /** Starts the command; [onComplete] runs once it ends or is cancelled. */ + /** Starts the command; [onComplete] runs once it has ended, or has stopped after a cancel. */ fun start(onComplete: () -> Unit) 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. Its slot is freed, and + * [await] returns, only once that is done. + * + * @param startCommand starts the process, on the command's coroutine. + * @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 startCommand: () -> StartedCommand, 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()) - private var process: Process? = null - private val stdoutBuilder = StringBuilder() - private val stderrBuilder = StringBuilder() - // Also run by cancel(): a cancel landing before the launched body starts skips its call. @Volatile - private var onComplete: () -> Unit = {} - - override val output: Flow = outputChannel.receiveAsFlow() - - override fun start(onComplete: () -> Unit) { - this.onComplete = onComplete - scope.launch { - val startTime = System.currentTimeMillis() - - runCatching { - withTimeout(timeoutMs) { - process = processBuilder.start() - val proc = process!! + private var process: Process? = null - val stdoutJob = launch { readStream(proc, isStdErr = false) } - val stderrJob = launch { readStream(proc, isStdErr = true) } + @Volatile + private var startTime = 0L - val exitCode = proc.waitFor() - stdoutJob.join() - stderrJob.join() + @Volatile + private var result: CommandResult? = null - outputChannel.send(CommandOutput.ExitCode(exitCode)) - outputChannel.close() + // Appended to by the reader threads, read by whichever thread ends the command. + private val stdoutBuilder = StringBuilder() + private val stderrBuilder = StringBuilder() - 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) - } - } - }.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) - } + override val output: Flow = outputChannel.receiveAsFlow() - is kotlinx.coroutines.CancellationException -> { - CommandResult.Cancelled(stdout, stderr) - } + override fun start(onComplete: () -> Unit) { + startTime = System.currentTimeMillis() + val job = scope.launch { result = runCommand() } + // However the coroutine ends: also when a cancel() before it ran skipped its body, or when + // stopping the command threw. + job.invokeOnCompletion { cause -> + val stdout = snapshot(stdoutBuilder) + val stderr = snapshot(stderrBuilder) + outputChannel.close() + // First, so that a caller resuming from await() finds the slot free. + onComplete() + resultDeferred.complete( + result ?: when (cause) { + is CancellationException -> CommandResult.Cancelled(stdout, stderr) + else -> CommandResult.Failure(-1, stdout, stderr, "Unexpected error: ${cause?.message}", duration()) + }, + ) + } + } - else -> { - CommandResult.Failure(-1, stdout, stderr, "Unexpected error: ${e.message}", duration) - } - } - if (resultDeferred.isActive) { - resultDeferred.complete(failureResult) + private suspend fun runCommand(): CommandResult { + var started: StartedCommand? = null + var readers = emptyList() + var exitCode: Int? = null + var outputClosed = false + var cancelled = false + var error: Throwable? = null + try { + withTimeoutOrNull(timeoutMs) { + // Recorded before the next suspension point, so that a cancel() landing while + // startCommand() ran, when there was no process yet to stop, has the finally below + // stop it (ADFA-7109). + val command = startCommand() + started = command + process = command.process + readers = + listOf( + readLines(command.process.inputStream, isStdErr = false), + readLines(command.process.errorStream, isStdErr = true), + ) + // Interruptible, so that the timeout and cancel() end the wait at once. + runInterruptible { command.process.waitFor() } + } + // Read from the process, not the block's result: one that exits just as the time runs + // out ended on its own. + exitCode = started?.process?.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: Throwable) { + // An Error too, as stage's runCatching did: it ends the command, not the IDE. + error = e + } finally { + withContext(NonCancellable) { + started?.let { command -> + if (exitCode == null || !outputClosed) command.processGroups.stop(command.process, command.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(command.process.inputStream, command.process.errorStream, command.process.outputStream) } + withTimeoutOrNull(READERS_STOP_MS) { readers.joinAll() } } + } - onComplete() + val stdout = snapshot(stdoutBuilder) + val stderr = snapshot(stderrBuilder) + exitCode?.let { outputChannel.trySend(CommandOutput.ExitCode(it)) } + return 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()) } } - private suspend fun readStream( - process: Process, + private fun duration() = System.currentTimeMillis() - startTime + + 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() - if (resultDeferred.isActive) { - resultDeferred.complete( - CommandResult.Cancelled(stdoutBuilder.toString(), stderrBuilder.toString()), - ) - } + // The command's coroutine stops the process and its group, then frees the slot and completes. 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..29ef6c9cd6 --- /dev/null +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/ProcessGroups.kt @@ -0,0 +1,208 @@ +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], unless neither works while [terminalSetsid] cannot run + * yet: the Terminal installs it at first-run setup, possibly after plugins have run commands, + * and where toybox's forks (Android 11) it is the only one that works. + */ + fun android(terminalSetsid: File): ProcessGroups = + android(terminalSetsid) { usableSetsid(listOf(ANDROID_SETSID, terminalSetsid.path), ANDROID_SH) } + + /** [android], with [findSetsid] in place of checking the candidates. */ + internal fun android( + terminalSetsid: File, + findSetsid: () -> String?, + ): ProcessGroups = + android[terminalSetsid.path] ?: synchronized(android) { + android[terminalSetsid.path] ?: run { + val setsid = findSetsid() + val groups = ProcessGroups(setsid, ::osSignal) + if (setsid != null || terminalSetsid.canExecute()) android[terminalSetsid.path] = groups + groups + } + } + + 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..b5c451756a 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,190 @@ 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.Collections +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicReference +import kotlin.concurrent.thread 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) = serviceFinding { processGroups } + + private fun serviceFinding(processGroups: () -> ProcessGroups) = + 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() } } + + /** [service]'s running-command count once it is [expected], or as it stands after [ms]. */ + private fun countWithin( + service: IdeCommandServiceImpl, + expected: Int, + ms: Long, + ): Int { + val deadline = System.currentTimeMillis() + ms + while (service.getRunningCommandCount() != expected && System.currentTimeMillis() < deadline) Thread.sleep(10) + return service.getRunningCommandCount() + } + + /** 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 +209,513 @@ 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. + val process = ProcessBuilder(SETSID, "sh", "-c", script, "sh", pidFile.path).start().also { pids(2) } + StartedCommand(process, grouped = true, 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(countWithin(service, 0, 1_000)).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", + { + val process = ProcessBuilder(SETSID, "sh", "-c", script, "sh", pidFile.path, releaseFile.path).start() + StartedCommand(process, grouped = true, 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) } + cancelled.forEach { it.awaitWithin(5_000) } + + 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 `a cancelled command keeps its slot until it has stopped`() { + assumeHostTools() + val stopping = CountDownLatch(1) + val release = CountDownLatch(1) + val service = service(ProcessGroups(SETSID, holdingTerm(stopping, release))) + val commands = List(3) { service.executeCommand(shell(STARTED_SLEEP), 60_000) } + // Started, so that the cancel has a group to stop. + pids(3) + + commands[0].cancel() + try { + assertThat(stopping.await(5, TimeUnit.SECONDS)).isTrue() + assertThrows(IllegalStateException::class.java) { service.executeCommand(shell("true"), 5_000) } + } finally { + release.countDown() + } + + assertThat(commands[0].awaitWithin(5_000)).isInstanceOf(CommandResult.Cancelled::class.java) + assertThat(service.executeCommand(shell("true"), 5_000).awaitWithin(5_000)).isInstanceOf(CommandResult.Success::class.java) + commands.drop(1).forEach { + it.cancel() + it.awaitWithin(5_000) + } + } + + @Test + fun `cancelAllCommands frees each slot only once its command has stopped`() { + assumeHostTools() + val stopping = CountDownLatch(1) + val release = CountDownLatch(1) + val service = service(ProcessGroups(SETSID, holdingTerm(stopping, release))) + val command = service.executeCommand(shell(STARTED_SLEEP), 60_000) + pids(1) + + service.cancelAllCommands() + try { + assertThat(stopping.await(5, TimeUnit.SECONDS)).isTrue() + assertThat(service.getRunningCommandCount()).isEqualTo(1) + } finally { + release.countDown() + } + + command.awaitWithin(5_000) + assertThat(service.getRunningCommandCount()).isEqualTo(0) + } + + @Test + fun `a command cancelled before its coroutine runs still frees its slot and completes`() { + val freed = AtomicBoolean(false) + val execution = CommandExecutionImpl("test", { throw AssertionError("started a cancelled command") }, timeoutMs = 5_000) + + // What a cancel landing between start() and the coroutine's first run leads to: no body runs. + execution.cancel() + execution.start { freed.set(true) } + + assertThat(execution.awaitWithin(1_000)).isInstanceOf(CommandResult.Cancelled::class.java) + assertThat(freed.get()).isTrue() + } + + /** Signals as [hostSignal] does, but holds the first TERM until [release]. */ + private fun holdingTerm( + stopping: CountDownLatch, + release: CountDownLatch, + ): (Int, GroupSignal) -> Boolean = + { pgid, signal -> + if (signal == GroupSignal.TERM) { + stopping.countDown() + release.await() + } + hostSignal(pgid, signal) + } + + @Test + fun `an Error starting a command fails it and frees its slot without escaping`() { + val service = serviceFinding { throw LinkageError("no setsid for this test") } + + val (result, uncaught) = catchingUncaught { service.executeCommand(shell("true"), 5_000).awaitWithin(5_000) } + + assertThat((result as CommandResult.Failure).error).isEqualTo("Unexpected error: no setsid for this test") + assertThat(service.getRunningCommandCount()).isEqualTo(0) + assertThat(uncaught).isEmpty() + } + + @Test + fun `a command whose stop throws still completes and frees its slot`() { + assumeHostTools() + val service = service(ProcessGroups(SETSID) { _, _ -> throw SecurityException("no signals for this test") }) + + val (result, _) = + catchingUncaught { service.executeCommand(shell(STARTED_SLEEP), 300).awaitWithin(5_000) } + + assertThat((result as CommandResult.Failure).error).isEqualTo("Unexpected error: no signals for this test") + assertThat(service.getRunningCommandCount()).isEqualTo(0) + } + + /** [block]'s result, and what reached the default uncaught-exception handler meanwhile. */ + private fun catchingUncaught(block: () -> T): Pair> { + val uncaught = Collections.synchronizedList(mutableListOf()) + val previous = Thread.getDefaultUncaughtExceptionHandler() + Thread.setDefaultUncaughtExceptionHandler { _, e -> uncaught += e } + try { + return block() to uncaught.toList() + } finally { + Thread.setDefaultUncaughtExceptionHandler(previous) + } + } + + @Test + fun `setsid is looked for as a shell command starts, not as the plugin loads or on the caller's thread`() { + assumeHostTools() + val looks = AtomicInteger() + val looking = CountDownLatch(1) + val release = CountDownLatch(1) + val service = + serviceFinding { + looks.incrementAndGet() + looking.countDown() + release.await() + hostGroups + } + assertThat(looks.get()).isEqualTo(0) + + val execution = AtomicReference() + val caller = thread { execution.set(service.executeCommand(shell("true"), 5_000)) } + try { + caller.join(2_000) + assertThat(execution.get()).isNotNull() + assertThat(looking.await(5, TimeUnit.SECONDS)).isTrue() + } finally { + release.countDown() + } + + assertThat(execution.get().awaitWithin(5_000)).isInstanceOf(CommandResult.Success::class.java) + assertThat(looks.get()).isEqualTo(1) + } + + @Test + fun `finding no setsid is checked again once the Terminal's setsid can run`() { + val terminalSetsid = File(tmp.newFolder("terminal-bin"), "setsid") + var found: String? = null + val looks = AtomicInteger() + val find = { + looks.incrementAndGet() + found + } + + assertThat(ProcessGroups.android(terminalSetsid, find).isolate(listOf(SH), null).grouped).isFalse() + ProcessGroups.android(terminalSetsid, find) + assertThat(looks.get()).isEqualTo(2) + + terminalSetsid.writeText("#!/bin/sh\nexec \"\$@\"\n") + terminalSetsid.setExecutable(true) + found = terminalSetsid.path + val groups = ProcessGroups.android(terminalSetsid, find) + + assertThat(groups.isolate(listOf(SH), null).grouped).isTrue() + assertThat(ProcessGroups.android(terminalSetsid, find)).isSameInstanceAs(groups) + assertThat(looks.get()).isEqualTo(3) + } + + @Test + fun `finding no setsid while the Terminal's can run is kept`() { + val terminalSetsid = + File(tmp.newFolder("terminal-bin"), "setsid").apply { + writeText("#!/bin/sh\n\"\$@\" &\nexit 0\n") + setExecutable(true) + } + val looks = AtomicInteger() + + val groups = ProcessGroups.android(terminalSetsid) { null.also { looks.incrementAndGet() } } + + assertThat(ProcessGroups.android(terminalSetsid) { null.also { looks.incrementAndGet() } }).isSameInstanceAs(groups) + assertThat(looks.get()).isEqualTo(1) + } + + @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 + + /** Writes its process id to `$1`, then sleeps. */ + const val STARTED_SLEEP = "echo \$\$ >> \"\$1\"; exec sleep 600" + } } 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..089c9c1163 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,24 @@ 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. The command goes in on +# stdin, as exec refuses an argument over 32 pages (128 KiB at 4 KiB pages). +if ! err=$(bash -O extglob -n <<<"$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..db1fa45f71 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,73 @@ 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 commandTooLongForOneExecArgumentRuns() { + val out = File(tmp.root, "out") + // exec refuses an argument over 32 pages: 128 KiB at 4 KiB pages, 512 KiB at 16 KiB. + val id = runner.prepare(": '${"a".repeat(1 shl 20)}'; touch ${out.path}", null) + + val output = rawOutput(id) + + // Only the exit code, as a failure message quoting the output would hold the whole command. + assertThat(Regex("\u001b]133;D;(\\d+);").find(output)?.groupValues?.get(1)).isEqualTo("0") + assertThat(out.exists()).isTrue() + } + + @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 +246,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