Skip to content

A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.

Terminal: replace serial stdin relay with podroid-bridge PTY

ExTv7b0ff96e7883
diff --git a/.gitignore b/.gitignore
index b75bafa..2b3762a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -39,6 +39,9 @@ app/src/main/jniLibs/arm64-v8a/libslirp.so
# Claude Code sessions
.claude/
+# AI Context (don't commit to repo)
+skill.md
+
# Misc
*.tmp
/captures/
diff --git a/Dockerfile.qemu b/Dockerfile.qemu
index 3e150e0..08b57f6 100644
--- a/Dockerfile.qemu
+++ b/Dockerfile.qemu
@@ -369,6 +369,15 @@ RUN cd ${QEMU_DIR} \
&& ! find build -path '*coroutine-sigaltstack*.o' -print -quit | grep -q . \
&& make install
+# ── podroid-bridge — serial socket ↔ PTY relay with SIGWINCH→RESIZE ──────────
+# Compiled as a PIE executable, renamed to .so so Android extracts it from APK.
+COPY podroid-bridge.c /tmp/podroid-bridge.c
+RUN ${CC} ${CFLAGS} -fPIE -pie \
+ ${LDFLAGS} \
+ /tmp/podroid-bridge.c \
+ -o /opt/qemu-out/podroid-bridge \
+ && cp /opt/qemu-out/podroid-bridge /opt/qemu-out/libpodroid-bridge.so
+
# ── Rename binary to .so; fix libslirp soname for Android APK packaging ───────
# Android APK packaging only extracts files matching lib*.so (no version suffix).
# QEMU was compiled with libslirp.so.0 as the soname. We rename the library to
@@ -387,5 +396,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends patchelf && rm
RUN mkdir -p /out/qemu/keymaps
COPY --from=builder /opt/qemu-out/libqemu-system-aarch64.so /out/
COPY --from=builder /opt/qemu-out/libslirp.so /out/
+COPY --from=builder /opt/qemu-out/libpodroid-bridge.so /out/
COPY --from=builder /opt/qemu-out/share/qemu/efi-virtio.rom /out/qemu/
COPY --from=builder /opt/qemu-out/share/qemu/keymaps/ /out/qemu/keymaps/
diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro
index 20bfba0..4d5b49d 100644
--- a/app/proguard-rules.pro
+++ b/app/proguard-rules.pro
@@ -1,20 +1,13 @@
# Podroid ProGuard rules
-# Termux terminal-emulator fields accessed via reflection
--keepclassmembers class com.termux.terminal.TerminalSession {
- private com.termux.terminal.TerminalEmulator mEmulator;
-}
-
-# Termux terminal-view renderer fields accessed via reflection for size calculation
--keepclassmembers class com.termux.view.TerminalRenderer {
- private float mFontWidth;
- private int mFontLineSpacing;
- private int mFontLineSpacingAndAscent;
-}
-
-# TerminalView fields set directly from TerminalScreen
+# TerminalView fields set directly from TerminalScreen to wire the session.
-keepclassmembers class com.termux.view.TerminalView {
public com.termux.terminal.TerminalSession mTermSession;
public com.termux.terminal.TerminalEmulator mEmulator;
- private com.termux.view.TerminalRenderer mRenderer;
+}
+
+# TerminalSession.mEmulator replaced via reflection in TerminalViewModel
+# to install a no-op TerminalOutput (prevents CPR garbage in the VM shell).
+-keepclassmembers class com.termux.terminal.TerminalSession {
+ com.termux.terminal.TerminalEmulator mEmulator;
}
diff --git a/app/src/main/java/com/excp/podroid/engine/PodroidQemu.kt b/app/src/main/java/com/excp/podroid/engine/PodroidQemu.kt
index 46dd323..4ffd606 100644
--- a/app/src/main/java/com/excp/podroid/engine/PodroidQemu.kt
+++ b/app/src/main/java/com/excp/podroid/engine/PodroidQemu.kt
@@ -2,20 +2,28 @@
* Podroid - Rootless Podman for Android
* Copyright (C) 2024 Podroid contributors
*
- * QEMU engine for Podroid. Manages the VM lifecycle, serial console I/O,
- * and a persistent terminal emulator that handles terminal queries (DA, DSR,
- * window size) even when the UI is detached.
+ * QEMU engine for Podroid. Manages the VM lifecycle and exposes two Unix
+ * sockets for the terminal layer:
+ *
+ * serial.sock — QEMU serial chardev (ttyAMA0 in the VM). The podroid-bridge
+ * binary connects here for bidirectional terminal I/O.
+ *
+ * ctrl.sock — QEMU virtio-console chardev (hvc0 in the VM). The bridge
+ * writes "RESIZE rows cols\n" here on SIGWINCH; the VM daemon
+ * calls stty on ttyAMA0 which triggers SIGWINCH in the VM.
+ *
+ * Boot monitoring: PodroidQemu connects to serial.sock and reads until the VM
+ * reaches the "Ready" stage (or until releaseSerial() is called). The bridge
+ * then takes over the connection for interactive terminal use.
*/
package com.excp.podroid.engine
import android.annotation.SuppressLint
import android.content.Context
+import android.net.LocalSocket
+import android.net.LocalSocketAddress
import android.util.Log
import com.excp.podroid.data.repository.PortForwardRule
-import com.termux.terminal.TerminalEmulator
-import com.termux.terminal.TerminalOutput
-import com.termux.terminal.TerminalSession
-import com.termux.terminal.TerminalSessionClient
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
@@ -23,8 +31,6 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.io.File
import java.io.FileOutputStream
-import java.io.OutputStream
-import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
@@ -44,46 +50,40 @@ class PodroidQemu @Inject constructor(
private val _bootStage = MutableStateFlow("")
val bootStage: StateFlow<String> = _bootStage.asStateFlow()
- /** Persistent terminal emulator that outlives the UI. */
- var terminalEmulator: TerminalEmulator? = null
- private set
-
@Volatile
var process: Process? = null
private set
+ /** Unix socket paths exposed to TerminalViewModel for the bridge binary. */
+ val serialSockPath: String get() = "${context.filesDir.absolutePath}/serial.sock"
+ val ctrlSockPath: String get() = "${context.filesDir.absolutePath}/ctrl.sock"
+
+ /** Boot-monitoring socket connection. Closed when the bridge takes over. */
@Volatile
- private var consoleOutputStream: OutputStream? = null
+ private var bootSocket: LocalSocket? = null
- private val writeQueue = LinkedBlockingQueue<ByteArray>()
+ private val qmpSocketPath: String get() = "${context.filesDir.absolutePath}/qmp.sock"
- /** Current terminal dimensions for responding to size queries. */
- @Volatile var terminalRows = 24
- @Volatile var terminalCols = 80
+ val qmpClient: QmpClient by lazy { QmpClient(qmpSocketPath) }
- /** Coroutine scope for I/O threads — cancelled on stop(). */
private var ioScope: CoroutineScope? = null
- /** Console text buffer — capped to prevent unbounded memory growth. */
private val consoleBuilder = StringBuilder()
- private val maxConsoleSize = 64 * 1024 // Keep last 64KB
-
- fun writeToConsole(data: ByteArray) {
- writeQueue.offer(data)
- }
-
- fun updateTerminalSize(cols: Int, rows: Int) {
- terminalCols = cols
- terminalRows = rows
- terminalEmulator?.resize(cols, rows)
- }
-
- /** Callback for raw console output. Used by TerminalViewModel for UI refresh. */
- @Volatile
- var onConsoleOutput: ((ByteArray, Int) -> Unit)? = null
-
- val qmpClient: QmpClient by lazy {
- QmpClient("${context.filesDir.absolutePath}/qmp.sock")
+ private val maxConsoleSize = 64 * 1024
+
+ /**
+ * Release the boot-monitoring serial connection so podroid-bridge can connect.
+ * Called by TerminalViewModel right before starting the bridge TerminalSession.
+ */
+ fun releaseSerial() {
+ _bootStage.value = "Ready"
+ val sock = bootSocket
+ bootSocket = null
+ if (sock != null) {
+ try { sock.shutdownInput() } catch (_: Exception) {}
+ try { sock.shutdownOutput() } catch (_: Exception) {}
+ try { sock.close() } catch (_: Exception) {}
+ }
}
fun start() = start(emptyList())
@@ -112,103 +112,31 @@ class PodroidQemu @Inject constructor(
_consoleText.value = ""
_bootStage.value = "Starting QEMU..."
+ // Clean up stale sockets from a previous run
+ File(serialSockPath).delete()
+ File(ctrlSockPath).delete()
+
try {
val cmd = buildCommand(qemuExe, portForwards, ramMb, cpus, sshEnabled, androidIp)
Log.d(TAG, "Launching: ${cmd.joinToString(" ")}")
val nativeDir = context.applicationInfo.nativeLibraryDir
- val filesDir = context.filesDir.absolutePath
-
val pb = ProcessBuilder(cmd).directory(context.filesDir)
- pb.environment()["LD_LIBRARY_PATH"] = "$nativeDir:$filesDir"
+ pb.environment()["LD_LIBRARY_PATH"] = "$nativeDir:${context.filesDir.absolutePath}"
val proc = pb.start()
process = proc
- consoleOutputStream = proc.outputStream
_bootStage.value = "Booting kernel..."
- // Create coroutine scope for I/O
val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
ioScope = scope
- // Writer coroutine — drains writeQueue to QEMU stdin
+ // Drain QEMU's own stderr (not serial — just QEMU startup messages)
scope.launch {
try {
- while (isActive && process?.isAlive == true) {
- val data = writeQueue.poll(500, TimeUnit.MILLISECONDS)
- if (data != null) {
- consoleOutputStream?.write(data)
- consoleOutputStream?.flush()
- }
- }
- } catch (e: Exception) {
- Log.d(TAG, "Console writer ended: ${e.message}")
- }
- }
-
- // Initialize persistent terminal emulator.
- // write() routes emulator responses (DA, DSR, cursor position) back
- // to the VM so TUI apps like nvim receive the answers they need.
- val qemuOutput = object : TerminalOutput() {
- override fun write(data: ByteArray, offset: Int, count: Int) {
- writeToConsole(data.copyOfRange(offset, offset + count))
- }
- override fun titleChanged(oldTitle: String?, newTitle: String?) {}
- override fun onCopyTextToClipboard(text: String?) {}
- override fun onPasteTextFromClipboard() {}
- override fun onBell() {}
- override fun onColorsChanged() {}
- }
- terminalEmulator = TerminalEmulator(
- qemuOutput, 80, 24, 2000, NoOpSessionClient
- )
-
- // Console reader — reads stdout, feeds emulator, detects boot stages
- val logFile = File(context.filesDir, "console.log")
- logFile.delete()
- scope.launch {
- FileOutputStream(logFile, true).use { logOut ->
val buf = ByteArray(4096)
- val input = proc.inputStream
- try {
- while (isActive) {
- val n = input.read(buf)
- if (n < 0) break
- val chunk = buf.copyOf(n)
- val text = String(chunk, Charsets.UTF_8)
-
- // Cap console buffer to prevent unbounded growth
- consoleBuilder.append(text)
- if (consoleBuilder.length > maxConsoleSize) {
- consoleBuilder.delete(0, consoleBuilder.length - maxConsoleSize)
- }
- _consoleText.value = consoleBuilder.toString()
-
- logOut.write(chunk, 0, n)
- logOut.flush()
-
- // Feed persistent emulator (renders screen buffer)
- terminalEmulator?.append(chunk, n)
-
- // Detect boot stages until "Ready" is reached
- if (_bootStage.value != "Ready") {
- detectBootStage(text)
- }
- onConsoleOutput?.invoke(chunk, n)
- }
- } catch (e: Exception) {
- Log.d(TAG, "Console reader ended: ${e.message}")
- }
- }
- }
-
- // Stderr drain
- scope.launch {
- try {
- val buf = ByteArray(4096)
- val err = proc.errorStream
while (isActive) {
- val n = err.read(buf)
+ val n = proc.errorStream.read(buf)
if (n < 0) break
Log.d("PodroidVM-err", String(buf, 0, n).trimEnd().take(300))
}
@@ -217,7 +145,10 @@ class PodroidQemu @Inject constructor(
}
}
- // Wait briefly, then mark as running if alive
+ // Boot monitor — connects to serial.sock once QEMU creates it
+ scope.launch { monitorBootSerial(proc) }
+
+ // Wait briefly, then confirm QEMU is alive
Thread.sleep(2000)
if (proc.isAlive) {
Log.d(TAG, "QEMU is running")
@@ -230,9 +161,9 @@ class PodroidQemu @Inject constructor(
return
}
- // Block until QEMU exits (keeps the calling service alive)
+ // Block until QEMU exits (keeps the calling service coroutine alive)
val exitCode = proc.waitFor()
- Log.d(TAG, "QEMU exited with code: $exitCode")
+ Log.d(TAG, "QEMU exited: $exitCode")
cleanup()
_state.value = if (exitCode == 0) VmState.Stopped else VmState.Error("Exit code $exitCode")
} catch (e: Exception) {
@@ -242,9 +173,83 @@ class PodroidQemu @Inject constructor(
}
}
+ /**
+ * Connects to serial.sock and reads boot output until:
+ * - The "Ready" stage is detected, or
+ * - releaseSerial() is called (bootSocket closed externally), or
+ * - The coroutine is cancelled.
+ *
+ * Writes all output to console.log for the test-deploy.sh validator and
+ * publishes boot stage updates to the UI.
+ */
+ private suspend fun monitorBootSerial(proc: Process) {
+ val sockFile = File(serialSockPath)
+
+ // Wait up to 8s for QEMU to create the socket
+ var waited = 0
+ while (waited < 8000 && !sockFile.exists() && proc.isAlive) {
+ delay(100)
+ waited += 100
+ }
+ if (!sockFile.exists()) {
+ Log.w(TAG, "serial.sock not found after ${waited}ms — boot detection disabled")
+ return
+ }
+
+ val sock = LocalSocket()
+ try {
+ sock.connect(LocalSocketAddress(serialSockPath, LocalSocketAddress.Namespace.FILESYSTEM))
+ bootSocket = sock
+ Log.d(TAG, "Boot monitor connected to serial.sock")
+ } catch (e: Exception) {
+ Log.w(TAG, "Boot monitor could not connect to serial.sock: ${e.message}")
+ sock.close()
+ return
+ }
+
+ val logFile = File(context.filesDir, "console.log")
+ logFile.delete()
+
+ try {
+ FileOutputStream(logFile, false).use { logOut ->
+ val buf = ByteArray(4096)
+ val input = sock.inputStream
+ while (true) {
+ val n = try {
+ input.read(buf)
+ } catch (_: Exception) {
+ break // socket closed by releaseSerial() or VM exit
+ }
+ if (n < 0) break
+
+ val chunk = buf.copyOf(n)
+ val text = String(chunk, Charsets.UTF_8)
+
+ consoleBuilder.append(text)
+ if (consoleBuilder.length > maxConsoleSize) {
+ consoleBuilder.delete(0, consoleBuilder.length - maxConsoleSize)
+ }
+ _consoleText.value = consoleBuilder.toString()
+
+ logOut.write(chunk, 0, n)
+ logOut.flush()
+
+ if (_bootStage.value != "Ready") {
+ detectBootStage(text)
+ }
+ }
+ }
+ } catch (e: Exception) {
+ Log.d(TAG, "Boot monitor ended: ${e.message}")
+ } finally {
+ try { sock.close() } catch (_: Exception) {}
+ bootSocket = null
+ Log.d(TAG, "Boot monitor disconnected — bridge can now connect")
+ }
+ }
+
private fun detectBootStage(text: String) {
when {
- // Check terminal conditions first — they may arrive in the same chunk as earlier stages
"podman run" in text || "Ready!" in text ->
_bootStage.value = "Ready"
"internet " in text || "Internet:" in text ->
@@ -267,17 +272,10 @@ class PodroidQemu @Inject constructor(
}
fun stop() {
- try {
- writeToConsole("sync\n".toByteArray())
- } catch (e: Exception) {
- Log.d(TAG, "Failed to send sync: ${e.message}")
- }
-
val proc = process
if (proc != null) {
proc.destroy()
try {
- // Wait up to 3 seconds for graceful exit
val exited = proc.waitFor(3, TimeUnit.SECONDS)
if (!exited) {
proc.destroyForcibly()
@@ -292,13 +290,10 @@ class PodroidQemu @Inject constructor(
}
private fun cleanup() {
+ releaseSerial()
ioScope?.cancel()
ioScope = null
process = null
- consoleOutputStream = null
- writeQueue.clear()
- terminalEmulator = null
- onConsoleOutput = null
_bootStage.value = ""
}
@@ -307,18 +302,15 @@ class PodroidQemu @Inject constructor(
portForwards: List<PortForwardRule>,
ramMb: Int,
cpus: Int,
- sshEnabled: Boolean = false,
- androidIp: String = "unknown",
+ sshEnabled: Boolean,
+ androidIp: String,
): List<String> {
val args = mutableListOf<String>()
- // GICv3 reduces interrupt-related vCPU exits vs the default GICv2
args += "-M"; args += "virt,gic-version=3"
args += "-cpu"; args += "max"
args += "-smp"; args += "$cpus"
- args += "-m"; args += "$ramMb"
- // thread=multi (MTTCG): each vCPU runs in its own host thread
- // tb-size=256: cap JIT translation cache at 256MB — default 1024MB thrashes mobile RAM
+ args += "-m"; args += "$ramMb"
args += "-accel"; args += "tcg,thread=multi,tb-size=256"
val kernelPath = File(context.filesDir, "vmlinuz-virt")
@@ -344,20 +336,14 @@ class PodroidQemu @Inject constructor(
val storagePath = File(context.filesDir, "storage.img")
if (storagePath.exists()) {
- // num-queues=cpus: with MTTCG each vCPU can drive its own I/O queue in parallel
args += "-device"; args += "virtio-blk-pci,drive=drive1,num-queues=$cpus"
- // cache=writeback: use host OS page cache instead of direct I/O — major speedup
- // for container workloads (image pulls, package installs, overlay writes)
- // aio=threads: thread-based AIO, safe in Android app sandbox (no io_uring/libaio needed)
- args += "-drive"; args += "file=${storagePath.absolutePath},if=none,id=drive1,format=raw,cache=writeback,aio=threads"
+ args += "-drive"; args += "file=${storagePath.absolutePath},if=none,id=drive1,format=raw,cache=writeback,aio=threads"
}
- // virtio-rng: feed host entropy to the guest so /dev/random never blocks.
- // Without this, container crypto ops (SSH keygen, TLS, package signing) stall under TCG.
args += "-object"; args += "rng-random,id=rng0,filename=/dev/urandom"
args += "-device"; args += "virtio-rng-pci,rng=rng0"
- // Downloads sharing via virtio-9p — tag must match init-podroid mount call
+ // Downloads folder sharing via virtio-9p
val downloadsDir = android.os.Environment.getExternalStoragePublicDirectory(
android.os.Environment.DIRECTORY_DOWNLOADS
)
@@ -375,7 +361,6 @@ class PodroidQemu @Inject constructor(
}
val netdevArg = buildString {
- // ipv6=off: removes unused IPv6 processing overhead from SLIRP
append("user,id=net0,ipv6=off")
for (rule in portForwards) {
append(",hostfwd=${rule.protocol}::${rule.hostPort}-:${rule.guestPort}")
@@ -384,10 +369,19 @@ class PodroidQemu @Inject constructor(
args += "-netdev"; args += netdevArg
args += "-device"; args += "virtio-net,netdev=net0"
- args += "-serial"; args += "stdio"
+ // ── Serial console (ttyAMA0) → unix socket for podroid-bridge ─────────
+ args += "-serial"; args += "unix:$serialSockPath,server,nowait"
+
+ // ── Control channel (hvc0) → unix socket for resize signalling ────────
+ // VM daemon reads "RESIZE rows cols\n" from /dev/hvc0 and calls stty
+ // on ttyAMA0 — Linux kernel automatically sends SIGWINCH to the foreground
+ // process group.
+ args += "-chardev"; args += "socket,id=ctrl0,path=$ctrlSockPath,server=on,wait=off"
+ args += "-device"; args += "virtio-serial-pci"
+ args += "-device"; args += "virtconsole,chardev=ctrl0,name=org.podroid.ctrl"
+
args += "-display"; args += "none"
- args += "-qmp"
- args += "unix:${context.filesDir.absolutePath}/qmp.sock,server,nowait"
+ args += "-qmp"; args += "unix:$qmpSocketPath,server,nowait"
args += "-overcommit"; args += "mem-lock=off"
return listOf(qemuExe.absolutePath) + args
@@ -401,18 +395,13 @@ class PodroidQemu @Inject constructor(
val desiredBytes = gb * 1024L * 1024L * 1024L
if (storageFile.exists()) {
- if (storageFile.length() == desiredBytes) {
- Log.d(TAG, "storage.img already correct size (${gb}GB)")
- return
- }
- Log.d(TAG, "storage.img size mismatch (is ${storageFile.length() / (1024*1024*1024)}GB, want ${gb}GB) — recreating")
+ if (storageFile.length() == desiredBytes) return
+ Log.d(TAG, "storage.img size mismatch — recreating")
storageFile.delete()
}
try {
- java.io.RandomAccessFile(storageFile, "rw").use { raf ->
- raf.setLength(desiredBytes)
- }
+ java.io.RandomAccessFile(storageFile, "rw").use { it.setLength(desiredBytes) }
Log.d(TAG, "Created storage.img (${gb}GB)")
} catch (e: Exception) {
Log.e(TAG, "Failed to create storage.img", e)
@@ -420,8 +409,7 @@ class PodroidQemu @Inject constructor(
}
private fun qemuExecutable(): File? {
- val nativeDir = context.applicationInfo.nativeLibraryDir
- val exe = File(nativeDir, "libqemu-system-aarch64.so")
+ val exe = File(context.applicationInfo.nativeLibraryDir, "libqemu-system-aarch64.so")
return if (exe.exists()) exe else null
}
@@ -429,23 +417,3 @@ class PodroidQemu @Inject constructor(
private const val TAG = "PodroidQemu"
}
}
-
-/** No-op TerminalSessionClient for the persistent emulator (no UI attached). */
-private object NoOpSessionClient : TerminalSessionClient {
- override fun onTextChanged(changedSession: TerminalSession) {}
- override fun onTitleChanged(changedSession: TerminalSession) {}
- override fun onSessionFinished(finishedSession: TerminalSession) {}
- override fun onCopyTextToClipboard(session: TerminalSession, text: String?) {}
- override fun onPasteTextFromClipboard(session: TerminalSession?) {}
- override fun onBell(session: TerminalSession) {}
- override fun onColorsChanged(session: TerminalSession) {}
- override fun onTerminalCursorStateChange(state: Boolean) {}
- override fun getTerminalCursorStyle(): Int = 0
- override fun logError(tag: String?, message: String?) {}
- override fun logWarn(tag: String?, message: String?) {}
- override fun logInfo(tag: String?, message: String?) {}
- override fun logDebug(tag: String?, message: String?) {}
- override fun logVerbose(tag: String?, message: String?) {}
- override fun logStackTraceWithMessage(tag: String?, message: String?, e: Exception?) {}
- override fun logStackTrace(tag: String?, e: Exception?) {}
-}
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalScreen.kt b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalScreen.kt
index 2c15ba5..b7b5cf8 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalScreen.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalScreen.kt
@@ -2,13 +2,14 @@
* Podroid - Rootless Podman for Android
* Copyright (C) 2024 Podroid contributors
*
- * Terminal screen using Termux TerminalView for full VT100/xterm emulation.
+ * Terminal screen using Termux TerminalView wired to the podroid-bridge
+ * binary via a real TerminalSession PTY. No reflection, no emulator
+ * injection. Window resize propagates through the normal PTY/SIGWINCH path.
*/
package com.excp.podroid.ui.screens.terminal
import android.app.Activity
import android.graphics.Typeface
-import android.util.Log
import android.view.WindowManager
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
@@ -57,7 +58,6 @@ import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import com.excp.podroid.engine.VmState
-import com.termux.terminal.TerminalSession
import com.termux.view.TerminalView
@OptIn(ExperimentalMaterial3Api::class)
@@ -105,28 +105,17 @@ fun TerminalScreen(
)
}
},
- colors = TopAppBarDefaults.topAppBarColors(
- containerColor = Color(0xFF1A1A1A),
- ),
+ colors = TopAppBarDefaults.topAppBarColors(containerColor = Color(0xFF1A1A1A)),
)
when (vmState) {
is VmState.Idle, is VmState.Stopped -> {
- Box(
- modifier = Modifier.weight(1f).fillMaxWidth(),
- contentAlignment = Alignment.Center,
- ) {
+ Box(modifier = Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Text("VM Not Running", color = Color.Red, fontSize = 18.sp, fontWeight = FontWeight.Bold)
Text(
- text = "VM Not Running",
- color = Color.Red,
- fontSize = 18.sp,
- fontWeight = FontWeight.Bold,
- )
- Text(
- text = "Start the VM from Home screen first",
- color = Color.Gray,
- fontSize = 14.sp,
+ "Start the VM from Home screen first",
+ color = Color.Gray, fontSize = 14.sp,
modifier = Modifier.padding(top = 8.dp),
)
}
@@ -134,37 +123,22 @@ fun TerminalScreen(
}
is VmState.Starting -> {
- Box(
- modifier = Modifier.weight(1f).fillMaxWidth(),
- contentAlignment = Alignment.Center,
- ) {
+ Box(modifier = Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(32.dp),
) {
- CircularProgressIndicator(
- color = Color(0xFF4FC3F7),
- strokeWidth = 3.dp,
- )
+ CircularProgressIndicator(color = Color(0xFF4FC3F7), strokeWidth = 3.dp)
Spacer(modifier = Modifier.height(24.dp))
- Text(
- text = "Starting VM...",
- color = Color.White,
- fontSize = 18.sp,
- fontWeight = FontWeight.Bold,
- )
+ Text("Starting VM...", color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold)
Spacer(modifier = Modifier.height(12.dp))
Text(
- text = bootStage.ifEmpty { "Initializing..." },
- color = Color(0xFF4FC3F7),
- fontSize = 14.sp,
+ bootStage.ifEmpty { "Initializing..." },
+ color = Color(0xFF4FC3F7), fontSize = 14.sp,
)
Spacer(modifier = Modifier.height(24.dp))
LinearProgressIndicator(
- modifier = Modifier
- .fillMaxWidth(0.7f)
- .height(4.dp)
- .clip(RoundedCornerShape(2.dp)),
+ modifier = Modifier.fillMaxWidth(0.7f).height(4.dp).clip(RoundedCornerShape(2.dp)),
color = Color(0xFF4FC3F7),
trackColor = Color(0xFF333333),
)
@@ -173,30 +147,19 @@ fun TerminalScreen(
}
is VmState.Error -> {
- Box(
- modifier = Modifier.weight(1f).fillMaxWidth(),
- contentAlignment = Alignment.Center,
- ) {
+ Box(modifier = Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Text("Error", color = Color.Red, fontSize = 18.sp, fontWeight = FontWeight.Bold)
Text(
- text = "Error",
- color = Color.Red,
- fontSize = 18.sp,
- fontWeight = FontWeight.Bold,
- )
- Text(
- text = (vmState as VmState.Error).message,
- color = Color.Gray,
- fontSize = 14.sp,
+ (vmState as VmState.Error).message,
+ color = Color.Gray, fontSize = 14.sp,
modifier = Modifier.padding(top = 8.dp, start = 16.dp, end = 16.dp),
textAlign = TextAlign.Center,
)
Spacer(modifier = Modifier.height(16.dp))
Text(
- text = "Tap to Retry",
- color = Color(0xFF4FC3F7),
- fontSize = 14.sp,
- fontWeight = FontWeight.Bold,
+ "Tap to Retry",
+ color = Color(0xFF4FC3F7), fontSize = 14.sp, fontWeight = FontWeight.Bold,
modifier = Modifier
.clip(RoundedCornerShape(8.dp))
.background(Color(0xFF333333))
@@ -208,26 +171,18 @@ fun TerminalScreen(
}
is VmState.Paused, is VmState.Saving, is VmState.Resuming -> {
- Box(
- modifier = Modifier.weight(1f).fillMaxWidth(),
- contentAlignment = Alignment.Center,
- ) {
+ Box(modifier = Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
- CircularProgressIndicator(
- color = Color(0xFF4FC3F7),
- strokeWidth = 3.dp,
- )
+ CircularProgressIndicator(color = Color(0xFF4FC3F7), strokeWidth = 3.dp)
Spacer(modifier = Modifier.height(16.dp))
Text(
- text = when (vmState) {
- is VmState.Paused -> "VM Paused"
- is VmState.Saving -> "Saving state..."
+ when (vmState) {
+ is VmState.Paused -> "VM Paused"
+ is VmState.Saving -> "Saving state..."
is VmState.Resuming -> "Resuming..."
- else -> ""
+ else -> ""
},
- color = Color.White,
- fontSize = 18.sp,
- fontWeight = FontWeight.Bold,
+ color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold,
)
}
}
@@ -254,11 +209,22 @@ fun TerminalScreen(
requestFocus()
- // Use layout listener to sync size once the view is actually measured
- addOnLayoutChangeListener { v, _, _, _, _, _, _, _, _ ->
- val tv = v as TerminalView
- val s = viewModel.session ?: return@addOnLayoutChangeListener
- syncTerminalSize(tv, s, viewModel)
+ /*
+ * Layout listener — fires on initial layout and when the keyboard
+ * opens/closes. TerminalView.updateSize() uses the renderer's
+ * exact font metrics, calculates cols/rows, calls
+ * session.updateSize() which:
+ * 1. Resizes the terminal emulator buffer
+ * 2. Calls ioctl(TIOCSWINSZ) on the PTY master
+ * 3. SIGWINCH → bridge → "RESIZE rows cols" → ctrl.sock → VM
+ */
+ addOnLayoutChangeListener { v, left, top, right, bottom,
+ oldLeft, oldTop, oldRight, oldBottom ->
+ val w = right - left
+ val h = bottom - top
+ if (w <= 0 || h <= 0) return@addOnLayoutChangeListener
+ if (w == oldRight - oldLeft && h == oldBottom - oldTop) return@addOnLayoutChangeListener
+ (v as TerminalView).updateSize()
}
}
},
@@ -268,7 +234,7 @@ fun TerminalScreen(
modifier = Modifier.fillMaxSize(),
)
- // Boot progress overlay — shown while VM is still initializing
+ // Boot progress overlay while VM is still initializing
if (bootStage.isNotEmpty() && bootStage != "Ready") {
Box(
modifier = Modifier
@@ -288,11 +254,7 @@ fun TerminalScreen(
modifier = Modifier.size(16.dp),
)
Spacer(modifier = Modifier.width(12.dp))
- Text(
- text = bootStage,
- color = Color(0xFF4FC3F7),
- fontSize = 13.sp,
- )
+ Text(bootStage, color = Color(0xFF4FC3F7), fontSize = 13.sp)
}
}
}
@@ -308,36 +270,6 @@ fun TerminalScreen(
}
}
-private fun syncTerminalSize(
- view: TerminalView,
- session: TerminalSession,
- viewModel: TerminalViewModel,
-) {
- if (view.width <= 0 || view.height <= 0) return
- try {
- val renderer = view.javaClass.getDeclaredField("mRenderer")
- .apply { isAccessible = true }.get(view) ?: return
- val rendererClass = renderer.javaClass
- val fw = rendererClass.getDeclaredField("mFontWidth")
- .apply { isAccessible = true }.getFloat(renderer)
- val fls = rendererClass.getDeclaredField("mFontLineSpacing")
- .apply { isAccessible = true }.getInt(renderer)
- val flsa = rendererClass.getDeclaredField("mFontLineSpacingAndAscent")
- .apply { isAccessible = true }.getInt(renderer)
-
- if (fw <= 0) return
-
- val cols = (view.width / fw).toInt().coerceAtLeast(4)
- val rows = ((view.height - flsa) / fls).coerceAtLeast(4)
-
- // TerminalView auto-resizes its emulator on layout, so just sync
- // the dimensions to QEMU (updateSize deduplicates and sends stty).
- viewModel.updateSize(cols, rows)
- } catch (e: Exception) {
- Log.w("TerminalScreen", "Resize failed: ${e.message}")
- }
-}
-
@Composable
private fun ExtraKeysRow(
onKey: (String) -> Unit,
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalViewModel.kt
index 1099641..c1aa142 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalViewModel.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/terminal/TerminalViewModel.kt
@@ -2,8 +2,22 @@
* Podroid - Rootless Podman for Android
* Copyright (C) 2024 Podroid contributors
*
- * Keyboard I/O is intercepted at the View level and forwarded to QEMU.
- * The TerminalSession's local subprocess is a benign dummy.
+ * Terminal ViewModel — wires TerminalView to the podroid-bridge binary.
+ *
+ * The bridge binary (libpodroid-bridge.so) runs as the TerminalSession
+ * subprocess. Termux allocates a real PTY for it; the bridge relays that
+ * PTY to QEMU's serial Unix socket. Window resize is handled properly:
+ *
+ * TerminalSession.updateSize(cols, rows)
+ * → ioctl(pty_master, TIOCSWINSZ) [Termux JNI]
+ * → SIGWINCH → bridge process
+ * → bridge reads new size via TIOCGWINSZ
+ * → writes "RESIZE rows cols\n" to ctrl.sock
+ * → VM daemon calls stty on /dev/ttyAMA0
+ * → Linux kernel sends SIGWINCH to VM foreground process group
+ * → nvim / htop / btop redraws correctly
+ *
+ * No reflection, no emulator injection, no sz stdin injection.
*/
package com.excp.podroid.ui.screens.terminal
@@ -16,24 +30,23 @@ import android.os.VibratorManager
import android.util.Log
import android.view.KeyEvent
import android.view.MotionEvent
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
import com.excp.podroid.data.repository.SettingsRepository
import com.excp.podroid.engine.PodroidQemu
import com.excp.podroid.engine.VmState
import com.termux.terminal.TerminalEmulator
+import com.termux.terminal.TerminalOutput
import com.termux.terminal.TerminalSession
import com.termux.terminal.TerminalSessionClient
import com.termux.view.TerminalView
import com.termux.view.TerminalViewClient
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
-import androidx.lifecycle.ViewModel
-import androidx.lifecycle.viewModelScope
-import kotlinx.coroutines.Job
-import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
-import kotlinx.coroutines.launch
+import java.io.File
import javax.inject.Inject
@HiltViewModel
@@ -48,22 +61,16 @@ class TerminalViewModel @Inject constructor(
val terminalFontSize: StateFlow<Int> = settingsRepository.terminalFontSize
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 20)
- @SuppressLint("StaticFieldLeak") // Nulled in onCleared(); ViewModel is nav-scoped, no real leak
+ @SuppressLint("StaticFieldLeak") // nulled in onCleared(); ViewModel is nav-scoped
private var terminalView: TerminalView? = null
- private var emulator: TerminalEmulator? = null
private var attached = false
+
var session: TerminalSession? = null
private set
var extraCtrl = false
var extraAlt = false
- /** Last terminal size sent to the VM via stty, to avoid redundant commands. */
- private var lastSyncedCols = 0
- private var lastSyncedRows = 0
- private var resizeJob: Job? = null
-
-
private val vibrator: Vibrator by lazy {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
(context.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager).defaultVibrator
@@ -80,20 +87,14 @@ class TerminalViewModel @Inject constructor(
override fun onTitleChanged(changedSession: TerminalSession) {}
override fun onSessionFinished(finishedSession: TerminalSession) {}
override fun onCopyTextToClipboard(session: TerminalSession, text: String?) {
- if (text != null) {
- val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE)
- as android.content.ClipboardManager
- clipboard.setPrimaryClip(android.content.ClipData.newPlainText("Terminal", text))
- }
+ if (text == null) return
+ val cb = context.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
+ cb.setPrimaryClip(android.content.ClipData.newPlainText("Terminal", text))
}
override fun onPasteTextFromClipboard(session: TerminalSession?) {
- val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE)
- as android.content.ClipboardManager
- val clip = clipboard.primaryClip
- if (clip != null && clip.itemCount > 0) {
- val text = clip.getItemAt(0).coerceToText(context).toString()
- qemu.writeToConsole(text.toByteArray(Charsets.UTF_8))
- }
+ val cb = context.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
+ val text = cb.primaryClip?.getItemAt(0)?.coerceToText(context)?.toString() ?: return
+ session?.write(text)
}
override fun onBell(session: TerminalSession) {
vibrator.vibrate(VibrationEffect.createOneShot(50, VibrationEffect.DEFAULT_AMPLITUDE))
@@ -131,46 +132,43 @@ class TerminalViewModel @Inject constructor(
override fun onKeyDown(keyCode: Int, e: KeyEvent?, session: TerminalSession?): Boolean {
if (e == null) return false
-
val bytes = when (keyCode) {
- KeyEvent.KEYCODE_ENTER -> byteArrayOf(13) // CR — getty translates to LF
- KeyEvent.KEYCODE_DEL -> byteArrayOf(127) // Backspace
- KeyEvent.KEYCODE_FORWARD_DEL -> "\u001b[3~".toByteArray()
- KeyEvent.KEYCODE_TAB -> byteArrayOf(9)
- KeyEvent.KEYCODE_ESCAPE -> byteArrayOf(27)
- KeyEvent.KEYCODE_DPAD_UP -> "\u001b[A".toByteArray()
- KeyEvent.KEYCODE_DPAD_DOWN -> "\u001b[B".toByteArray()
- KeyEvent.KEYCODE_DPAD_RIGHT -> "\u001b[C".toByteArray()
- KeyEvent.KEYCODE_DPAD_LEFT -> "\u001b[D".toByteArray()
- KeyEvent.KEYCODE_MOVE_HOME -> "\u001b[H".toByteArray()
- KeyEvent.KEYCODE_MOVE_END -> "\u001b[F".toByteArray()
- KeyEvent.KEYCODE_PAGE_UP -> "\u001b[5~".toByteArray()
- KeyEvent.KEYCODE_PAGE_DOWN -> "\u001b[6~".toByteArray()
- KeyEvent.KEYCODE_INSERT -> "\u001b[2~".toByteArray()
- KeyEvent.KEYCODE_F1 -> "\u001bOP".toByteArray()
- KeyEvent.KEYCODE_F2 -> "\u001bOQ".toByteArray()
- KeyEvent.KEYCODE_F3 -> "\u001bOR".toByteArray()
- KeyEvent.KEYCODE_F4 -> "\u001bOS".toByteArray()
- KeyEvent.KEYCODE_F5 -> "\u001b[15~".toByteArray()
- KeyEvent.KEYCODE_F6 -> "\u001b[17~".toByteArray()
- KeyEvent.KEYCODE_F7 -> "\u001b[18~".toByteArray()
- KeyEvent.KEYCODE_F8 -> "\u001b[19~".toByteArray()
- KeyEvent.KEYCODE_F9 -> "\u001b[20~".toByteArray()
- KeyEvent.KEYCODE_F10 -> "\u001b[21~".toByteArray()
- KeyEvent.KEYCODE_F11 -> "\u001b[23~".toByteArray()
- KeyEvent.KEYCODE_F12 -> "\u001b[24~".toByteArray()
+ KeyEvent.KEYCODE_ENTER -> byteArrayOf(13)
+ KeyEvent.KEYCODE_DEL -> byteArrayOf(127)
+ KeyEvent.KEYCODE_FORWARD_DEL -> "\u001b[3~".toByteArray()
+ KeyEvent.KEYCODE_TAB -> byteArrayOf(9)
+ KeyEvent.KEYCODE_ESCAPE -> byteArrayOf(27)
+ KeyEvent.KEYCODE_DPAD_UP -> "\u001b[A".toByteArray()
+ KeyEvent.KEYCODE_DPAD_DOWN -> "\u001b[B".toByteArray()
+ KeyEvent.KEYCODE_DPAD_RIGHT -> "\u001b[C".toByteArray()
+ KeyEvent.KEYCODE_DPAD_LEFT -> "\u001b[D".toByteArray()
+ KeyEvent.KEYCODE_MOVE_HOME -> "\u001b[H".toByteArray()
+ KeyEvent.KEYCODE_MOVE_END -> "\u001b[F".toByteArray()
+ KeyEvent.KEYCODE_PAGE_UP -> "\u001b[5~".toByteArray()
+ KeyEvent.KEYCODE_PAGE_DOWN -> "\u001b[6~".toByteArray()
+ KeyEvent.KEYCODE_INSERT -> "\u001b[2~".toByteArray()
+ KeyEvent.KEYCODE_F1 -> "\u001bOP".toByteArray()
+ KeyEvent.KEYCODE_F2 -> "\u001bOQ".toByteArray()
+ KeyEvent.KEYCODE_F3 -> "\u001bOR".toByteArray()
+ KeyEvent.KEYCODE_F4 -> "\u001bOS".toByteArray()
+ KeyEvent.KEYCODE_F5 -> "\u001b[15~".toByteArray()
+ KeyEvent.KEYCODE_F6 -> "\u001b[17~".toByteArray()
+ KeyEvent.KEYCODE_F7 -> "\u001b[18~".toByteArray()
+ KeyEvent.KEYCODE_F8 -> "\u001b[19~".toByteArray()
+ KeyEvent.KEYCODE_F9 -> "\u001b[20~".toByteArray()
+ KeyEvent.KEYCODE_F10 -> "\u001b[21~".toByteArray()
+ KeyEvent.KEYCODE_F11 -> "\u001b[23~".toByteArray()
+ KeyEvent.KEYCODE_F12 -> "\u001b[24~".toByteArray()
else -> null
}
-
if (bytes != null) {
- qemu.writeToConsole(bytes)
+ session?.write(bytes, 0, bytes.size)
return true
}
return false
}
override fun onKeyUp(keyCode: Int, e: KeyEvent?): Boolean = false
-
override fun onLongPress(event: MotionEvent?): Boolean = false
override fun readControlKey(): Boolean = extraCtrl
override fun readAltKey(): Boolean = extraAlt
@@ -178,23 +176,14 @@ class TerminalViewModel @Inject constructor(
override fun readFnKey(): Boolean = false
override fun onCodePoint(codePoint: Int, ctrlDown: Boolean, session: TerminalSession?): Boolean {
+ val bytes: ByteArray
if ((ctrlDown || extraCtrl) && codePoint in 64..127) {
- qemu.writeToConsole(byteArrayOf((codePoint and 0x1f).toByte()))
- extraCtrl = false
- extraAlt = false
- return true
- }
-
-
- val chars = Character.toChars(codePoint)
- val charBytes = String(chars).toByteArray(Charsets.UTF_8)
- if (extraAlt) {
- // Alt sends ESC prefix followed by the character
- qemu.writeToConsole(byteArrayOf(27) + charBytes)
+ bytes = byteArrayOf((codePoint and 0x1f).toByte())
} else {
- qemu.writeToConsole(charBytes)
+ val charBytes = String(Character.toChars(codePoint)).toByteArray(Charsets.UTF_8)
+ bytes = if (extraAlt) byteArrayOf(27) + charBytes else charBytes
}
-
+ session?.write(bytes, 0, bytes.size)
extraCtrl = false
extraAlt = false
return true
@@ -218,121 +207,145 @@ class TerminalViewModel @Inject constructor(
terminalView = view
}
- fun updateSize(cols: Int, rows: Int) {
- qemu.updateTerminalSize(cols, rows)
- if (cols != lastSyncedCols || rows != lastSyncedRows) {
- lastSyncedCols = cols
- lastSyncedRows = rows
- // Debounce: wait for layout to settle (e.g. keyboard animation)
- // before sending stty to avoid flooding the console.
- resizeJob?.cancel()
- resizeJob = viewModelScope.launch {
- delay(500)
- syncSize()
- }
- }
- }
-
- fun syncSize() {
- val rows = qemu.terminalRows
- val cols = qemu.terminalCols
- if (rows <= 0 || cols <= 0) return
- // Use the sz helper script which sets stty and erases its own echo.
- val cmd = "\u0015sz $rows $cols\n"
- qemu.writeToConsole(cmd.toByteArray(Charsets.UTF_8))
- }
-
+ /**
+ * Creates the TerminalSession backed by podroid-bridge.
+ *
+ * Steps:
+ * 1. Release PodroidQemu's boot-monitoring socket so bridge can connect.
+ * 2. Start the bridge binary as the session subprocess.
+ * 3. Termux allocates a real PTY; bridge relays PTY ↔ serial.sock.
+ *
+ * Resize flow (fully automatic after this):
+ * TerminalView layout change → updateSize(cols, rows)
+ * → TerminalSession.updateSize → ioctl TIOCSWINSZ on PTY master
+ * → SIGWINCH to bridge → bridge writes RESIZE to ctrl.sock
+ * → VM daemon → stty on ttyAMA0 → SIGWINCH in VM
+ */
fun createSession() {
if (attached) return
attached = true
+ // Hand off the serial socket from boot monitoring to the bridge.
+ // shutdownInput() + close() tells the boot monitor to exit; the short
+ // sleep lets QEMU detect the disconnect and re-listen before the bridge
+ // tries to connect (QEMU serial only serves one client at a time).
+ qemu.releaseSerial()
+ Thread.sleep(500)
+
+ val bridgeExe = File(context.applicationInfo.nativeLibraryDir, "libpodroid-bridge.so")
+ if (!bridgeExe.exists()) {
+ Log.e(TAG, "podroid-bridge not found at ${bridgeExe.absolutePath}")
+ return
+ }
+
val sess = TerminalSession(
- "/system/bin/tail",
+ bridgeExe.absolutePath,
context.filesDir.absolutePath,
- arrayOf("tail", "-f", "/dev/null"),
+ arrayOf(bridgeExe.absolutePath, qemu.serialSockPath, qemu.ctrlSockPath),
null,
2000,
sessionClient,
)
- session = sess
-
- val emu = qemu.terminalEmulator
- emulator = emu
-
- if (emu == null) {
- Log.e(TAG, "Cannot attach: VM terminal emulator is null")
- return
- }
-
- sess.updateSize(qemu.terminalCols, qemu.terminalRows)
-
- // Inject persistent emulator into the session via reflection
+ // TerminalSession defers subprocess creation until the first updateSize()
+ // call triggers initializeEmulator(). Force it now so the bridge process
+ // starts and the PTY file descriptor is allocated.
+ sess.updateSize(80, 24)
+
+ // Busybox ash sends \033[6n (cursor position query) on every prompt.
+ // The Termux TerminalEmulator responds with \033[row;colR via TerminalOutput
+ // → bridge stdin → serial → VM ttyAMA0. Due to bridge round-trip latency,
+ // the response arrives after ash's readline has timed out waiting for it,
+ // so ash treats it as keyboard input and displays "^[[16;5R" garbage.
+ //
+ // Fix: replace the session's emulator with one whose TerminalOutput is a
+ // no-op — all emulator responses are dropped. Keyboard input is unaffected
+ // because it flows through session.write() → PTY master (separate path).
try {
- val emulatorField = TerminalSession::class.java.getDeclaredField("mEmulator")
- emulatorField.isAccessible = true
- emulatorField.set(sess, emu)
- Log.d(TAG, "Session emulator injected OK")
+ val noOpOutput = object : TerminalOutput() {
+ override fun write(data: ByteArray, offset: Int, count: Int) {}
+ override fun titleChanged(oldTitle: String?, newTitle: String?) {}
+ override fun onCopyTextToClipboard(text: String?) {}
+ override fun onPasteTextFromClipboard() {}
+ override fun onBell() {}
+ override fun onColorsChanged() {}
+ }
+ val displayEmulator = TerminalEmulator(noOpOutput, 80, 24, 2000, sessionClient)
+ val field = TerminalSession::class.java.getDeclaredField("mEmulator")
+ field.isAccessible = true
+ field.set(sess, displayEmulator)
+ Log.d(TAG, "Emulator output replaced — CPR responses will be dropped")
} catch (e: Exception) {
- Log.e(TAG, "Reflection setup failed", e)
+ Log.w(TAG, "Could not replace emulator output: ${e.message}")
}
- // QEMU output → trigger UI refresh
- qemu.onConsoleOutput = { _, _ ->
- terminalView?.let { view ->
- view.post {
- view.onScreenUpdated()
- view.invalidate()
- }
- }
- }
+ session = sess
+ Log.d(TAG, "Bridge session created — PTY connected to ${qemu.serialSockPath}")
+ }
+
+ /**
+ * Triggered by the layout listener in TerminalScreen when the view dimensions
+ * change (initial layout, keyboard open/close, rotation).
+ *
+ * Calls TerminalSession.updateSize which:
+ * 1. Resizes the local terminal emulator buffer.
+ * 2. Calls ioctl(pty_master_fd, TIOCSWINSZ) via Termux JNI.
+ * 3. The kernel sends SIGWINCH to the bridge process.
+ * 4. The bridge sends RESIZE to ctrl.sock → VM gets proper SIGWINCH.
+ */
+ fun updateSize(cols: Int, rows: Int) {
+ session?.updateSize(cols, rows)
+ }
+
+ /**
+ * SYNC button — re-sends the current size through the full chain.
+ * Useful if the VM missed a resize event (e.g., during intensive I/O).
+ */
+ fun syncSize() {
+ val emu = session?.emulator ?: return
+ session?.updateSize(emu.mColumns, emu.mRows)
}
fun sendExtraKey(key: String) {
- if (key == "SYNC") {
- syncSize()
- return
- }
when (key) {
+ "SYNC" -> { syncSize(); return }
"CTRL" -> { extraCtrl = !extraCtrl; return }
- "ALT" -> { extraAlt = !extraAlt; return }
+ "ALT" -> { extraAlt = !extraAlt; return }
}
val bytes = when (key) {
- "ESC" -> byteArrayOf(27)
- "TAB" -> byteArrayOf(9)
- "UP" -> "\u001b[A".toByteArray()
+ "ESC" -> byteArrayOf(27)
+ "TAB" -> byteArrayOf(9)
+ "UP" -> "\u001b[A".toByteArray()
"DOWN" -> "\u001b[B".toByteArray()
"LEFT" -> "\u001b[D".toByteArray()
- "RIGHT" -> "\u001b[C".toByteArray()
+ "RIGHT"-> "\u001b[C".toByteArray()
"HOME" -> "\u001b[H".toByteArray()
- "END" -> "\u001b[F".toByteArray()
+ "END" -> "\u001b[F".toByteArray()
"PGUP" -> "\u001b[5~".toByteArray()
"PGDN" -> "\u001b[6~".toByteArray()
- "F1" -> "\u001bOP".toByteArray()
- "F2" -> "\u001bOQ".toByteArray()
- "F3" -> "\u001bOR".toByteArray()
- "F4" -> "\u001bOS".toByteArray()
- "F5" -> "\u001b[15~".toByteArray()
- "F6" -> "\u001b[17~".toByteArray()
- "F7" -> "\u001b[18~".toByteArray()
- "F8" -> "\u001b[19~".toByteArray()
- "F9" -> "\u001b[20~".toByteArray()
- "F10" -> "\u001b[21~".toByteArray()
- "F11" -> "\u001b[23~".toByteArray()
- "F12" -> "\u001b[24~".toByteArray()
- "-" -> "-".toByteArray()
- "|" -> "|".toByteArray()
- "/" -> "/".toByteArray()
- else -> return
+ "F1" -> "\u001bOP".toByteArray()
+ "F2" -> "\u001bOQ".toByteArray()
+ "F3" -> "\u001bOR".toByteArray()
+ "F4" -> "\u001bOS".toByteArray()
+ "F5" -> "\u001b[15~".toByteArray()
+ "F6" -> "\u001b[17~".toByteArray()
+ "F7" -> "\u001b[18~".toByteArray()
+ "F8" -> "\u001b[19~".toByteArray()
+ "F9" -> "\u001b[20~".toByteArray()
+ "F10" -> "\u001b[21~".toByteArray()
+ "F11" -> "\u001b[23~".toByteArray()
+ "F12" -> "\u001b[24~".toByteArray()
+ "-" -> "-".toByteArray()
+ "|" -> "|".toByteArray()
+ "/" -> "/".toByteArray()
+ else -> return
}
- qemu.writeToConsole(bytes)
+ session?.write(bytes, 0, bytes.size)
extraCtrl = false
extraAlt = false
}
override fun onCleared() {
super.onCleared()
- qemu.onConsoleOutput = null
- emulator = null
terminalView = null
session = null
attached = false
diff --git a/app/src/main/jniLibs/arm64-v8a/libpodroid-bridge.so b/app/src/main/jniLibs/arm64-v8a/libpodroid-bridge.so
new file mode 100755
index 0000000..72659f7
Binary files /dev/null and b/app/src/main/jniLibs/arm64-v8a/libpodroid-bridge.so differ
diff --git a/build-qemu-android.sh b/build-qemu-android.sh
index 957e267..e018004 100755
--- a/build-qemu-android.sh
+++ b/build-qemu-android.sh
@@ -41,6 +41,7 @@ ASSETS="${SCRIPT_DIR}/app/src/main/assets"
# Extract binaries
docker cp "${CONTAINER}:/out/libqemu-system-aarch64.so" "${JNILIBS}/libqemu-system-aarch64.so"
docker cp "${CONTAINER}:/out/libslirp.so" "${JNILIBS}/libslirp.so"
+docker cp "${CONTAINER}:/out/libpodroid-bridge.so" "${JNILIBS}/libpodroid-bridge.so"
# Extract ROM and keymaps
docker cp "${CONTAINER}:/out/qemu/efi-virtio.rom" "${ASSETS}/qemu/efi-virtio.rom"
@@ -93,6 +94,7 @@ echo "=== [4/4] Done! ==="
echo ""
echo " libqemu-system-aarch64.so → ${JNILIBS}/"
echo " libslirp.so → ${JNILIBS}/"
+echo " libpodroid-bridge.so → ${JNILIBS}/"
echo " ROM + keymaps → ${ASSETS}/qemu/"
echo ""
echo " Now run: ./gradlew assembleDebug"
diff --git a/init-podroid b/init-podroid
index 6e63bc2..74d2154 100644
--- a/init-podroid
+++ b/init-podroid
@@ -260,20 +260,33 @@ stty -ixon -ixoff -iexten -echoctl 2>/dev/null
cd /root
PROF
-# ── Silent resize helper ─────────────────────────────────────────────────────
-cat > /usr/local/bin/sz <<'SZ'
-#!/bin/sh
-stty rows "$1" cols "$2" 2>/dev/null
-printf '\033[1A\033[2K'
-SZ
-chmod +x /usr/local/bin/sz
+# ── Resize control daemon ─────────────────────────────────────────────────────
+# Reads "RESIZE rows cols\n" from /dev/hvc0 (virtio-console, mapped from
+# ctrl.sock on the Android side by podroid-bridge on SIGWINCH).
+# stty on /dev/ttyAMA0 calls TIOCSWINSZ; the Linux kernel automatically
+# sends SIGWINCH to the foreground process group — nvim/htop/btop resize
+# correctly without any stdin injection.
+(
+ for i in $(seq 1 30); do
+ [ -c /dev/hvc0 ] && break
+ sleep 1
+ done
+ [ -c /dev/hvc0 ] || exit 0
+ while IFS= read -r line; do
+ case "$line" in
+ RESIZE\ *)
+ set -- $line
+ stty rows "$2" cols "$3" < /dev/ttyAMA0 2>/dev/null
+ ;;
+ esac
+ done < /dev/hvc0
+) &
# ── Login wrapper ─────────────────────────────────────────────────────────────
cat > /usr/local/bin/podroid-login <<'LOGIN'
#!/bin/sh
. /etc/profile
cat /etc/motd
-resize >/dev/null 2>&1
exec /bin/sh
LOGIN
chmod +x /usr/local/bin/podroid-login
diff --git a/podroid-bridge.c b/podroid-bridge.c
new file mode 100644
index 0000000..0741611
--- /dev/null
+++ b/podroid-bridge.c
@@ -0,0 +1,159 @@
+/*
+ * podroid-bridge — Serial socket terminal bridge for Podroid
+ *
+ * Relays data between:
+ * stdin/stdout (TerminalSession PTY, managed by Termux)
+ * serial.sock (QEMU unix socket serial — ttyAMA0 in the VM)
+ *
+ * On SIGWINCH (triggered by TerminalSession.updateSize → ioctl TIOCSWINSZ):
+ * reads the new PTY dimensions and sends "RESIZE rows cols\n" to ctrl.sock.
+ * The VM daemon reads from /dev/hvc0 and calls stty on ttyAMA0 — the Linux
+ * kernel automatically sends SIGWINCH to the foreground process group.
+ *
+ * argv[1] = path to serial.sock (QEMU serial unix socket)
+ * argv[2] = path to ctrl.sock (QEMU virtio-console ctrl chardev socket)
+ *
+ * Built for Android ARM64 with 16KB page alignment.
+ * Shipped as libpodroid-bridge.so so Android extracts it from the APK.
+ */
+
+#include <errno.h>
+#include <signal.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/select.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <termios.h>
+#include <unistd.h>
+
+static volatile sig_atomic_t g_winch = 0;
+static int g_ctrl_fd = -1;
+
+static void on_winch(int sig) {
+ (void)sig;
+ g_winch = 1;
+}
+
+static int connect_unix(const char *path) {
+ int fd = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (fd < 0) return -1;
+ struct sockaddr_un addr;
+ memset(&addr, 0, sizeof(addr));
+ addr.sun_family = AF_UNIX;
+ strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
+ if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
+ close(fd);
+ return -1;
+ }
+ return fd;
+}
+
+static void send_resize(void) {
+ if (g_ctrl_fd < 0) return;
+ struct winsize ws;
+ memset(&ws, 0, sizeof(ws));
+ if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) < 0) return;
+ if (ws.ws_row == 0 || ws.ws_col == 0) return;
+ char msg[64];
+ int n = snprintf(msg, sizeof(msg), "RESIZE %d %d\n", ws.ws_row, ws.ws_col);
+ if (n > 0) {
+ /* Ignore write errors — ctrl is best-effort */
+ (void)write(g_ctrl_fd, msg, n);
+ }
+}
+
+static int write_all(int fd, const char *buf, int n) {
+ int written = 0;
+ while (written < n) {
+ int w = write(fd, buf + written, n - written);
+ if (w <= 0) return -1;
+ written += w;
+ }
+ return 0;
+}
+
+int main(int argc, char *argv[]) {
+ if (argc < 3) {
+ fprintf(stderr, "Usage: %s <serial.sock> <ctrl.sock>\n", argv[0]);
+ return 1;
+ }
+
+ /* Retry serial connection — QEMU only serves one client at a time on the
+ * unix socket, so the boot monitor may still be connected briefly after
+ * releaseSerial() on the Android side. */
+ int serial_fd = -1;
+ for (int attempt = 0; attempt < 50; attempt++) { /* up to 10 seconds */
+ serial_fd = connect_unix(argv[1]);
+ if (serial_fd >= 0) break;
+ usleep(200000); /* 200ms */
+ }
+ if (serial_fd < 0) {
+ fprintf(stderr, "podroid-bridge: cannot connect to %s after retries: %s\n",
+ argv[1], strerror(errno));
+ return 1;
+ }
+
+ /* Put the local PTY into raw mode — the VM's ttyAMA0 handles echo,
+ * line editing, and signal generation. Without this, both the local PTY
+ * and the remote terminal echo, causing every keystroke to appear twice. */
+ {
+ struct termios raw;
+ if (tcgetattr(STDIN_FILENO, &raw) == 0) {
+ cfmakeraw(&raw);
+ tcsetattr(STDIN_FILENO, TCSANOW, &raw);
+ }
+ }
+
+ /* ctrl socket is optional — resize won't propagate if unavailable */
+ g_ctrl_fd = connect_unix(argv[2]);
+
+ /* Send initial terminal size right away so the VM has it from first keypress */
+ send_resize();
+
+ signal(SIGWINCH, on_winch);
+
+ char buf[4096];
+ for (;;) {
+ if (g_winch) {
+ g_winch = 0;
+ send_resize();
+ }
+
+ fd_set rfds;
+ FD_ZERO(&rfds);
+ FD_SET(STDIN_FILENO, &rfds);
+ FD_SET(serial_fd, &rfds);
+ int nfds = serial_fd + 1;
+
+ /*
+ * 100ms timeout so we re-check g_winch even when there is no I/O.
+ * Keeps resize responsive without busy-looping.
+ */
+ struct timeval tv = { .tv_sec = 0, .tv_usec = 100000 };
+ int ret = select(nfds, &rfds, NULL, NULL, &tv);
+ if (ret < 0) {
+ if (errno == EINTR) continue;
+ break;
+ }
+
+ /* Keyboard → serial */
+ if (FD_ISSET(STDIN_FILENO, &rfds)) {
+ int n = read(STDIN_FILENO, buf, sizeof(buf));
+ if (n <= 0) break;
+ if (write_all(serial_fd, buf, n) < 0) break;
+ }
+
+ /* Serial → screen */
+ if (FD_ISSET(serial_fd, &rfds)) {
+ int n = read(serial_fd, buf, sizeof(buf));
+ if (n <= 0) break;
+ if (write_all(STDOUT_FILENO, buf, n) < 0) break;
+ }
+ }
+
+ close(serial_fd);
+ if (g_ctrl_fd >= 0) close(g_ctrl_fd);
+ return 0;
+}